content
stringlengths 28
1.34M
|
---|
import { ValueTransformer } from 'typeorm';
/**
* Decimal types are returned as strings (e.g. "20.00") by some DBs, e.g. MySQL & Postgres
*/
export class DecimalTransformer implements ValueTransformer {
to(value: any): any {
return value;
}
from(value: any): any {
return Number.parseFloat(value);
}
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomAddressFields } from '../custom-entity-fields';
import { Customer } from '../customer/customer.entity';
import { Country } from '../region/country.entity';
/**
* @description
* Represents a {@link Customer}'s address.
*
* @docsCategory entities
*/
@Entity()
export class Address extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<Address>) {
super(input);
}
@Index()
@ManyToOne(type => Customer, customer => customer.addresses)
customer: Customer;
@Column({ default: '' }) fullName: string;
@Column({ default: '' })
company: string;
@Column() streetLine1: string;
@Column({ default: '' })
streetLine2: string;
@Column({ default: '' }) city: string;
@Column({ default: '' })
province: string;
@Column({ default: '' }) postalCode: string;
@Index()
@ManyToOne(type => Country)
country: Country;
@Column({ default: '' })
phoneNumber: string;
@Column({ default: false })
defaultShippingAddress: boolean;
@Column({ default: false })
defaultBillingAddress: boolean;
@Column(type => CustomAddressFields)
customFields: CustomAddressFields;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinColumn, OneToOne } from 'typeorm';
import { SoftDeletable } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomAdministratorFields } from '../custom-entity-fields';
import { User } from '../user/user.entity';
/**
* @description
* An administrative user who has access to the Admin UI and Admin API. The
* specific permissions of the Administrator are determined by the assigned
* {@link Role}s.
*
* @docsCategory entities
*/
@Entity()
export class Administrator extends VendureEntity implements SoftDeletable, HasCustomFields {
constructor(input?: DeepPartial<Administrator>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
@Column() firstName: string;
@Column() lastName: string;
@Column({ unique: true })
emailAddress: string;
@OneToOne(type => User)
@JoinColumn()
user: User;
@Column(type => CustomAdministratorFields)
customFields: CustomAdministratorFields;
}
|
import { AssetType } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { ChannelAware, Taggable } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { Collection } from '../collection/collection.entity';
import { CustomAssetFields } from '../custom-entity-fields';
import { Product } from '../product/product.entity';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { Tag } from '../tag/tag.entity';
/**
* @description
* An Asset represents a file such as an image which can be associated with certain other entities
* such as Products.
*
* @docsCategory entities
*/
@Entity()
export class Asset extends VendureEntity implements Taggable, ChannelAware, HasCustomFields {
constructor(input?: DeepPartial<Asset>) {
super(input);
}
@Column() name: string;
@Column('varchar') type: AssetType;
@Column() mimeType: string;
@Column({ default: 0 }) width: number;
@Column({ default: 0 }) height: number;
@Column() fileSize: number;
@Column() source: string;
@Column() preview: string;
@Column('simple-json', { nullable: true })
focalPoint?: { x: number; y: number };
@ManyToMany(type => Tag)
@JoinTable()
tags: Tag[];
@ManyToMany(type => Channel)
@JoinTable()
channels: Channel[];
@OneToMany(type => Collection, collection => collection.featuredAsset)
featuredInCollections?: Collection[];
@OneToMany(type => ProductVariant, productVariant => productVariant.featuredAsset)
featuredInVariants?: ProductVariant[];
@OneToMany(type => Product, product => product.featuredAsset)
featuredInProducts?: Product[];
@Column(type => CustomAssetFields)
customFields: CustomAssetFields;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Index, ManyToOne } from 'typeorm';
import { Orderable } from '../../common/types/common-types';
import { Asset } from '../asset/asset.entity';
import { VendureEntity } from '../base/base.entity';
/**
* @description
* This base class is extended in order to enable specific ordering of the one-to-many
* Entity -> Assets relation. Using a many-to-many relation does not provide a way
* to guarantee order of the Assets, so this entity is used in place of the
* usual join table that would be created by TypeORM.
* See https://typeorm.io/#/many-to-many-relations/many-to-many-relations-with-custom-properties
*
* @docsCategory entities
*/
export abstract class OrderableAsset extends VendureEntity implements Orderable {
protected constructor(input?: DeepPartial<OrderableAsset>) {
super(input);
}
@Column()
assetId: ID;
@Index()
@ManyToOne(type => Asset, { eager: true, onDelete: 'CASCADE' })
asset: Asset;
@Column()
position: number;
}
|
import { Entity, Index, ManyToOne, TableInheritance } from 'typeorm';
import { VendureEntity } from '../base/base.entity';
import { User } from '../user/user.entity';
/**
* @description
* An AuthenticationMethod represents the means by which a {@link User} is authenticated. There are two kinds:
* {@link NativeAuthenticationMethod} and {@link ExternalAuthenticationMethod}.
*
* @docsCategory entities
* @docsPage AuthenticationMethod
*/
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export abstract class AuthenticationMethod extends VendureEntity {
@Index()
@ManyToOne(type => User, user => user.authenticationMethods)
user: User;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Column } from 'typeorm';
import { AuthenticationMethod } from './authentication-method.entity';
/**
* @description
* This method is used when an external authentication service is used to authenticate Vendure Users.
* Examples of external auth include social logins or corporate identity servers.
*
* @docsCategory entities
* @docsPage AuthenticationMethod
*/
@ChildEntity()
export class ExternalAuthenticationMethod extends AuthenticationMethod {
constructor(input: DeepPartial<ExternalAuthenticationMethod>) {
super(input);
}
@Column()
strategy: string;
@Column()
externalIdentifier: string;
@Column('simple-json')
metadata: any;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Column } from 'typeorm';
import { AuthenticationMethod } from './authentication-method.entity';
/**
* @description
* This is the default, built-in authentication method which uses a identifier (typically username or email address)
* and password combination to authenticate a User.
*
* @docsCategory entities
* @docsPage AuthenticationMethod
*/
@ChildEntity()
export class NativeAuthenticationMethod extends AuthenticationMethod {
constructor(input?: DeepPartial<NativeAuthenticationMethod>) {
super(input);
}
@Column()
identifier: string;
@Column({ select: false }) passwordHash: string;
@Column({ type: 'varchar', nullable: true })
verificationToken: string | null;
@Column({ type: 'varchar', nullable: true })
passwordResetToken: string | null;
/**
* @description
* A token issued when a User requests to change their identifier (typically
* an email address)
*/
@Column({ type: 'varchar', nullable: true })
identifierChangeToken: string | null;
/**
* @description
* When a request has been made to change the User's identifier, the new identifier
* will be stored here until it has been verified, after which it will
* replace the current value of the `identifier` field.
*/
@Column({ type: 'varchar', nullable: true })
pendingIdentifier: string | null;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { describe, expect, it } from 'vitest';
import { Calculated } from '../../common/index';
import { CalculatedPropertySubscriber } from '../subscribers';
import { VendureEntity } from './base.entity';
class ChildEntity extends VendureEntity {
constructor(input?: DeepPartial<ChildEntity>) {
super(input);
}
name: string;
get nameLoud(): string {
return this.name.toUpperCase();
}
}
class ChildEntityWithCalculated extends VendureEntity {
constructor(input?: DeepPartial<ChildEntity>) {
super(input);
}
name: string;
@Calculated()
get nameLoudCalculated(): string {
return this.name.toUpperCase();
}
}
describe('VendureEntity', () => {
it('instantiating a child entity', () => {
const child = new ChildEntity({
name: 'foo',
});
expect(child.name).toBe('foo');
expect(child.nameLoud).toBe('FOO');
});
it('instantiating from existing entity with getter', () => {
const child1 = new ChildEntity({
name: 'foo',
});
const child2 = new ChildEntity(child1);
expect(child2.name).toBe('foo');
expect(child2.nameLoud).toBe('FOO');
});
it('instantiating from existing entity with calculated getter', () => {
const calculatedPropertySubscriber = new CalculatedPropertySubscriber();
const child1 = new ChildEntityWithCalculated({
name: 'foo',
});
// This is what happens to entities after being loaded from the DB
calculatedPropertySubscriber.afterLoad(child1);
const child2 = new ChildEntityWithCalculated(child1);
expect(child2.name).toBe('foo');
expect(child2.nameLoudCalculated).toBe('FOO');
});
});
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { CreateDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
import { PrimaryGeneratedId } from '../entity-id.decorator';
/**
* @description
* This is the base class from which all entities inherit. The type of
* the `id` property is defined by the {@link EntityIdStrategy}.
*
* @docsCategory entities
*/
export abstract class VendureEntity {
protected constructor(input?: DeepPartial<VendureEntity>) {
if (input) {
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(input))) {
if (descriptor.get && !descriptor.set) {
// A getter has been moved to the entity instance
// by the CalculatedPropertySubscriber
// and cannot be copied over to the new instance.
continue;
}
(this as any)[key] = descriptor.value;
}
}
}
@PrimaryGeneratedId()
id: ID;
@CreateDateColumn() createdAt: Date;
@UpdateDateColumn() updatedAt: Date;
}
|
import { CurrencyCode, LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToMany, ManyToOne } from 'typeorm';
import { Customer, PaymentMethod, Promotion, Role, ShippingMethod, StockLocation } from '..';
import { VendureEntity } from '../base/base.entity';
import { Collection } from '../collection/collection.entity';
import { CustomChannelFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { Facet } from '../facet/facet.entity';
import { FacetValue } from '../facet-value/facet-value.entity';
import { Product } from '../product/product.entity';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { Seller } from '../seller/seller.entity';
import { Zone } from '../zone/zone.entity';
/**
* @description
* A Channel represents a distinct sales channel and configures defaults for that
* channel.
*
* * Set a channel-specific currency, language, tax and shipping defaults
* * Assign only specific Products to the Channel (with Channel-specific prices)
* * Create Administrator roles limited to the Channel
* * Assign only specific StockLocations, Assets, Facets, Collections, Promotions, ShippingMethods & PaymentMethods to the Channel
* * Have Orders and Customers associated with specific Channels.
*
* In Vendure, Channels have a number of different uses, such as:
*
* * Multi-region stores, where there is a distinct website for each territory with its own available inventory, pricing, tax and shipping rules.
* * Creating distinct rules and inventory for different sales channels such as Amazon.
* * Specialized stores offering a subset of the main inventory.
* * Implementing multi-vendor marketplace applications.
*
* @docsCategory entities
*/
@Entity()
export class Channel extends VendureEntity {
constructor(input?: DeepPartial<Channel>) {
super(input);
if (!input || !input.token) {
this.token = this.generateToken();
}
}
/**
* @description
* The name of the Channel. For example "US Webstore" or "German Webstore".
*/
@Column({ unique: true })
code: string;
/**
* @description
* A unique token (string) used to identify the Channel in the `vendure-token` header of the
* GraphQL API requests.
*/
@Column({ unique: true })
token: string;
@Column({ default: '', nullable: true })
description: string;
@Index()
@ManyToOne(type => Seller, seller => seller.channels)
seller?: Seller;
@EntityId({ nullable: true })
sellerId?: ID;
@Column('varchar') defaultLanguageCode: LanguageCode;
@Column({ type: 'simple-array', nullable: true })
availableLanguageCodes: LanguageCode[];
@Index()
@ManyToOne(type => Zone, zone => zone.defaultTaxZoneChannels)
defaultTaxZone: Zone;
@Index()
@ManyToOne(type => Zone, zone => zone.defaultShippingZoneChannels)
defaultShippingZone: Zone;
@Column('varchar')
defaultCurrencyCode: CurrencyCode;
@Column({ type: 'simple-array', nullable: true })
availableCurrencyCodes: CurrencyCode[];
/**
* @description
* Specifies the default value for inventory tracking for ProductVariants.
* Can be overridden per ProductVariant, but this value determines the default
* if not otherwise specified.
*/
@Column({ default: true })
trackInventory: boolean;
/**
* @description
* Specifies the value of stockOnHand at which a given ProductVariant is considered
* out of stock.
*/
@Column({ default: 0 })
outOfStockThreshold: number;
@Column(type => CustomChannelFields)
customFields: CustomChannelFields;
@Column() pricesIncludeTax: boolean;
@ManyToMany(type => Product, product => product.channels, { onDelete: 'CASCADE' })
products: Product[];
@ManyToMany(type => ProductVariant, productVariant => productVariant.channels, { onDelete: 'CASCADE' })
productVariants: ProductVariant[];
@ManyToMany(type => FacetValue, facetValue => facetValue.channels, { onDelete: 'CASCADE' })
facetValues: FacetValue[];
@ManyToMany(type => Facet, facet => facet.channels, { onDelete: 'CASCADE' })
facets: Facet[];
@ManyToMany(type => Collection, collection => collection.channels, { onDelete: 'CASCADE' })
collections: Collection[];
@ManyToMany(type => Promotion, promotion => promotion.channels, { onDelete: 'CASCADE' })
promotions: Promotion[];
@ManyToMany(type => PaymentMethod, paymentMethod => paymentMethod.channels, { onDelete: 'CASCADE' })
paymentMethods: PaymentMethod[];
@ManyToMany(type => ShippingMethod, shippingMethod => shippingMethod.channels, { onDelete: 'CASCADE' })
shippingMethods: ShippingMethod[];
@ManyToMany(type => Customer, customer => customer.channels, { onDelete: 'CASCADE' })
customers: Customer[];
@ManyToMany(type => Role, role => role.channels, { onDelete: 'CASCADE' })
roles: Role[];
@ManyToMany(type => StockLocation, stockLocation => stockLocation.channels, { onDelete: 'CASCADE' })
stockLocations: StockLocation[];
private generateToken(): string {
const randomString = () => Math.random().toString(36).substr(3, 10);
return `${randomString()}${randomString()}`;
}
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { OrderableAsset } from '../asset/orderable-asset.entity';
import { Collection } from './collection.entity';
@Entity()
export class CollectionAsset extends OrderableAsset {
constructor(input?: DeepPartial<CollectionAsset>) {
super(input);
}
@Column()
collectionId: ID;
@Index()
@ManyToOne(type => Collection, collection => collection.assets, { onDelete: 'CASCADE' })
collection: Collection;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomCollectionFieldsTranslation } from '../custom-entity-fields';
import { Collection } from './collection.entity';
@Entity()
export class CollectionTranslation extends VendureEntity implements Translation<Collection>, HasCustomFields {
constructor(input?: DeepPartial<Translation<Collection>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index({ unique: false })
@Column()
slug: string;
@Column('text') description: string;
@Index()
@ManyToOne(type => Collection, base => base.translations, { onDelete: 'CASCADE' })
base: Collection;
@Column(type => CustomCollectionFieldsTranslation)
customFields: CustomCollectionFieldsTranslation;
}
|
import { ConfigurableOperation } from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import {
Column,
Entity,
Index,
JoinTable,
ManyToMany,
ManyToOne,
OneToMany,
Tree,
TreeChildren,
TreeParent,
} from 'typeorm';
import { ChannelAware, Orderable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { Asset } from '../asset/asset.entity';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomCollectionFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { CollectionAsset } from './collection-asset.entity';
import { CollectionTranslation } from './collection-translation.entity';
/**
* @description
* A Collection is a grouping of {@link Product}s based on various configurable criteria.
*
* @docsCategory entities
*/
@Entity()
@Tree('closure-table')
export class Collection
extends VendureEntity
implements Translatable, HasCustomFields, ChannelAware, Orderable
{
constructor(input?: DeepPartial<Collection>) {
super(input);
}
@Column({ default: false })
isRoot: boolean;
@Column()
position: number;
@Column({ default: false })
isPrivate: boolean;
name: LocaleString;
description: LocaleString;
slug: LocaleString;
@OneToMany(type => CollectionTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<Collection>>;
@Index()
@ManyToOne(type => Asset, asset => asset.featuredInCollections, { onDelete: 'SET NULL' })
featuredAsset: Asset;
@OneToMany(type => CollectionAsset, collectionAsset => collectionAsset.collection)
assets: CollectionAsset[];
@Column('simple-json') filters: ConfigurableOperation[];
/**
* @since 2.0.0
*/
@Column({ default: true }) inheritFilters: boolean;
@ManyToMany(type => ProductVariant, productVariant => productVariant.collections)
@JoinTable()
productVariants: ProductVariant[];
@Column(type => CustomCollectionFields)
customFields: CustomCollectionFields;
@TreeChildren()
children: Collection[];
@TreeParent()
parent: Collection;
@EntityId({ nullable: true })
parentId: ID;
@ManyToMany(type => Channel, channel => channel.collections)
@JoinTable()
channels: Channel[];
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, ManyToMany, OneToMany } from 'typeorm';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomCustomerGroupFields } from '../custom-entity-fields';
import { Customer } from '../customer/customer.entity';
import { TaxRate } from '../tax-rate/tax-rate.entity';
/**
* @description
* A grouping of {@link Customer}s which enables features such as group-based promotions
* or tax rules.
*
* @docsCategory entities
*/
@Entity()
export class CustomerGroup extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<CustomerGroup>) {
super(input);
}
@Column() name: string;
@ManyToMany(type => Customer, customer => customer.groups)
customers: Customer[];
@Column(type => CustomCustomerGroupFields)
customFields: CustomCustomerGroupFields;
@OneToMany(type => TaxRate, taxRate => taxRate.zone)
taxRates: TaxRate[];
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinColumn, JoinTable, ManyToMany, OneToMany, OneToOne } from 'typeorm';
import { ChannelAware, SoftDeletable } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { Address } from '../address/address.entity';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomCustomerFields } from '../custom-entity-fields';
import { CustomerGroup } from '../customer-group/customer-group.entity';
import { Order } from '../order/order.entity';
import { User } from '../user/user.entity';
/**
* @description
* This entity represents a customer of the store, typically an individual person. A Customer can be
* a guest, in which case it has no associated {@link User}. Customers with registered account will
* have an associated User entity.
*
* @docsCategory entities
*/
@Entity()
export class Customer extends VendureEntity implements ChannelAware, HasCustomFields, SoftDeletable {
constructor(input?: DeepPartial<Customer>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
@Column({ nullable: true })
title: string;
@Column() firstName: string;
@Column() lastName: string;
@Column({ nullable: true })
phoneNumber: string;
@Column()
emailAddress: string;
@ManyToMany(type => CustomerGroup, group => group.customers)
@JoinTable()
groups: CustomerGroup[];
@OneToMany(type => Address, address => address.customer)
addresses: Address[];
@OneToMany(type => Order, order => order.customer)
orders: Order[];
@OneToOne(type => User, { eager: true })
@JoinColumn()
user?: User;
@Column(type => CustomCustomerFields)
customFields: CustomCustomerFields;
@ManyToMany(type => Channel, channel => channel.customers)
@JoinTable()
channels: Channel[];
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { VendureEntity } from '../base/base.entity';
import { CustomFacetValueFieldsTranslation } from '../custom-entity-fields';
import { FacetValue } from './facet-value.entity';
@Entity()
export class FacetValueTranslation extends VendureEntity implements Translation<FacetValue> {
constructor(input?: DeepPartial<Translation<FacetValue>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index()
@ManyToOne(type => FacetValue, base => base.translations, { onDelete: 'CASCADE' })
base: FacetValue;
@Column(type => CustomFacetValueFieldsTranslation)
customFields: CustomFacetValueFieldsTranslation;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, JoinTable, ManyToMany, ManyToOne, OneToMany } from 'typeorm';
import { ChannelAware } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomFacetValueFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { Facet } from '../facet/facet.entity';
import { Product } from '../product/product.entity';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { FacetValueTranslation } from './facet-value-translation.entity';
/**
* @description
* A particular value of a {@link Facet}.
*
* @docsCategory entities
*/
@Entity()
export class FacetValue extends VendureEntity implements Translatable, HasCustomFields, ChannelAware {
constructor(input?: DeepPartial<FacetValue>) {
super(input);
}
name: LocaleString;
@Column() code: string;
@OneToMany(type => FacetValueTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<FacetValue>>;
@Index()
@ManyToOne(type => Facet, group => group.values, { onDelete: 'CASCADE' })
facet: Facet;
@EntityId()
facetId: ID;
@Column(type => CustomFacetValueFields)
customFields: CustomFacetValueFields;
@ManyToMany(type => Channel, channel => channel.facetValues)
@JoinTable()
channels: Channel[];
@ManyToMany(() => Product, product => product.facetValues, { onDelete: 'CASCADE' })
products: Product[];
@ManyToMany(type => ProductVariant, productVariant => productVariant.facetValues)
productVariants: ProductVariant[];
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomFacetFieldsTranslation } from '../custom-entity-fields';
import { Facet } from './facet.entity';
@Entity()
export class FacetTranslation extends VendureEntity implements Translation<Facet>, HasCustomFields {
constructor(input?: DeepPartial<Translation<FacetTranslation>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index()
@ManyToOne(type => Facet, base => base.translations, { onDelete: 'CASCADE' })
base: Facet;
@Column(type => CustomFacetFieldsTranslation)
customFields: CustomFacetFieldsTranslation;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { ChannelAware } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomFacetFields } from '../custom-entity-fields';
import { FacetValue } from '../facet-value/facet-value.entity';
import { FacetTranslation } from './facet-translation.entity';
/**
* @description
* A Facet is a class of properties which can be applied to a {@link Product} or {@link ProductVariant}.
* They are used to enable [faceted search](https://en.wikipedia.org/wiki/Faceted_search) whereby products
* can be filtered along a number of dimensions (facets).
*
* For example, there could be a Facet named "Brand" which has a number of {@link FacetValue}s representing
* the various brands of product, e.g. "Apple", "Samsung", "Dell", "HP" etc.
*
* @docsCategory entities
*/
@Entity()
export class Facet extends VendureEntity implements Translatable, HasCustomFields, ChannelAware {
constructor(input?: DeepPartial<Facet>) {
super(input);
}
name: LocaleString;
@Column({ default: false })
isPrivate: boolean;
@Column({ unique: true })
code: string;
@OneToMany(type => FacetTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<Facet>>;
@OneToMany(type => FacetValue, value => value.facet)
values: FacetValue[];
@Column(type => CustomFacetFields)
customFields: CustomFacetFields;
@ManyToMany(type => Channel, channel => channel.facets)
@JoinTable()
channels: Channel[];
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, ManyToMany, OneToMany } from 'typeorm';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { FulfillmentState } from '../../service/helpers/fulfillment-state-machine/fulfillment-state';
import { VendureEntity } from '../base/base.entity';
import { CustomFulfillmentFields } from '../custom-entity-fields';
import { Order } from '../order/order.entity';
import { FulfillmentLine } from '../order-line-reference/fulfillment-line.entity';
/**
* @description
* This entity represents a fulfillment of an Order or part of it, i.e. which {@link OrderLine}s have been
* delivered to the Customer after successful payment.
*
* @docsCategory entities
*/
@Entity()
export class Fulfillment extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<Fulfillment>) {
super(input);
}
@Column('varchar') state: FulfillmentState;
@Column({ default: '' })
trackingCode: string;
@Column()
method: string;
@Column()
handlerCode: string;
@OneToMany(type => FulfillmentLine, fulfillmentLine => fulfillmentLine.fulfillment)
lines: FulfillmentLine[];
@ManyToMany(type => Order, order => order.fulfillments)
orders: Order[];
@Column(type => CustomFulfillmentFields)
customFields: CustomFulfillmentFields;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity } from 'typeorm';
import { VendureEntity } from '..';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { CustomGlobalSettingsFields } from '../custom-entity-fields';
@Entity()
export class GlobalSettings extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<GlobalSettings>) {
super(input);
}
/**
* @deprecated use `Channel.availableLanguageCodes`
*/
@Column('simple-array')
availableLanguages: LanguageCode[];
/**
* @description
* Specifies the default value for inventory tracking for ProductVariants.
* Can be overridden per ProductVariant, but this value determines the default
* if not otherwise specified.
*
* @deprecated use `Channel.trackInventory`
*/
@Column({ default: true })
trackInventory: boolean;
/**
* @description
* Specifies the value of stockOnHand at which a given ProductVariant is considered
* out of stock.
*
* @deprecated use `Channel.outOfStockThreshold`
*/
@Column({ default: 0 })
outOfStockThreshold: number;
@Column(type => CustomGlobalSettingsFields)
customFields: CustomGlobalSettingsFields;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { Customer } from '../customer/customer.entity';
import { HistoryEntry } from './history-entry.entity';
/**
* @description
* Represents an event in the history of a particular {@link Customer}.
*
* @docsCategory entities
*/
@ChildEntity()
export class CustomerHistoryEntry extends HistoryEntry {
constructor(input: DeepPartial<CustomerHistoryEntry>) {
super(input);
}
@Index()
@ManyToOne(type => Customer, { onDelete: 'CASCADE' })
customer: Customer;
}
|
import { HistoryEntryType } from '@vendure/common/lib/generated-types';
import { Column, Entity, Index, ManyToOne, TableInheritance } from 'typeorm';
import { Administrator } from '../administrator/administrator.entity';
import { VendureEntity } from '../base/base.entity';
/**
* @description
* An abstract entity representing an entry in the history of an Order ({@link OrderHistoryEntry})
* or a Customer ({@link CustomerHistoryEntry}).
*
* @docsCategory entities
*/
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'discriminator' } })
export abstract class HistoryEntry extends VendureEntity {
@Index()
@ManyToOne(type => Administrator)
administrator?: Administrator;
@Column({ nullable: false, type: 'varchar' })
readonly type: HistoryEntryType;
@Column()
isPublic: boolean;
@Column('simple-json')
data: any;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { Order } from '../order/order.entity';
import { HistoryEntry } from './history-entry.entity';
/**
* @description
* Represents an event in the history of a particular {@link Order}.
*
* @docsCategory entities
*/
@ChildEntity()
export class OrderHistoryEntry extends HistoryEntry {
constructor(input: DeepPartial<OrderHistoryEntry>) {
super(input);
}
@Index()
@ManyToOne(type => Order, { onDelete: 'CASCADE' })
order: Order;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { EntityId } from '../entity-id.decorator';
import { Fulfillment } from '../fulfillment/fulfillment.entity';
import { OrderLineReference } from './order-line-reference.entity';
/**
* @description
* This entity represents a line from an {@link Order} which has been fulfilled by a {@link Fulfillment}.
*
* @docsCategory entities
* @docsPage OrderLineReference
*/
@ChildEntity()
export class FulfillmentLine extends OrderLineReference {
constructor(input?: DeepPartial<FulfillmentLine>) {
super(input);
}
@Index()
@ManyToOne(type => Fulfillment, fulfillment => fulfillment.lines)
fulfillment: Fulfillment;
@EntityId()
fulfillmentId: ID;
}
|
import { ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne, TableInheritance } from 'typeorm';
import { VendureEntity } from '../base/base.entity';
import { EntityId } from '../entity-id.decorator';
import { OrderLine } from '../order-line/order-line.entity';
/**
* @description
* This is an abstract base class for entities which reference an {@link OrderLine}.
*
* @docsCategory entities
* @docsPage OrderLineReference
*/
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'discriminator' } })
export abstract class OrderLineReference extends VendureEntity {
@Column()
quantity: number;
@Index()
@ManyToOne(type => OrderLine, line => line.linesReferences, { onDelete: 'CASCADE' })
orderLine: OrderLine;
@EntityId()
orderLineId: ID;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { EntityId } from '../entity-id.decorator';
import { OrderModification } from '../order-modification/order-modification.entity';
import { OrderLineReference } from './order-line-reference.entity';
/**
* @description
* This entity represents a line from an {@link Order} which has been modified by an {@link OrderModification}.
*
* @docsCategory entities
* @docsPage OrderLineReference
*/
@ChildEntity()
export class OrderModificationLine extends OrderLineReference {
constructor(input?: DeepPartial<OrderModificationLine>) {
super(input);
}
@Index()
@ManyToOne(type => OrderModification, modification => modification.lines)
modification: OrderModification;
@EntityId()
modificationId: ID;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { EntityId } from '../entity-id.decorator';
import { Refund } from '../refund/refund.entity';
import { OrderLineReference } from './order-line-reference.entity';
/**
* @description
* This entity represents a line from an {@link Order} which has been refunded by a {@link Refund}.
*
* @docsCategory entities
* @docsPage OrderLineReference
*/
@ChildEntity()
export class RefundLine extends OrderLineReference {
constructor(input?: DeepPartial<RefundLine>) {
super(input);
}
@Index()
@ManyToOne(type => Refund, refund => refund.lines)
refund: Refund;
@EntityId()
refundId: ID;
}
|
import { Adjustment, AdjustmentType, Discount, TaxLine } from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { summate } from '@vendure/common/lib/shared-utils';
import { Column, Entity, Index, ManyToOne, OneToMany, OneToOne } from 'typeorm';
import { Calculated } from '../../common/calculated-decorator';
import { roundMoney } from '../../common/round-money';
import { grossPriceOf, netPriceOf } from '../../common/tax-utils';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { Asset } from '../asset/asset.entity';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomOrderLineFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { Money } from '../money.decorator';
import { Order } from '../order/order.entity';
import { OrderLineReference } from '../order-line-reference/order-line-reference.entity';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { ShippingLine } from '../shipping-line/shipping-line.entity';
import { Allocation } from '../stock-movement/allocation.entity';
import { Cancellation } from '../stock-movement/cancellation.entity';
import { Sale } from '../stock-movement/sale.entity';
import { TaxCategory } from '../tax-category/tax-category.entity';
/**
* @description
* A single line on an {@link Order} which contains information about the {@link ProductVariant} and
* quantity ordered, as well as the price and tax information.
*
* @docsCategory entities
*/
@Entity()
export class OrderLine extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<OrderLine>) {
super(input);
}
/**
* @description
* The {@link Channel} of the {@link Seller} for a multivendor setup.
*/
@Index()
@ManyToOne(type => Channel, { nullable: true, onDelete: 'SET NULL' })
sellerChannel?: Channel;
@EntityId({ nullable: true })
sellerChannelId?: ID;
/**
* @description
* The {@link ShippingLine} to which this line has been assigned.
* This is determined by the configured {@link ShippingLineAssignmentStrategy}.
*/
@Index()
@ManyToOne(type => ShippingLine, shippingLine => shippingLine.orderLines, {
nullable: true,
onDelete: 'SET NULL',
})
shippingLine?: ShippingLine;
@EntityId({ nullable: true })
shippingLineId?: ID;
/**
* @description
* The {@link ProductVariant} which is being ordered.
*/
@Index()
@ManyToOne(type => ProductVariant, productVariant => productVariant.lines, { onDelete: 'CASCADE' })
productVariant: ProductVariant;
@EntityId()
productVariantId: ID;
@Index()
@ManyToOne(type => TaxCategory)
taxCategory: TaxCategory;
@Index()
@ManyToOne(type => Asset, asset => asset.featuredInVariants, { onDelete: 'SET NULL' })
featuredAsset: Asset;
@Index()
@ManyToOne(type => Order, order => order.lines, { onDelete: 'CASCADE' })
order: Order;
@OneToMany(type => OrderLineReference, lineRef => lineRef.orderLine)
linesReferences: OrderLineReference[];
@OneToMany(type => Sale, sale => sale.orderLine)
sales: Sale[];
@Column()
quantity: number;
/**
* @description
* The quantity of this OrderLine at the time the order was placed (as per the {@link OrderPlacedStrategy}).
*/
@Column({ default: 0 })
orderPlacedQuantity: number;
/**
* @description
* The price as calculated when the OrderLine was first added to the Order. Usually will be identical to the
* `listPrice`, except when the ProductVariant price has changed in the meantime and a re-calculation of
* the Order has been performed.
*/
@Money({ nullable: true })
initialListPrice: number;
/**
* @description
* This is the price as listed by the ProductVariant (and possibly modified by the {@link OrderItemPriceCalculationStrategy}),
* which, depending on the current Channel, may or may not include tax.
*/
@Money()
listPrice: number;
/**
* @description
* Whether the listPrice includes tax, which depends on the settings of the current Channel.
*/
@Column()
listPriceIncludesTax: boolean;
@Column('simple-json')
adjustments: Adjustment[];
@Column('simple-json')
taxLines: TaxLine[];
@OneToMany(type => Cancellation, cancellation => cancellation.orderLine)
cancellations: Cancellation[];
@OneToMany(type => Allocation, allocation => allocation.orderLine)
allocations: Allocation[];
@Column(type => CustomOrderLineFields)
customFields: CustomOrderLineFields;
/**
* @description
* The price of a single unit, excluding tax and discounts.
*/
@Calculated()
get unitPrice(): number {
return roundMoney(this._unitPrice());
}
/**
* @description
* The price of a single unit, including tax but excluding discounts.
*/
@Calculated()
get unitPriceWithTax(): number {
return roundMoney(this._unitPriceWithTax());
}
/**
* @description
* Non-zero if the `unitPrice` has changed since it was initially added to Order.
*/
@Calculated()
get unitPriceChangeSinceAdded(): number {
const { initialListPrice, listPriceIncludesTax } = this;
const initialPrice = listPriceIncludesTax
? netPriceOf(initialListPrice, this.taxRate)
: initialListPrice;
return roundMoney(this._unitPrice() - initialPrice);
}
/**
* @description
* Non-zero if the `unitPriceWithTax` has changed since it was initially added to Order.
*/
@Calculated()
get unitPriceWithTaxChangeSinceAdded(): number {
const { initialListPrice, listPriceIncludesTax } = this;
const initialPriceWithTax = listPriceIncludesTax
? initialListPrice
: grossPriceOf(initialListPrice, this.taxRate);
return roundMoney(this._unitPriceWithTax() - initialPriceWithTax);
}
/**
* @description
* The price of a single unit including discounts, excluding tax.
*
* If Order-level discounts have been applied, this will not be the
* actual taxable unit price (see `proratedUnitPrice`), but is generally the
* correct price to display to customers to avoid confusion
* about the internal handling of distributed Order-level discounts.
*/
@Calculated()
get discountedUnitPrice(): number {
return roundMoney(this._discountedUnitPrice());
}
/**
* @description
* The price of a single unit including discounts and tax
*/
@Calculated()
get discountedUnitPriceWithTax(): number {
return roundMoney(this._discountedUnitPriceWithTax());
}
/**
* @description
* The actual unit price, taking into account both item discounts _and_ prorated (proportionally-distributed)
* Order-level discounts. This value is the true economic value of a single unit in this OrderLine, and is used in tax
* and refund calculations.
*/
@Calculated()
get proratedUnitPrice(): number {
return roundMoney(this._proratedUnitPrice());
}
/**
* @description
* The `proratedUnitPrice` including tax.
*/
@Calculated()
get proratedUnitPriceWithTax(): number {
return roundMoney(this._proratedUnitPriceWithTax());
}
@Calculated()
get unitTax(): number {
return this.unitPriceWithTax - this.unitPrice;
}
@Calculated()
get proratedUnitTax(): number {
return this.proratedUnitPriceWithTax - this.proratedUnitPrice;
}
@Calculated()
get taxRate(): number {
return summate(this.taxLines, 'taxRate');
}
/**
* @description
* The total price of the line excluding tax and discounts.
*/
@Calculated()
get linePrice(): number {
return roundMoney(this._unitPrice(), this.quantity);
}
/**
* @description
* The total price of the line including tax but excluding discounts.
*/
@Calculated()
get linePriceWithTax(): number {
return roundMoney(this._unitPriceWithTax(), this.quantity);
}
/**
* @description
* The price of the line including discounts, excluding tax.
*/
@Calculated()
get discountedLinePrice(): number {
// return roundMoney(this.linePrice + this.getLineAdjustmentsTotal(false, AdjustmentType.PROMOTION));
return roundMoney(this._discountedUnitPrice(), this.quantity);
}
/**
* @description
* The price of the line including discounts and tax.
*/
@Calculated()
get discountedLinePriceWithTax(): number {
return roundMoney(this._discountedUnitPriceWithTax(), this.quantity);
}
@Calculated()
get discounts(): Discount[] {
const priceIncludesTax = this.listPriceIncludesTax;
// Group discounts together, so that it does not list a new
// discount row for each item in the line
const groupedDiscounts = new Map<string, Discount>();
for (const adjustment of this.adjustments) {
const discountGroup = groupedDiscounts.get(adjustment.adjustmentSource);
const unitAdjustmentAmount =
(adjustment.amount / Math.max(this.orderPlacedQuantity, this.quantity)) * this.quantity;
const amount = priceIncludesTax
? netPriceOf(unitAdjustmentAmount, this.taxRate)
: unitAdjustmentAmount;
const amountWithTax = priceIncludesTax
? unitAdjustmentAmount
: grossPriceOf(unitAdjustmentAmount, this.taxRate);
if (discountGroup) {
discountGroup.amount += amount;
discountGroup.amountWithTax += amountWithTax;
} else {
groupedDiscounts.set(adjustment.adjustmentSource, {
...(adjustment as Omit<Adjustment, '__typename'>),
amount: roundMoney(amount),
amountWithTax: roundMoney(amountWithTax),
});
}
}
return [...groupedDiscounts.values()];
}
/**
* @description
* The total tax on this line.
*/
@Calculated()
get lineTax(): number {
return this.linePriceWithTax - this.linePrice;
}
/**
* @description
* The actual line price, taking into account both item discounts _and_ prorated (proportionally-distributed)
* Order-level discounts. This value is the true economic value of the OrderLine, and is used in tax
* and refund calculations.
*/
@Calculated()
get proratedLinePrice(): number {
// return roundMoney(this.linePrice + this.getLineAdjustmentsTotal(false));
return roundMoney(this._proratedUnitPrice(), this.quantity);
}
/**
* @description
* The `proratedLinePrice` including tax.
*/
@Calculated()
get proratedLinePriceWithTax(): number {
// return roundMoney(this.linePriceWithTax + this.getLineAdjustmentsTotal(true));
return roundMoney(this._proratedUnitPriceWithTax(), this.quantity);
}
@Calculated()
get proratedLineTax(): number {
return this.proratedLinePriceWithTax - this.proratedLinePrice;
}
addAdjustment(adjustment: Adjustment) {
// We should not allow adding adjustments which would
// result in a negative unit price
const maxDiscount =
(this.listPriceIncludesTax ? this.proratedLinePriceWithTax : this.proratedLinePrice) * -1;
const limitedAdjustment: Adjustment = {
...adjustment,
amount: Math.max(maxDiscount, adjustment.amount),
};
if (limitedAdjustment.amount !== 0) {
this.adjustments = this.adjustments.concat(limitedAdjustment);
}
}
/**
* Clears Adjustments from all OrderItems of the given type. If no type
* is specified, then all adjustments are removed.
*/
clearAdjustments(type?: AdjustmentType) {
if (!type) {
this.adjustments = [];
} else {
this.adjustments = this.adjustments ? this.adjustments.filter(a => a.type !== type) : [];
}
}
private _unitPrice(): number {
return this.listPriceIncludesTax ? netPriceOf(this.listPrice, this.taxRate) : this.listPrice;
}
private _unitPriceWithTax(): number {
return this.listPriceIncludesTax ? this.listPrice : grossPriceOf(this.listPrice, this.taxRate);
}
private _discountedUnitPrice(): number {
const result = this.listPrice + this.getUnitAdjustmentsTotal(AdjustmentType.PROMOTION);
return this.listPriceIncludesTax ? netPriceOf(result, this.taxRate) : result;
}
private _discountedUnitPriceWithTax(): number {
const result = this.listPrice + this.getUnitAdjustmentsTotal(AdjustmentType.PROMOTION);
return this.listPriceIncludesTax ? result : grossPriceOf(result, this.taxRate);
}
/**
* @description
* Calculates the prorated unit price, excluding tax. This function performs no
* rounding, so before being exposed publicly via the GraphQL API, the returned value
* needs to be rounded to ensure it is an integer.
*/
private _proratedUnitPrice(): number {
const result = this.listPrice + this.getUnitAdjustmentsTotal();
return this.listPriceIncludesTax ? netPriceOf(result, this.taxRate) : result;
}
/**
* @description
* Calculates the prorated unit price, including tax. This function performs no
* rounding, so before being exposed publicly via the GraphQL API, the returned value
* needs to be rounded to ensure it is an integer.
*/
private _proratedUnitPriceWithTax(): number {
const result = this.listPrice + this.getUnitAdjustmentsTotal();
return this.listPriceIncludesTax ? result : grossPriceOf(result, this.taxRate);
}
/**
* @description
* The total of all price adjustments. Will typically be a negative number due to discounts.
*/
private getUnitAdjustmentsTotal(type?: AdjustmentType): number {
if (!this.adjustments || this.quantity === 0) {
return 0;
}
return this.adjustments
.filter(adjustment => (type ? adjustment.type === type : true))
.map(adjustment => adjustment.amount / Math.max(this.orderPlacedQuantity, this.quantity))
.reduce((total, a) => total + a, 0);
}
/**
* @description
* The total of all price adjustments. Will typically be a negative number due to discounts.
*/
private getLineAdjustmentsTotal(withTax: boolean, type?: AdjustmentType): number {
if (!this.adjustments || this.quantity === 0) {
return 0;
}
const sum = this.adjustments
.filter(adjustment => (type ? adjustment.type === type : true))
.map(adjustment => adjustment.amount)
.reduce((total, a) => total + a, 0);
const adjustedForQuantityChanges =
sum * (this.quantity / Math.max(this.orderPlacedQuantity, this.quantity));
if (withTax) {
return this.listPriceIncludesTax
? adjustedForQuantityChanges
: grossPriceOf(adjustedForQuantityChanges, this.taxRate);
} else {
return this.listPriceIncludesTax
? netPriceOf(adjustedForQuantityChanges, this.taxRate)
: adjustedForQuantityChanges;
}
}
}
|
import { OrderAddress } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, JoinColumn, ManyToOne, OneToMany, OneToOne } from 'typeorm';
import { Calculated } from '../../common/calculated-decorator';
import { VendureEntity } from '../base/base.entity';
import { Money } from '../money.decorator';
import { Order } from '../order/order.entity';
import { OrderModificationLine } from '../order-line-reference/order-modification-line.entity';
import { Payment } from '../payment/payment.entity';
import { Refund } from '../refund/refund.entity';
import { Surcharge } from '../surcharge/surcharge.entity';
/**
* @description
* An entity which represents a modification to an order which has been placed, and
* then modified afterwards by an administrator.
*
* @docsCategory entities
*/
@Entity()
export class OrderModification extends VendureEntity {
constructor(input?: DeepPartial<OrderModification>) {
super(input);
}
@Column()
note: string;
@Index()
@ManyToOne(type => Order, order => order.modifications, { onDelete: 'CASCADE' })
order: Order;
@OneToMany(type => OrderModificationLine, line => line.modification)
lines: OrderModificationLine[];
@OneToMany(type => Surcharge, surcharge => surcharge.orderModification)
surcharges: Surcharge[];
@Money()
priceChange: number;
@OneToOne(type => Payment)
@JoinColumn()
payment?: Payment;
@OneToOne(type => Refund)
@JoinColumn()
refund?: Refund;
@Column('simple-json', { nullable: true }) shippingAddressChange: OrderAddress;
@Column('simple-json', { nullable: true }) billingAddressChange: OrderAddress;
@Calculated()
get isSettled(): boolean {
if (this.priceChange === 0) {
return true;
}
return !!this.payment || !!this.refund;
}
}
|
import { AdjustmentType } from '@vendure/common/lib/generated-types';
import { summate } from '@vendure/common/lib/shared-utils';
import { beforeAll, describe, expect, it } from 'vitest';
import { ensureConfigLoaded } from '../../config/config-helpers';
import { createOrder, createRequestContext, taxCategoryStandard } from '../../testing/order-test-utils';
import { ShippingLine } from '../shipping-line/shipping-line.entity';
import { Surcharge } from '../surcharge/surcharge.entity';
import { Order } from './order.entity';
describe('Order entity methods', () => {
beforeAll(async () => {
await ensureConfigLoaded();
});
describe('taxSummary', () => {
it('single rate across items', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
});
order.lines.forEach(i => (i.taxLines = [{ taxRate: 5, description: 'tax a' }]));
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 1600,
taxTotal: 80,
},
]);
assertOrderTaxesAddsUp(order);
});
it('different rate on each item', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
});
order.lines[0].taxLines = [{ taxRate: 5, description: 'tax a' }];
order.lines[1].taxLines = [{ taxRate: 7.5, description: 'tax b' }];
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 600,
taxTotal: 30,
},
{
description: 'tax b',
taxRate: 7.5,
taxBase: 1000,
taxTotal: 75,
},
]);
assertOrderTaxesAddsUp(order);
});
it('multiple rates on each item', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
});
order.lines[0].taxLines = [
{ taxRate: 5, description: 'tax a' },
{ taxRate: 7.5, description: 'tax b' },
];
order.lines[1].taxLines = [
{ taxRate: 5, description: 'tax a' },
{ taxRate: 7.5, description: 'tax b' },
];
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 1600,
taxTotal: 80,
},
{
description: 'tax b',
taxRate: 7.5,
taxBase: 1600,
taxTotal: 121,
},
]);
assertOrderTaxesAddsUp(order);
});
it('multiple rates on each item, prorated order discount', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
});
order.lines[0].taxLines = [
{ taxRate: 5, description: 'tax a' },
{ taxRate: 7.5, description: 'tax b' },
];
order.lines[0].adjustments = [
{
amount: -60,
adjustmentSource: 'some order discount',
description: 'some order discount',
type: AdjustmentType.DISTRIBUTED_ORDER_PROMOTION,
},
];
order.lines[1].taxLines = [
{ taxRate: 5, description: 'tax a' },
{ taxRate: 7.5, description: 'tax b' },
];
order.lines[1].adjustments = [
{
amount: -100,
adjustmentSource: 'some order discount',
description: 'some order discount',
type: AdjustmentType.DISTRIBUTED_ORDER_PROMOTION,
},
];
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 1440,
taxTotal: 72,
},
{
description: 'tax b',
taxRate: 7.5,
taxBase: 1440,
taxTotal: 109,
},
]);
assertOrderTaxesAddsUp(order);
});
it('multiple rates on each item, item discount, prorated order discount', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
});
order.lines[0].taxLines = [
{ taxRate: 5, description: 'tax a' },
{ taxRate: 7.5, description: 'tax b' },
];
order.lines[0].adjustments = [
{
amount: -60,
adjustmentSource: 'some order discount',
description: 'some order discount',
type: AdjustmentType.DISTRIBUTED_ORDER_PROMOTION,
},
{
amount: -250,
adjustmentSource: 'some item discount',
description: 'some item discount',
type: AdjustmentType.PROMOTION,
},
];
order.lines[1].taxLines = [
{ taxRate: 5, description: 'tax a' },
{ taxRate: 7.5, description: 'tax b' },
];
order.lines[1].adjustments = [
{
amount: -100,
adjustmentSource: 'some order discount',
description: 'some order discount',
type: AdjustmentType.DISTRIBUTED_ORDER_PROMOTION,
},
];
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 1190,
taxTotal: 59,
},
{
description: 'tax b',
taxRate: 7.5,
taxBase: 1190,
taxTotal: 90,
},
]);
assertOrderTaxesAddsUp(order);
});
it('zero rate', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
],
});
order.lines[0].taxLines = [{ taxRate: 0, description: 'zero-rate' }];
expect(order.taxSummary).toEqual([
{
description: 'zero-rate',
taxRate: 0,
taxBase: 600,
taxTotal: 0,
},
]);
assertOrderTaxesAddsUp(order);
});
it('with shipping', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
});
order.lines[0].taxLines = [{ taxRate: 5, description: 'tax a' }];
order.lines[1].taxLines = [{ taxRate: 5, description: 'tax a' }];
order.shippingLines = [
new ShippingLine({
listPrice: 500,
listPriceIncludesTax: false,
taxLines: [
{
taxRate: 20,
description: 'shipping tax',
},
],
}),
];
order.shipping = 500;
order.shippingWithTax = 600;
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 1600,
taxTotal: 80,
},
{
description: 'shipping tax',
taxRate: 20,
taxBase: 500,
taxTotal: 100,
},
]);
assertOrderTaxesAddsUp(order);
});
it('with surcharge', () => {
const ctx = createRequestContext({ pricesIncludeTax: false });
const order = createOrder({
ctx,
lines: [
{
listPrice: 300,
taxCategory: taxCategoryStandard,
quantity: 2,
},
{
listPrice: 1000,
taxCategory: taxCategoryStandard,
quantity: 1,
},
],
surcharges: [
new Surcharge({
description: 'Special surcharge',
listPrice: 400,
listPriceIncludesTax: ctx.channel.pricesIncludeTax,
taxLines: [
{ description: 'Special surcharge tax', taxRate: 50 },
{ description: 'Special surcharge second tax', taxRate: 20 },
],
sku: 'special-surcharge',
}),
new Surcharge({
description: 'Other surcharge',
listPrice: 500,
listPriceIncludesTax: ctx.channel.pricesIncludeTax,
taxLines: [{ description: 'Other surcharge tax', taxRate: 0 }],
sku: 'other-surcharge',
}),
],
});
order.lines.forEach(i => (i.taxLines = [{ taxRate: 5, description: 'tax a' }]));
expect(order.taxSummary).toEqual([
{
description: 'tax a',
taxRate: 5,
taxBase: 1600,
taxTotal: 80,
},
{
description: 'Special surcharge tax',
taxRate: 50,
taxBase: 400,
taxTotal: 200,
},
{
description: 'Special surcharge second tax',
taxRate: 20,
taxBase: 400,
taxTotal: 80,
},
{
description: 'Other surcharge tax',
taxRate: 0,
taxBase: 500,
taxTotal: 0,
},
]);
assertOrderTaxesAddsUp(order);
});
});
});
function assertOrderTaxesAddsUp(order: Order) {
const summaryTaxTotal = summate(order.taxSummary, 'taxTotal');
const lineTotal = summate(order.lines, 'proratedLinePrice');
const lineTotalWithTax = summate(order.lines, 'proratedLinePriceWithTax');
const shippingTax = (order.shippingWithTax ?? 0) - (order.shipping ?? 0);
const surchargesTotal = summate(order.surcharges, 'price');
const surchargesTotalWithTax = summate(order.surcharges, 'priceWithTax');
expect(lineTotalWithTax - lineTotal + shippingTax + (surchargesTotalWithTax - surchargesTotal)).toBe(
summaryTaxTotal,
);
}
|
import {
CurrencyCode,
Discount,
OrderAddress,
OrderTaxSummary,
OrderType,
TaxLine,
} from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { summate } from '@vendure/common/lib/shared-utils';
import { Column, Entity, Index, JoinTable, ManyToMany, ManyToOne, OneToMany } from 'typeorm';
import { Calculated } from '../../common/calculated-decorator';
import { InternalServerError } from '../../common/error/errors';
import { ChannelAware } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { OrderState } from '../../service/helpers/order-state-machine/order-state';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomOrderFields } from '../custom-entity-fields';
import { Customer } from '../customer/customer.entity';
import { EntityId } from '../entity-id.decorator';
import { Fulfillment } from '../fulfillment/fulfillment.entity';
import { Money } from '../money.decorator';
import { OrderLine } from '../order-line/order-line.entity';
import { OrderModification } from '../order-modification/order-modification.entity';
import { Payment } from '../payment/payment.entity';
import { Promotion } from '../promotion/promotion.entity';
import { ShippingLine } from '../shipping-line/shipping-line.entity';
import { Surcharge } from '../surcharge/surcharge.entity';
/**
* @description
* An Order is created whenever a {@link Customer} adds an item to the cart. It contains all the
* information required to fulfill an order: which {@link ProductVariant}s in what quantities;
* the shipping address and price; any applicable promotions; payments etc.
*
* An Order exists in a well-defined state according to the {@link OrderState} type. A state machine
* is used to govern the transition from one state to another.
*
* @docsCategory entities
*/
@Entity()
export class Order extends VendureEntity implements ChannelAware, HasCustomFields {
constructor(input?: DeepPartial<Order>) {
super(input);
}
@Column('varchar', { default: OrderType.Regular })
type: OrderType;
@OneToMany(type => Order, sellerOrder => sellerOrder.aggregateOrder)
sellerOrders: Order[];
@Index()
@ManyToOne(type => Order, aggregateOrder => aggregateOrder.sellerOrders)
aggregateOrder?: Order;
@EntityId({ nullable: true })
aggregateOrderId?: ID;
/**
* @description
* A unique code for the Order, generated according to the
* {@link OrderCodeStrategy}. This should be used as an order reference
* for Customers, rather than the Order's id.
*/
@Column()
@Index({ unique: true })
code: string;
@Column('varchar') state: OrderState;
/**
* @description
* Whether the Order is considered "active", meaning that the
* Customer can still make changes to it and has not yet completed
* the checkout process.
* This is governed by the {@link OrderPlacedStrategy}.
*/
@Column({ default: true })
active: boolean;
/**
* @description
* The date & time that the Order was placed, i.e. the Customer
* completed the checkout and the Order is no longer "active".
* This is governed by the {@link OrderPlacedStrategy}.
*/
@Column({ nullable: true })
orderPlacedAt?: Date;
@Index()
@ManyToOne(type => Customer, customer => customer.orders)
customer?: Customer;
@EntityId({ nullable: true })
customerId?: ID;
@OneToMany(type => OrderLine, line => line.order)
lines: OrderLine[];
/**
* @description
* Surcharges are arbitrary modifications to the Order total which are neither
* ProductVariants nor discounts resulting from applied Promotions. For example,
* one-off discounts based on customer interaction, or surcharges based on payment
* methods.
*/
@OneToMany(type => Surcharge, surcharge => surcharge.order)
surcharges: Surcharge[];
/**
* @description
* An array of all coupon codes applied to the Order.
*/
@Column('simple-array')
couponCodes: string[];
/**
* @description
* Promotions applied to the order. Only gets populated after the payment process has completed,
* i.e. the Order is no longer active.
*/
@ManyToMany(type => Promotion, promotion => promotion.orders)
@JoinTable()
promotions: Promotion[];
@Column('simple-json') shippingAddress: OrderAddress;
@Column('simple-json') billingAddress: OrderAddress;
@OneToMany(type => Payment, payment => payment.order)
payments: Payment[];
@ManyToMany(type => Fulfillment, fulfillment => fulfillment.orders)
@JoinTable()
fulfillments: Fulfillment[];
@Column('varchar')
currencyCode: CurrencyCode;
@Column(type => CustomOrderFields)
customFields: CustomOrderFields;
@EntityId({ nullable: true })
taxZoneId?: ID;
@ManyToMany(type => Channel)
@JoinTable()
channels: Channel[];
@OneToMany(type => OrderModification, modification => modification.order)
modifications: OrderModification[];
/**
* @description
* The subTotal is the total of all OrderLines in the Order. This figure also includes any Order-level
* discounts which have been prorated (proportionally distributed) amongst the OrderItems.
* To get a total of all OrderLines which does not account for prorated discounts, use the
* sum of {@link OrderLine}'s `discountedLinePrice` values.
*/
@Money()
subTotal: number;
/**
* @description
* Same as subTotal, but inclusive of tax.
*/
@Money()
subTotalWithTax: number;
/**
* @description
* The shipping charges applied to this order.
*/
@OneToMany(type => ShippingLine, shippingLine => shippingLine.order)
shippingLines: ShippingLine[];
/**
* @description
* The total of all the `shippingLines`.
*/
@Money({ default: 0 })
shipping: number;
@Money({ default: 0 })
shippingWithTax: number;
@Calculated({ relations: ['lines', 'shippingLines'] })
get discounts(): Discount[] {
this.throwIfLinesNotJoined('discounts');
const groupedAdjustments = new Map<string, Discount>();
for (const line of this.lines ?? []) {
for (const discount of line.discounts) {
const adjustment = groupedAdjustments.get(discount.adjustmentSource);
if (adjustment) {
adjustment.amount += discount.amount;
adjustment.amountWithTax += discount.amountWithTax;
} else {
groupedAdjustments.set(discount.adjustmentSource, { ...discount });
}
}
}
for (const shippingLine of this.shippingLines ?? []) {
for (const discount of shippingLine.discounts) {
const adjustment = groupedAdjustments.get(discount.adjustmentSource);
if (adjustment) {
adjustment.amount += discount.amount;
adjustment.amountWithTax += discount.amountWithTax;
} else {
groupedAdjustments.set(discount.adjustmentSource, { ...discount });
}
}
}
return [...groupedAdjustments.values()];
}
/**
* @description
* Equal to `subTotal` plus `shipping`
*/
@Calculated({
query: qb =>
qb
.leftJoin(
qb1 => {
return qb1
.from(Order, 'order')
.select('order.shipping + order.subTotal', 'total')
.addSelect('order.id', 'oid');
},
't1',
't1.oid = order.id',
)
.addSelect('t1.total', 'total'),
expression: 'total',
})
get total(): number {
return this.subTotal + (this.shipping || 0);
}
/**
* @description
* The final payable amount. Equal to `subTotalWithTax` plus `shippingWithTax`.
*/
@Calculated({
query: qb =>
qb
.leftJoin(
qb1 => {
return qb1
.from(Order, 'order')
.select('order.shippingWithTax + order.subTotalWithTax', 'twt')
.addSelect('order.id', 'oid');
},
't1',
't1.oid = order.id',
)
.addSelect('t1.twt', 'twt'),
expression: 'twt',
})
get totalWithTax(): number {
return this.subTotalWithTax + (this.shippingWithTax || 0);
}
@Calculated({
relations: ['lines'],
query: qb => {
qb.leftJoin(
qb1 => {
return qb1
.from(Order, 'order')
.select('SUM(lines.quantity)', 'qty')
.addSelect('order.id', 'oid')
.leftJoin('order.lines', 'lines')
.groupBy('order.id');
},
't1',
't1.oid = order.id',
).addSelect('t1.qty', 'qty');
},
expression: 'qty',
})
get totalQuantity(): number {
this.throwIfLinesNotJoined('totalQuantity');
return summate(this.lines, 'quantity');
}
/**
* @description
* A summary of the taxes being applied to this Order.
*/
@Calculated({ relations: ['lines'] })
get taxSummary(): OrderTaxSummary[] {
this.throwIfLinesNotJoined('taxSummary');
const taxRateMap = new Map<
string,
{ rate: number; base: number; tax: number; description: string }
>();
const taxId = (taxLine: TaxLine): string => `${taxLine.description}:${taxLine.taxRate}`;
const taxableLines = [
...(this.lines ?? []),
...(this.shippingLines ?? []),
...(this.surcharges ?? []),
];
for (const line of taxableLines) {
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(([taxRate, row]) => ({
taxRate: row.rate,
description: row.description,
taxBase: row.base,
taxTotal: row.tax,
}));
}
private throwIfLinesNotJoined(propertyName: keyof Order) {
if (this.lines == null) {
const errorMessage = [
`The property "${propertyName}" on the Order entity requires the Order.lines relation to be joined.`,
"This can be done with the EntityHydratorService: `await entityHydratorService.hydrate(ctx, order, { relations: ['lines'] })`",
];
throw new InternalServerError(errorMessage.join('\n'));
}
}
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomPaymentMethodFieldsTranslation } from '../custom-entity-fields';
import { PaymentMethod } from './payment-method.entity';
@Entity()
export class PaymentMethodTranslation
extends VendureEntity
implements Translation<PaymentMethod>, HasCustomFields
{
constructor(input?: DeepPartial<Translation<PaymentMethod>>) {
super(input);
// This is a workaround for the fact that
// MySQL does not support default values on TEXT columns
if (this.description === undefined) {
this.description = '';
}
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Column('text') description: string;
@Index()
@ManyToOne(type => PaymentMethod, base => base.translations, { onDelete: 'CASCADE' })
base: PaymentMethod;
@Column(type => CustomPaymentMethodFieldsTranslation)
customFields: CustomPaymentMethodFieldsTranslation;
}
|
import { ConfigurableOperation } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { ChannelAware } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomPaymentMethodFields } from '../custom-entity-fields';
import { PaymentMethodTranslation } from './payment-method-translation.entity';
/**
* @description
* A PaymentMethod is created automatically according to the configured {@link PaymentMethodHandler}s defined
* in the {@link PaymentOptions} config.
*
* @docsCategory entities
*/
@Entity()
export class PaymentMethod extends VendureEntity implements Translatable, ChannelAware, HasCustomFields {
constructor(input?: DeepPartial<PaymentMethod>) {
super(input);
}
name: LocaleString;
@Column({ default: '' }) code: string;
description: LocaleString;
@OneToMany(type => PaymentMethodTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<PaymentMethod>>;
@Column() enabled: boolean;
@Column('simple-json', { nullable: true }) checker: ConfigurableOperation | null;
@Column('simple-json') handler: ConfigurableOperation;
@ManyToMany(type => Channel, channel => channel.paymentMethods)
@JoinTable()
channels: Channel[];
@Column(type => CustomPaymentMethodFields)
customFields: CustomPaymentMethodFields;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne, OneToMany } from 'typeorm';
import { PaymentMetadata } from '../../common/types/common-types';
import { PaymentState } from '../../service/helpers/payment-state-machine/payment-state';
import { VendureEntity } from '../base/base.entity';
import { Money } from '../money.decorator';
import { Order } from '../order/order.entity';
import { Refund } from '../refund/refund.entity';
/**
* @description
* A Payment represents a single payment transaction and exists in a well-defined state
* defined by the {@link PaymentState} type.
*
* @docsCategory entities
*/
@Entity()
export class Payment extends VendureEntity {
constructor(input?: DeepPartial<Payment>) {
super(input);
}
@Column() method: string;
@Money() amount: number;
@Column('varchar') state: PaymentState;
@Column({ type: 'varchar', nullable: true })
errorMessage: string | undefined;
@Column({ nullable: true })
transactionId: string;
@Column('simple-json') metadata: PaymentMetadata;
@Index()
@ManyToOne(type => Order, order => order.payments)
order: Order;
@OneToMany(type => Refund, refund => refund.payment)
refunds: Refund[];
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductOptionGroupFieldsTranslation } from '../custom-entity-fields';
import { ProductOptionGroup } from './product-option-group.entity';
@Entity()
export class ProductOptionGroupTranslation
extends VendureEntity
implements Translation<ProductOptionGroup>, HasCustomFields
{
constructor(input?: DeepPartial<Translation<ProductOptionGroup>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index()
@ManyToOne(type => ProductOptionGroup, base => base.translations, { onDelete: 'CASCADE' })
base: ProductOptionGroup;
@Column(type => CustomProductOptionGroupFieldsTranslation)
customFields: CustomProductOptionGroupFieldsTranslation;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne, OneToMany } from 'typeorm';
import { SoftDeletable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductOptionGroupFields } from '../custom-entity-fields';
import { Product } from '../product/product.entity';
import { ProductOption } from '../product-option/product-option.entity';
import { ProductOptionGroupTranslation } from './product-option-group-translation.entity';
/**
* @description
* A grouping of one or more {@link ProductOption}s.
*
* @docsCategory entities
*/
@Entity()
export class ProductOptionGroup
extends VendureEntity
implements Translatable, HasCustomFields, SoftDeletable
{
constructor(input?: DeepPartial<ProductOptionGroup>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
name: LocaleString;
@Column()
code: string;
@OneToMany(type => ProductOptionGroupTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<ProductOptionGroup>>;
@OneToMany(type => ProductOption, option => option.group)
options: ProductOption[];
@Index()
@ManyToOne(type => Product, product => product.optionGroups)
product: Product;
@Column(type => CustomProductOptionGroupFields)
customFields: CustomProductOptionGroupFields;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductOptionFieldsTranslation } from '../custom-entity-fields';
import { ProductOption } from './product-option.entity';
@Entity()
export class ProductOptionTranslation
extends VendureEntity
implements Translation<ProductOption>, HasCustomFields
{
constructor(input?: DeepPartial<Translation<ProductOption>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index()
@ManyToOne(type => ProductOption, base => base.translations, { onDelete: 'CASCADE' })
base: ProductOption;
@Column(type => CustomProductOptionFieldsTranslation)
customFields: CustomProductOptionFieldsTranslation;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToMany, ManyToOne, OneToMany } from 'typeorm';
import { SoftDeletable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductOptionFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { ProductOptionGroup } from '../product-option-group/product-option-group.entity';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { ProductOptionTranslation } from './product-option-translation.entity';
/**
* @description
* A ProductOption is used to differentiate {@link ProductVariant}s from one another.
*
* @docsCategory entities
*/
@Entity()
export class ProductOption extends VendureEntity implements Translatable, HasCustomFields, SoftDeletable {
constructor(input?: DeepPartial<ProductOption>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
name: LocaleString;
@Column() code: string;
@OneToMany(type => ProductOptionTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<ProductOption>>;
@Index()
@ManyToOne(type => ProductOptionGroup, group => group.options)
group: ProductOptionGroup;
@EntityId()
groupId: ID;
@ManyToMany(type => ProductVariant, variant => variant.options)
productVariants: ProductVariant[];
@Column(type => CustomProductOptionFields)
customFields: CustomProductOptionFields;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { OrderableAsset } from '../asset/orderable-asset.entity';
import { ProductVariant } from './product-variant.entity';
@Entity()
export class ProductVariantAsset extends OrderableAsset {
constructor(input?: DeepPartial<ProductVariantAsset>) {
super(input);
}
@Column()
productVariantId: ID;
@Index()
@ManyToOne(type => ProductVariant, variant => variant.assets, { onDelete: 'CASCADE' })
productVariant: ProductVariant;
}
|
import { CurrencyCode } from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductVariantPriceFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { Money } from '../money.decorator';
import { ProductVariant } from './product-variant.entity';
/**
* @description
* A ProductVariantPrice is a Channel-specific price for a ProductVariant. For every Channel to
* which a ProductVariant is assigned, there will be a corresponding ProductVariantPrice entity.
*
* @docsCategory entities
*/
@Entity()
export class ProductVariantPrice extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<ProductVariantPrice>) {
super(input);
}
@Money() price: number;
@EntityId({ nullable: true }) channelId: ID;
@Column('varchar')
currencyCode: CurrencyCode;
@Index()
@ManyToOne(type => ProductVariant, variant => variant.productVariantPrices, { onDelete: 'CASCADE' })
variant: ProductVariant;
@Column(type => CustomProductVariantPriceFields)
customFields: CustomProductVariantPriceFields;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductVariantFieldsTranslation } from '../custom-entity-fields';
import { ProductVariant } from './product-variant.entity';
@Entity()
export class ProductVariantTranslation
extends VendureEntity
implements Translation<ProductVariant>, HasCustomFields
{
constructor(input?: DeepPartial<Translation<ProductVariant>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index()
@ManyToOne(type => ProductVariant, base => base.translations, { onDelete: 'CASCADE' })
base: ProductVariant;
@Column(type => CustomProductVariantFieldsTranslation)
customFields: CustomProductVariantFieldsTranslation;
}
|
import { CurrencyCode, GlobalFlag } from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, JoinTable, ManyToMany, ManyToOne, OneToMany } from 'typeorm';
import { Calculated } from '../../common/calculated-decorator';
import { roundMoney } from '../../common/round-money';
import { ChannelAware, SoftDeletable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { Asset } from '../asset/asset.entity';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { Collection } from '../collection/collection.entity';
import { CustomProductVariantFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { FacetValue } from '../facet-value/facet-value.entity';
import { OrderLine } from '../order-line/order-line.entity';
import { Product } from '../product/product.entity';
import { ProductOption } from '../product-option/product-option.entity';
import { StockLevel } from '../stock-level/stock-level.entity';
import { StockMovement } from '../stock-movement/stock-movement.entity';
import { TaxCategory } from '../tax-category/tax-category.entity';
import { TaxRate } from '../tax-rate/tax-rate.entity';
import { ProductVariantAsset } from './product-variant-asset.entity';
import { ProductVariantPrice } from './product-variant-price.entity';
import { ProductVariantTranslation } from './product-variant-translation.entity';
/**
* @description
* A ProductVariant represents a single stock keeping unit (SKU) in the store's inventory.
* Whereas a {@link Product} is a "container" of variants, the variant itself holds the
* data on price, tax category etc. When one adds items to their cart, they are adding
* ProductVariants, not Products.
*
* @docsCategory entities
*/
@Entity()
export class ProductVariant
extends VendureEntity
implements Translatable, HasCustomFields, SoftDeletable, ChannelAware
{
constructor(input?: DeepPartial<ProductVariant>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
name: LocaleString;
@Column({ default: true })
enabled: boolean;
@Column()
sku: string;
/**
* Calculated at run-time
*/
listPrice: number;
/**
* Calculated at run-time
*/
listPriceIncludesTax: boolean;
/**
* Calculated at run-time
*/
currencyCode: CurrencyCode;
@Calculated({
expression: 'productvariant__productVariantPrices.price',
})
get price(): number {
if (this.listPrice == null) {
return 0;
}
return roundMoney(
this.listPriceIncludesTax ? this.taxRateApplied.netPriceOf(this.listPrice) : this.listPrice,
);
}
@Calculated({
// Note: this works fine for sorting by priceWithTax, but filtering will return inaccurate
// results due to this expression not taking taxes into account. This is because the tax
// rate is calculated at run-time in the application layer based on the current context,
// and is unknown to the database.
expression: 'productvariant__productVariantPrices.price',
})
get priceWithTax(): number {
if (this.listPrice == null) {
return 0;
}
return roundMoney(
this.listPriceIncludesTax ? this.listPrice : this.taxRateApplied.grossPriceOf(this.listPrice),
);
}
/**
* Calculated at run-time
*/
taxRateApplied: TaxRate;
@Index()
@ManyToOne(type => Asset, asset => asset.featuredInVariants, { onDelete: 'SET NULL' })
featuredAsset: Asset;
@OneToMany(type => ProductVariantAsset, productVariantAsset => productVariantAsset.productVariant, {
onDelete: 'SET NULL',
})
assets: ProductVariantAsset[];
@Index()
@ManyToOne(type => TaxCategory, taxCategory => taxCategory.productVariants)
taxCategory: TaxCategory;
@OneToMany(type => ProductVariantPrice, price => price.variant, { eager: true })
productVariantPrices: ProductVariantPrice[];
@OneToMany(type => ProductVariantTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<ProductVariant>>;
@Index()
@ManyToOne(type => Product, product => product.variants)
product: Product;
@EntityId({ nullable: true })
productId: ID;
/**
* @description
* Specifies the value of stockOnHand at which the ProductVariant is considered
* out of stock.
*/
@Column({ default: 0 })
outOfStockThreshold: number;
/**
* @description
* When true, the `outOfStockThreshold` value will be taken from the GlobalSettings and the
* value set on this ProductVariant will be ignored.
*/
@Column({ default: true })
useGlobalOutOfStockThreshold: boolean;
@Column({ type: 'varchar', default: GlobalFlag.INHERIT })
trackInventory: GlobalFlag;
@OneToMany(type => StockLevel, stockLevel => stockLevel.productVariant)
stockLevels: StockLevel[];
@OneToMany(type => StockMovement, stockMovement => stockMovement.productVariant)
stockMovements: StockMovement[];
@ManyToMany(type => ProductOption, productOption => productOption.productVariants)
@JoinTable()
options: ProductOption[];
@ManyToMany(type => FacetValue, facetValue => facetValue.productVariants)
@JoinTable()
facetValues: FacetValue[];
@Column(type => CustomProductVariantFields)
customFields: CustomProductVariantFields;
@ManyToMany(type => Collection, collection => collection.productVariants)
collections: Collection[];
@ManyToMany(type => Channel, channel => channel.productVariants)
@JoinTable()
channels: Channel[];
@OneToMany(type => OrderLine, orderLine => orderLine.productVariant)
lines: OrderLine[];
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { OrderableAsset } from '../asset/orderable-asset.entity';
import { Product } from './product.entity';
@Entity()
export class ProductAsset extends OrderableAsset {
constructor(input?: DeepPartial<ProductAsset>) {
super(input);
}
@Column()
productId: ID;
@Index()
@ManyToOne(type => Product, product => product.assets, { onDelete: 'CASCADE' })
product: Product;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomProductFieldsTranslation } from '../custom-entity-fields';
import { Product } from './product.entity';
@Entity()
export class ProductTranslation extends VendureEntity implements Translation<Product>, HasCustomFields {
constructor(input?: DeepPartial<Translation<Product>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index({ unique: false })
@Column()
slug: string;
@Column('text') description: string;
@Index()
@ManyToOne(type => Product, base => base.translations)
base: Product;
@Column(type => CustomProductFieldsTranslation)
customFields: CustomProductFieldsTranslation;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, JoinTable, ManyToMany, ManyToOne, OneToMany } from 'typeorm';
import { ChannelAware, SoftDeletable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { Asset } from '../asset/asset.entity';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomProductFields } from '../custom-entity-fields';
import { FacetValue } from '../facet-value/facet-value.entity';
import { ProductOptionGroup } from '../product-option-group/product-option-group.entity';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { ProductAsset } from './product-asset.entity';
import { ProductTranslation } from './product-translation.entity';
/**
* @description
* A Product contains one or more {@link ProductVariant}s and serves as a container for those variants,
* providing an overall name, description etc.
*
* @docsCategory entities
*/
@Entity()
export class Product
extends VendureEntity
implements Translatable, HasCustomFields, ChannelAware, SoftDeletable
{
constructor(input?: DeepPartial<Product>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
name: LocaleString;
slug: LocaleString;
description: LocaleString;
@Column({ default: true })
enabled: boolean;
@Index()
@ManyToOne(type => Asset, asset => asset.featuredInProducts, { onDelete: 'SET NULL' })
featuredAsset: Asset;
@OneToMany(type => ProductAsset, productAsset => productAsset.product)
assets: ProductAsset[];
@OneToMany(type => ProductTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<Product>>;
@OneToMany(type => ProductVariant, variant => variant.product)
variants: ProductVariant[];
@OneToMany(type => ProductOptionGroup, optionGroup => optionGroup.product)
optionGroups: ProductOptionGroup[];
@ManyToMany(type => FacetValue, facetValue => facetValue.products)
@JoinTable()
facetValues: FacetValue[];
@ManyToMany(type => Channel, channel => channel.products)
@JoinTable()
channels: Channel[];
@Column(type => CustomProductFields)
customFields: CustomProductFields;
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomPromotionFieldsTranslation } from '../custom-entity-fields';
import { Promotion } from './promotion.entity';
@Entity()
export class PromotionTranslation extends VendureEntity implements Translation<Promotion>, HasCustomFields {
constructor(input?: DeepPartial<Translation<Promotion>>) {
super(input);
// This is a workaround for the fact that
// MySQL does not support default values on TEXT columns
if (this.description === undefined) {
this.description = '';
}
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Column('text') description: string;
@Index()
@ManyToOne(type => Promotion, base => base.translations, { onDelete: 'CASCADE' })
base: Promotion;
@Column(type => CustomPromotionFieldsTranslation)
customFields: CustomPromotionFieldsTranslation;
}
|
import { Adjustment, AdjustmentType, ConfigurableOperation } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { RequestContext } from '../../api/common/request-context';
import { roundMoney } from '../../common/round-money';
import { AdjustmentSource } from '../../common/types/adjustment-source';
import { ChannelAware, SoftDeletable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { getConfig } from '../../config/config-helpers';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import {
PromotionAction,
PromotionItemAction,
PromotionOrderAction,
PromotionShippingAction,
} from '../../config/promotion/promotion-action';
import { PromotionCondition, PromotionConditionState } from '../../config/promotion/promotion-condition';
import { Channel } from '../channel/channel.entity';
import { CustomPromotionFields } from '../custom-entity-fields';
import { Order } from '../order/order.entity';
import { OrderLine } from '../order-line/order-line.entity';
import { ShippingLine } from '../shipping-line/shipping-line.entity';
import { PromotionTranslation } from './promotion-translation.entity';
export interface ApplyOrderItemActionArgs {
orderLine: OrderLine;
}
export interface ApplyOrderActionArgs {
order: Order;
}
export interface ApplyShippingActionArgs {
shippingLine: ShippingLine;
order: Order;
}
export interface PromotionState {
[code: string]: PromotionConditionState;
}
export type PromotionTestResult = boolean | PromotionState;
/**
* @description
* A Promotion is used to define a set of conditions under which promotions actions (typically discounts)
* will be applied to an Order.
*
* Each assigned {@link PromotionCondition} is checked against the Order, and if they all return `true`,
* then each assign {@link PromotionItemAction} / {@link PromotionOrderAction} is applied to the Order.
*
* @docsCategory entities
*/
@Entity()
export class Promotion
extends AdjustmentSource
implements ChannelAware, SoftDeletable, HasCustomFields, Translatable
{
type = AdjustmentType.PROMOTION;
private readonly allConditions: { [code: string]: PromotionCondition } = {};
private readonly allActions: {
[code: string]: PromotionItemAction | PromotionOrderAction | PromotionShippingAction;
} = {};
constructor(
input?: DeepPartial<Promotion> & {
promotionConditions?: Array<PromotionCondition<any>>;
promotionActions?: Array<PromotionAction<any>>;
},
) {
super(input);
const conditions =
(input && input.promotionConditions) || getConfig().promotionOptions.promotionConditions || [];
const actions =
(input && input.promotionActions) || getConfig().promotionOptions.promotionActions || [];
this.allConditions = conditions.reduce((hash, o) => ({ ...hash, [o.code]: o }), {});
this.allActions = actions.reduce((hash, o) => ({ ...hash, [o.code]: o }), {});
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
@Column({ type: Date, nullable: true })
startsAt: Date | null;
@Column({ type: Date, nullable: true })
endsAt: Date | null;
@Column({ nullable: true })
couponCode: string;
@Column({ nullable: true })
perCustomerUsageLimit: number;
@Column({ nullable: true })
usageLimit: number;
name: LocaleString;
description: LocaleString;
@OneToMany(type => PromotionTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<Promotion>>;
@Column() enabled: boolean;
@ManyToMany(type => Channel, channel => channel.promotions)
@JoinTable()
channels: Channel[];
@ManyToMany(type => Order, order => order.promotions)
orders: Order[];
@Column(type => CustomPromotionFields)
customFields: CustomPromotionFields;
@Column('simple-json') conditions: ConfigurableOperation[];
@Column('simple-json') actions: ConfigurableOperation[];
/**
* @description
* The PriorityScore is used to determine the sequence in which multiple promotions are tested
* on a given order. A higher number moves the Promotion towards the end of the sequence.
*
* The score is derived from the sum of the priorityValues of the PromotionConditions and
* PromotionActions comprising this Promotion.
*
* An example illustrating the need for a priority is this:
*
*
* Consider 2 Promotions, 1) buy 1 get one free and 2) 10% off when order total is over $50.
* If Promotion 2 is evaluated prior to Promotion 1, then it can trigger the 10% discount even
* if the subsequent application of Promotion 1 brings the order total down to way below $50.
*/
@Column() priorityScore: number;
async apply(
ctx: RequestContext,
args: ApplyOrderActionArgs | ApplyOrderItemActionArgs | ApplyShippingActionArgs,
state?: PromotionState,
): Promise<Adjustment | undefined> {
let amount = 0;
state = state || {};
for (const action of this.actions) {
const promotionAction = this.allActions[action.code];
if (promotionAction instanceof PromotionItemAction) {
if (this.isOrderItemArg(args)) {
const { orderLine } = args;
amount += roundMoney(
await promotionAction.execute(ctx, orderLine, action.args, state, this),
);
}
} else if (promotionAction instanceof PromotionOrderAction) {
if (this.isOrderArg(args)) {
const { order } = args;
amount += roundMoney(await promotionAction.execute(ctx, order, action.args, state, this));
}
} else if (promotionAction instanceof PromotionShippingAction) {
if (this.isShippingArg(args)) {
const { shippingLine, order } = args;
amount += roundMoney(
await promotionAction.execute(ctx, shippingLine, order, action.args, state, this),
);
}
}
}
if (amount !== 0) {
return {
amount,
type: this.type,
description: this.name,
adjustmentSource: this.getSourceId(),
data: {},
};
}
}
async test(ctx: RequestContext, order: Order): Promise<PromotionTestResult> {
if (this.endsAt && this.endsAt < new Date()) {
return false;
}
if (this.startsAt && this.startsAt > new Date()) {
return false;
}
if (this.couponCode && !order.couponCodes.includes(this.couponCode)) {
return false;
}
const promotionState: PromotionState = {};
for (const condition of this.conditions) {
const promotionCondition = this.allConditions[condition.code];
if (!promotionCondition) {
return false;
}
const applicableOrConditionState = await promotionCondition.check(
ctx,
order,
condition.args,
this,
);
if (!applicableOrConditionState) {
return false;
}
if (typeof applicableOrConditionState === 'object') {
promotionState[condition.code] = applicableOrConditionState;
}
}
return promotionState;
}
async activate(ctx: RequestContext, order: Order) {
for (const action of this.actions) {
const promotionAction = this.allActions[action.code];
await promotionAction.onActivate(ctx, order, action.args, this);
}
}
async deactivate(ctx: RequestContext, order: Order) {
for (const action of this.actions) {
const promotionAction = this.allActions[action.code];
await promotionAction.onDeactivate(ctx, order, action.args, this);
}
}
private isShippingAction(
value: PromotionItemAction | PromotionOrderAction | PromotionShippingAction,
): value is PromotionItemAction {
return value instanceof PromotionShippingAction;
}
private isOrderArg(
value: ApplyOrderItemActionArgs | ApplyOrderActionArgs | ApplyShippingActionArgs,
): value is ApplyOrderActionArgs {
return !this.isOrderItemArg(value) && !this.isShippingArg(value);
}
private isOrderItemArg(
value: ApplyOrderItemActionArgs | ApplyOrderActionArgs | ApplyShippingActionArgs,
): value is ApplyOrderItemActionArgs {
return value.hasOwnProperty('orderLine');
}
private isShippingArg(
value: ApplyOrderItemActionArgs | ApplyOrderActionArgs | PromotionShippingAction,
): value is ApplyShippingActionArgs {
return value.hasOwnProperty('shippingLine');
}
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, JoinColumn, JoinTable, ManyToOne, OneToMany } from 'typeorm';
import { PaymentMetadata } from '../../common/types/common-types';
import { RefundState } from '../../service/helpers/refund-state-machine/refund-state';
import { VendureEntity } from '../base/base.entity';
import { EntityId } from '../entity-id.decorator';
import { Money } from '../money.decorator';
import { RefundLine } from '../order-line-reference/refund-line.entity';
import { Payment } from '../payment/payment.entity';
@Entity()
export class Refund extends VendureEntity {
constructor(input?: DeepPartial<Refund>) {
super(input);
}
/**
* @deprecated Since v2.2, the `items` field will not be used by default. Instead, the `total` field
* alone will be used to determine the refund amount.
*/
@Money() items: number;
/**
* @deprecated Since v2.2, the `shipping` field will not be used by default. Instead, the `total` field
* alone will be used to determine the refund amount.
*/
@Money() shipping: number;
/**
* @deprecated Since v2.2, the `adjustment` field will not be used by default. Instead, the `total` field
* alone will be used to determine the refund amount.
*/
@Money() adjustment: number;
@Money() total: number;
@Column() method: string;
@Column({ nullable: true }) reason: string;
@Column('varchar') state: RefundState;
@Column({ nullable: true }) transactionId: string;
@OneToMany(type => RefundLine, line => line.refund)
@JoinTable()
lines: RefundLine[];
@Index()
@ManyToOne(type => Payment, payment => payment.refunds)
@JoinColumn()
payment: Payment;
@EntityId()
paymentId: ID;
@Column('simple-json') metadata: PaymentMetadata;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity } from 'typeorm';
import { Region, RegionType } from './region.entity';
/**
* @description
* A country to which is available when creating / updating an {@link Address}. Countries are
* grouped together into {@link Zone}s which are in turn used to determine applicable shipping
* and taxes for an {@link Order}.
*
* @docsCategory entities
*/
@ChildEntity()
export class Country extends Region {
constructor(input?: DeepPartial<Country>) {
super(input);
}
readonly type: RegionType = 'country';
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity } from 'typeorm';
import { Region, RegionType } from './region.entity';
/**
* @description
* A Province represents an administrative subdivision of a {@link Country}. For example, in the
* United States, the country would be "United States" and the province would be "California".
*
* @docsCategory entities
*/
@ChildEntity()
export class Province extends Region {
constructor(input?: DeepPartial<Province>) {
super(input);
}
readonly type: RegionType = 'province';
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomRegionFieldsTranslation } from '../custom-entity-fields';
import { Region } from './region.entity';
@Entity()
export class RegionTranslation extends VendureEntity implements Translation<Region>, HasCustomFields {
constructor(input?: DeepPartial<Translation<RegionTranslation>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column() name: string;
@Index()
@ManyToOne(type => Region, base => base.translations, { onDelete: 'CASCADE' })
base: Region;
@Column(type => CustomRegionFieldsTranslation)
customFields: CustomRegionFieldsTranslation;
}
|
import { ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, JoinColumn, ManyToOne, OneToMany, TableInheritance } from 'typeorm';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomRegionFields } from '../custom-entity-fields';
import { EntityId } from '../entity-id.decorator';
import { RegionTranslation } from './region-translation.entity';
export type RegionType = 'country' | 'province' | string;
/**
* @description
* A Region represents a geographical administrative unit, such as a Country, Province, State, Prefecture etc.
* This is an abstract class which is extended by the {@link Country} and {@link Province} entities.
* Regions can be grouped into {@link Zone}s which are in turn used to determine applicable shipping and taxes for an {@link Order}.
*
* @docsCategory entities
*/
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'discriminator' } })
export abstract class Region extends VendureEntity implements Translatable, HasCustomFields {
/**
* @description
* A code representing the region. The code format will depend on the type of region. For
* example, a Country code will be a 2-letter ISO code, whereas a Province code could use
* a format relevant to the type of province, e.g. a US state code like "CA".
*/
@Column() code: string;
@Column({ nullable: false, type: 'varchar' })
readonly type: RegionType;
name: LocaleString;
@Index()
@ManyToOne(type => Region, { nullable: true, onDelete: 'SET NULL' })
parent?: Region;
@EntityId({ nullable: true })
parentId?: ID;
@Column() enabled: boolean;
@OneToMany(type => RegionTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<Region>>;
@Column(type => CustomRegionFields)
customFields: CustomRegionFields;
}
|
import { Permission } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany } from 'typeorm';
import { ChannelAware } from '../../common/types/common-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
/**
* @description
* A Role represents a collection of permissions which determine the authorization
* level of a {@link User} on a given set of {@link Channel}s.
*
* @docsCategory entities
*/
@Entity()
export class Role extends VendureEntity implements ChannelAware {
constructor(input?: DeepPartial<Role>) {
super(input);
}
@Column() code: string;
@Column() description: string;
@Column('simple-array') permissions: Permission[];
@ManyToMany(type => Channel, channel => channel.roles)
@JoinTable()
channels: Channel[];
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, OneToMany } from 'typeorm';
import { Channel } from '..';
import { SoftDeletable } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomSellerFields } from '../custom-entity-fields';
/**
* @description
* A Seller represents the person or organization who is selling the goods on a given {@link Channel}.
* By default, a single-channel Vendure installation will have a single default Seller.
*
* @docsCategory entities
*/
@Entity()
export class Seller extends VendureEntity implements SoftDeletable, HasCustomFields {
constructor(input?: DeepPartial<Seller>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
@Column() name: string;
@Column(type => CustomSellerFields)
customFields: CustomSellerFields;
@OneToMany(type => Channel, channel => channel.seller)
channels: Channel[];
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, ManyToOne } from 'typeorm';
import { Order } from '../order/order.entity';
import { Session } from './session.entity';
/**
* @description
* An anonymous session is created when a unauthenticated user interacts with restricted operations,
* such as calling the `activeOrder` query in the Shop API. Anonymous sessions allow a guest Customer
* to maintain an order without requiring authentication and a registered account beforehand.
*
* @docsCategory entities
*/
@ChildEntity()
export class AnonymousSession extends Session {
constructor(input: DeepPartial<AnonymousSession>) {
super(input);
}
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Column, Index, ManyToOne } from 'typeorm';
import { User } from '../user/user.entity';
import { Session } from './session.entity';
/**
* @description
* An AuthenticatedSession is created upon successful authentication.
*
* @docsCategory entities
*/
@ChildEntity()
export class AuthenticatedSession extends Session {
constructor(input: DeepPartial<AuthenticatedSession>) {
super(input);
}
/**
* @description
* The {@link User} who has authenticated to create this session.
*/
@Index()
@ManyToOne(type => User, user => user.sessions)
user: User;
/**
* @description
* The name of the {@link AuthenticationStrategy} used when authenticating
* to create this session.
*/
@Column()
authenticationStrategy: string;
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne, TableInheritance } from 'typeorm';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { Customer } from '../customer/customer.entity';
import { EntityId } from '../entity-id.decorator';
import { Order } from '../order/order.entity';
import { User } from '../user/user.entity';
/**
* @description
* A Session is created when a user makes a request to restricted API operations. A Session can be an {@link AnonymousSession}
* in the case of un-authenticated users, otherwise it is an {@link AuthenticatedSession}.
*
* @docsCategory entities
*/
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export abstract class Session extends VendureEntity {
@Index({ unique: true })
@Column()
token: string;
@Column() expires: Date;
@Column() invalidated: boolean;
@EntityId({ nullable: true })
activeOrderId?: ID;
@Index()
@ManyToOne(type => Order)
activeOrder: Order | null;
@EntityId({ nullable: true })
activeChannelId?: ID;
@Index()
@ManyToOne(type => Channel)
activeChannel: Channel | null;
}
|
import { Adjustment, AdjustmentType, Discount, TaxLine } from '@vendure/common/lib/generated-types';
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { summate } from '@vendure/common/lib/shared-utils';
import { Column, Entity, Index, ManyToOne, OneToMany } from 'typeorm';
import { OrderLine } from '..';
import { Calculated } from '../../common/calculated-decorator';
import { roundMoney } from '../../common/round-money';
import { grossPriceOf, netPriceOf } from '../../common/tax-utils';
import { VendureEntity } from '../base/base.entity';
import { EntityId } from '../entity-id.decorator';
import { Money } from '../money.decorator';
import { Order } from '../order/order.entity';
import { ShippingMethod } from '../shipping-method/shipping-method.entity';
/**
* @description
* A ShippingLine is created when a {@link ShippingMethod} is applied to an {@link Order}.
* It contains information about the price of the shipping method, any discounts that were
* applied, and the resulting tax on the shipping method.
*
* @docsCategory entities
*/
@Entity()
export class ShippingLine extends VendureEntity {
constructor(input?: DeepPartial<ShippingLine>) {
super(input);
}
@EntityId()
shippingMethodId: ID | null;
@Index()
@ManyToOne(type => ShippingMethod)
shippingMethod: ShippingMethod;
@Index()
@ManyToOne(type => Order, order => order.shippingLines, { onDelete: 'CASCADE' })
order: Order;
@Money()
listPrice: number;
@Column()
listPriceIncludesTax: boolean;
@Column('simple-json')
adjustments: Adjustment[];
@Column('simple-json')
taxLines: TaxLine[];
@OneToMany(type => OrderLine, orderLine => orderLine.shippingLine)
orderLines: OrderLine[];
@Calculated()
get price(): number {
return this.listPriceIncludesTax ? netPriceOf(this.listPrice, this.taxRate) : this.listPrice;
}
@Calculated()
get priceWithTax(): number {
return roundMoney(
this.listPriceIncludesTax ? this.listPrice : grossPriceOf(this.listPrice, this.taxRate),
);
}
@Calculated()
get discountedPrice(): number {
const result = this.listPrice + this.getAdjustmentsTotal();
return roundMoney(this.listPriceIncludesTax ? netPriceOf(result, this.taxRate) : result);
}
@Calculated()
get discountedPriceWithTax(): number {
const result = this.listPrice + this.getAdjustmentsTotal();
return roundMoney(this.listPriceIncludesTax ? result : grossPriceOf(result, this.taxRate));
}
@Calculated()
get taxRate(): number {
return summate(this.taxLines, 'taxRate');
}
@Calculated()
get discounts(): Discount[] {
return (
this.adjustments?.map(adjustment => {
const amount = roundMoney(
this.listPriceIncludesTax
? netPriceOf(adjustment.amount, this.taxRate)
: adjustment.amount,
);
const amountWithTax = roundMoney(
this.listPriceIncludesTax
? adjustment.amount
: grossPriceOf(adjustment.amount, this.taxRate),
);
return {
...(adjustment as Omit<Adjustment, '__typename'>),
amount,
amountWithTax,
};
}) ?? []
);
}
addAdjustment(adjustment: Adjustment) {
this.adjustments = this.adjustments.concat(adjustment);
}
clearAdjustments() {
this.adjustments = [];
}
/**
* @description
* The total of all price adjustments. Will typically be a negative number due to discounts.
*/
private getAdjustmentsTotal(): number {
return summate(this.adjustments, 'amount');
}
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Translation } from '../../common/types/locale-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomShippingMethodFieldsTranslation } from '../custom-entity-fields';
import { Product } from '../product/product.entity';
import { ShippingMethod } from './shipping-method.entity';
@Entity()
export class ShippingMethodTranslation
extends VendureEntity
implements Translation<ShippingMethod>, HasCustomFields
{
constructor(input?: DeepPartial<Translation<Product>>) {
super(input);
}
@Column('varchar') languageCode: LanguageCode;
@Column({ default: '' }) name: string;
@Column({ default: '' }) description: string;
@Index()
@ManyToOne(type => ShippingMethod, base => base.translations, { onDelete: 'CASCADE' })
base: ShippingMethod;
@Column(type => CustomShippingMethodFieldsTranslation)
customFields: CustomShippingMethodFieldsTranslation;
}
|
import { ConfigurableOperation } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { RequestContext } from '../../api/common/request-context';
import { roundMoney } from '../../common/round-money';
import { ChannelAware, SoftDeletable } from '../../common/types/common-types';
import { LocaleString, Translatable, Translation } from '../../common/types/locale-types';
import { getConfig } from '../../config/config-helpers';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import {
ShippingCalculationResult,
ShippingCalculator,
} from '../../config/shipping-method/shipping-calculator';
import { ShippingEligibilityChecker } from '../../config/shipping-method/shipping-eligibility-checker';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomShippingMethodFields } from '../custom-entity-fields';
import { Order } from '../order/order.entity';
import { ShippingMethodTranslation } from './shipping-method-translation.entity';
/**
* @description
* A ShippingMethod is used to apply a shipping price to an {@link Order}. It is composed of a
* {@link ShippingEligibilityChecker} and a {@link ShippingCalculator}. For a given Order,
* the `checker` is used to determine whether this ShippingMethod can be used. If yes, then
* the ShippingMethod can be applied and the `calculator` is used to determine the price of
* shipping.
*
* @docsCategory entities
*/
@Entity()
export class ShippingMethod
extends VendureEntity
implements ChannelAware, SoftDeletable, HasCustomFields, Translatable
{
private readonly allCheckers: { [code: string]: ShippingEligibilityChecker } = {};
private readonly allCalculators: { [code: string]: ShippingCalculator } = {};
constructor(input?: DeepPartial<ShippingMethod>) {
super(input);
const checkers = getConfig().shippingOptions.shippingEligibilityCheckers || [];
const calculators = getConfig().shippingOptions.shippingCalculators || [];
this.allCheckers = checkers.reduce((hash, o) => ({ ...hash, [o.code]: o }), {});
this.allCalculators = calculators.reduce((hash, o) => ({ ...hash, [o.code]: o }), {});
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
@Column() code: string;
name: LocaleString;
description: LocaleString;
@Column('simple-json') checker: ConfigurableOperation;
@Column('simple-json') calculator: ConfigurableOperation;
@Column()
fulfillmentHandlerCode: string;
@ManyToMany(type => Channel, channel => channel.shippingMethods)
@JoinTable()
channels: Channel[];
@OneToMany(type => ShippingMethodTranslation, translation => translation.base, { eager: true })
translations: Array<Translation<ShippingMethod>>;
@Column(type => CustomShippingMethodFields)
customFields: CustomShippingMethodFields;
async apply(ctx: RequestContext, order: Order): Promise<ShippingCalculationResult | undefined> {
const calculator = this.allCalculators[this.calculator.code];
if (calculator) {
const response = await calculator.calculate(ctx, order, this.calculator.args, this);
if (response) {
const { price, priceIncludesTax, taxRate, metadata } = response;
return {
price: roundMoney(price),
priceIncludesTax,
taxRate,
metadata,
};
}
}
}
async test(ctx: RequestContext, order: Order): Promise<boolean> {
const checker = this.allCheckers[this.checker.code];
if (checker) {
return checker.check(ctx, order, this.checker.args, this);
} else {
return false;
}
}
}
|
import { DeepPartial, ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { VendureEntity } from '../base/base.entity';
import { EntityId } from '../entity-id.decorator';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { StockLocation } from '../stock-location/stock-location.entity';
/**
* @description
* A StockLevel represents the number of a particular {@link ProductVariant} which are available
* at a particular {@link StockLocation}.
*
* @docsCategory entities
*/
@Entity()
@Index(['productVariantId', 'stockLocationId'], { unique: true })
export class StockLevel extends VendureEntity {
constructor(input: DeepPartial<StockLevel>) {
super(input);
}
@Index()
@ManyToOne(type => ProductVariant, productVariant => productVariant.stockLevels, { onDelete: 'CASCADE' })
productVariant: ProductVariant;
@EntityId()
productVariantId: ID;
@Index()
@ManyToOne(type => StockLocation, { onDelete: 'CASCADE' })
stockLocation: StockLocation;
@EntityId()
stockLocationId: ID;
@Column()
stockOnHand: number;
@Column()
stockAllocated: number;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { ChannelAware } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomStockLocationFields } from '../custom-entity-fields';
import { StockMovement } from '../stock-movement/stock-movement.entity';
/**
* @description
* A StockLocation represents a physical location where stock is held. For example, a warehouse or a shop.
*
* When the stock of a {@link ProductVariant} is adjusted, the adjustment is applied to a specific StockLocation,
* and the stockOnHand of that ProductVariant is updated accordingly. When there are multiple StockLocations
* configured, the {@link StockLocationStrategy} is used to determine which StockLocation should be used for
* a given operation.
*
* @docsCategory entities
*/
@Entity()
export class StockLocation extends VendureEntity implements HasCustomFields, ChannelAware {
constructor(input: DeepPartial<StockLocation>) {
super(input);
}
@Column()
name: string;
@Column()
description: string;
@Column(type => CustomStockLocationFields)
customFields: CustomStockLocationFields;
@ManyToMany(type => Channel, channel => channel.stockLocations)
@JoinTable()
channels: Channel[];
@OneToMany(type => StockMovement, movement => movement.stockLocation)
stockMovements: StockMovement[];
}
|
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { OrderLine } from '../order-line/order-line.entity';
import { StockMovement } from './stock-movement.entity';
/**
* @description
* An Allocation is created for each ProductVariant in an Order when the checkout is completed
* (as configured by the {@link StockAllocationStrategy}. This prevents stock being sold twice.
*
* @docsCategory entities
* @docsPage StockMovement
*/
@ChildEntity()
export class Allocation extends StockMovement {
readonly type = StockMovementType.ALLOCATION;
constructor(input: DeepPartial<Allocation>) {
super(input);
}
@Index()
@ManyToOne(type => OrderLine, orderLine => orderLine.allocations)
orderLine: OrderLine;
}
|
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, ManyToOne } from 'typeorm';
import { OrderLine } from '../order-line/order-line.entity';
import { StockMovement } from './stock-movement.entity';
/**
* @description
* A Cancellation is created when OrderItems from a fulfilled Order are cancelled.
*
* @docsCategory entities
* @docsPage StockMovement
*/
@ChildEntity()
export class Cancellation extends StockMovement {
readonly type = StockMovementType.CANCELLATION;
constructor(input: DeepPartial<Cancellation>) {
super(input);
}
// @Index() omitted as it would conflict with the orderLineId index from the Allocation entity
@ManyToOne(type => OrderLine, orderLine => orderLine.cancellations)
orderLine: OrderLine;
}
|
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, ManyToOne } from 'typeorm';
import { OrderLine } from '../order-line/order-line.entity';
import { StockMovement } from './stock-movement.entity';
/**
* @description
* A Release is created when OrderItems which have been allocated (but not yet fulfilled)
* are cancelled.
*
* @docsCategory entities
* @docsPage StockMovement
*/
@ChildEntity()
export class Release extends StockMovement {
readonly type = StockMovementType.RELEASE;
constructor(input: DeepPartial<Release>) {
super(input);
}
// @Index() omitted as it would conflict with the orderLineId index from the Allocation entity
@ManyToOne(type => OrderLine)
orderLine: OrderLine;
}
|
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity, Index, ManyToOne } from 'typeorm';
import { OrderLine } from '../order-line/order-line.entity';
import { StockMovement } from './stock-movement.entity';
/**
* @description
* A Sale is created when OrderItems are fulfilled.
*
* @docsCategory entities
* @docsPage StockMovement
*/
@ChildEntity()
export class Sale extends StockMovement {
readonly type = StockMovementType.SALE;
constructor(input: DeepPartial<Sale>) {
super(input);
}
// @Index() omitted as it would conflict with the orderLineId index from the Allocation entity
@ManyToOne(type => OrderLine, line => line.sales)
orderLine: OrderLine;
}
|
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { ChildEntity } from 'typeorm';
import { StockMovement } from './stock-movement.entity';
/**
* @description
* A StockAdjustment is created when the `stockOnHand` level of a ProductVariant is manually adjusted.
*
* @docsCategory entities
* @docsPage StockMovement
*/
@ChildEntity()
export class StockAdjustment extends StockMovement {
readonly type = StockMovementType.ADJUSTMENT;
constructor(input: DeepPartial<StockAdjustment>) {
super(input);
}
}
|
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne, TableInheritance } from 'typeorm';
import { VendureEntity } from '../base/base.entity';
import { EntityId } from '../entity-id.decorator';
import { ProductVariant } from '../product-variant/product-variant.entity';
import { StockLocation } from '../stock-location/stock-location.entity';
/**
* @description
* A StockMovement is created whenever stock of a particular ProductVariant goes in
* or out.
*
* @docsCategory entities
* @docsPage StockMovement
* @docsWeight 0
*/
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'discriminator' } })
export abstract class StockMovement extends VendureEntity {
@Column({ nullable: false, type: 'varchar' })
readonly type: StockMovementType;
@Index()
@ManyToOne(type => ProductVariant, variant => variant.stockMovements)
productVariant: ProductVariant;
@Index()
@ManyToOne(type => StockLocation, stockLocation => stockLocation.stockMovements, { onDelete: 'CASCADE' })
stockLocation: StockLocation;
@EntityId()
stockLocationId: ID;
@Column()
quantity: number;
}
|
import { TaxLine } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { summate } from '@vendure/common/lib/shared-utils';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { Calculated } from '../../common/calculated-decorator';
import { roundMoney } from '../../common/round-money';
import { grossPriceOf, netPriceOf } from '../../common/tax-utils';
import { VendureEntity } from '../base/base.entity';
import { Money } from '../money.decorator';
import { Order } from '../order/order.entity';
import { OrderModification } from '../order-modification/order-modification.entity';
/**
* @description
* A Surcharge represents an arbitrary extra item on an {@link Order} which is not
* a ProductVariant. It can be used to e.g. represent payment-related surcharges.
*
* @docsCategory entities
*/
@Entity()
export class Surcharge extends VendureEntity {
constructor(input?: DeepPartial<Surcharge>) {
super(input);
}
@Column()
description: string;
@Money()
listPrice: number;
@Column()
listPriceIncludesTax: boolean;
@Column()
sku: string;
@Column('simple-json')
taxLines: TaxLine[];
@Index()
@ManyToOne(type => Order, order => order.surcharges, { onDelete: 'CASCADE' })
order: Order;
@Index()
@ManyToOne(type => OrderModification, orderModification => orderModification.surcharges)
orderModification: OrderModification;
@Calculated()
get price(): number {
return roundMoney(
this.listPriceIncludesTax ? netPriceOf(this.listPrice, this.taxRate) : this.listPrice,
);
}
@Calculated()
get priceWithTax(): number {
return roundMoney(
this.listPriceIncludesTax ? this.listPrice : grossPriceOf(this.listPrice, this.taxRate),
);
}
@Calculated()
get taxRate(): number {
return summate(this.taxLines, 'taxRate');
}
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity } from 'typeorm';
import { VendureEntity } from '../base/base.entity';
/**
* @description
* A tag is an arbitrary label which can be applied to certain entities.
* It is used to help organize and filter those entities.
*
* @docsCategory entities
*/
@Entity()
export class Tag extends VendureEntity {
constructor(input?: DeepPartial<Tag>) {
super(input);
}
@Column()
value: string;
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, OneToMany } from 'typeorm';
import { TaxRate } from '..';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomTaxCategoryFields } from '../custom-entity-fields';
import { ProductVariant } from '../product-variant/product-variant.entity';
/**
* @description
* A TaxCategory defines what type of taxes to apply to a {@link ProductVariant}.
*
* @docsCategory entities
*/
@Entity()
export class TaxCategory extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<TaxCategory>) {
super(input);
}
@Column() name: string;
@Column({ default: false }) isDefault: boolean;
@Column(type => CustomTaxCategoryFields)
customFields: CustomTaxCategoryFields;
@OneToMany(type => ProductVariant, productVariant => productVariant.taxCategory)
productVariants: ProductVariant[];
@OneToMany(type => TaxRate, taxRate => taxRate.category)
taxRates: TaxRate[];
}
|
import { TaxLine } from '@vendure/common/lib/generated-types';
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, Index, ManyToOne } from 'typeorm';
import { grossPriceOf, netPriceOf, taxComponentOf, taxPayableOn } from '../../common/tax-utils';
import { idsAreEqual } from '../../common/utils';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { CustomTaxRateFields } from '../custom-entity-fields';
import { CustomerGroup } from '../customer-group/customer-group.entity';
import { TaxCategory } from '../tax-category/tax-category.entity';
import { DecimalTransformer } from '../value-transformers';
import { Zone } from '../zone/zone.entity';
/**
* @description
* A TaxRate defines the rate of tax to apply to a {@link ProductVariant} based on three factors:
*
* 1. the ProductVariant's {@link TaxCategory}
* 2. the applicable {@link Zone} ("applicable" being defined by the configured {@link TaxZoneStrategy})
* 3. the {@link CustomerGroup} of the current Customer
*
* @docsCategory entities
*/
@Entity()
export class TaxRate extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<TaxRate>) {
super(input);
}
@Column() name: string;
@Column() enabled: boolean;
@Column({ type: 'decimal', precision: 5, scale: 2, transformer: new DecimalTransformer() }) value: number;
@Index()
@ManyToOne(type => TaxCategory, taxCategory => taxCategory.taxRates)
category: TaxCategory;
@Index()
@ManyToOne(type => Zone, zone => zone.taxRates)
zone: Zone;
@Index()
@ManyToOne(type => CustomerGroup, customerGroup => customerGroup.taxRates, { nullable: true })
customerGroup?: CustomerGroup;
@Column(type => CustomTaxRateFields)
customFields: CustomTaxRateFields;
/**
* Returns the tax component of a given gross price.
*/
taxComponentOf(grossPrice: number): number {
return taxComponentOf(grossPrice, this.value);
}
/**
* Given a gross (tax-inclusive) price, returns the net price.
*/
netPriceOf(grossPrice: number): number {
return netPriceOf(grossPrice, this.value);
}
/**
* Returns the tax applicable to the given net price.
*/
taxPayableOn(netPrice: number): number {
return taxPayableOn(netPrice, this.value);
}
/**
* Given a net price, return the gross price (net + tax)
*/
grossPriceOf(netPrice: number): number {
return grossPriceOf(netPrice, this.value);
}
apply(price: number): TaxLine {
return {
description: this.name,
taxRate: this.value,
};
}
test(zone: Zone, taxCategory: TaxCategory): boolean {
return idsAreEqual(taxCategory.id, this.category.id) && idsAreEqual(zone.id, this.zone.id);
}
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { InternalServerError } from '../../common/error/errors';
import { SoftDeletable } from '../../common/types/common-types';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { AuthenticationMethod } from '../authentication-method/authentication-method.entity';
import { NativeAuthenticationMethod } from '../authentication-method/native-authentication-method.entity';
import { VendureEntity } from '../base/base.entity';
import { CustomUserFields } from '../custom-entity-fields';
import { Role } from '../role/role.entity';
import { AuthenticatedSession } from '../session/authenticated-session.entity';
/**
* @description
* A User represents any authenticated user of the Vendure API. This includes both
* {@link Administrator}s as well as registered {@link Customer}s.
*
* @docsCategory entities
*/
@Entity()
export class User extends VendureEntity implements HasCustomFields, SoftDeletable {
constructor(input?: DeepPartial<User>) {
super(input);
}
@Column({ type: Date, nullable: true })
deletedAt: Date | null;
@Column()
identifier: string;
@OneToMany(type => AuthenticationMethod, method => method.user)
authenticationMethods: AuthenticationMethod[];
@Column({ default: false })
verified: boolean;
@ManyToMany(type => Role)
@JoinTable()
roles: Role[];
@Column({ type: Date, nullable: true })
lastLogin: Date | null;
@Column(type => CustomUserFields)
customFields: CustomUserFields;
@OneToMany(type => AuthenticatedSession, session => session.user)
sessions: AuthenticatedSession[];
getNativeAuthenticationMethod(): NativeAuthenticationMethod;
getNativeAuthenticationMethod(strict?: boolean): NativeAuthenticationMethod | undefined;
getNativeAuthenticationMethod(strict?: boolean): NativeAuthenticationMethod | undefined {
if (!this.authenticationMethods) {
throw new InternalServerError('error.user-authentication-methods-not-loaded');
}
const match = this.authenticationMethods.find(
(m): m is NativeAuthenticationMethod => m instanceof NativeAuthenticationMethod,
);
if (!match && (strict === undefined || strict)) {
throw new InternalServerError('error.native-authentication-methods-not-found');
}
return match;
}
}
|
import { DeepPartial } from '@vendure/common/lib/shared-types';
import { Column, Entity, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { HasCustomFields } from '../../config/custom-field/custom-field-types';
import { VendureEntity } from '../base/base.entity';
import { Channel } from '../channel/channel.entity';
import { CustomZoneFields } from '../custom-entity-fields';
import { Country } from '../region/country.entity';
import { Region } from '../region/region.entity';
import { TaxRate } from '../tax-rate/tax-rate.entity';
/**
* @description
* A Zone is a grouping of one or more {@link Country} entities. It is used for
* calculating applicable shipping and taxes.
*
* @docsCategory entities
*/
@Entity()
export class Zone extends VendureEntity implements HasCustomFields {
constructor(input?: DeepPartial<Zone>) {
super(input);
}
@Column() name: string;
@ManyToMany(type => Region)
@JoinTable()
members: Region[];
@Column(type => CustomZoneFields)
customFields: CustomZoneFields;
@OneToMany(type => Channel, country => country.defaultShippingZone)
defaultShippingZoneChannels: Channel[];
@OneToMany(type => Channel, country => country.defaultTaxZone)
defaultTaxZoneChannels: Channel[];
@OneToMany(type => TaxRate, taxRate => taxRate.zone)
taxRates: TaxRate[];
}
|
import { Module } from '@nestjs/common';
import { ConnectionModule } from '../connection/connection.module';
import { EventBus } from './event-bus';
@Module({
imports: [ConnectionModule],
providers: [EventBus],
exports: [EventBus],
})
export class EventBusModule {}
|
import { firstValueFrom, Subject } from 'rxjs';
import { QueryRunner } from 'typeorm';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { EventBus } from './event-bus';
import { VendureEvent } from './vendure-event';
class MockTransactionSubscriber {
awaitRelease(queryRunner: QueryRunner): Promise<QueryRunner> {
return Promise.resolve(queryRunner);
}
}
describe('EventBus', () => {
let eventBus: EventBus;
beforeEach(() => {
eventBus = new EventBus(new MockTransactionSubscriber() as any);
});
it('can publish without subscribers', () => {
const event = new TestEvent('foo');
expect(async () => await eventBus.publish(event)).not.toThrow();
});
describe('ofType()', () => {
it('single handler is called once', async () => {
const handler = vi.fn();
const event = new TestEvent('foo');
eventBus.ofType(TestEvent).subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(event);
});
it('single handler is called on multiple events', async () => {
const handler = vi.fn();
const event1 = new TestEvent('foo');
const event2 = new TestEvent('bar');
const event3 = new TestEvent('baz');
eventBus.ofType(TestEvent).subscribe(handler);
await eventBus.publish(event1);
await eventBus.publish(event2);
await eventBus.publish(event3);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(3);
expect(handler).toHaveBeenCalledWith(event1);
expect(handler).toHaveBeenCalledWith(event2);
expect(handler).toHaveBeenCalledWith(event3);
});
it('multiple handler are called', async () => {
const handler1 = vi.fn();
const handler2 = vi.fn();
const handler3 = vi.fn();
const event = new TestEvent('foo');
eventBus.ofType(TestEvent).subscribe(handler1);
eventBus.ofType(TestEvent).subscribe(handler2);
eventBus.ofType(TestEvent).subscribe(handler3);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler1).toHaveBeenCalledWith(event);
expect(handler2).toHaveBeenCalledWith(event);
expect(handler3).toHaveBeenCalledWith(event);
});
it('handler is not called for other events', async () => {
const handler = vi.fn();
const event = new OtherTestEvent('foo');
eventBus.ofType(TestEvent).subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).not.toHaveBeenCalled();
});
it('ofType() returns a subscription', async () => {
const handler = vi.fn();
const event = new TestEvent('foo');
const subscription = eventBus.ofType(TestEvent).subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
await eventBus.publish(event);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(1);
});
it('unsubscribe() only unsubscribes own handler', async () => {
const handler1 = vi.fn();
const handler2 = vi.fn();
const event = new TestEvent('foo');
const subscription1 = eventBus.ofType(TestEvent).subscribe(handler1);
const subscription2 = eventBus.ofType(TestEvent).subscribe(handler2);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(1);
subscription1.unsubscribe();
await eventBus.publish(event);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(3);
});
});
describe('filter()', () => {
it('single handler is called once', async () => {
const handler = vi.fn();
const event = new TestEvent('foo');
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(event);
});
it('single handler is called on multiple events', async () => {
const handler = vi.fn();
const event1 = new TestEvent('foo');
const event2 = new TestEvent('bar');
const event3 = new TestEvent('baz');
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler);
await eventBus.publish(event1);
await eventBus.publish(event2);
await eventBus.publish(event3);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(3);
expect(handler).toHaveBeenCalledWith(event1);
expect(handler).toHaveBeenCalledWith(event2);
expect(handler).toHaveBeenCalledWith(event3);
});
it('multiple handler are called', async () => {
const handler1 = vi.fn();
const handler2 = vi.fn();
const handler3 = vi.fn();
const event = new TestEvent('foo');
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler1);
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler2);
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler3);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler1).toHaveBeenCalledWith(event);
expect(handler2).toHaveBeenCalledWith(event);
expect(handler3).toHaveBeenCalledWith(event);
});
it('handler is not called for other events', async () => {
const handler = vi.fn();
const event = new OtherTestEvent('foo');
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).not.toHaveBeenCalled();
});
it('handler is called for instance of child classes', async () => {
const handler = vi.fn();
const event = new ChildTestEvent('bar', 'foo');
eventBus.filter(vendureEvent => vendureEvent instanceof TestEvent).subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalled();
});
it('filter() returns a subscription', async () => {
const handler = vi.fn();
const event = new TestEvent('foo');
const subscription = eventBus
.filter(vendureEvent => vendureEvent instanceof TestEvent)
.subscribe(handler);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
await eventBus.publish(event);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler).toHaveBeenCalledTimes(1);
});
it('unsubscribe() only unsubscribes own handler', async () => {
const handler1 = vi.fn();
const handler2 = vi.fn();
const event = new TestEvent('foo');
const subscription1 = eventBus
.filter(vendureEvent => vendureEvent instanceof TestEvent)
.subscribe(handler1);
const subscription2 = eventBus
.filter(vendureEvent => vendureEvent instanceof TestEvent)
.subscribe(handler2);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(1);
subscription1.unsubscribe();
await eventBus.publish(event);
await eventBus.publish(event);
await new Promise(resolve => setImmediate(resolve));
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(3);
});
});
describe('blocking event handlers', () => {
it('calls the handler function', async () => {
const event = new TestEvent('foo');
const spy = vi.fn((e: VendureEvent) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy(e),
id: 'test-handler',
event: TestEvent,
});
await eventBus.publish(event);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(event);
});
it('throws when attempting to register with a duplicate id', () => {
eventBus.registerBlockingEventHandler({
handler: e => undefined,
id: 'test-handler',
event: TestEvent,
});
expect(() => {
eventBus.registerBlockingEventHandler({
handler: e => undefined,
id: 'test-handler',
event: TestEvent,
});
}).toThrowError(
'A handler with the id "test-handler" is already registered for the event TestEvent',
);
});
it('calls multiple handler functions', async () => {
const event = new TestEvent('foo');
const spy1 = vi.fn((e: VendureEvent) => undefined);
const spy2 = vi.fn((e: VendureEvent) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy1(e),
id: 'test-handler1',
event: TestEvent,
});
eventBus.registerBlockingEventHandler({
handler: e => spy2(e),
id: 'test-handler2',
event: TestEvent,
});
await eventBus.publish(event);
expect(spy1).toHaveBeenCalledTimes(1);
expect(spy1).toHaveBeenCalledWith(event);
expect(spy2).toHaveBeenCalledTimes(1);
expect(spy2).toHaveBeenCalledWith(event);
});
it('handles multiple events', async () => {
const event1 = new TestEvent('foo');
const event2 = new OtherTestEvent('bar');
const spy = vi.fn((e: VendureEvent) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy(e),
id: 'test-handler',
event: [TestEvent, OtherTestEvent],
});
await eventBus.publish(event1);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(event1);
await eventBus.publish(event2);
expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenCalledWith(event2);
});
it('publish method throws in a handler throws', async () => {
const event = new TestEvent('foo');
eventBus.registerBlockingEventHandler({
handler: () => {
throw new Error('test error');
},
id: 'test-handler',
event: TestEvent,
});
await expect(eventBus.publish(event)).rejects.toThrow('test error');
});
it('order of execution with "before" property', async () => {
const event = new TestEvent('foo');
const spy = vi.fn((input: string) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler1'),
id: 'test-handler1',
event: TestEvent,
});
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler2'),
id: 'test-handler2',
event: TestEvent,
before: 'test-handler1',
});
await eventBus.publish(event);
expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenNthCalledWith(1, 'test-handler2');
expect(spy).toHaveBeenNthCalledWith(2, 'test-handler1');
});
it('order of execution with "after" property', async () => {
const event = new TestEvent('foo');
const spy = vi.fn((input: string) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler1'),
id: 'test-handler1',
event: TestEvent,
after: 'test-handler2',
});
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler2'),
id: 'test-handler2',
event: TestEvent,
});
await eventBus.publish(event);
expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenNthCalledWith(1, 'test-handler2');
expect(spy).toHaveBeenNthCalledWith(2, 'test-handler1');
});
it('throws if there is a cycle in before ordering', () => {
const spy = vi.fn((input: string) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler1'),
id: 'test-handler1',
event: TestEvent,
before: 'test-handler2',
});
expect(() =>
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler2'),
id: 'test-handler2',
event: TestEvent,
before: 'test-handler1',
}),
).toThrowError(
'Circular dependency detected between event handlers test-handler1 and test-handler2',
);
});
it('throws if there is a cycle in after ordering', () => {
const spy = vi.fn((input: string) => undefined);
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler1'),
id: 'test-handler1',
event: TestEvent,
after: 'test-handler2',
});
expect(() =>
eventBus.registerBlockingEventHandler({
handler: e => spy('test-handler2'),
id: 'test-handler2',
event: TestEvent,
after: 'test-handler1',
}),
).toThrowError(
'Circular dependency detected between event handlers test-handler1 and test-handler2',
);
});
it('blocks execution of the publish method', async () => {
const event = new TestEvent('foo');
const subject = new Subject<void>();
eventBus.registerBlockingEventHandler({
handler: e => firstValueFrom(subject.asObservable()),
id: 'test-handler',
event: TestEvent,
});
const publishPromise = eventBus.publish(event);
expect(publishPromise).toBeInstanceOf(Promise);
let resolved = false;
void publishPromise.then(() => (resolved = true));
expect(resolved).toBe(false);
await new Promise(resolve => setTimeout(resolve, 50));
expect(resolved).toBe(false);
// Handler only resolves after the subject emits
subject.next();
// Allow the event loop to tick
await new Promise(resolve => setTimeout(resolve, 0));
// Now the promise should be resolved
expect(resolved).toBe(true);
});
});
});
class TestEvent extends VendureEvent {
constructor(public payload: string) {
super();
}
}
class ChildTestEvent extends TestEvent {
constructor(
public childPayload: string,
payload: string,
) {
super(payload);
}
}
class OtherTestEvent extends VendureEvent {
constructor(public payload: string) {
super();
}
}
|
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { Type } from '@vendure/common/lib/shared-types';
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import { Observable, Subject } from 'rxjs';
import { filter, mergeMap, takeUntil } from 'rxjs/operators';
import { EntityManager } from 'typeorm';
import { RequestContext } from '../api/common/request-context';
import { TRANSACTION_MANAGER_KEY } from '../common/constants';
import { Logger } from '../config/logger/vendure-logger';
import { TransactionSubscriber, TransactionSubscriberError } from '../connection/transaction-subscriber';
import { VendureEvent } from './vendure-event';
/**
* @description
* Options for registering a blocking event handler.
*
* @since 2.2.0
* @docsCategory events
*/
export type BlockingEventHandlerOptions<T extends VendureEvent> = {
/**
* @description
* The event type to which the handler should listen.
* Can be a single event type or an array of event types.
*/
event: Type<T> | Array<Type<T>>;
/**
* @description
* The handler function which will be executed when the event is published.
* If the handler returns a Promise, the event publishing code will wait for the Promise to resolve
* before continuing. Any errors thrown by the handler will cause the event publishing code to fail.
*/
handler: (event: T) => void | Promise<void>;
/**
* @description
* A unique identifier for the handler. This can then be used to specify the order in which
* handlers should be executed using the `before` and `after` options in other handlers.
*/
id: string;
/**
* @description
* The ID of another handler which this handler should execute before.
*/
before?: string;
/**
* @description
* The ID of another handler which this handler should execute after.
*/
after?: string;
};
/**
* @description
* The EventBus is used to globally publish events which can then be subscribed to.
*
* Events are published whenever certain actions take place within the Vendure server, for example:
*
* * when a Product is updated ({@link ProductEvent})
* * when an Order transitions state ({@link OrderStateTransitionEvent})
* * when a Customer registers a new account ({@link AccountRegistrationEvent})
*
* Using the EventBus it is possible to subscribe to an take action when these events occur.
* This is done with the `.ofType()` method, which takes an event type and returns an rxjs observable
* stream of events:
*
* @example
* ```ts
* import { OnApplicationBootstrap } from '\@nestjs/common';
* import { EventBus, PluginCommonModule, VendurePlugin } from '\@vendure/core';
* import { filter } from 'rxjs/operators';
*
* \@VendurePlugin({
* imports: [PluginCommonModule]
* })
* export class MyPlugin implements OnApplicationBootstrap {
*
* constructor(private eventBus: EventBus) {}
*
* async onApplicationBootstrap() {
*
* this.eventBus
* .ofType(OrderStateTransitionEvent)
* .pipe(
* filter(event => event.toState === 'PaymentSettled'),
* )
* .subscribe((event) => {
* // do some action when this event fires
* });
* }
* }
* ```
*
* @docsCategory events
* */
@Injectable()
export class EventBus implements OnModuleDestroy {
private eventStream = new Subject<VendureEvent>();
private destroy$ = new Subject<void>();
private blockingEventHandlers = new Map<Type<VendureEvent>, Array<BlockingEventHandlerOptions<any>>>();
constructor(private transactionSubscriber: TransactionSubscriber) {}
/**
* @description
* Publish an event which any subscribers can react to.
*
* @example
* ```ts
* await eventBus.publish(new SomeEvent());
* ```
*/
async publish<T extends VendureEvent>(event: T): Promise<void> {
this.eventStream.next(event);
await this.executeBlockingEventHandlers(event);
}
/**
* @description
* Returns an RxJS Observable stream of events of the given type.
* If the event contains a {@link RequestContext} object, the subscriber
* will only get called after any active database transactions are complete.
*
* This means that the subscriber function can safely access all updated
* data related to the event.
*/
ofType<T extends VendureEvent>(type: Type<T>): Observable<T> {
return this.eventStream.asObservable().pipe(
takeUntil(this.destroy$),
filter(e => e.constructor === type),
mergeMap(event => this.awaitActiveTransactions(event)),
filter(notNullOrUndefined),
) as Observable<T>;
}
/**
* @description
* Returns an RxJS Observable stream of events filtered by a custom predicate.
* If the event contains a {@link RequestContext} object, the subscriber
* will only get called after any active database transactions are complete.
*
* This means that the subscriber function can safely access all updated
* data related to the event.
*/
filter<T extends VendureEvent>(predicate: (event: VendureEvent) => boolean): Observable<T> {
return this.eventStream.asObservable().pipe(
takeUntil(this.destroy$),
filter(e => predicate(e)),
mergeMap(event => this.awaitActiveTransactions(event)),
filter(notNullOrUndefined),
) as Observable<T>;
}
/**
* @description
* Register an event handler function which will be executed when an event of the given type is published,
* and will block execution of the code which published the event until the handler has completed.
*
* This is useful when you need assurance that the event handler has successfully completed, and you want
* the triggering code to fail if the handler fails.
*
* ::: warning
* This API should be used with caution, as errors or performance issues in the handler can cause the
* associated operation to be slow or fail entirely. For this reason, any handler which takes longer than
* 100ms to execute will log a warning. Any non-trivial task to be performed in a blocking event handler
* should be offloaded to a background job using the {@link JobQueueService}.
*
* Also, be aware that the handler will be executed in the _same database transaction_ as the code which published
* the event (as long as you pass the `ctx` object from the event to any TransactionalConnection calls).
* :::
*
* @example
* ```ts
* eventBus.registerBlockingEventHandler({
* event: OrderStateTransitionEvent,
* id: 'my-order-state-transition-handler',
* handler: async (event) => {
* // perform some synchronous task
* }
* });
* ```
*
* @since 2.2.0
*/
registerBlockingEventHandler<T extends VendureEvent>(handlerOptions: BlockingEventHandlerOptions<T>) {
const events = Array.isArray(handlerOptions.event) ? handlerOptions.event : [handlerOptions.event];
for (const event of events) {
let handlers = this.blockingEventHandlers.get(event);
const handlerWithIdAlreadyExists = handlers?.some(h => h.id === handlerOptions.id);
if (handlerWithIdAlreadyExists) {
throw new Error(
`A handler with the id "${handlerOptions.id}" is already registered for the event ${event.name}`,
);
}
if (handlers) {
handlers.push(handlerOptions);
} else {
handlers = [handlerOptions];
}
const orderedHandlers = this.orderEventHandlers(handlers);
this.blockingEventHandlers.set(event, orderedHandlers);
}
}
/** @internal */
onModuleDestroy(): any {
this.destroy$.next();
}
private async executeBlockingEventHandlers<T extends VendureEvent>(event: T): Promise<void> {
const blockingHandlers = this.blockingEventHandlers.get(event.constructor as Type<T>);
for (const options of blockingHandlers || []) {
const timeStart = new Date().getTime();
await options.handler(event);
const timeEnd = new Date().getTime();
const timeTaken = timeEnd - timeStart;
Logger.debug(`Blocking event handler ${options.id} took ${timeTaken}ms`);
if (timeTaken > 100) {
Logger.warn(
[
`Blocking event handler ${options.id} took ${timeTaken}ms`,
`Consider optimizing the handler by moving the logic to a background job or using a more efficient algorithm.`,
].join('\n'),
);
}
}
}
private orderEventHandlers<T extends VendureEvent>(
handlers: Array<BlockingEventHandlerOptions<T>>,
): Array<BlockingEventHandlerOptions<T>> {
let orderedHandlers: Array<BlockingEventHandlerOptions<T>> = [];
const handlerMap: Map<string, BlockingEventHandlerOptions<T>> = new Map();
// Create a map of handlers by ID for efficient lookup
for (const handler of handlers) {
handlerMap.set(handler.id, handler);
}
// Helper function to recursively add handlers in correct order
const addHandler = (handler: BlockingEventHandlerOptions<T>) => {
// If the handler is already in the ordered list, skip it
if (orderedHandlers.includes(handler)) {
return;
}
// If an "after" handler is specified, add it recursively
if (handler.after) {
const afterHandler = handlerMap.get(handler.after);
if (afterHandler) {
if (afterHandler.after === handler.id) {
throw new Error(
`Circular dependency detected between event handlers ${handler.id} and ${afterHandler.id}`,
);
}
orderedHandlers = orderedHandlers.filter(h => h.id !== afterHandler.id);
addHandler(afterHandler);
}
}
// Add the current handler
orderedHandlers.push(handler);
// If a "before" handler is specified, add it recursively
if (handler.before) {
const beforeHandler = handlerMap.get(handler.before);
if (beforeHandler) {
if (beforeHandler.before === handler.id) {
throw new Error(
`Circular dependency detected between event handlers ${handler.id} and ${beforeHandler.id}`,
);
}
orderedHandlers = orderedHandlers.filter(h => h.id !== beforeHandler.id);
addHandler(beforeHandler);
}
}
};
// Start adding handlers from the original list
for (const handler of handlers) {
addHandler(handler);
}
return orderedHandlers;
}
/**
* If the Event includes a RequestContext property, we need to check for any active transaction
* associated with it, and if there is one, we await that transaction to either commit or rollback
* before publishing the event.
*
* The reason for this is that if the transaction is still active when event subscribers execute,
* this can cause a couple of issues:
*
* 1. If the transaction hasn't completed by the time the subscriber runs, the new data inside
* the transaction will not be available to the subscriber.
* 2. If the subscriber gets a reference to the EntityManager which has an active transaction,
* and then the transaction completes, and then the subscriber attempts a DB operation using that
* EntityManager, a fatal QueryRunnerAlreadyReleasedError will be thrown.
*
* For more context on these two issues, see:
*
* * https://github.com/vendure-ecommerce/vendure/issues/520
* * https://github.com/vendure-ecommerce/vendure/issues/1107
*/
private async awaitActiveTransactions<T extends VendureEvent>(event: T): Promise<T | undefined> {
const entry = Object.entries(event).find(([_, value]) => value instanceof RequestContext);
if (!entry) {
return event;
}
const [key, ctx]: [string, RequestContext] = entry;
const transactionManager: EntityManager | undefined = (ctx as any)[TRANSACTION_MANAGER_KEY];
if (!transactionManager?.queryRunner) {
return event;
}
try {
await this.transactionSubscriber.awaitCommit(transactionManager.queryRunner);
// Copy context and remove transaction manager
// This will prevent queries to released query runner
const newContext = ctx.copy();
delete (newContext as any)[TRANSACTION_MANAGER_KEY];
// Reassign new context
(event as any)[key] = newContext;
return event;
} catch (e: any) {
if (e instanceof TransactionSubscriberError) {
// Expected commit, but rollback or something else happened.
// This is still reliable behavior, return undefined
// as event should not be exposed from this transaction
return;
}
throw e;
}
}
}
|
export * from './event-bus';
export * from './event-bus.module';
export * from './vendure-event';
export * from './vendure-entity-event';
export * from './events/account-registration-event';
export * from './events/account-verified-event';
export * from './events/administrator-event';
export * from './events/asset-channel-event';
export * from './events/asset-event';
export * from './events/attempted-login-event';
export * from './events/change-channel-event';
export * from './events/channel-event';
export * from './events/collection-event';
export * from './events/collection-modification-event';
export * from './events/country-event';
export * from './events/coupon-code-event';
export * from './events/customer-address-event';
export * from './events/customer-event';
export * from './events/customer-group-event';
export * from './events/customer-group-change-event';
export * from './events/facet-event';
export * from './events/facet-value-event';
export * from './events/fulfillment-event';
export * from './events/fulfillment-state-transition-event';
export * from './events/global-settings-event';
export * from './events/history-entry-event';
export * from './events/identifier-change-event';
export * from './events/identifier-change-request-event';
export * from './events/initializer-event';
export * from './events/login-event';
export * from './events/logout-event';
export * from './events/order-event';
export * from './events/order-line-event';
export * from './events/order-placed-event';
export * from './events/order-state-transition-event';
export * from './events/password-reset-event';
export * from './events/password-reset-verified-event';
export * from './events/payment-method-event';
export * from './events/payment-state-transition-event';
export * from './events/product-channel-event';
export * from './events/product-event';
export * from './events/product-option-event';
export * from './events/product-option-group-change-event';
export * from './events/product-option-group-event';
export * from './events/product-variant-channel-event';
export * from './events/product-variant-event';
export * from './events/product-variant-price-event';
export * from './events/promotion-event';
export * from './events/refund-state-transition-event';
export * from './events/role-change-event';
export * from './events/role-event';
export * from './events/search-event';
export * from './events/seller-event';
export * from './events/shipping-method-event';
export * from './events/stock-movement-event';
export * from './events/tax-category-event';
export * from './events/tax-rate-event';
export * from './events/tax-rate-modification-event';
export * from './events/zone-event';
export * from './events/zone-members-event';
|
import { RequestContext } from '../api';
import { VendureEvent } from './vendure-event';
/**
* @description
* The base class for all entity events used by the EventBus system.
* * For event type `'deleted'` the input will most likely be an `id: ID`
*
* @docsCategory events
* */
export abstract class VendureEntityEvent<Entity, Input = any> extends VendureEvent {
public readonly entity: Entity;
public readonly type: 'created' | 'updated' | 'deleted';
public readonly ctx: RequestContext;
public readonly input?: Input;
protected constructor(
entity: Entity,
type: 'created' | 'updated' | 'deleted',
ctx: RequestContext,
input?: Input,
) {
super();
this.entity = entity;
this.type = type;
this.ctx = ctx;
this.input = input;
}
}
|
/**
* @description
* The base class for all events used by the EventBus system.
*
* @docsCategory events
* */
export abstract class VendureEvent {
public readonly createdAt: Date;
protected constructor() {
this.createdAt = new Date();
}
}
|
import { RequestContext } from '../../api/common/request-context';
import { User } from '../../entity/user/user.entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired when a new user registers an account, either as a stand-alone signup or after
* placing an order.
*
* @docsCategory events
* @docsPage Event Types
*/
export class AccountRegistrationEvent extends VendureEvent {
constructor(public ctx: RequestContext, public user: User) {
super();
}
}
|
import { RequestContext } from '../../api/common/request-context';
import { Customer } from '../../entity/customer/customer.entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired when a users email address successfully gets verified after
* the `verifyCustomerAccount` mutation was executed.
*
* @docsCategory events
* @docsPage Event Types
*/
export class AccountVerifiedEvent extends VendureEvent {
constructor(public ctx: RequestContext, public customer: Customer) {
super();
}
}
|
import { CreateAdministratorInput, UpdateAdministratorInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Administrator } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type AdministratorInputTypes = CreateAdministratorInput | UpdateAdministratorInput | ID;
/**
* @description
* This event is fired whenever a {@link Administrator} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class AdministratorEvent extends VendureEntityEvent<Administrator, AdministratorInputTypes> {
constructor(
ctx: RequestContext,
entity: Administrator,
type: 'created' | 'updated' | 'deleted',
input?: AdministratorInputTypes,
) {
super(entity, type, ctx, input);
}
}
|
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api/common/request-context';
import { Asset } from '../../entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired whenever an {@link Asset} is assigned or removed
* From a channel.
*
* @docsCategory events
* @docsPage Event Types
*/
export class AssetChannelEvent extends VendureEvent {
constructor(
public ctx: RequestContext,
public asset: Asset,
public channelId: ID,
public type: 'assigned' | 'removed',
) {
super();
}
}
|
import { CreateAssetInput, DeleteAssetInput, UpdateAssetInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Asset } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type AssetInputTypes = CreateAssetInput | UpdateAssetInput | DeleteAssetInput | ID;
/**
* @description
* This event is fired whenever a {@link Asset} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class AssetEvent extends VendureEntityEvent<Asset, AssetInputTypes> {
constructor(
ctx: RequestContext,
entity: Asset,
type: 'created' | 'updated' | 'deleted',
input?: AssetInputTypes,
) {
super(entity, type, ctx, input);
}
/**
* Return an asset field to become compatible with the
* deprecated old version of AssetEvent
* @deprecated Use `entity` instead
* @since 1.4
*/
get asset(): Asset {
return this.entity;
}
}
|
import { RequestContext } from '../../api/common/request-context';
import { User } from '../../entity/user/user.entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired when an attempt is made to log in via the shop or admin API `login` mutation.
* The `strategy` represents the name of the AuthenticationStrategy used in the login attempt.
* If the "native" strategy is used, the additional `identifier` property will be available.
*
* @docsCategory events
* @docsPage Event Types
*/
export class AttemptedLoginEvent extends VendureEvent {
constructor(public ctx: RequestContext, public strategy: string, public identifier?: string) {
super();
}
}
|
import { ID, Type } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { ChannelAware } from '../../common';
import { VendureEntity } from '../../entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired whenever an {@link ChannelAware} entity is assigned or removed
* from a channel. The entity property contains the value before updating the channels.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class ChangeChannelEvent<T extends ChannelAware & VendureEntity> extends VendureEvent {
constructor(
public ctx: RequestContext,
public entity: T,
public channelIds: ID[],
public type: 'assigned' | 'removed',
public entityType?: Type<T>,
) {
super();
}
}
|
import { CreateChannelInput, UpdateChannelInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Channel } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type ChannelInputTypes = CreateChannelInput | UpdateChannelInput | ID;
/**
* @description
* This event is fired whenever a {@link Channel} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class ChannelEvent extends VendureEntityEvent<Channel, ChannelInputTypes> {
constructor(
ctx: RequestContext,
entity: Channel,
type: 'created' | 'updated' | 'deleted',
input?: ChannelInputTypes,
) {
super(entity, type, ctx, input);
}
}
|
import { CreateCollectionInput, UpdateCollectionInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Collection } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type CollectionInputTypes = CreateCollectionInput | UpdateCollectionInput | ID;
/**
* @description
* This event is fired whenever a {@link Collection} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class CollectionEvent extends VendureEntityEvent<Collection, CollectionInputTypes> {
constructor(
ctx: RequestContext,
entity: Collection,
type: 'created' | 'updated' | 'deleted',
input?: CollectionInputTypes,
) {
super(entity, type, ctx, input);
}
}
|
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api/common/request-context';
import { Collection } from '../../entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired whenever a Collection is modified in some way. The `productVariantIds`
* argument is an array of ids of all ProductVariants which:
*
* 1. were part of this collection prior to modification and are no longer
* 2. are now part of this collection after modification but were not before
*
* @docsCategory events
* @docsPage Event Types
*/
export class CollectionModificationEvent extends VendureEvent {
constructor(public ctx: RequestContext, public collection: Collection, public productVariantIds: ID[]) {
super();
}
}
|
import { CreateCountryInput, UpdateCountryInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Country } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type CountryInputTypes = CreateCountryInput | UpdateCountryInput | ID;
/**
* @description
* This event is fired whenever a {@link Country} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class CountryEvent extends VendureEntityEvent<Country, CountryInputTypes> {
constructor(
ctx: RequestContext,
entity: Country,
type: 'created' | 'updated' | 'deleted',
input?: CountryInputTypes,
) {
super(entity, type, ctx, input);
}
}
|
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api/common/request-context';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired whenever an coupon code of an active {@link Promotion}
* is assigned or removed to an {@link Order}.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class CouponCodeEvent extends VendureEvent {
constructor(
public ctx: RequestContext,
public couponCode: string,
public orderId: ID,
public type: 'assigned' | 'removed',
) {
super();
}
}
|
import { CreateAddressInput, UpdateAddressInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Address } from '../../entity/address/address.entity';
import { VendureEntityEvent } from '../vendure-entity-event';
/**
* Possible input types for Address mutations
*/
type CustomerAddressInputTypes = CreateAddressInput | UpdateAddressInput | ID;
/**
* @description
* This event is fired whenever a {@link Address} is added, updated
* or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class CustomerAddressEvent extends VendureEntityEvent<Address, CustomerAddressInputTypes> {
constructor(
public ctx: RequestContext,
public entity: Address,
public type: 'created' | 'updated' | 'deleted',
public input?: CustomerAddressInputTypes,
) {
super(entity, type, ctx, input);
}
/**
* Return an address field to become compatible with the
* deprecated old version of CustomerAddressEvent
* @deprecated Use `entity` instead
*/
get address(): Address {
return this.entity;
}
}
|
import { CreateCustomerInput, UpdateCustomerInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api/common/request-context';
import { Customer } from '../../entity/customer/customer.entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type CustomerInputTypes =
| CreateCustomerInput
| UpdateCustomerInput
| (Partial<CreateCustomerInput> & { emailAddress: string })
| ID;
/**
* @description
* This event is fired whenever a {@link Customer} is added, updated
* or deleted.
*
* @docsCategory events
* @docsPage Event Types
*/
export class CustomerEvent extends VendureEntityEvent<Customer, CustomerInputTypes> {
constructor(
ctx: RequestContext,
entity: Customer,
type: 'created' | 'updated' | 'deleted',
input?: CustomerInputTypes,
) {
super(entity, type, ctx, input);
}
/**
* Return an customer field to become compatible with the
* deprecated old version of CustomerEvent
* @deprecated Use `entity` instead
* @since 1.4
*/
get customer(): Customer {
return this.entity;
}
}
|
import { RequestContext } from '../../api/common/request-context';
import { Customer } from '../../entity/customer/customer.entity';
import { CustomerGroup } from '../../entity/customer-group/customer-group.entity';
import { VendureEvent } from '../vendure-event';
/**
* @description
* This event is fired whenever one or more {@link Customer} is assigned to or removed from a
* {@link CustomerGroup}.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class CustomerGroupChangeEvent extends VendureEvent {
constructor(
public ctx: RequestContext,
public customers: Customer[],
public customGroup: CustomerGroup,
public type: 'assigned' | 'removed',
) {
super();
}
}
|
import { CreateCustomerGroupInput, UpdateCustomerGroupInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { CustomerGroup } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type CustomerGroupInputTypes = CreateCustomerGroupInput | UpdateCustomerGroupInput | ID;
/**
* @description
* This event is fired whenever a {@link CustomerGroup} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class CustomerGroupEvent extends VendureEntityEvent<CustomerGroup, CustomerGroupInputTypes> {
constructor(
ctx: RequestContext,
entity: CustomerGroup,
type: 'created' | 'updated' | 'deleted',
input?: CustomerGroupInputTypes,
) {
super(entity, type, ctx, input);
}
}
|
import { CreateFacetInput, UpdateFacetInput } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { Facet } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type FacetInputTypes = CreateFacetInput | UpdateFacetInput | ID;
/**
* @description
* This event is fired whenever a {@link Facet} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class FacetEvent extends VendureEntityEvent<Facet, FacetInputTypes> {
constructor(
ctx: RequestContext,
entity: Facet,
type: 'created' | 'updated' | 'deleted',
input?: FacetInputTypes,
) {
super(entity, type, ctx, input);
}
}
|
import {
CreateFacetValueInput,
CreateFacetValueWithFacetInput,
UpdateFacetValueInput,
} from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api';
import { FacetValue } from '../../entity';
import { VendureEntityEvent } from '../vendure-entity-event';
type FacetValueInputTypes =
| CreateFacetValueInput
| CreateFacetValueWithFacetInput
| UpdateFacetValueInput
| ID;
/**
* @description
* This event is fired whenever a {@link FacetValue} is added, updated or deleted.
*
* @docsCategory events
* @docsPage Event Types
* @since 1.4
*/
export class FacetValueEvent extends VendureEntityEvent<FacetValue, FacetValueInputTypes> {
constructor(
ctx: RequestContext,
entity: FacetValue,
type: 'created' | 'updated' | 'deleted',
input?: FacetValueInputTypes,
) {
super(entity, type, ctx, input);
}
}
|