content
stringlengths
28
1.34M
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { FulfillmentHandler } from './fulfillment-handler'; export const manualFulfillmentHandler = new FulfillmentHandler({ code: 'manual-fulfillment', description: [{ languageCode: LanguageCode.en, value: 'Manually enter fulfillment details' }], args: { method: { type: 'string', required: false, }, trackingCode: { type: 'string', required: false, }, }, createFulfillment: (ctx, orders, orderItems, args) => { return { method: args.method, trackingCode: args.trackingCode, }; }, });
import { JobListOptions } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { Job } from '../../job-queue'; import { JobQueueStrategy } from './job-queue-strategy'; /** * @description * Defines a job queue strategy that can be inspected using the default admin ui * * @docsCategory JobQueue */ export interface InspectableJobQueueStrategy extends JobQueueStrategy { /** * @description * Returns a job by its id. */ findOne(id: ID): Promise<Job | undefined>; /** * @description * Returns a list of jobs according to the specified options. */ findMany(options?: JobListOptions): Promise<PaginatedList<Job>>; /** * @description * Returns an array of jobs for the given ids. */ findManyById(ids: ID[]): Promise<Job[]>; /** * @description * Remove all settled jobs in the specified queues older than the given date. * If no queueName is passed, all queues will be considered. If no olderThan * date is passed, all jobs older than the current time will be removed. * * Returns a promise of the number of jobs removed. */ removeSettledJobs(queueNames?: string[], olderThan?: Date): Promise<number>; cancelJob(jobId: ID): Promise<Job | undefined>; } export function isInspectableJobQueueStrategy( strategy: JobQueueStrategy, ): strategy is InspectableJobQueueStrategy { return ( (strategy as InspectableJobQueueStrategy).findOne !== undefined && (strategy as InspectableJobQueueStrategy).findMany !== undefined && (strategy as InspectableJobQueueStrategy).findManyById !== undefined && (strategy as InspectableJobQueueStrategy).removeSettledJobs !== undefined ); }
import { JobListOptions } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { InjectableStrategy } from '../../common'; import { JobData, JobQueueStrategyJobOptions } from '../../job-queue'; import { Job } from '../../job-queue'; import { JobOptions } from '../../job-queue'; /** * @description * Defines how the jobs in the {@link JobQueueService} are persisted and * accessed. Custom strategies can be defined to make use of external * services such as Redis. * * :::info * * This is configured via the `jobQueueOptions.jobQueueStrategy` property of * your VendureConfig. * * ::: * * @docsCategory JobQueue */ export interface JobQueueStrategy extends InjectableStrategy { /** * @description * Add a new job to the queue. */ add<Data extends JobData<Data> = object>(job: Job<Data>, jobOptions?: JobQueueStrategyJobOptions<Data>): Promise<Job<Data>>; /** * @description * Start the job queue */ start<Data extends JobData<Data> = object>( queueName: string, process: (job: Job<Data>) => Promise<any>, ): Promise<void>; /** * @description * Stops a queue from running. Its not guaranteed to stop immediately. */ stop<Data extends JobData<Data> = object>( queueName: string, process: (job: Job<Data>) => Promise<any>, ): Promise<void>; }
import { afterEach, beforeEach, describe, expect, it, SpyInstance, vi } from 'vitest'; import { DefaultLogger } from './default-logger'; import { Logger, LogLevel } from './vendure-logger'; describe('DefaultLogger', () => { let stdOutSpy: SpyInstance; beforeEach(() => { stdOutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); }); afterEach(() => { stdOutSpy.mockRestore(); }); it('logLevel Debug', () => { const logger = new DefaultLogger({ level: LogLevel.Debug }); Logger.useLogger(logger); Logger.debug('AAAA'); expect(stdOutSpy).toHaveBeenCalledTimes(1); expect(stdOutSpy.mock.calls[0][0]).toContain('AAAA'); Logger.verbose('BBBB'); expect(stdOutSpy).toHaveBeenCalledTimes(2); expect(stdOutSpy.mock.calls[1][0]).toContain('BBBB'); Logger.info('CCCC'); expect(stdOutSpy).toHaveBeenCalledTimes(3); expect(stdOutSpy.mock.calls[2][0]).toContain('CCCC'); Logger.warn('DDDD'); expect(stdOutSpy).toHaveBeenCalledTimes(4); expect(stdOutSpy.mock.calls[3][0]).toContain('DDDD'); Logger.error('EEEE'); expect(stdOutSpy).toHaveBeenCalledTimes(5); expect(stdOutSpy.mock.calls[4][0]).toContain('EEEE'); }); it('logLevel Verbose', () => { const logger = new DefaultLogger({ level: LogLevel.Verbose }); Logger.useLogger(logger); Logger.debug('AAAA'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.verbose('BBBB'); expect(stdOutSpy).toHaveBeenCalledTimes(1); expect(stdOutSpy.mock.calls[0][0]).toContain('BBBB'); Logger.info('CCCC'); expect(stdOutSpy).toHaveBeenCalledTimes(2); expect(stdOutSpy.mock.calls[1][0]).toContain('CCCC'); Logger.warn('DDDD'); expect(stdOutSpy).toHaveBeenCalledTimes(3); expect(stdOutSpy.mock.calls[2][0]).toContain('DDDD'); Logger.error('EEEE'); expect(stdOutSpy).toHaveBeenCalledTimes(4); expect(stdOutSpy.mock.calls[3][0]).toContain('EEEE'); }); it('logLevel Info', () => { const logger = new DefaultLogger({ level: LogLevel.Info }); Logger.useLogger(logger); Logger.debug('AAAA'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.verbose('BBBB'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.info('CCCC'); expect(stdOutSpy).toHaveBeenCalledTimes(1); expect(stdOutSpy.mock.calls[0][0]).toContain('CCCC'); Logger.warn('DDDD'); expect(stdOutSpy).toHaveBeenCalledTimes(2); expect(stdOutSpy.mock.calls[1][0]).toContain('DDDD'); Logger.error('EEEE'); expect(stdOutSpy).toHaveBeenCalledTimes(3); expect(stdOutSpy.mock.calls[2][0]).toContain('EEEE'); }); it('logLevel Warn', () => { const logger = new DefaultLogger({ level: LogLevel.Warn }); Logger.useLogger(logger); Logger.debug('AAAA'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.verbose('BBBB'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.info('CCCC'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.warn('DDDD'); expect(stdOutSpy).toHaveBeenCalledTimes(1); expect(stdOutSpy.mock.calls[0][0]).toContain('DDDD'); Logger.error('EEEE'); expect(stdOutSpy).toHaveBeenCalledTimes(2); expect(stdOutSpy.mock.calls[1][0]).toContain('EEEE'); }); it('logLevel Error', () => { const logger = new DefaultLogger({ level: LogLevel.Error }); Logger.useLogger(logger); Logger.debug('AAAA'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.verbose('BBBB'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.info('CCCC'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.warn('DDDD'); expect(stdOutSpy).toHaveBeenCalledTimes(0); Logger.error('EEEE'); expect(stdOutSpy).toHaveBeenCalledTimes(1); expect(stdOutSpy.mock.calls[0][0]).toContain('EEEE'); }); });
import pc from 'picocolors'; import { Logger, LogLevel, VendureLogger } from './vendure-logger'; const DEFAULT_CONTEXT = 'Vendure Server'; /** * @description * The default logger, which logs to the console (stdout) with optional timestamps. Since this logger is part of the * default Vendure configuration, you do not need to specify it explicitly in your server config. You would only need * to specify it if you wish to change the log level (which defaults to `LogLevel.Info`) or remove the timestamp. * * @example * ```ts * import { DefaultLogger, LogLevel, VendureConfig } from '\@vendure/core'; * * export config: VendureConfig = { * // ... * logger: new DefaultLogger({ level: LogLevel.Debug, timestamp: false }), * } * ``` * * @docsCategory Logger */ export class DefaultLogger implements VendureLogger { /** @internal */ level: LogLevel = LogLevel.Info; private readonly timestamp: boolean; private defaultContext = DEFAULT_CONTEXT; private readonly localeStringOptions = { year: '2-digit', hour: 'numeric', minute: 'numeric', day: 'numeric', month: 'numeric', } as const; private static originalLogLevel: LogLevel; constructor(options?: { level?: LogLevel; timestamp?: boolean }) { this.level = options && options.level != null ? options.level : LogLevel.Info; this.timestamp = options && options.timestamp !== undefined ? options.timestamp : true; } /** * @description * A work-around to hide the info-level logs generated by Nest when bootstrapping the AppModule. * To be run directly before the `NestFactory.create()` call in the `bootstrap()` function. * * See https://github.com/nestjs/nest/issues/1838 * @internal */ static hideNestBoostrapLogs(): void { const { logger } = Logger; if (logger instanceof DefaultLogger) { if (logger.level === LogLevel.Info) { this.originalLogLevel = LogLevel.Info; logger.level = LogLevel.Warn; } } } /** * @description * If the log level was changed by `hideNestBoostrapLogs()`, this method will restore the * original log level. To be run directly after the `NestFactory.create()` call in the * `bootstrap()` function. * * See https://github.com/nestjs/nest/issues/1838 * @internal */ static restoreOriginalLogLevel(): void { const { logger } = Logger; if (logger instanceof DefaultLogger && DefaultLogger.originalLogLevel !== undefined) { logger.level = DefaultLogger.originalLogLevel; } } setDefaultContext(defaultContext: string) { this.defaultContext = defaultContext; } error(message: string, context?: string, trace?: string | undefined): void { if (context === 'ExceptionsHandler' && this.level < LogLevel.Verbose) { // In Nest v7, there is an ExternalExceptionFilter which catches *all* // errors and logs them, no matter the LogLevel attached to the error. // This results in overly-noisy logger output (e.g. a failed login attempt // will log a full stack trace). This check means we only let it log if // we are in Verbose or Debug mode. return; } if (this.level >= LogLevel.Error) { this.logMessage( pc.red('error'), pc.red(this.ensureString(message) + (trace ? `\n${trace}` : '')), context, ); } } warn(message: string, context?: string): void { if (this.level >= LogLevel.Warn) { this.logMessage(pc.yellow('warn'), pc.yellow(this.ensureString(message)), context); } } info(message: string, context?: string): void { if (this.level >= LogLevel.Info) { this.logMessage(pc.blue('info'), this.ensureString(message), context); } } verbose(message: string, context?: string): void { if (this.level >= LogLevel.Verbose) { this.logMessage(pc.magenta('verbose'), this.ensureString(message), context); } } debug(message: string, context?: string): void { if (this.level >= LogLevel.Debug) { this.logMessage(pc.magenta('debug'), this.ensureString(message), context); } } private logMessage(prefix: string, message: string, context?: string) { process.stdout.write( [prefix, this.logTimestamp(), this.logContext(context), message, '\n'].join(' '), ); } private logContext(context?: string) { return pc.cyan(`[${context || this.defaultContext}]`); } private logTimestamp() { if (this.timestamp) { const timestamp = new Date(Date.now()).toLocaleString(undefined, this.localeStringOptions); return pc.gray(timestamp + ' -'); } else { return ''; } } private ensureString(message: string | object | any[]): string { return typeof message === 'string' ? message : JSON.stringify(message, null, 2); } }
import { VendureLogger } from './vendure-logger'; /** * A logger that does not log. */ export class NoopLogger implements VendureLogger { debug(message: string, context?: string): void { // noop! } error(message: string, context?: string, trace?: string): void { // noop! } info(message: string, context?: string): void { // noop! } verbose(message: string, context?: string): void { // noop! } warn(message: string, context?: string): void { // noop! } }
import { Logger as TypeOrmLoggerInterface, QueryRunner } from 'typeorm'; import { LoggerOptions } from 'typeorm/logger/LoggerOptions'; import { Logger } from './vendure-logger'; const context = 'TypeORM'; type typeOrmLogLevel = Exclude<LoggerOptions, 'all' | boolean>[number]; const defaultLoggerOptions: LoggerOptions = ['error', 'warn', 'schema', 'migration']; /** * A custom logger for TypeORM which delegates to the Vendure Logger service. */ export class TypeOrmLogger implements TypeOrmLoggerInterface { constructor(private options: LoggerOptions = defaultLoggerOptions) {} log(level: 'log' | 'info' | 'warn', message: any, queryRunner?: QueryRunner): any { switch (level) { case 'info': if (this.shouldDisplay('info')) { Logger.info(message, context); } break; case 'log': if (this.shouldDisplay('log')) { Logger.info(message, context); } break; case 'warn': if (this.shouldDisplay('warn')) { Logger.warn(message, context); } break; } } logMigration(message: string, queryRunner?: QueryRunner): any { Logger.info(message, context); } logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): any { if (this.shouldDisplay('query')) { const sql = this.formatQueryWithParams(query, parameters); Logger.debug(`Query: ${sql}`, context); } } logQueryError(error: string, query: string, parameters?: any[], queryRunner?: QueryRunner): any { if (this.shouldDisplay('error')) { const sql = this.formatQueryWithParams(query, parameters); Logger.error(`Query error: ${sql}`, context); Logger.verbose(error, context); } } logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner): any { const sql = this.formatQueryWithParams(query, parameters); Logger.warn('Query is slow: ' + sql); Logger.warn('Execution time: ' + time.toString()); } logSchemaBuild(message: string, queryRunner?: QueryRunner): any { if (this.shouldDisplay('schema')) { Logger.info(message, context); } } private shouldDisplay(logType: typeOrmLogLevel): boolean { return ( this.options === 'all' || this.options === true || (Array.isArray(this.options) && this.options.includes(logType)) ); } private formatQueryWithParams(query: string, parameters?: any[]) { return ( query + (parameters?.length ? ' -- PARAMETERS: ' + this.stringifyParams(parameters).toString() : '') ); } /** * Converts parameters to a string. * Sometimes parameters can have circular objects and therefor we are handle this case too. */ private stringifyParams(parameters: any[]) { try { return JSON.stringify(parameters); } catch (error) { // most probably circular objects in parameters return parameters; } } }
import { LoggerService } from '@nestjs/common'; /** * @description * An enum of valid logging levels. * * @docsCategory Logger */ export enum LogLevel { /** * @description * Log Errors only. These are usually indicative of some potentially * serious issue, so should be acted upon. */ Error = 0, /** * @description * Warnings indicate that some situation may require investigation * and handling. But not as serious as an Error. */ Warn = 1, /** * @description * Logs general information such as startup messages. */ Info = 2, /** * @description * Logs additional information */ Verbose = 3, /** * @description * Logs detailed info useful in debug scenarios, including stack traces for * all errors. In production this would probably generate too much noise. */ Debug = 4, } /** * @description * The VendureLogger interface defines the shape of a logger service which may be provided in * the config. * * @docsCategory Logger */ export interface VendureLogger { error(message: string, context?: string, trace?: string): void; warn(message: string, context?: string): void; info(message: string, context?: string): void; verbose(message: string, context?: string): void; debug(message: string, context?: string): void; setDefaultContext?(defaultContext: string): void; } const noopLogger: VendureLogger = { error() { /* */ }, warn() { /* */ }, info() { /* */ }, verbose() { /* */ }, debug() { /* */ }, }; /** * @description * The Logger is responsible for all logging in a Vendure application. * * It is intended to be used as a static class: * * @example * ```ts * import { Logger } from '\@vendure/core'; * * Logger.info(`Some log message`, 'My Vendure Plugin'); * ``` * * The actual implementation - where the logs are written to - is defined by the {@link VendureLogger} * instance configured in the {@link VendureConfig}. By default, the {@link DefaultLogger} is used, which * logs to the console. * * ## Implementing a custom logger * * A custom logger can be passed to the `logger` config option by creating a class which implements the * {@link VendureLogger} interface. For example, here is how you might go about implementing a logger which * logs to a file: * * @example * ```ts * import { VendureLogger } from '\@vendure/core'; * import fs from 'fs'; * * // A simple custom logger which writes all logs to a file. * export class SimpleFileLogger implements VendureLogger { * private logfile: fs.WriteStream; * * constructor(logfileLocation: string) { * this.logfile = fs.createWriteStream(logfileLocation, { flags: 'w' }); * } * * error(message: string, context?: string) { * this.logfile.write(`ERROR: [${context}] ${message}\n`); * } * warn(message: string, context?: string) { * this.logfile.write(`WARN: [${context}] ${message}\n`); * } * info(message: string, context?: string) { * this.logfile.write(`INFO: [${context}] ${message}\n`); * } * verbose(message: string, context?: string) { * this.logfile.write(`VERBOSE: [${context}] ${message}\n`); * } * debug(message: string, context?: string) { * this.logfile.write(`DEBUG: [${context}] ${message}\n`); * } * } * * // in the VendureConfig * export const config = { * // ... * logger: new SimpleFileLogger('server.log'), * } * ``` * * @docsCategory Logger */ export class Logger implements LoggerService { private static _instance: typeof Logger = Logger; private static _logger: VendureLogger; static get logger(): VendureLogger { return this._logger || noopLogger; } private get instance(): typeof Logger { const { _instance } = Logger; return _instance; } /** @internal */ static useLogger(logger: VendureLogger) { Logger._logger = logger; } /** @internal */ error(message: any, trace?: string, context?: string): any { this.instance.error(message, context, trace); } /** @internal */ warn(message: any, context?: string): any { this.instance.warn(message, context); } /** @internal */ log(message: any, context?: string): any { this.instance.info(message, context); } /** @internal */ verbose(message: any, context?: string): any { this.instance.verbose(message, context); } /** @internal */ debug(message: any, context?: string): any { this.instance.debug(message, context); } static error(message: string, context?: string, trace?: string): void { Logger.logger.error(message, context, trace); } static warn(message: string, context?: string): void { Logger.logger.warn(message, context); } static info(message: string, context?: string): void { Logger.logger.info(message, context); } static verbose(message: string, context?: string): void { Logger.logger.verbose(message, context); } static debug(message: string, context?: string): void { Logger.logger.debug(message, context); } }
import { DocumentNode } from 'graphql'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; export const ACTIVE_ORDER_INPUT_FIELD_NAME = 'activeOrderInput'; /** * @description * This strategy is used to determine the active Order for all order-related operations in * the Shop API. By default, all the Shop API operations that relate to the active Order (e.g. * `activeOrder`, `addItemToOrder`, `applyCouponCode` etc.) will implicitly create a new Order * and set it on the current Session, and then read the session to obtain the active Order. * This behaviour is defined by the {@link DefaultActiveOrderStrategy}. * * The `InputType` generic argument should correspond to the input type defined by the * `defineInputType()` method. * * When `defineInputType()` is used, then the following Shop API operations will receive an additional * `activeOrderInput` argument allowing the active order input to be specified: * * - `activeOrder` * - `eligibleShippingMethods` * - `eligiblePaymentMethods` * - `nextOrderStates` * - `addItemToOrder` * - `adjustOrderLine` * - `removeOrderLine` * - `removeAllOrderLines` * - `applyCouponCode` * - `removeCouponCode` * - `addPaymentToOrder` * - `setCustomerForOrder` * - `setOrderShippingAddress` * - `setOrderBillingAddress` * - `setOrderShippingMethod` * - `setOrderCustomFields` * - `transitionOrderToState` * * @example * ```GraphQL {hl_lines=[5]} * mutation AddItemToOrder { * addItemToOrder( * productVariantId: 42, * quantity: 1, * activeOrderInput: { token: "123456" } * ) { * ...on Order { * id * # ...etc * } * } * } * ``` * * @example * ```ts * import { ID } from '\@vendure/common/lib/shared-types'; * import { * ActiveOrderStrategy, * CustomerService, * idsAreEqual, * Injector, * Order, * OrderService, * RequestContext, * TransactionalConnection, * } from '\@vendure/core'; * import gql from 'graphql-tag'; * * // This strategy assumes a "orderToken" custom field is defined on the Order * // entity, and uses that token to perform a lookup to determine the active Order. * // * // Additionally, it does _not_ define a `createActiveOrder()` method, which * // means that a custom mutation would be required to create the initial Order in * // the first place and set the "orderToken" custom field. * class TokenActiveOrderStrategy implements ActiveOrderStrategy<{ token: string }> { * readonly name = 'orderToken'; * * private connection: TransactionalConnection; * private orderService: OrderService; * * init(injector: Injector) { * this.connection = injector.get(TransactionalConnection); * this.orderService = injector.get(OrderService); * } * * defineInputType = () => gql` * input OrderTokenActiveOrderInput { * token: String * } * `; * * async determineActiveOrder(ctx: RequestContext, input: { token: string }) { * const qb = this.connection * .getRepository(ctx, Order) * .createQueryBuilder('order') * .leftJoinAndSelect('order.customer', 'customer') * .leftJoinAndSelect('customer.user', 'user') * .where('order.customFields.orderToken = :orderToken', { orderToken: input.token }); * * const order = await qb.getOne(); * if (!order) { * return; * } * // Ensure the active user is the owner of this Order * const orderUserId = order.customer && order.customer.user && order.customer.user.id; * if (order.customer && idsAreEqual(orderUserId, ctx.activeUserId)) { * return order; * } * } * } * * // in vendure-config.ts * export const config = { * // ... * orderOptions: { * activeOrderStrategy: new TokenActiveOrderStrategy(), * }, * } * ``` * * @since 1.9.0 * @docsCategory orders */ export interface ActiveOrderStrategy<InputType extends Record<string, any> | void = void> extends InjectableStrategy { /** * @description * The name of the strategy, e.g. "orderByToken", which will also be used as the * field name in the ActiveOrderInput type. */ readonly name: string; /** * @description * Defines the type of the GraphQL Input object expected by the `activeOrderInput` * input argument. * * @example * For example, given the following: * * ```ts * defineInputType() { * return gql` * input OrderTokenInput { * token: String! * } * `; * } * ``` * * assuming the strategy name is "orderByToken", then the resulting call to `activeOrder` (or any of the other * affected Shop API operations) would look like: * * ```GraphQL * activeOrder(activeOrderInput: { * orderByToken: { * token: "foo" * } * }) { * # ... * } * ``` * * **Note:** if more than one graphql `input` type is being defined (as in a nested input type), then * the _first_ input will be assumed to be the top-level input. */ defineInputType?: () => DocumentNode; /** * @description * Certain mutations such as `addItemToOrder` can automatically create a new Order if one does not exist. * In these cases, this method will be called to create the new Order. * * If automatic creation of an Order does not make sense in your strategy, then leave this method * undefined. You'll then need to take care of creating an order manually by defining a custom mutation. */ createActiveOrder?: (ctx: RequestContext, input: InputType) => Promise<Order>; /** * @description * This method is used to determine the active Order based on the current RequestContext in addition to any * input values provided, as defined by the `defineInputType` method of this strategy. * * Note that this method is invoked frequently, so you should aim to keep it efficient. The returned Order, * for example, does not need to have its various relations joined. */ determineActiveOrder(ctx: RequestContext, input: InputType): Promise<Order | undefined>; }
import { RequestContext } from '../../api/common/request-context'; import { PriceCalculationResult } from '../../common/types/common-types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; /** * @description * This strategy defines how we handle the situation where an item exists in an Order, and * then later on another is added but in the meantime the price of the ProductVariant has changed. * * By default, the latest price will be used. Any price changes resulting from using a newer price * will be reflected in the GraphQL `OrderLine.unitPrice[WithTax]ChangeSinceAdded` field. * * :::info * * This is configured via the `orderOptions.changedPriceHandlingStrategy` property of * your VendureConfig. * * ::: * * @docsCategory orders */ export interface ChangedPriceHandlingStrategy extends InjectableStrategy { /** * @description * This method is called when adding to or adjusting OrderLines, if the latest price * (as determined by the ProductVariant price, potentially modified by the configured * {@link OrderItemPriceCalculationStrategy}) differs from the initial price at the time * that the OrderLine was created. */ handlePriceChange( ctx: RequestContext, current: PriceCalculationResult, orderLine: OrderLine, order: Order, ): PriceCalculationResult | Promise<PriceCalculationResult>; }
import { RequestContext } from '../../api/common/request-context'; import { InternalServerError } from '../../common/error/errors'; import { Injector } from '../../common/injector'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Order } from '../../entity/order/order.entity'; import { ActiveOrderStrategy } from './active-order-strategy'; /** * @description * The default {@link ActiveOrderStrategy}, which uses the current {@link Session} to determine * the active Order, and requires no additional input in the Shop API since it is based on the * session which is part of the RequestContext. * * @since 1.9.0 * @docsCategory orders */ export class DefaultActiveOrderStrategy implements ActiveOrderStrategy { private connection: TransactionalConnection; private orderService: import('../../service/services/order.service').OrderService; private sessionService: import('../../service/services/session.service').SessionService; name: 'default-active-order-strategy'; async init(injector: Injector) { this.connection = injector.get(TransactionalConnection); // Lazy import these dependencies to avoid a circular dependency issue in NestJS. const { OrderService } = await import('../../service/services/order.service.js'); const { SessionService } = await import('../../service/services/session.service.js'); this.orderService = injector.get(OrderService); this.sessionService = injector.get(SessionService); } createActiveOrder(ctx: RequestContext) { return this.orderService.create(ctx, ctx.activeUserId); } async determineActiveOrder(ctx: RequestContext) { if (!ctx.session) { throw new InternalServerError('error.no-active-session'); } let order = ctx.session.activeOrderId ? await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .leftJoin('order.channels', 'channel') .where('order.id = :orderId', { orderId: ctx.session.activeOrderId }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .getOne() : undefined; if (order && order.active === false) { // edge case where an inactive order may not have been // removed from the session, i.e. the regular process was interrupted await this.sessionService.unsetActiveOrder(ctx, ctx.session); order = undefined; } if (!order) { if (ctx.activeUserId) { order = await this.orderService.getActiveOrderForUser(ctx, ctx.activeUserId); } } return order || undefined; } }
import { RequestContext } from '../../api/common/request-context'; import { PriceCalculationResult } from '../../common/types/common-types'; import { ChangedPriceHandlingStrategy } from './changed-price-handling-strategy'; /** * @description * The default {@link ChangedPriceHandlingStrategy} will always use the latest price when * updating existing OrderLines. */ export class DefaultChangedPriceHandlingStrategy implements ChangedPriceHandlingStrategy { handlePriceChange(ctx: RequestContext, current: PriceCalculationResult): PriceCalculationResult { return current; } }
import { CreateCustomerInput, SetCustomerForOrderResult } from '@vendure/common/lib/generated-shop-types'; import { RequestContext } from '../../api/common/request-context'; import { ErrorResultUnion } from '../../common/error/error-result'; import { AlreadyLoggedInError, GuestCheckoutError } from '../../common/error/generated-graphql-shop-errors'; import { Injector } from '../../common/injector'; import { Customer, Order } from '../../entity/index'; import { CustomerService } from '../../service/services/customer.service'; import { GuestCheckoutStrategy } from './guest-checkout-strategy'; /** * @description * Options available for the {@link DefaultGuestCheckoutStrategy}. * * @docsCategory orders * @docsPage DefaultGuestCheckoutStrategy * @since 2.0.0 */ export interface DefaultGuestCheckoutStrategyOptions { /** * @description * Whether to allow guest checkouts. * * @default true */ allowGuestCheckouts?: boolean; /** * @description * Whether to allow guest checkouts for customers who already have an account. * Note that when this is enabled, the details provided in the `CreateCustomerInput` * will overwrite the existing customer details of the registered customer. * * @default false */ allowGuestCheckoutForRegisteredCustomers?: boolean; } /** * @description * The default implementation of the {@link GuestCheckoutStrategy}. This strategy allows * guest checkouts by default, but can be configured to disallow them. * * @example * ```ts * import { DefaultGuestCheckoutStrategy, VendureConfig } from '\@vendure/core'; * * export const config: VendureConfig = { * orderOptions: { * guestCheckoutStrategy: new DefaultGuestCheckoutStrategy({ * allowGuestCheckouts: false, * allowGuestCheckoutForRegisteredCustomers: false, * }), * }, * // ... * }; * ``` * * @docsCategory orders * @docsPage DefaultGuestCheckoutStrategy * @docsWeight 0 * @since 2.0.0 */ export class DefaultGuestCheckoutStrategy implements GuestCheckoutStrategy { private customerService: CustomerService; private readonly options: Required<DefaultGuestCheckoutStrategyOptions> = { allowGuestCheckouts: true, allowGuestCheckoutForRegisteredCustomers: false, }; init(injector: Injector) { this.customerService = injector.get(CustomerService); } constructor(options?: DefaultGuestCheckoutStrategyOptions) { this.options = { ...this.options, ...(options ?? {}), }; } async setCustomerForOrder( ctx: RequestContext, order: Order, input: CreateCustomerInput, ): Promise<ErrorResultUnion<SetCustomerForOrderResult, Customer>> { if (!this.options.allowGuestCheckouts) { return new GuestCheckoutError({ errorDetail: 'Guest checkouts are disabled' }); } if (ctx.activeUserId) { return new AlreadyLoggedInError(); } const errorOnExistingUser = !this.options.allowGuestCheckoutForRegisteredCustomers; const customer = await this.customerService.createOrUpdate(ctx, input, errorOnExistingUser); return customer; } }
import { RequestContext } from '../../api/common/request-context'; import { PriceCalculationResult } from '../../common/types/common-types'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { OrderItemPriceCalculationStrategy } from './order-item-price-calculation-strategy'; /** * @description * The default {@link OrderItemPriceCalculationStrategy}, which simply passes through the price of * the ProductVariant without performing any calculations * * @docsCategory orders */ export class DefaultOrderItemPriceCalculationStrategy implements OrderItemPriceCalculationStrategy { calculateUnitPrice( ctx: RequestContext, productVariant: ProductVariant, ): PriceCalculationResult | Promise<PriceCalculationResult> { return { price: productVariant.listPrice, priceIncludesTax: productVariant.listPriceIncludesTax, }; } }
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; import { OrderPlacedStrategy } from './order-placed-strategy'; /** * @description * The default {@link OrderPlacedStrategy}. The order is set as "placed" when it transitions from * 'ArrangingPayment' to either 'PaymentAuthorized' or 'PaymentSettled'. * * @docsCategory orders */ export class DefaultOrderPlacedStrategy implements OrderPlacedStrategy { shouldSetAsPlaced( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean { return fromState === 'ArrangingPayment' && (toState === 'PaymentAuthorized' || toState === 'PaymentSettled') ? true : false; } }
import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { RequestContext } from '../../api/common/request-context'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { OrderModification } from '../../entity/order-modification/order-modification.entity'; import { Payment } from '../../entity/payment/payment.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { OrderPlacedEvent } from '../../event-bus/events/order-placed-event'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; import { orderItemsAreDelivered, orderItemsArePartiallyDelivered, orderItemsArePartiallyShipped, orderItemsAreShipped, orderLinesAreAllCancelled, orderTotalIsCovered, totalCoveredByPayments, } from '../../service/helpers/utils/order-utils'; import { OrderProcess } from './order-process'; declare module '../../service/helpers/order-state-machine/order-state' { interface OrderStates { ArrangingPayment: never; PaymentAuthorized: never; PaymentSettled: never; PartiallyShipped: never; Shipped: never; PartiallyDelivered: never; Delivered: never; Modifying: never; ArrangingAdditionalPayment: never; } } /** * @description * Options which can be passed to the {@link configureDefaultOrderProcess} function * to configure an instance of the default {@link OrderProcess}. By default, all * options are set to `true`. * * @docsCategory Orders * @docsPage OrderProcess * @since 2.0.0 */ export interface DefaultOrderProcessOptions { /** * @description * Prevents an Order from transitioning out of the `Modifying` state if * the Order price has changed and there is no Payment or Refund associated * with the Modification. * * @default true */ checkModificationPayments?: boolean; /** * @description * Prevents an Order from transitioning out of the `ArrangingAdditionalPayment` state if * the Order's Payments do not cover the full amount of `totalWithTax`. * * @default true */ checkAdditionalPaymentsAmount?: boolean; /** * @description * Prevents the transition from `AddingItems` to any other state (apart from `Cancelled`) if * and of the ProductVariants no longer exists due to deletion. * * @default true */ checkAllVariantsExist?: boolean; /** * @description * Prevents transition to the `ArrangingPayment` state if the active Order has no lines. * * @default true */ arrangingPaymentRequiresContents?: boolean; /** * @description * Prevents transition to the `ArrangingPayment` state if the active Order has no customer * associated with it. * * @default true */ arrangingPaymentRequiresCustomer?: boolean; /** * @description * Prevents transition to the `ArrangingPayment` state if the active Order has no shipping * method set. * * @default true */ arrangingPaymentRequiresShipping?: boolean; /** * @description * Prevents transition to the `ArrangingPayment` state if there is insufficient saleable * stock to cover the contents of the Order. * * @default true */ arrangingPaymentRequiresStock?: boolean; /** * @description * Prevents transition to the `PaymentAuthorized` or `PaymentSettled` states if the order * `totalWithTax` amount is not covered by Payment(s) in the corresponding states. * * @default true */ checkPaymentsCoverTotal?: boolean; /** * @description * Prevents transition to the `Cancelled` state unless all OrderItems are already * cancelled. * * @default true */ checkAllItemsBeforeCancel?: boolean; /** * @description * Prevents transition to the `Shipped`, `PartiallyShipped`, `Delivered` & `PartiallyDelivered` states unless * there are corresponding Fulfillments in the correct states to allow this. E.g. `Shipped` only if all items in * the Order are part of a Fulfillment which itself is in the `Shipped` state. * * @default true */ checkFulfillmentStates?: boolean; } /** * @description * Used to configure a customized instance of the default {@link OrderProcess} that ships with Vendure. * Using this function allows you to turn off certain checks and constraints that are enabled by default. * * ```ts * import { configureDefaultOrderProcess, VendureConfig } from '\@vendure/core'; * * const myCustomOrderProcess = configureDefaultOrderProcess({ * // Disable the constraint that requires * // Orders to have a shipping method assigned * // before payment. * arrangingPaymentRequiresShipping: false, * }); * * export const config: VendureConfig = { * orderOptions: { * process: [myCustomOrderProcess], * }, * }; * ``` * The {@link DefaultOrderProcessOptions} type defines all available options. If you require even * more customization, you can create your own implementation of the {@link OrderProcess} interface. * * * @docsCategory Orders * @docsPage OrderProcess * @since 2.0.0 */ export function configureDefaultOrderProcess(options: DefaultOrderProcessOptions) { let connection: TransactionalConnection; let productVariantService: import('../../service/index').ProductVariantService; let configService: import('../config.service').ConfigService; let eventBus: import('../../event-bus/index').EventBus; let stockMovementService: import('../../service/index').StockMovementService; let stockLevelService: import('../../service/index').StockLevelService; let historyService: import('../../service/index').HistoryService; let orderSplitter: import('../../service/index').OrderSplitter; const orderProcess: OrderProcess<OrderState> = { transitions: { Created: { to: ['AddingItems', 'Draft'], }, Draft: { to: ['Cancelled', 'ArrangingPayment'], }, AddingItems: { to: ['ArrangingPayment', 'Cancelled'], }, ArrangingPayment: { to: ['PaymentAuthorized', 'PaymentSettled', 'AddingItems', 'Cancelled'], }, PaymentAuthorized: { to: ['PaymentSettled', 'Cancelled', 'Modifying', 'ArrangingAdditionalPayment'], }, PaymentSettled: { to: [ 'PartiallyDelivered', 'Delivered', 'PartiallyShipped', 'Shipped', 'Cancelled', 'Modifying', 'ArrangingAdditionalPayment', ], }, PartiallyShipped: { to: ['Shipped', 'PartiallyDelivered', 'Cancelled', 'Modifying'], }, Shipped: { to: ['PartiallyDelivered', 'Delivered', 'Cancelled', 'Modifying'], }, PartiallyDelivered: { to: ['Delivered', 'Cancelled', 'Modifying'], }, Delivered: { to: ['Cancelled'], }, Modifying: { to: [ 'PaymentAuthorized', 'PaymentSettled', 'PartiallyShipped', 'Shipped', 'PartiallyDelivered', 'ArrangingAdditionalPayment', ], }, ArrangingAdditionalPayment: { to: [ 'PaymentAuthorized', 'PaymentSettled', 'PartiallyShipped', 'Shipped', 'PartiallyDelivered', 'Cancelled', ], }, Cancelled: { to: [], }, }, async init(injector) { // Lazily import these services to avoid a circular dependency error // due to this being used as part of the DefaultConfig const ConfigService = await import('../config.service.js').then(m => m.ConfigService); const EventBus = await import('../../event-bus/index.js').then(m => m.EventBus); const StockMovementService = await import('../../service/index.js').then( m => m.StockMovementService, ); const StockLevelService = await import('../../service/index.js').then(m => m.StockLevelService); const HistoryService = await import('../../service/index.js').then(m => m.HistoryService); const OrderSplitter = await import('../../service/index.js').then(m => m.OrderSplitter); const ProductVariantService = await import('../../service/index.js').then( m => m.ProductVariantService, ); connection = injector.get(TransactionalConnection); productVariantService = injector.get(ProductVariantService); configService = injector.get(ConfigService); eventBus = injector.get(EventBus); stockMovementService = injector.get(StockMovementService); stockLevelService = injector.get(StockLevelService); historyService = injector.get(HistoryService); orderSplitter = injector.get(OrderSplitter); }, async onTransitionStart(fromState, toState, { ctx, order }) { if (options.checkModificationPayments !== false && fromState === 'Modifying') { const modifications = await connection .getRepository(ctx, OrderModification) .find({ where: { order: { id: order.id } }, relations: ['refund', 'payment'] }); if (toState === 'ArrangingAdditionalPayment') { if ( 0 < modifications.length && modifications.every(modification => modification.isSettled) ) { return 'message.cannot-transition-no-additional-payments-needed'; } } else { if (modifications.some(modification => !modification.isSettled)) { return 'message.cannot-transition-without-modification-payment'; } } } if ( options.checkAdditionalPaymentsAmount !== false && fromState === 'ArrangingAdditionalPayment' ) { if (toState === 'Cancelled') { return; } const existingPayments = await connection.getRepository(ctx, Payment).find({ relations: ['refunds'], where: { order: { id: order.id }, }, }); order.payments = existingPayments; const deficit = order.totalWithTax - totalCoveredByPayments(order); if (0 < deficit) { return 'message.cannot-transition-from-arranging-additional-payment'; } } if ( options.checkAllVariantsExist !== false && fromState === 'AddingItems' && toState !== 'Cancelled' && order.lines.length > 0 ) { const variantIds = unique(order.lines.map(l => l.productVariant.id)); const qb = connection .getRepository(ctx, ProductVariant) .createQueryBuilder('variant') .leftJoin('variant.product', 'product') .where('variant.deletedAt IS NULL') .andWhere('product.deletedAt IS NULL') .andWhere('variant.id IN (:...variantIds)', { variantIds }); const availableVariants = await qb.getMany(); if (availableVariants.length !== variantIds.length) { return 'message.cannot-transition-order-contains-products-which-are-unavailable'; } } if (toState === 'ArrangingPayment') { if (options.arrangingPaymentRequiresContents !== false && order.lines.length === 0) { return 'message.cannot-transition-to-payment-when-order-is-empty'; } if (options.arrangingPaymentRequiresCustomer !== false && !order.customer) { return 'message.cannot-transition-to-payment-without-customer'; } if ( options.arrangingPaymentRequiresShipping !== false && (!order.shippingLines || order.shippingLines.length === 0) ) { return 'message.cannot-transition-to-payment-without-shipping-method'; } if (options.arrangingPaymentRequiresStock !== false) { const variantsWithInsufficientSaleableStock: ProductVariant[] = []; for (const line of order.lines) { const availableStock = await productVariantService.getSaleableStockLevel( ctx, line.productVariant, ); if (line.quantity > availableStock) { variantsWithInsufficientSaleableStock.push(line.productVariant); } } if (variantsWithInsufficientSaleableStock.length) { return ctx.translate( 'message.cannot-transition-to-payment-due-to-insufficient-stock', { productVariantNames: variantsWithInsufficientSaleableStock .map(v => v.name) .join(', '), }, ); } } } if (options.checkPaymentsCoverTotal !== false) { if (toState === 'PaymentAuthorized') { const hasAnAuthorizedPayment = !!order.payments.find(p => p.state === 'Authorized'); if (!orderTotalIsCovered(order, ['Authorized', 'Settled']) || !hasAnAuthorizedPayment) { return 'message.cannot-transition-without-authorized-payments'; } } if (toState === 'PaymentSettled' && !orderTotalIsCovered(order, 'Settled')) { return 'message.cannot-transition-without-settled-payments'; } } if (options.checkAllItemsBeforeCancel !== false) { if ( toState === 'Cancelled' && fromState !== 'AddingItems' && fromState !== 'ArrangingPayment' ) { if (!orderLinesAreAllCancelled(order)) { return 'message.cannot-transition-unless-all-cancelled'; } } } if (options.checkFulfillmentStates !== false) { if (toState === 'PartiallyShipped') { const orderWithFulfillments = await findOrderWithFulfillments(ctx, order.id); if (!orderItemsArePartiallyShipped(orderWithFulfillments)) { return 'message.cannot-transition-unless-some-order-items-shipped'; } } if (toState === 'Shipped') { const orderWithFulfillments = await findOrderWithFulfillments(ctx, order.id); if (!orderItemsAreShipped(orderWithFulfillments)) { return 'message.cannot-transition-unless-all-order-items-shipped'; } } if (toState === 'PartiallyDelivered') { const orderWithFulfillments = await findOrderWithFulfillments(ctx, order.id); if (!orderItemsArePartiallyDelivered(orderWithFulfillments)) { return 'message.cannot-transition-unless-some-order-items-delivered'; } } if (toState === 'Delivered') { const orderWithFulfillments = await findOrderWithFulfillments(ctx, order.id); if (!orderItemsAreDelivered(orderWithFulfillments)) { return 'message.cannot-transition-unless-all-order-items-delivered'; } } } }, async onTransitionEnd(fromState, toState, data) { const { ctx, order } = data; const { stockAllocationStrategy, orderPlacedStrategy } = configService.orderOptions; if (order.active) { const shouldSetAsPlaced = orderPlacedStrategy.shouldSetAsPlaced( ctx, fromState, toState, order, ); if (shouldSetAsPlaced) { order.active = false; order.orderPlacedAt = new Date(); await Promise.all( order.lines.map(line => { line.orderPlacedQuantity = line.quantity; return connection .getRepository(ctx, OrderLine) .update(line.id, { orderPlacedQuantity: line.quantity }); }), ); await eventBus.publish(new OrderPlacedEvent(fromState, toState, ctx, order)); await orderSplitter.createSellerOrders(ctx, order); } } const shouldAllocateStock = await stockAllocationStrategy.shouldAllocateStock( ctx, fromState, toState, order, ); if (shouldAllocateStock) { await stockMovementService.createAllocationsForOrder(ctx, order); } if (toState === 'Cancelled') { order.active = false; } if (fromState === 'Draft' && toState === 'ArrangingPayment') { // Once we exit the Draft state, we can consider the order active, // which will allow us to run the OrderPlacedStrategy at the correct point. order.active = true; } await historyService.createHistoryEntryForOrder({ orderId: order.id, type: HistoryEntryType.ORDER_STATE_TRANSITION, ctx, data: { from: fromState, to: toState, }, }); }, }; async function findOrderWithFulfillments(ctx: RequestContext, id: ID): Promise<Order> { return await connection.getEntityOrThrow(ctx, Order, id, { relations: ['lines', 'fulfillments', 'fulfillments.lines', 'fulfillments.lines.fulfillment'], }); } return orderProcess; } /** * @description * This is the built-in {@link OrderProcess} that ships with Vendure. A customized version of this process * can be created using the {@link configureDefaultOrderProcess} function, which allows you to pass in an object * to enable/disable certain checks. * * @docsCategory Orders * @docsPage OrderProcess * @since 2.0.0 */ export const defaultOrderProcess = configureDefaultOrderProcess({});
import { OrderSellerStrategy } from './order-seller-strategy'; /** * @description * The DefaultOrderSellerStrategy treats the Order as single-vendor. * * @since 2.0.0 * @docsCategory orders * @docsPage OrderSellerStrategy */ export class DefaultOrderSellerStrategy implements OrderSellerStrategy { // By default, Orders will not get split. }
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; import { StockAllocationStrategy } from './stock-allocation-strategy'; /** * @description * Allocates stock when the Order transitions from `ArrangingPayment` to either * `PaymentAuthorized` or `PaymentSettled`. * * @docsCategory orders */ export class DefaultStockAllocationStrategy implements StockAllocationStrategy { shouldAllocateStock( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean | Promise<boolean> { return ( fromState === 'ArrangingPayment' && (toState === 'PaymentAuthorized' || toState === 'PaymentSettled') ); } }
import { CreateCustomerInput, SetCustomerForOrderResult } from '@vendure/common/lib/generated-shop-types'; import { RequestContext } from '../../api/common/request-context'; import { ErrorResultUnion } from '../../common/error/error-result'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Customer } from '../../entity/customer/customer.entity'; import { Order } from '../../entity/order/order.entity'; /** * @description * A strategy that determines how to deal with guest checkouts - i.e. when a customer * checks out without being logged in. For example, a strategy could be used to implement * business rules such as: * * - No guest checkouts allowed * - No guest checkouts allowed for customers who already have an account * - No guest checkouts allowed for customers who have previously placed an order * - Allow guest checkouts, but create a new Customer entity if the email address * is already in use * - Allow guest checkouts, but update the existing Customer entity if the email address * is already in use * * :::info * * This is configured via the `orderOptions.guestCheckoutStrategy` property of * your VendureConfig. * * ::: * * @docsCategory orders * @since 2.0.0 */ export interface GuestCheckoutStrategy extends InjectableStrategy { /** * @description * This method is called when the `setCustomerForOrder` mutation is executed. * It should return either a Customer object or an ErrorResult. */ setCustomerForOrder( ctx: RequestContext, order: Order, input: CreateCustomerInput, ): | ErrorResultUnion<SetCustomerForOrderResult, Customer> | Promise<ErrorResultUnion<SetCustomerForOrderResult, Customer>>; }
import { describe, expect, it } from 'vitest'; import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { createOrderFromLines } from '../../testing/order-test-utils'; import { MergeOrdersStrategy } from './merge-orders-strategy'; describe('MergeOrdersStrategy', () => { const strategy = new MergeOrdersStrategy(); const ctx = RequestContext.empty(); it('both orders empty', () => { const guestOrder = new Order({ lines: [] }); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([]); }); it('existingOrder empty', () => { const guestLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 1, quantity: 2 }]); }); it('guestOrder empty', () => { const existingLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = new Order({ lines: [] }); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 1, quantity: 2 }]); }); it('both orders have non-conflicting lines', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 201 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 21, quantity: 2 }, { orderLineId: 22, quantity: 1 }, { orderLineId: 1, quantity: 1 }, { orderLineId: 2, quantity: 1 }, { orderLineId: 3, quantity: 1 }, ]); }); it('both orders have lines, some of which conflict', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 102 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 22, quantity: 1 }, { orderLineId: 1, quantity: 1 }, { orderLineId: 2, quantity: 2 }, { orderLineId: 3, quantity: 1 }, ]); }); it('equivalent customFields are merged', () => { const guestLines = [{ lineId: 21, quantity: 2, productVariantId: 102, customFields: { foo: 'bar' } }]; const existingLines = [ { lineId: 2, quantity: 1, productVariantId: 102, customFields: { foo: 'bar' } }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 2, quantity: 2, customFields: { foo: 'bar' } }]); }); it('differing customFields are not merged', () => { const guestLines = [{ lineId: 21, quantity: 2, productVariantId: 102, customFields: { foo: 'bar' } }]; const existingLines = [ { lineId: 2, quantity: 1, productVariantId: 102, customFields: { foo: 'quux' } }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 21, quantity: 2, customFields: { foo: 'bar' } }, { orderLineId: 2, quantity: 1, customFields: { foo: 'quux' } }, ]); }); it('returns a new array', () => { const guestLines = [{ lineId: 21, quantity: 2, productVariantId: 102 }]; const existingLines = [{ lineId: 1, quantity: 1, productVariantId: 101 }]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).not.toBe(guestOrder.lines); expect(result).not.toBe(existingOrder.lines); }); });
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { MergedOrderLine, OrderMergeStrategy, toMergedOrderLine } from './order-merge-strategy'; /** * @description * Merges both Orders. If the guest order contains items which are already in the * existing Order, the guest Order quantity will replace that of the existing Order. * * @docsCategory orders * @docsPage Merge Strategies */ export class MergeOrdersStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order): MergedOrderLine[] { const mergedLines: MergedOrderLine[] = existingOrder.lines.map(toMergedOrderLine); const guestLines = guestOrder.lines.slice(); for (const guestLine of guestLines.reverse()) { const existingLine = this.findCorrespondingLine(existingOrder, guestLine); if (!existingLine) { mergedLines.unshift(toMergedOrderLine(guestLine)); } else { const matchingMergedLine = mergedLines.find(l => l.orderLineId === existingLine.id); if (matchingMergedLine) { matchingMergedLine.quantity = guestLine.quantity; } } } return mergedLines; } private findCorrespondingLine(existingOrder: Order, guestLine: OrderLine): OrderLine | undefined { return existingOrder.lines.find( line => line.productVariant.id === guestLine.productVariant.id && JSON.stringify(line.customFields) === JSON.stringify(guestLine.customFields), ); } }
import ms from 'ms'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; /** * @description * The OrderByCodeAccessStrategy determines how access to a placed Order via the * orderByCode query is granted. * With a custom strategy anonymous access could be made permanent or tied to specific * conditions like IP range or an Order status. * * @example * This example grants access to the requested Order to anyone – unless it's Monday. * ```ts * export class NotMondayOrderByCodeAccessStrategy implements OrderByCodeAccessStrategy { * canAccessOrder(ctx: RequestContext, order: Order): boolean { * const MONDAY = 1; * const today = (new Date()).getDay(); * * return today !== MONDAY; * } * } * ``` * * :::info * * This is configured via the `orderOptions.orderByCodeAccessStrategy` property of * your VendureConfig. * * ::: * * @since 1.1.0 * @docsCategory orders * @docsPage OrderByCodeAccessStrategy */ export interface OrderByCodeAccessStrategy extends InjectableStrategy { /** * @description * Gives or denies permission to access the requested Order */ canAccessOrder(ctx: RequestContext, order: Order): boolean | Promise<boolean>; } /** * @description * The default OrderByCodeAccessStrategy used by Vendure. It permitts permanent access to * the Customer owning the Order and anyone within a given time period after placing the Order * (defaults to 2h). * * @param anonymousAccessDuration value for [ms](https://github.com/vercel/ms), e.g. `2h` for 2 hours or `5d` for 5 days * * @docsCategory orders * @docsPage OrderByCodeAccessStrategy */ export class DefaultOrderByCodeAccessStrategy implements OrderByCodeAccessStrategy { private anonymousAccessDuration; constructor(anonymousAccessDuration: string) { this.anonymousAccessDuration = anonymousAccessDuration; } canAccessOrder(ctx: RequestContext, order: Order): boolean { // Order owned by active user const activeUserMatches = order?.customer?.user?.id === ctx.activeUserId; // For guest Customers, allow access to the Order for the following // time period const anonymousAccessPermitted = () => { const anonymousAccessLimit = ms(this.anonymousAccessDuration); const orderPlaced = order.orderPlacedAt ? +order.orderPlacedAt : 0; const now = Date.now(); return now - orderPlaced < anonymousAccessLimit; }; return (ctx.activeUserId && activeUserMatches) || (!ctx.activeUserId && anonymousAccessPermitted()); } }
import { RequestContext } from '../../api/common/request-context'; import { generatePublicId } from '../../common/generate-public-id'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * The OrderCodeStrategy determines how Order codes are generated. * A custom strategy can be defined which e.g. integrates with an * existing system to generate a code: * * :::info * * This is configured via the `orderOptions.orderCodeStrategy` property of * your VendureConfig. * * ::: * * @example * ```ts * class MyOrderCodeStrategy implements OrderCodeStrategy { * // Some imaginary service which calls out to an existing external * // order management system. * private mgmtService: ExternalOrderManagementService; * * init(injector: Injector) { * this.mgmtService = injector.get(ExternalOrderManagementService); * } * * async generate(ctx: RequestContext) { * const result = await this.mgmtService.getAvailableOrderParams(); * return result.code; * } * } * ``` * * @docsCategory orders * @docsPage OrderCodeStrategy */ export interface OrderCodeStrategy extends InjectableStrategy { /** * @description * Generates the order code. */ generate(ctx: RequestContext): string | Promise<string>; } /** * @description * The default OrderCodeStrategy generates a random string consisting * of 16 uppercase letters and numbers. * * @docsCategory orders * @docsPage OrderCodeStrategy */ export class DefaultOrderCodeStrategy implements OrderCodeStrategy { generate(ctx: RequestContext): string { return generatePublicId(); } }
import { RequestContext } from '../../api/common/request-context'; import { PriceCalculationResult } from '../../common/types/common-types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; /** * @description * The OrderItemPriceCalculationStrategy defines the listPrice of an OrderLine when adding an item to an Order. By default the * {@link DefaultOrderItemPriceCalculationStrategy} is used. * * :::info * * This is configured via the `orderOptions.orderItemPriceCalculationStrategy` property of * your VendureConfig. * * ::: * * ### When is the strategy invoked ? * * addItemToOrder (only on the new order line) * * adjustOrderLine (only on the adjusted order line) * * setOrderShippingAddress (on all order lines) * * setOrderBillingAddress (on all order lines) * * ### OrderItemPriceCalculationStrategy vs Promotions * Both the OrderItemPriceCalculationStrategy and Promotions can be used to alter the price paid for a product. * * The main difference is when a Promotion is applied, it adds a `discount` line to the Order, and the regular * price is used for the value of `OrderLine.listPrice` property, whereas * the OrderItemPriceCalculationStrategy actually alters the value of `OrderLine.listPrice` itself, and does not * add any discounts to the Order. * * Use OrderItemPriceCalculationStrategy if: * * * The price calculation is based on the properties of the ProductVariant and any CustomFields * specified on the OrderLine, for example via a product configurator. * * The logic is a permanent part of your business requirements. * * Use Promotions if: * * * You want to implement "discounts" and "special offers" * * The calculation is not a permanent part of your business requirements. * * The price depends on dynamic aspects such as quantities and which other * ProductVariants are in the Order. * * The configuration of the logic needs to be manipulated via the Admin UI. * * ### Example use-cases * * A custom OrderItemPriceCalculationStrategy can be used to implement things like: * * * A gift-wrapping service, where a boolean custom field is defined on the OrderLine. If `true`, * a gift-wrapping surcharge would be added to the price. * * A product-configurator where e.g. various finishes, colors, and materials can be selected and stored * as OrderLine custom fields (see [the Custom Fields guide](/guides/developer-guide/custom-fields/). * * Price lists or bulk pricing, where different price bands are stored e.g. in a customField on the ProductVariant, and this * is used to calculate the price based on the current quantity. * * @docsCategory Orders */ export interface OrderItemPriceCalculationStrategy extends InjectableStrategy { /** * @description * Receives the ProductVariant to be added to the Order as well as any OrderLine custom fields and returns * the price for a single unit. * * Note: if you have any `relation` type custom fields defined on the OrderLine entity, they will only be * passed in to this method if they are set to `eager: true`. Otherwise, you can use the {@link EntityHydrator} * to join the missing relations. * * Note: the `quantity` argument was added in v2.0.0 */ calculateUnitPrice( ctx: RequestContext, productVariant: ProductVariant, orderLineCustomFields: { [key: string]: any }, order: Order, quantity: number, ): PriceCalculationResult | Promise<PriceCalculationResult>; }
import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; /** * @description * The result of the {@link OrderMergeStrategy} `merge` method. * * @docsCategory orders * @docsPage OrderMergeStrategy */ export interface MergedOrderLine { orderLineId: ID; quantity: number; customFields?: any; } export function toMergedOrderLine(line: OrderLine): MergedOrderLine { return { orderLineId: line.id, quantity: line.quantity, customFields: line.customFields, }; } /** * @description * An OrderMergeStrategy defines what happens when a Customer with an existing Order * signs in with a guest Order, where both Orders may contain differing OrderLines. * * Somehow these differing OrderLines need to be reconciled into a single collection * of OrderLines. The OrderMergeStrategy defines the rules governing this reconciliation. * * :::info * * This is configured via the `orderOptions.mergeStrategy` property of * your VendureConfig. * * ::: * * @docsCategory orders * @docsPage OrderMergeStrategy * @docsWeight 0 */ export interface OrderMergeStrategy extends InjectableStrategy { /** * @description * Merges the lines of the guest Order with those of the existing Order which is associated * with the active customer. */ merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order): MergedOrderLine[]; }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; /** * @description * This strategy is responsible for deciding at which stage in the order process * the Order will be set as "placed" (i.e. the Customer has checked out, and * next it must be processed by an Administrator). * * By default, the order is set as "placed" when it transitions from * 'ArrangingPayment' to either 'PaymentAuthorized' or 'PaymentSettled'. * * :::info * * This is configured via the `orderOptions.orderPlacedStrategy` property of * your VendureConfig. * * ::: * * @docsCategory orders */ export interface OrderPlacedStrategy extends InjectableStrategy { /** * @description * This method is called whenever an _active_ Order transitions from one state to another. * If it resolves to `true`, then the Order will be set as "placed", which means: * * * Order.active = false * * Order.placedAt = new Date() * * Any active Promotions are linked to the Order */ shouldSetAsPlaced( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean | Promise<boolean>; }
import { OnTransitionEndFn, OnTransitionErrorFn, OnTransitionStartFn, StateMachineConfig, Transitions, } from '../../common/finite-state-machine/types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { CustomOrderStates, OrderState, OrderTransitionData, } from '../../service/helpers/order-state-machine/order-state'; /** * @description * An OrderProcess is used to define the way the order process works as in: what states an Order can be * in, and how it may transition from one state to another. Using the `onTransitionStart()` hook, an * OrderProcess can perform checks before allowing a state transition to occur, and the `onTransitionEnd()` * hook allows logic to be executed after a state change. * * For detailed description of the interface members, see the {@link StateMachineConfig} docs. * * :::info * * This is configured via the `orderOptions.process` property of * your VendureConfig. * * ::: * * @docsCategory orders * @docsPage OrderProcess * @docsWeight 0 */ export interface OrderProcess<State extends keyof CustomOrderStates | string> extends InjectableStrategy { transitions?: Transitions<State, State | OrderState> & Partial<Transitions<OrderState | State>>; onTransitionStart?: OnTransitionStartFn<State | OrderState, OrderTransitionData>; onTransitionEnd?: OnTransitionEndFn<State | OrderState, OrderTransitionData>; onTransitionError?: OnTransitionErrorFn<State | OrderState>; } /** * @description * Used to define extensions to or modifications of the default order process. * * @deprecated Use OrderProcess */ export interface CustomOrderProcess<State extends keyof CustomOrderStates | string> extends OrderProcess<State> {}
import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Channel } from '../../entity/channel/channel.entity'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { ShippingLine } from '../../entity/shipping-line/shipping-line.entity'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; /** * @description * The contents of the aggregate Order which make up a single seller Order. * * @since 2.0.0 * @docsCategory orders * @docsPage OrderSellerStrategy */ export interface SplitOrderContents { channelId: ID; state: OrderState; lines: OrderLine[]; shippingLines: ShippingLine[]; } /** * @description * This strategy defines how an Order can be split into multiple sub-orders for the use-case of * a multivendor application. * * :::info * * This is configured via the `orderOptions.orderSellerStrategy` property of * your VendureConfig. * * ::: * * @since 2.0.0 * @docsCategory orders * @docsPage OrderSellerStrategy * @docsWeight 0 */ export interface OrderSellerStrategy extends InjectableStrategy { /** * @description * This method is called whenever a new OrderLine is added to the Order via the `addItemToOrder` mutation or the * underlying `addItemToOrder()` method of the {@link OrderService}. * * It should return the ID of the Channel to which this OrderLine will be assigned, which will be used to set the * {@link OrderLine} `sellerChannel` property. */ setOrderLineSellerChannel?( ctx: RequestContext, orderLine: OrderLine, ): Channel | undefined | Promise<Channel | undefined>; /** * @description * Upon checkout (by default, when the Order moves from "active" to "inactive" according to the {@link OrderPlacedStrategy}), * this method will be called in order to split the Order into multiple Orders, one for each Seller. */ splitOrder?(ctx: RequestContext, order: Order): SplitOrderContents[] | Promise<SplitOrderContents[]>; /** * @description * This method is called after splitting the orders, including calculating the totals for each of the seller Orders. * This method can be used to set platform fee surcharges on the seller Orders as well as perform any payment processing * needed. */ afterSellerOrdersCreated?( ctx: RequestContext, aggregateOrder: Order, sellerOrders: Order[], ): void | Promise<void>; }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { OrderState } from '../../service/helpers/order-state-machine/order-state'; /** * @description * This strategy is responsible for deciding at which stage in the order process * stock will be allocated. * * :::info * * This is configured via the `orderOptions.stockAllocationStrategy` property of * your VendureConfig. * * ::: * * @docsCategory orders */ export interface StockAllocationStrategy extends InjectableStrategy { /** * @description * This method is called whenever an Order transitions from one state to another. * If it resolves to `true`, then stock will be allocated for this order. */ shouldAllocateStock( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean | Promise<boolean>; }
import { describe, expect, it } from 'vitest'; import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { createOrderFromLines } from '../../testing/order-test-utils'; import { UseExistingStrategy } from './use-existing-strategy'; describe('UseExistingStrategy', () => { const strategy = new UseExistingStrategy(); const ctx = RequestContext.empty(); it('both orders empty', () => { const guestOrder = new Order({ lines: [] }); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([]); }); it('existingOrder empty', () => { const guestLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([]); }); it('guestOrder empty', () => { const existingLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = new Order({ lines: [] }); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 1, quantity: 2 }]); }); it('both orders have non-conflicting lines', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 201 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 1, quantity: 1 }, { orderLineId: 2, quantity: 1 }, { orderLineId: 3, quantity: 1 }, ]); }); it('both orders have conflicting lines, some of which conflict', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 102 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 1, quantity: 1 }, { orderLineId: 2, quantity: 1 }, { orderLineId: 3, quantity: 1 }, ]); }); });
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { MergedOrderLine, OrderMergeStrategy, toMergedOrderLine } from './order-merge-strategy'; /** * @description * The guest order is discarded and the existing order is used as the active order. * * @docsCategory orders * @docsPage Merge Strategies */ export class UseExistingStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order): MergedOrderLine[] { return existingOrder.lines.map(toMergedOrderLine); } }
import { describe, expect, it } from 'vitest'; import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { createOrderFromLines } from '../../testing/order-test-utils'; import { UseGuestIfExistingEmptyStrategy } from './use-guest-if-existing-empty-strategy'; describe('UseGuestIfExistingEmptyStrategy', () => { const strategy = new UseGuestIfExistingEmptyStrategy(); const ctx = RequestContext.empty(); it('both orders empty', () => { const guestOrder = new Order({ lines: [] }); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([]); }); it('existingOrder empty', () => { const guestLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 1, quantity: 2 }]); }); it('guestOrder empty', () => { const existingLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = new Order({ lines: [] }); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 1, quantity: 2 }]); }); it('both orders have non-conflicting lines', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 201 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 1, quantity: 1 }, { orderLineId: 2, quantity: 1 }, { orderLineId: 3, quantity: 1 }, ]); }); it('both orders have lines, some of which conflict', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 102 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 1, quantity: 1 }, { orderLineId: 2, quantity: 1 }, { orderLineId: 3, quantity: 1 }, ]); }); });
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { MergedOrderLine, OrderMergeStrategy, toMergedOrderLine } from './order-merge-strategy'; /** * @description * If the existing order is empty, then the guest order is used. Otherwise the existing order is used. * * @docsCategory orders * @docsPage Merge Strategies */ export class UseGuestIfExistingEmptyStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order): MergedOrderLine[] { return existingOrder.lines.length ? existingOrder.lines.map(toMergedOrderLine) : guestOrder.lines.map(toMergedOrderLine); } }
import { describe, expect, it } from 'vitest'; import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { createOrderFromLines } from '../../testing/order-test-utils'; import { UseGuestStrategy } from './use-guest-strategy'; describe('UseGuestStrategy', () => { const strategy = new UseGuestStrategy(); const ctx = RequestContext.empty(); it('both orders empty', () => { const guestOrder = new Order({ lines: [] }); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([]); }); it('existingOrder empty', () => { const guestLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = new Order({ lines: [] }); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([{ orderLineId: 1, quantity: 2 }]); }); it('guestOrder empty', () => { const existingLines = [{ lineId: 1, quantity: 2, productVariantId: 100 }]; const guestOrder = new Order({ lines: [] }); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([]); }); it('both orders have non-conflicting lines', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 201 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 21, quantity: 2 }, { orderLineId: 22, quantity: 1 }, ]); }); it('both orders have conflicting lines, some of which conflict', () => { const guestLines = [ { lineId: 21, quantity: 2, productVariantId: 102 }, { lineId: 22, quantity: 1, productVariantId: 202 }, ]; const existingLines = [ { lineId: 1, quantity: 1, productVariantId: 101 }, { lineId: 2, quantity: 1, productVariantId: 102 }, { lineId: 3, quantity: 1, productVariantId: 103 }, ]; const guestOrder = createOrderFromLines(guestLines); const existingOrder = createOrderFromLines(existingLines); const result = strategy.merge(ctx, guestOrder, existingOrder); expect(result).toEqual([ { orderLineId: 21, quantity: 2 }, { orderLineId: 22, quantity: 1 }, ]); }); });
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { MergedOrderLine, OrderMergeStrategy, toMergedOrderLine } from './order-merge-strategy'; /** * @description * Any existing order is discarded and the guest order is set as the active order. * * @docsCategory orders * @docsPage Merge Strategies */ export class UseGuestStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order): MergedOrderLine[] { return guestOrder.lines.map(toMergedOrderLine); } }
import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { PaymentState } from '../../service/helpers/payment-state-machine/payment-state'; import { orderTotalIsCovered } from '../../service/helpers/utils/order-utils'; import { PaymentProcess } from './payment-process'; declare module '../../service/helpers/payment-state-machine/payment-state' { interface PaymentStates { Authorized: never; Settled: never; Declined: never; } } let configService: import('../config.service').ConfigService; let orderService: import('../../service/services/order.service').OrderService; let historyService: import('../../service/index').HistoryService; /** * @description * The default {@link PaymentProcess} * * @docsCategory payment */ export const defaultPaymentProcess: PaymentProcess<PaymentState> = { transitions: { Created: { to: ['Authorized', 'Settled', 'Declined', 'Error', 'Cancelled'], }, Authorized: { to: ['Settled', 'Error', 'Cancelled'], }, Settled: { to: ['Cancelled'], }, Declined: { to: ['Cancelled'], }, Error: { to: ['Cancelled'], }, Cancelled: { to: [], }, }, async init(injector) { // Lazily import these services to avoid a circular dependency error // due to this being used as part of the DefaultConfig const ConfigService = await import('../config.service.js').then(m => m.ConfigService); const HistoryService = await import('../../service/index.js').then(m => m.HistoryService); const OrderService = await import('../../service/services/order.service.js').then( m => m.OrderService, ); configService = injector.get(ConfigService); historyService = injector.get(HistoryService); orderService = injector.get(OrderService); }, async onTransitionStart(fromState, toState, data) { // nothing here by default }, async onTransitionEnd(fromState, toState, data) { const { ctx, payment, order } = data; order.payments = await orderService.getOrderPayments(ctx, order.id); await historyService.createHistoryEntryForOrder({ ctx: data.ctx, orderId: data.order.id, type: HistoryEntryType.ORDER_PAYMENT_TRANSITION, data: { paymentId: data.payment.id, from: fromState, to: toState, }, }); if ( orderTotalIsCovered(order, 'Settled') && order.state !== 'PaymentSettled' && order.state !== 'ArrangingAdditionalPayment' ) { await orderService.transitionToState(ctx, order.id, 'PaymentSettled'); } else if ( orderTotalIsCovered(order, ['Authorized', 'Settled']) && order.state !== 'PaymentAuthorized' && order.state !== 'ArrangingAdditionalPayment' ) { await orderService.transitionToState(ctx, order.id, 'PaymentAuthorized'); } }, };
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { CreatePaymentResult, PaymentMethodHandler } from './payment-method-handler'; /** * @description * A dummy PaymentMethodHandler which simply creates a Payment without any integration * with an external payment provider. Intended only for use in development. * * By specifying certain metadata keys, failures can be simulated: * @example * ```GraphQL * addPaymentToOrder(input: { * method: 'dummy-payment-method', * metadata: { * shouldDecline: false, * shouldError: false, * shouldErrorOnSettle: true, * } * }) { * # ... * } * ``` * * @docsCategory payment */ export const dummyPaymentHandler = new PaymentMethodHandler({ code: 'dummy-payment-handler', description: [ { languageCode: LanguageCode.en, value: 'A dummy payment provider intended for testing and development only.', }, ], args: { automaticSettle: { type: 'boolean', label: [ { languageCode: LanguageCode.en, value: 'Authorize and settle in 1 step', }, ], description: [ { languageCode: LanguageCode.en, value: 'If enabled, Payments will be created in the "Settled" state.', }, ], required: true, defaultValue: false, }, }, createPayment: async (ctx, order, amount, args, metadata, method) => { if (metadata.shouldDecline) { return { amount, state: 'Declined' as const, metadata: { errorMessage: 'Simulated decline', }, }; } else if (metadata.shouldError) { return { amount, state: 'Error' as const, errorMessage: 'Simulated error', metadata: { errorMessage: 'Simulated error', }, }; } else { return { amount, state: args.automaticSettle ? 'Settled' : 'Authorized', transactionId: Math.random().toString(36).substr(3), metadata, }; } }, settlePayment: async (ctx, order, payment, args, method) => { if (payment.metadata.shouldErrorOnSettle) { return { success: false, errorMessage: 'Simulated settlement error', }; } return { success: true, }; }, cancelPayment: (ctx, order, payment) => { return { success: true, metadata: { cancellationDate: new Date().toISOString(), }, }; }, });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { CreatePaymentResult, PaymentMethodHandler } from './payment-method-handler'; /** * A dummy API to simulate an SDK provided by a popular payments service. */ const gripeSDK = { charges: { create: (options: any) => { return Promise.resolve({ id: Math.random().toString(36).substr(3), }); }, capture: async (transactionId: string) => { return true; }, }, }; /** * An example of a payment method which sets up and authorizes the payment on the client side and then * requires a further step on the server side to charge the card. */ export const examplePaymentHandler = new PaymentMethodHandler({ code: 'example-payment-provider', description: [{ languageCode: LanguageCode.en, value: 'Example Payment Provider' }], args: { automaticCapture: { type: 'boolean', required: false }, apiKey: { type: 'string', required: false }, }, createPayment: async (ctx, order, amount, args, metadata, method): Promise<CreatePaymentResult> => { try { const result = await gripeSDK.charges.create({ apiKey: args.apiKey, amount, source: metadata.authToken, }); return { amount, state: args.automaticCapture ? 'Settled' : 'Authorized', transactionId: result.id.toString(), metadata, }; } catch (err: any) { return { amount, state: 'Declined' as const, metadata: { errorMessage: err.message, }, }; } }, settlePayment: async (ctx, order, payment, args, method) => { const result = await gripeSDK.charges.capture(payment.transactionId); return { success: result, metadata: { captureId: '1234567', }, }; }, });
import { ConfigArg } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { Order, PaymentMethod } from '../../entity'; /** * @description * Configuration passed into the constructor of a {@link PaymentMethodEligibilityChecker} to * configure its behavior. * * @docsCategory payment * @docsPage PaymentMethodEligibilityChecker */ export interface PaymentMethodEligibilityCheckerConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { check: CheckPaymentMethodEligibilityCheckerFn<T>; } /** * @description * The PaymentMethodEligibilityChecker class is used to check whether an order qualifies for a * given {@link PaymentMethod}. * * @example * ```ts * const ccPaymentEligibilityChecker = new PaymentMethodEligibilityChecker({ * code: 'order-total-payment-eligibility-checker', * description: [{ languageCode: LanguageCode.en, value: 'Checks that the order total is above some minimum value' }], * args: { * orderMinimum: { type: 'int', ui: { component: 'currency-form-input' } }, * }, * check: (ctx, order, args) => { * return order.totalWithTax >= args.orderMinimum; * }, * }); * ``` * * @docsCategory payment * @docsPage PaymentMethodEligibilityChecker * @docsWeight 0 */ export class PaymentMethodEligibilityChecker< T extends ConfigArgs = ConfigArgs, > extends ConfigurableOperationDef<T> { private readonly checkFn: CheckPaymentMethodEligibilityCheckerFn<T>; constructor(config: PaymentMethodEligibilityCheckerConfig<T>) { super(config); this.checkFn = config.check; } /** * @description * Check the given Order to determine whether it is eligible. * * @internal */ async check( ctx: RequestContext, order: Order, args: ConfigArg[], method: PaymentMethod, ): Promise<boolean | string> { return this.checkFn(ctx, order, this.argsArrayToHash(args), method); } } /** * @description * A function which implements logic to determine whether a given {@link Order} is eligible for * a particular payment method. If the function resolves to `false` or a string, the check is * considered to have failed. A string result can be used to provide information about the * reason for ineligibility, if desired. * * @docsCategory payment * @docsPage PaymentMethodEligibilityChecker */ export type CheckPaymentMethodEligibilityCheckerFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, method: PaymentMethod, ) => boolean | string | Promise<boolean | string>;
import { ConfigArg, RefundOrderInput } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { OnTransitionStartFn, StateMachineConfig } from '../../common/finite-state-machine/types'; import { PaymentMetadata } from '../../common/types/common-types'; import { Order, Payment, PaymentMethod } from '../../entity'; import { PaymentState, PaymentTransitionData, } from '../../service/helpers/payment-state-machine/payment-state'; import { RefundState } from '../../service/helpers/refund-state-machine/refund-state'; export type OnPaymentTransitionStartReturnType = ReturnType< Required<StateMachineConfig<any>>['onTransitionStart'] >; /** * @description * This object is the return value of the {@link CreatePaymentFn}. * * @docsCategory payment * @docsPage Payment Method Types */ export interface CreatePaymentResult { /** * @description * The amount (as an integer - i.e. $10 = `1000`) that this payment is for. * Typically this should equal the Order total, unless multiple payment methods * are being used for the order. */ amount: number; /** * @description * The {@link PaymentState} of the resulting Payment. * * In a single-step payment flow, this should be set to `'Settled'`. * In a two-step flow, this should be set to `'Authorized'`. * * If using a {@link CustomPaymentProcess}, may be something else * entirely according to your business logic. */ state: Exclude<PaymentState, 'Error'>; /** * @description * The unique payment reference code typically assigned by * the payment provider. */ transactionId?: string; /** * @description * If the payment is declined or fails for ome other reason, pass the * relevant error message here, and it gets returned with the * ErrorResponse of the `addPaymentToOrder` mutation. */ errorMessage?: string; /** * @description * This field can be used to store other relevant data which is often * provided by the payment provider, such as security data related to * the payment method or data used in troubleshooting or debugging. * * Any data stored in the optional `public` property will be available * via the Shop API. This is useful for certain checkout flows such as * external gateways, where the payment provider returns a unique * url which must then be passed to the storefront app. */ metadata?: PaymentMetadata; } /** * @description * This object is the return value of the {@link CreatePaymentFn} when there has been an error. * * @docsCategory payment * @docsPage Payment Method Types */ export interface CreatePaymentErrorResult { amount: number; state: 'Error'; transactionId?: string; errorMessage: string; metadata?: PaymentMetadata; } /** * @description * This object is the return value of the {@link CreateRefundFn}. * * @docsCategory payment * @docsPage Payment Method Types */ export interface CreateRefundResult { state: RefundState; transactionId?: string; metadata?: PaymentMetadata; } /** * @description * This object is the return value of the {@link SettlePaymentFn} when the Payment * has been successfully settled. * * @docsCategory payment * @docsPage Payment Method Types */ export interface SettlePaymentResult { success: true; metadata?: PaymentMetadata; } /** * @description * This object is the return value of the {@link SettlePaymentFn} when the Payment * could not be settled. * * @docsCategory payment * @docsPage Payment Method Types */ export interface SettlePaymentErrorResult { success: false; /** * @description * The state to transition this Payment to upon unsuccessful settlement. * Defaults to `Error`. Note that if using a different state, it must be * legal to transition to that state from the `Authorized` state according * to the PaymentState config (which can be customized using the * {@link CustomPaymentProcess}). */ state?: Exclude<PaymentState, 'Settled'>; /** * @description * The message that will be returned when attempting to settle the payment, and will * also be persisted as `Payment.errorMessage`. */ errorMessage?: string; metadata?: PaymentMetadata; } /** * @description * This object is the return value of the {@link CancelPaymentFn} when the Payment * has been successfully cancelled. * * @docsCategory payment * @docsPage Payment Method Types */ export interface CancelPaymentResult { success: true; metadata?: PaymentMetadata; } /** * @description * This object is the return value of the {@link CancelPaymentFn} when the Payment * could not be cancelled. * * @docsCategory payment * @docsPage Payment Method Types */ export interface CancelPaymentErrorResult { success: false; /** * @description * The state to transition this Payment to upon unsuccessful cancellation. * Defaults to `Error`. Note that if using a different state, it must be * legal to transition to that state from the `Authorized` state according * to the PaymentState config (which can be customized using the * {@link CustomPaymentProcess}). */ state?: Exclude<PaymentState, 'Cancelled'>; /** * @description * The message that will be returned when attempting to cancel the payment, and will * also be persisted as `Payment.errorMessage`. */ errorMessage?: string; metadata?: PaymentMetadata; } /** * @description * This function contains the logic for creating a payment. See {@link PaymentMethodHandler} for an example. * * Returns a {@link CreatePaymentResult}. * * @docsCategory payment * @docsPage Payment Method Types */ export type CreatePaymentFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, amount: number, args: ConfigArgValues<T>, metadata: PaymentMetadata, method: PaymentMethod, ) => CreatePaymentResult | CreatePaymentErrorResult | Promise<CreatePaymentResult | CreatePaymentErrorResult>; /** * @description * This function contains the logic for settling a payment. See {@link PaymentMethodHandler} for an example. * * @docsCategory payment * @docsPage Payment Method Types */ export type SettlePaymentFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, payment: Payment, args: ConfigArgValues<T>, method: PaymentMethod, ) => SettlePaymentResult | SettlePaymentErrorResult | Promise<SettlePaymentResult | SettlePaymentErrorResult>; /** * @description * This function contains the logic for cancelling a payment. See {@link PaymentMethodHandler} for an example. * * @docsCategory payment * @docsPage Payment Method Types */ export type CancelPaymentFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, payment: Payment, args: ConfigArgValues<T>, method: PaymentMethod, ) => CancelPaymentResult | CancelPaymentErrorResult | Promise<CancelPaymentResult | CancelPaymentErrorResult>; /** * @description * This function contains the logic for creating a refund. See {@link PaymentMethodHandler} for an example. * * @docsCategory payment * @docsPage Payment Method Types */ export type CreateRefundFn<T extends ConfigArgs> = ( ctx: RequestContext, input: RefundOrderInput, amount: number, order: Order, payment: Payment, args: ConfigArgValues<T>, method: PaymentMethod, ) => CreateRefundResult | Promise<CreateRefundResult>; /** * @description * Defines the object which is used to construct the {@link PaymentMethodHandler}. * * @docsCategory payment */ export interface PaymentMethodConfigOptions<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { /** * @description * This function provides the logic for creating a payment. For example, * it may call out to a third-party service with the data and should return a * {@link CreatePaymentResult} object contains the details of the payment. */ createPayment: CreatePaymentFn<T>; /** * @description * This function provides the logic for settling a payment, also known as "capturing". * For payment integrations that settle/capture the payment on creation (i.e. the * `createPayment()` method returns with a state of `'Settled'`) this method * need only return `{ success: true }`. */ settlePayment: SettlePaymentFn<T>; /** * @description * This function provides the logic for cancelling a payment, which would be invoked when a call is * made to the `cancelPayment` mutation in the Admin API. Cancelling a payment can apply * if, for example, you have created a "payment intent" with the payment provider but not yet * completed the payment. It allows the incomplete payment to be cleaned up on the provider's end * if it gets cancelled via Vendure. * * @since 1.7.0 */ cancelPayment?: CancelPaymentFn<T>; /** * @description * This function provides the logic for refunding a payment created with this * payment method. Some payment providers may not provide the facility to * programmatically create a refund. In such a case, this method should be * omitted and any Refunds will have to be settled manually by an administrator. */ createRefund?: CreateRefundFn<T>; /** * @description * This function, when specified, will be invoked before any transition from one {@link PaymentState} to another. * The return value (a sync / async `boolean`) is used to determine whether the transition is permitted. */ onStateTransitionStart?: OnTransitionStartFn<PaymentState, PaymentTransitionData>; } /** * @description * A PaymentMethodHandler contains the code which is used to generate a Payment when a call to the * `addPaymentToOrder` mutation is made. It contains any necessary steps of interfacing with a * third-party payment gateway before the Payment is created and can also define actions to fire * when the state of the payment is changed. * * PaymentMethodHandlers are instantiated using a {@link PaymentMethodConfigOptions} object, which * configures the business logic used to create, settle and refund payments. * * @example * ```ts * import { PaymentMethodHandler, CreatePaymentResult, SettlePaymentResult, LanguageCode } from '\@vendure/core'; * // A mock 3rd-party payment SDK * import gripeSDK from 'gripe'; * * export const examplePaymentHandler = new PaymentMethodHandler({ * code: 'example-payment-provider', * description: [{ * languageCode: LanguageCode.en, * value: 'Example Payment Provider', * }], * args: { * apiKey: { type: 'string' }, * }, * createPayment: async (ctx, order, amount, args, metadata): Promise<CreatePaymentResult> => { * try { * const result = await gripeSDK.charges.create({ * amount, * apiKey: args.apiKey, * source: metadata.authToken, * }); * return { * amount: order.total, * state: 'Settled' as const, * transactionId: result.id.toString(), * metadata: result.outcome, * }; * } catch (err: any) { * return { * amount: order.total, * state: 'Declined' as const, * metadata: { * errorMessage: err.message, * }, * }; * } * }, * settlePayment: async (ctx, order, payment, args): Promise<SettlePaymentResult> => { * return { success: true }; * } * }); * ``` * * @docsCategory payment */ export class PaymentMethodHandler<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { private readonly createPaymentFn: CreatePaymentFn<T>; private readonly settlePaymentFn: SettlePaymentFn<T>; private readonly cancelPaymentFn?: CancelPaymentFn<T>; private readonly createRefundFn?: CreateRefundFn<T>; private readonly onTransitionStartFn?: OnTransitionStartFn<PaymentState, PaymentTransitionData>; constructor(config: PaymentMethodConfigOptions<T>) { super(config); this.createPaymentFn = config.createPayment; this.settlePaymentFn = config.settlePayment; this.cancelPaymentFn = config.cancelPayment; this.createRefundFn = config.createRefund; this.onTransitionStartFn = config.onStateTransitionStart; } /** * @description * Called internally to create a new Payment * * @internal */ async createPayment( ctx: RequestContext, order: Order, amount: number, args: ConfigArg[], metadata: PaymentMetadata, method: PaymentMethod, ) { const paymentConfig = await this.createPaymentFn( ctx, order, amount, this.argsArrayToHash(args), metadata, method, ); return { method: this.code, metadata: {}, ...paymentConfig, }; } /** * @description * Called internally to settle a payment * * @internal */ async settlePayment( ctx: RequestContext, order: Order, payment: Payment, args: ConfigArg[], method: PaymentMethod, ) { return this.settlePaymentFn(ctx, order, payment, this.argsArrayToHash(args), method); } /** * @description * Called internally to cancel a payment * * @internal */ async cancelPayment( ctx: RequestContext, order: Order, payment: Payment, args: ConfigArg[], method: PaymentMethod, ) { return this.cancelPaymentFn?.(ctx, order, payment, this.argsArrayToHash(args), method); } /** * @description * Called internally to create a refund * * @internal */ async createRefund( ctx: RequestContext, input: RefundOrderInput, amount: number, order: Order, payment: Payment, args: ConfigArg[], method: PaymentMethod, ) { return this.createRefundFn ? this.createRefundFn(ctx, input, amount, order, payment, this.argsArrayToHash(args), method) : false; } /** * @description * This function is called before the state of a Payment is transitioned. If the PaymentMethodHandler * was instantiated with a `onStateTransitionStart` function, that function will be invoked and its * return value used to determine whether the transition can occur. * * @internal */ onStateTransitionStart( fromState: PaymentState, toState: PaymentState, data: PaymentTransitionData, ): OnPaymentTransitionStartReturnType { if (typeof this.onTransitionStartFn === 'function') { return this.onTransitionStartFn(fromState, toState, data); } else { return true; } } }
import { OnTransitionEndFn, OnTransitionErrorFn, OnTransitionStartFn, Transitions, } from '../../common/finite-state-machine/types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { CustomPaymentStates, PaymentState, PaymentTransitionData, } from '../../service/helpers/payment-state-machine/payment-state'; /** * @description * A PaymentProcess is used to define the way the payment process works as in: what states a Payment can be * in, and how it may transition from one state to another. Using the `onTransitionStart()` hook, a * PaymentProcess can perform checks before allowing a state transition to occur, and the `onTransitionEnd()` * hook allows logic to be executed after a state change. * * For detailed description of the interface members, see the {@link StateMachineConfig} docs. * * :::info * * This is configured via the `paymentOptions.process` property of * your VendureConfig. * * ::: * * @docsCategory payment * @since 2.0.0 */ export interface PaymentProcess<State extends keyof CustomPaymentStates | string> extends InjectableStrategy { transitions?: Transitions<State, State | PaymentState> & Partial<Transitions<PaymentState | State>>; onTransitionStart?: OnTransitionStartFn<State | PaymentState, PaymentTransitionData>; onTransitionEnd?: OnTransitionEndFn<State | PaymentState, PaymentTransitionData>; onTransitionError?: OnTransitionErrorFn<State | PaymentState>; } /** * @description * Used to define extensions to or modifications of the default payment process. * * For detailed description of the interface members, see the {@link StateMachineConfig} docs. * * @deprecated use PaymentProcess */ export interface CustomPaymentProcess<State extends keyof CustomPaymentStates | string> extends PaymentProcess<State> {}
import { buyXGetYFreeAction } from './actions/buy-x-get-y-free-action'; import { discountOnItemWithFacets } from './actions/facet-values-percentage-discount-action'; import { freeShipping } from './actions/free-shipping-action'; import { orderFixedDiscount } from './actions/order-fixed-discount-action'; import { orderPercentageDiscount } from './actions/order-percentage-discount-action'; import { productsPercentageDiscount } from './actions/product-percentage-discount-action'; import { buyXGetYFreeCondition } from './conditions/buy-x-get-y-free-condition'; import { containsProducts } from './conditions/contains-products-condition'; import { customerGroup } from './conditions/customer-group-condition'; import { hasFacetValues } from './conditions/has-facet-values-condition'; import { minimumOrderAmount } from './conditions/min-order-amount-condition'; export * from './promotion-action'; export * from './promotion-condition'; export * from './actions/facet-values-percentage-discount-action'; export * from './actions/order-percentage-discount-action'; export * from './actions/product-percentage-discount-action'; export * from './actions/free-shipping-action'; export * from './actions/buy-x-get-y-free-action'; export * from './actions/order-fixed-discount-action'; export * from './conditions/has-facet-values-condition'; export * from './conditions/min-order-amount-condition'; export * from './conditions/contains-products-condition'; export * from './conditions/customer-group-condition'; export * from './conditions/buy-x-get-y-free-condition'; export * from './utils/facet-value-checker'; export const defaultPromotionActions = [ orderFixedDiscount, orderPercentageDiscount, discountOnItemWithFacets, productsPercentageDiscount, freeShipping, buyXGetYFreeAction, ]; export const defaultPromotionConditions = [ minimumOrderAmount, hasFacetValues, containsProducts, customerGroup, buyXGetYFreeCondition, ];
import { ConfigArg } from '@vendure/common/lib/generated-types'; import { pick } from '@vendure/common/lib/pick'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { Promotion, PromotionState } from '../../entity'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { ShippingLine } from '../../entity/shipping-line/shipping-line.entity'; import { PromotionCondition } from './promotion-condition'; /** * Unwrap a promise type */ type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T; /** * Extract the (non-false) return value of the PromotionCondition "check" function. */ type ConditionCheckReturnType<T extends PromotionCondition<any>> = Exclude< Awaited<ReturnType<T['check']>>, false >; /** * Converts an array of PromotionCondition types into a tuple, thus preserving the * distinct type of each condition in the array. */ export type ConditionTuple<C extends Array<PromotionCondition<any>>> = [...C]; /** * Converts an array of PromotionConditions into a tuple of the type: * [<condition code>, <check function return value>] */ type CodesStateTuple<T extends ConditionTuple<Array<PromotionCondition<any>>>> = { [K in keyof T]: T[K] extends PromotionCondition<any> ? [T[K]['code'], ConditionCheckReturnType<T[K]>] : never; }; /** * Convert a tuple into a union * [[string, number], [number, boolean]] => [string, number] | [number, boolean] */ type TupleToUnion<T extends any[]> = T[number]; /** * Converts an array of PromotionConditions into an object of the type: * { * [PromotionCondition.code]: ReturnType<PromotionCondition.check()> * } */ export type ConditionState< U extends Array<PromotionCondition<any>>, T extends [string, any] = TupleToUnion<CodesStateTuple<ConditionTuple<U>>>, > = { [key in T[0]]: Extract<T, [key, any]>[1] }; /** * @description * The function which is used by a PromotionItemAction to calculate the * discount on the OrderLine. * * @docsCategory promotions * @docsPage promotion-action */ export type ExecutePromotionItemActionFn<T extends ConfigArgs, U extends Array<PromotionCondition<any>>> = ( ctx: RequestContext, orderLine: OrderLine, args: ConfigArgValues<T>, state: ConditionState<U>, promotion: Promotion, ) => number | Promise<number>; /** * @description * The function which is used by a PromotionOrderAction to calculate the * discount on the Order. * * @docsCategory promotions * @docsPage promotion-action */ export type ExecutePromotionOrderActionFn<T extends ConfigArgs, U extends Array<PromotionCondition<any>>> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, state: ConditionState<U>, promotion: Promotion, ) => number | Promise<number>; /** * @description * The function which is used by a PromotionOrderAction to calculate the * discount on the Order. * * @docsCategory promotions * @docsPage promotion-action */ export type ExecutePromotionShippingActionFn< T extends ConfigArgs, U extends Array<PromotionCondition<any>>, > = ( ctx: RequestContext, shippingLine: ShippingLine, order: Order, args: ConfigArgValues<T>, state: ConditionState<U>, promotion: Promotion, ) => number | Promise<number>; /** * @description * The signature of a PromotionAction's side-effect functions `onActivate` and `onDeactivate`. * * @docsCategory promotions * @docsPage promotion-action * @since 1.8.0 * @experimental */ type PromotionActionSideEffectFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, promotion: Promotion, ) => void | Promise<void>; /** * @description * Configuration for all types of {@link PromotionAction}. * * @docsCategory promotions * @docsPage promotion-action */ export interface PromotionActionConfig< T extends ConfigArgs, U extends Array<PromotionCondition<any>> | undefined, > extends ConfigurableOperationDefOptions<T> { /** * @description * Used to determine the order of application of multiple Promotions * on the same Order. See the {@link Promotion} `priorityScore` field for * more information. * * @default 0 */ priorityValue?: number; /** * @description * Allows PromotionActions to define one or more PromotionConditions as dependencies. Having a PromotionCondition * as a dependency has the following consequences: * 1. A Promotion using this PromotionAction is only valid if it also contains all PromotionConditions * on which it depends. * 2. The `execute()` function will receive a statically-typed `state` argument which will contain * the return values of the PromotionConditions' `check()` function. */ conditions?: U extends undefined ? undefined : ConditionTuple<Exclude<U, undefined>>; /** * @description * An optional side effect function which is invoked when the promotion * becomes active. It can be used for things like adding a free gift to the order * or other side effects that are unrelated to price calculations. * * If used, make sure to use the corresponding `onDeactivate` function to clean up * or reverse any side effects as needed. * * @since 1.8.0 * @experimental */ onActivate?: PromotionActionSideEffectFn<T>; /** * @description * Used to reverse or clean up any side effects executed as part of the `onActivate` function. * * @since 1.8.0 * @experimental */ onDeactivate?: PromotionActionSideEffectFn<T>; } /** * @description * Configuration for a {@link PromotionItemAction} * * @docsCategory promotions * @docsPage promotion-action */ export interface PromotionItemActionConfig<T extends ConfigArgs, U extends PromotionCondition[]> extends PromotionActionConfig<T, U> { /** * @description * The function which contains the promotion calculation logic. * Should resolve to a number which represents the amount by which to discount * the OrderLine, i.e. the number should be negative. */ execute: ExecutePromotionItemActionFn<T, U>; } /** * @description * * @docsCategory promotions * @docsPage promotion-action */ export interface PromotionOrderActionConfig<T extends ConfigArgs, U extends PromotionCondition[]> extends PromotionActionConfig<T, U> { /** * @description * The function which contains the promotion calculation logic. * Should resolve to a number which represents the amount by which to discount * the Order, i.e. the number should be negative. */ execute: ExecutePromotionOrderActionFn<T, U>; } /** * @description * * @docsCategory promotions * @docsPage promotion-action */ export interface PromotionShippingActionConfig<T extends ConfigArgs, U extends PromotionCondition[]> extends PromotionActionConfig<T, U> { /** * @description * The function which contains the promotion calculation logic. * Should resolve to a number which represents the amount by which to discount * the Shipping, i.e. the number should be negative. */ execute: ExecutePromotionShippingActionFn<T, U>; } /** * @description * An abstract class which is extended by {@link PromotionItemAction}, {@link PromotionOrderAction}, * and {@link PromotionShippingAction}. * * @docsCategory promotions * @docsPage promotion-action * @docsWeight 0 */ export abstract class PromotionAction< T extends ConfigArgs = ConfigArgs, U extends PromotionCondition[] | undefined = any, > extends ConfigurableOperationDef<T> { /** * @description * Used to determine the order of application of multiple Promotions * on the same Order. See the {@link Promotion} `priorityScore` field for * more information. * * @default 0 */ readonly priorityValue: number; /** @internal */ readonly conditions?: U; /** @internal */ protected readonly onActivateFn?: PromotionActionSideEffectFn<T>; /** @internal */ protected readonly onDeactivateFn?: PromotionActionSideEffectFn<T>; protected constructor(config: PromotionActionConfig<T, U>) { super(config); this.priorityValue = config.priorityValue || 0; this.conditions = config.conditions; this.onActivateFn = config.onActivate; this.onDeactivateFn = config.onDeactivate; } /** @internal */ abstract execute(...arg: any[]): number | Promise<number>; /** @internal */ onActivate( ctx: RequestContext, order: Order, args: ConfigArg[], promotion: Promotion, ): void | Promise<void> { return this.onActivateFn?.(ctx, order, this.argsArrayToHash(args), promotion); } /** @internal */ onDeactivate( ctx: RequestContext, order: Order, args: ConfigArg[], promotion: Promotion, ): void | Promise<void> { return this.onDeactivateFn?.(ctx, order, this.argsArrayToHash(args), promotion); } } /** * @description * Represents a PromotionAction which applies to individual {@link OrderLine}s. * * @example * ```ts * // Applies a percentage discount to each OrderLine * const itemPercentageDiscount = new PromotionItemAction({ * code: 'item_percentage_discount', * args: { discount: 'percentage' }, * execute(ctx, orderItem, orderLine, args) { * return -orderLine.unitPrice * (args.discount / 100); * }, * description: 'Discount every item by { discount }%', * }); * ``` * * @docsCategory promotions * @docsPage promotion-action * @docsWeight 1 */ export class PromotionItemAction< T extends ConfigArgs = ConfigArgs, U extends Array<PromotionCondition<any>> = [], > extends PromotionAction<T, U> { private readonly executeFn: ExecutePromotionItemActionFn<T, U>; constructor(config: PromotionItemActionConfig<T, U>) { super(config); this.executeFn = config.execute; } /** @internal */ execute( ctx: RequestContext, orderLine: OrderLine, args: ConfigArg[], state: PromotionState, promotion: Promotion, ) { const actionState = this.conditions ? pick( state, this.conditions.map(c => c.code), ) : {}; return this.executeFn( ctx, orderLine, this.argsArrayToHash(args), actionState as ConditionState<U>, promotion, ); } } /** * @description * Represents a PromotionAction which applies to the {@link Order} as a whole. * * @example * ```ts * // Applies a percentage discount to the entire Order * const orderPercentageDiscount = new PromotionOrderAction({ * code: 'order_percentage_discount', * args: { discount: 'percentage' }, * execute(ctx, order, args) { * return -order.subTotal * (args.discount / 100); * }, * description: 'Discount order by { discount }%', * }); * ``` * * @docsCategory promotions * @docsPage promotion-action * @docsWeight 2 */ export class PromotionOrderAction< T extends ConfigArgs = ConfigArgs, U extends PromotionCondition[] = [], > extends PromotionAction<T, U> { private readonly executeFn: ExecutePromotionOrderActionFn<T, U>; constructor(config: PromotionOrderActionConfig<T, U>) { super(config); this.executeFn = config.execute; } /** @internal */ execute( ctx: RequestContext, order: Order, args: ConfigArg[], state: PromotionState, promotion: Promotion, ) { const actionState = this.conditions ? pick( state, this.conditions.map(c => c.code), ) : {}; return this.executeFn( ctx, order, this.argsArrayToHash(args), actionState as ConditionState<U>, promotion, ); } } /** * @description * Represents a PromotionAction which applies to the shipping cost of an Order. * * @docsCategory promotions * @docsPage promotion-action * @docsWeight 3 */ export class PromotionShippingAction< T extends ConfigArgs = ConfigArgs, U extends PromotionCondition[] = [], > extends PromotionAction<T, U> { private readonly executeFn: ExecutePromotionShippingActionFn<T, U>; constructor(config: PromotionShippingActionConfig<T, U>) { super(config); this.executeFn = config.execute; } /** @internal */ execute( ctx: RequestContext, shippingLine: ShippingLine, order: Order, args: ConfigArg[], state: PromotionState, promotion: Promotion, ) { const actionState = this.conditions ? pick( state, this.conditions.map(c => c.code), ) : {}; return this.executeFn( ctx, shippingLine, order, this.argsArrayToHash(args), actionState as ConditionState<U>, promotion, ); } }
import { ConfigArg } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { Order } from '../../entity/order/order.entity'; import { Promotion } from '../../entity/promotion/promotion.entity'; export type PromotionConditionState = Record<string, unknown>; export type CheckPromotionConditionResult = boolean | PromotionConditionState; /** * @description * A function which checks whether or not a given {@link Order} satisfies the {@link PromotionCondition}. * * The function should return either a `boolean` or and plain object type: * * * `false`: The condition is not satisfied - do not apply PromotionActions * * `true`: The condition is satisfied, apply PromotionActions * * `{ [key: string]: any; }`: The condition is satisfied, apply PromotionActions * _and_ pass this object into the PromotionAction's `state` argument. * * @docsCategory promotions * @docsPage promotion-condition */ export type CheckPromotionConditionFn<T extends ConfigArgs, R extends CheckPromotionConditionResult> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, promotion: Promotion, ) => R | Promise<R>; /** * @description * This object is used to configure a PromotionCondition. * * @docsCategory promotions * @docsPage promotion-condition * @docsWeight 1 */ export interface PromotionConditionConfig< T extends ConfigArgs, C extends string, R extends CheckPromotionConditionResult, > extends ConfigurableOperationDefOptions<T> { code: C; check: CheckPromotionConditionFn<T, R>; priorityValue?: number; } /** * @description * PromotionConditions are used to create {@link Promotion}s. The purpose of a PromotionCondition * is to check the order against a particular predicate function (the `check` function) and to return * `true` if the Order satisfies the condition, or `false` if it does not. * * @docsCategory promotions * @docsPage promotion-condition * @docsWeight 0 */ export class PromotionCondition< T extends ConfigArgs = ConfigArgs, C extends string = string, R extends CheckPromotionConditionResult = any, > extends ConfigurableOperationDef<T> { /** * @description * Used to determine the order of application of multiple Promotions * on the same Order. See the {@link Promotion} `priorityScore` field for * more information. * * @default 0 */ readonly priorityValue: number; private readonly checkFn: CheckPromotionConditionFn<T, R>; get code(): C { return super.code as C; } constructor(config: PromotionConditionConfig<T, C, R>) { super(config); this.checkFn = config.check; this.priorityValue = config.priorityValue || 0; } /** * @description * This is the function which contains the conditional logic to decide whether * a Promotion should apply to an Order. See {@link CheckPromotionConditionFn}. */ async check(ctx: RequestContext, order: Order, args: ConfigArg[], promotion: Promotion): Promise<R> { return this.checkFn(ctx, order, this.argsArrayToHash(args), promotion); } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { idsAreEqual } from '../../../common/utils'; import { buyXGetYFreeCondition } from '../conditions/buy-x-get-y-free-condition'; import { PromotionItemAction } from '../promotion-action'; export const buyXGetYFreeAction = new PromotionItemAction({ code: 'buy_x_get_y_free', description: [ { languageCode: LanguageCode.en, value: 'Buy X products, get Y products free', }, ], args: {}, conditions: [buyXGetYFreeCondition], execute(ctx, orderLine, args, state) { const freeItemsPerLine = state.buy_x_get_y_free.freeItemsPerLine; const freeQuantity = freeItemsPerLine[orderLine.id]; if (freeQuantity) { const unitPrice = ctx.channel.pricesIncludeTax ? orderLine.unitPriceWithTax : orderLine.unitPrice; return -unitPrice * (freeQuantity / orderLine.quantity); } return 0; }, });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { PromotionItemAction } from '../promotion-action'; import { FacetValueChecker } from '../utils/facet-value-checker'; let facetValueChecker: FacetValueChecker; export const discountOnItemWithFacets = new PromotionItemAction({ code: 'facet_based_discount', args: { discount: { type: 'float', ui: { component: 'number-form-input', suffix: '%', }, }, facets: { type: 'ID', list: true, ui: { component: 'facet-value-form-input' }, }, }, init(injector) { facetValueChecker = new FacetValueChecker(injector.get(TransactionalConnection)); }, async execute(ctx, orderLine, args) { if (await facetValueChecker.hasFacetValues(orderLine, args.facets, ctx)) { const unitPrice = ctx.channel.pricesIncludeTax ? orderLine.unitPriceWithTax : orderLine.unitPrice; return -unitPrice * (args.discount / 100); } return 0; }, description: [ { languageCode: LanguageCode.en, value: 'Discount products with these facets by { discount }%' }, ], });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { PromotionShippingAction } from '../promotion-action'; export const freeShipping = new PromotionShippingAction({ code: 'free_shipping', args: {}, execute(ctx, shippingLine, order, args) { return ctx.channel.pricesIncludeTax ? -shippingLine.priceWithTax : -shippingLine.price; }, description: [{ languageCode: LanguageCode.en, value: 'Free shipping' }], });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { PromotionOrderAction } from '../promotion-action'; export const orderFixedDiscount = new PromotionOrderAction({ code: 'order_fixed_discount', args: { discount: { type: 'int', ui: { component: 'currency-form-input', }, }, }, execute(ctx, order, args) { const upperBound = ctx.channel.pricesIncludeTax ? order.subTotalWithTax : order.subTotal; return -Math.min(args.discount, upperBound); }, description: [{ languageCode: LanguageCode.en, value: 'Discount order by fixed amount' }], });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { PromotionOrderAction } from '../promotion-action'; export const orderPercentageDiscount = new PromotionOrderAction({ code: 'order_percentage_discount', args: { discount: { type: 'float', ui: { component: 'number-form-input', suffix: '%', }, }, }, execute(ctx, order, args) { const orderTotal = ctx.channel.pricesIncludeTax ? order.subTotalWithTax : order.subTotal; return -orderTotal * (args.discount / 100); }, description: [{ languageCode: LanguageCode.en, value: 'Discount order by { discount }%' }], });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { idsAreEqual } from '../../../common/utils'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; import { PromotionItemAction } from '../promotion-action'; export const productsPercentageDiscount = new PromotionItemAction({ code: 'products_percentage_discount', description: [{ languageCode: LanguageCode.en, value: 'Discount specified products by { discount }%' }], args: { discount: { type: 'float', ui: { component: 'number-form-input', suffix: '%', }, }, productVariantIds: { type: 'ID', list: true, ui: { component: 'product-selector-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Product variants' }], }, }, execute(ctx, orderLine, args) { if (lineContainsIds(args.productVariantIds, orderLine)) { const unitPrice = ctx.channel.pricesIncludeTax ? orderLine.unitPriceWithTax : orderLine.unitPrice; return -unitPrice * (args.discount / 100); } return 0; }, }); function lineContainsIds(ids: ID[], line: OrderLine): boolean { return !!ids.find(id => idsAreEqual(id, line.productVariant.id)); }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; import { PromotionCondition } from '../promotion-condition'; export const buyXGetYFreeCondition = new PromotionCondition({ code: 'buy_x_get_y_free', description: [ { languageCode: LanguageCode.en, value: 'Buy X products, get Y products free', }, ], args: { amountX: { type: 'int', defaultValue: 2, }, variantIdsX: { type: 'ID', list: true, ui: { component: 'product-selector-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Buy amountX of these variants' }], }, amountY: { type: 'int', defaultValue: 1, }, variantIdsY: { type: 'ID', list: true, ui: { component: 'product-selector-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Get amountY of these variants for free' }], }, }, async check(ctx, order, args) { const xIds = createIdentityMap(args.variantIdsX); const yIds = createIdentityMap(args.variantIdsY); let matches = 0; const freeItemCandidates: OrderLine[] = []; for (const line of order.lines) { const variantId = line.productVariant.id; if (variantId in xIds) { matches += line.quantity; } if (variantId in yIds) { freeItemCandidates.push(line); } } const quantity = Math.floor(matches / args.amountX); if (!quantity || !freeItemCandidates.length) return false; const freeLines = freeItemCandidates.sort((a, b) => { const unitPriceA = ctx.channel.pricesIncludeTax ? a.unitPriceWithTax : a.unitPrice; const unitPriceB = ctx.channel.pricesIncludeTax ? b.unitPriceWithTax : b.unitPrice; if (unitPriceA < unitPriceB) return -1; if (unitPriceA > unitPriceB) return 1; return 0; }); let placesToAllocate = args.amountY; const freeItemsPerLine: { [lineId: string]: number } = {}; for (const freeLine of freeLines) { if (placesToAllocate === 0) break; const freeQuantity = Math.min(freeLine.quantity, placesToAllocate); freeItemsPerLine[freeLine.id] = freeQuantity; placesToAllocate -= freeQuantity; } return { freeItemsPerLine }; }, }); function createIdentityMap(ids: ID[]): Record<ID, ID> { return ids.reduce((map: Record<ID, ID>, id) => ({ ...map, [id]: id }), {}); }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { idsAreEqual } from '../../../common/utils'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; import { PromotionCondition } from '../promotion-condition'; export const containsProducts = new PromotionCondition({ code: 'contains_products', description: [ { languageCode: LanguageCode.en, value: 'Buy at least { minimum } of the specified products' }, ], args: { minimum: { type: 'int', defaultValue: 1, }, productVariantIds: { type: 'ID', list: true, ui: { component: 'product-selector-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Product variants' }], }, }, async check(ctx, order, args) { const ids = args.productVariantIds; let matches = 0; for (const line of order.lines) { if (lineContainsIds(ids, line)) { matches += line.quantity; } } return args.minimum <= matches; }, }); function lineContainsIds(ids: ID[], line: OrderLine): boolean { return !!ids.find(id => idsAreEqual(id, line.productVariant.id)); }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { Subscription } from 'rxjs'; import { TtlCache } from '../../../common/ttl-cache'; import { idsAreEqual } from '../../../common/utils'; import { EventBus } from '../../../event-bus/event-bus'; import { CustomerGroupChangeEvent } from '../../../event-bus/events/customer-group-change-event'; import { PromotionCondition } from '../promotion-condition'; let customerService: import('../../../service/services/customer.service').CustomerService; let subscription: Subscription | undefined; const fiveMinutes = 5 * 60 * 1000; const cache = new TtlCache<ID, ID[]>({ ttl: fiveMinutes }); export const customerGroup = new PromotionCondition({ code: 'customer_group', description: [{ languageCode: LanguageCode.en, value: 'Customer is a member of the specified group' }], args: { customerGroupId: { type: 'ID', ui: { component: 'customer-group-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Customer group' }], }, }, async init(injector) { // Lazily-imported to avoid circular dependency issues. const { CustomerService } = await import('../../../service/services/customer.service.js'); customerService = injector.get(CustomerService); subscription = injector .get(EventBus) .ofType(CustomerGroupChangeEvent) .subscribe(event => { // When a customer is added to or removed from a group, we need // to invalidate the cache for that customer id for (const customer of event.customers) { cache.delete(customer.id); } }); }, destroy() { subscription?.unsubscribe(); }, async check(ctx, order, args) { if (!order.customer) { return false; } const customerId = order.customer.id; let groupIds = cache.get(customerId); if (!groupIds) { const groups = await customerService.getCustomerGroups(ctx, customerId); groupIds = groups.map(g => g.id); cache.set(customerId, groupIds); } return !!groupIds.find(id => idsAreEqual(id, args.customerGroupId)); }, });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { PromotionCondition } from '../promotion-condition'; import { FacetValueChecker } from '../utils/facet-value-checker'; let facetValueChecker: FacetValueChecker; export const hasFacetValues = new PromotionCondition({ code: 'at_least_n_with_facets', description: [ { languageCode: LanguageCode.en, value: 'Buy at least { minimum } products with the given facets' }, ], args: { minimum: { type: 'int', defaultValue: 1 }, facets: { type: 'ID', list: true, ui: { component: 'facet-value-form-input' } }, }, init(injector) { facetValueChecker = new FacetValueChecker(injector.get(TransactionalConnection)); }, // eslint-disable-next-line no-shadow,@typescript-eslint/no-shadow async check(ctx, order, args) { let matches = 0; for (const line of order.lines) { if (await facetValueChecker.hasFacetValues(line, args.facets, ctx)) { matches += line.quantity; } } return args.minimum <= matches; }, });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { PromotionCondition } from '../promotion-condition'; export const minimumOrderAmount = new PromotionCondition({ description: [{ languageCode: LanguageCode.en, value: 'If order total is greater than { amount }' }], code: 'minimum_order_amount', args: { amount: { type: 'int', defaultValue: 100, ui: { component: 'currency-form-input' }, }, taxInclusive: { type: 'boolean', defaultValue: false }, }, check(ctx, order, args) { if (args.taxInclusive) { return order.subTotalWithTax >= args.amount; } else { return order.subTotal >= args.amount; } }, priorityValue: 10, });
import { ID } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { RequestContext } from '../../../api'; import { TtlCache } from '../../../common/ttl-cache'; import { idsAreEqual } from '../../../common/utils'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; import { ProductVariant } from '../../../entity/product-variant/product-variant.entity'; /** * @description * The FacetValueChecker is a helper class used to determine whether a given OrderLine consists * of ProductVariants containing the given FacetValues. * * @example * ```ts * import { FacetValueChecker, LanguageCode, PromotionCondition, TransactionalConnection } from '\@vendure/core'; * * let facetValueChecker: FacetValueChecker; * * export const hasFacetValues = new PromotionCondition({ * code: 'at_least_n_with_facets', * description: [ * { languageCode: LanguageCode.en, value: 'Buy at least { minimum } products with the given facets' }, * ], * args: { * minimum: { type: 'int' }, * facets: { type: 'ID', list: true, ui: { component: 'facet-value-form-input' } }, * }, * init(injector) { * facetValueChecker = new FacetValueChecker(injector.get(TransactionalConnection)); * }, * async check(ctx, order, args) { * let matches = 0; * for (const line of order.lines) { * if (await facetValueChecker.hasFacetValues(line, args.facets)) { * matches += line.quantity; * } * } * return args.minimum <= matches; * }, * }); * ``` * * @docsCategory Promotions */ export class FacetValueChecker { private variantCache = new TtlCache<ID, ProductVariant>({ ttl: 5000 }); constructor(private connection: TransactionalConnection) {} /** * @description * Checks a given {@link OrderLine} against the facetValueIds and returns * `true` if the associated {@link ProductVariant} & {@link Product} together * have *all* the specified {@link FacetValue}s. */ async hasFacetValues(orderLine: OrderLine, facetValueIds: ID[], ctx?: RequestContext): Promise<boolean> { let variant = this.variantCache.get(orderLine.productVariant.id); if (!variant) { variant = await this.connection .getRepository(ctx, ProductVariant) .findOne({ where: { id: orderLine.productVariant.id }, relations: ['product', 'product.facetValues', 'facetValues'], }) .then(result => result ?? undefined); if (!variant) { return false; } this.variantCache.set(variant.id, variant); } const allFacetValues = unique([...variant.facetValues, ...variant.product.facetValues], 'id'); return facetValueIds.reduce( (result, id) => result && !!allFacetValues.find(fv => idsAreEqual(fv.id, id)), true as boolean, ); } }
import { CachedSession, SessionCacheStrategy } from './session-cache-strategy'; /** * @description * Caches session in memory, using a LRU cache implementation. Not suitable for * multi-server setups since the cache will be local to each instance, reducing * its effectiveness. By default the cache has a size of 1000, meaning that after * 1000 sessions have been cached, any new sessions will cause the least-recently-used * session to be evicted (removed) from the cache. * * The cache size can be configured by passing a different number to the constructor * function. * * @docsCategory auth */ export class InMemorySessionCacheStrategy implements SessionCacheStrategy { private readonly cache = new Map<string, CachedSession>(); private readonly cacheSize: number = 1000; constructor(cacheSize?: number) { if (cacheSize != null) { if (cacheSize < 1) { throw new Error('cacheSize must be a positive integer'); } this.cacheSize = Math.round(cacheSize); } } delete(sessionToken: string) { this.cache.delete(sessionToken); } get(sessionToken: string) { const item = this.cache.get(sessionToken); if (item) { // refresh key this.cache.delete(sessionToken); this.cache.set(sessionToken, item); } return item; } set(session: CachedSession) { this.cache.set(session.token, session); if (this.cache.has(session.token)) { // refresh key this.cache.delete(session.token); } else if (this.cache.size === this.cacheSize) { // evict oldest this.cache.delete(this.first()); } this.cache.set(session.token, session); } clear() { this.cache.clear(); } private first() { return this.cache.keys().next().value; } }
import { CachedSession, SessionCacheStrategy } from './session-cache-strategy'; /** * @description * A cache that doesn't cache. The cache lookup will miss every time * so the session will always be taken from the database. * * @docsCategory auth */ export class NoopSessionCacheStrategy implements SessionCacheStrategy { clear() { return undefined; } delete(sessionToken: string) { return undefined; } get(sessionToken: string) { return undefined; } set(session: CachedSession) { return undefined; } }
import { ID } from '@vendure/common/lib/shared-types'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { UserChannelPermissions } from '../../service/helpers/utils/get-user-channels-permissions'; /** * @description * A simplified representation of the User associated with the * current Session. * * @docsCategory auth * @docsPage SessionCacheStrategy */ export type CachedSessionUser = { id: ID; identifier: string; verified: boolean; channelPermissions: UserChannelPermissions[]; }; /** * @description * A simplified representation of a Session which is easy to * store. * * @docsCategory auth * @docsPage SessionCacheStrategy */ export type CachedSession = { /** * @description * The timestamp after which this cache entry is considered stale and * a fresh copy of the data will be set. Based on the `sessionCacheTTL` * option. */ cacheExpiry: number; id: ID; token: string; expires: Date; activeOrderId?: ID; authenticationStrategy?: string; user?: CachedSessionUser; activeChannelId?: ID; }; /** * @description * This strategy defines how sessions get cached. Since most requests will need the Session * object for permissions data, it can become a bottleneck to go to the database and do a multi-join * SQL query each time. Therefore, we cache the session data only perform the SQL query once and upon * invalidation of the cache. * * The Vendure default is to use a the {@link InMemorySessionCacheStrategy}, which is fast and suitable for * single-instance deployments. However, for multi-instance deployments (horizontally scaled, serverless etc.), * you will need to define a custom strategy that stores the session cache in a shared data store, such as in the * DB or in Redis. * * :::info * * This is configured via the `authOptions.sessionCacheStrategy` property of * your VendureConfig. * * ::: * * Here's an example implementation using Redis. To use this, you need to add the * [ioredis package](https://www.npmjs.com/package/ioredis) as a dependency. * * @example * ```ts * import { CachedSession, Logger, SessionCacheStrategy, VendurePlugin } from '\@vendure/core'; * import { Redis, RedisOptions } from 'ioredis'; * * export interface RedisSessionCachePluginOptions { * namespace?: string; * redisOptions?: RedisOptions; * } * const loggerCtx = 'RedisSessionCacheStrategy'; * const DEFAULT_NAMESPACE = 'vendure-session-cache'; * const DEFAULT_TTL = 86400; * * export class RedisSessionCacheStrategy implements SessionCacheStrategy { * private client: Redis; * constructor(private options: RedisSessionCachePluginOptions) {} * * init() { * this.client = new Redis(this.options.redisOptions as RedisOptions); * this.client.on('error', err => Logger.error(err.message, loggerCtx, err.stack)); * } * * async destroy() { * await this.client.quit(); * } * * async get(sessionToken: string): Promise<CachedSession | undefined> { * try { * const retrieved = await this.client.get(this.namespace(sessionToken)); * if (retrieved) { * try { * return JSON.parse(retrieved); * } catch (e: any) { * Logger.error(`Could not parse cached session data: ${e.message}`, loggerCtx); * } * } * } catch (e: any) { * Logger.error(`Could not get cached session: ${e.message}`, loggerCtx); * } * } * * async set(session: CachedSession) { * try { * await this.client.set(this.namespace(session.token), JSON.stringify(session), 'EX', DEFAULT_TTL); * } catch (e: any) { * Logger.error(`Could not set cached session: ${e.message}`, loggerCtx); * } * } * * async delete(sessionToken: string) { * try { * await this.client.del(this.namespace(sessionToken)); * } catch (e: any) { * Logger.error(`Could not delete cached session: ${e.message}`, loggerCtx); * } * } * * clear() { * // not implemented * } * * private namespace(key: string) { * return `${this.options.namespace ?? DEFAULT_NAMESPACE}:${key}`; * } * } * * \@VendurePlugin({ * configuration: config => { * config.authOptions.sessionCacheStrategy = new RedisSessionCacheStrategy( * RedisSessionCachePlugin.options, * ); * return config; * }, * }) * export class RedisSessionCachePlugin { * static options: RedisSessionCachePluginOptions; * static init(options: RedisSessionCachePluginOptions) { * this.options = options; * return this; * } * } * ``` * * @docsCategory auth * @docsPage SessionCacheStrategy * @docsWeight 0 */ export interface SessionCacheStrategy extends InjectableStrategy { /** * @description * Store the session in the cache. When caching a session, the data * should not be modified apart from performing any transforms needed to * get it into a state to be stored, e.g. JSON.stringify(). */ set(session: CachedSession): void | Promise<void>; /** * @description * Retrieve the session from the cache */ get(sessionToken: string): CachedSession | undefined | Promise<CachedSession | undefined>; /** * @description * Delete a session from the cache */ delete(sessionToken: string): void | Promise<void>; /** * @description * Clear the entire cache */ clear(): void | Promise<void>; }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { ShippingCalculator } from './shipping-calculator'; export enum TaxSetting { include = 'include', exclude = 'exclude', auto = 'auto', } export const defaultShippingCalculator = new ShippingCalculator({ code: 'default-shipping-calculator', description: [{ languageCode: LanguageCode.en, value: 'Default Flat-Rate Shipping Calculator' }], args: { rate: { type: 'int', defaultValue: 0, ui: { component: 'currency-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Shipping price' }], }, includesTax: { type: 'string', defaultValue: TaxSetting.auto, ui: { component: 'select-form-input', options: [ { label: [{ languageCode: LanguageCode.en, value: 'Includes tax' }], value: TaxSetting.include, }, { label: [{ languageCode: LanguageCode.en, value: 'Excludes tax' }], value: TaxSetting.exclude, }, { label: [{ languageCode: LanguageCode.en, value: 'Auto (based on Channel)' }], value: TaxSetting.auto, }, ], }, label: [{ languageCode: LanguageCode.en, value: 'Price includes tax' }], }, taxRate: { type: 'int', defaultValue: 0, ui: { component: 'number-form-input', suffix: '%' }, label: [{ languageCode: LanguageCode.en, value: 'Tax rate' }], }, }, calculate: (ctx, order, args) => { return { price: args.rate, taxRate: args.taxRate, priceIncludesTax: getPriceIncludesTax(ctx, args.includesTax as any), }; }, }); function getPriceIncludesTax(ctx: RequestContext, setting: TaxSetting): boolean { switch (setting) { case TaxSetting.auto: return ctx.channel.pricesIncludeTax; case TaxSetting.exclude: return false; case TaxSetting.include: return true; } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { ShippingEligibilityChecker } from './shipping-eligibility-checker'; export const defaultShippingEligibilityChecker = new ShippingEligibilityChecker({ code: 'default-shipping-eligibility-checker', description: [{ languageCode: LanguageCode.en, value: 'Default Shipping Eligibility Checker' }], args: { orderMinimum: { type: 'int', defaultValue: 0, ui: { component: 'currency-form-input' }, label: [{ languageCode: LanguageCode.en, value: 'Minimum order value' }], description: [ { languageCode: LanguageCode.en, value: 'Order is eligible only if its total is greater or equal to this value', }, ], }, }, check: (ctx, order, args) => { return order.subTotalWithTax >= args.orderMinimum; }, });
import { RequestContext } from '../../api/common/request-context'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { ShippingLine } from '../../entity/shipping-line/shipping-line.entity'; import { ShippingLineAssignmentStrategy } from './shipping-line-assignment-strategy'; /** * @description * This is the default {@link ShippingLineAssignmentStrategy} which simply assigns all OrderLines to the * ShippingLine, and is suitable for the most common scenario of a single shipping method per Order. * * @since 2.0.0 * @docsCategory shipping */ export class DefaultShippingLineAssignmentStrategy implements ShippingLineAssignmentStrategy { assignShippingLineToOrderLines( ctx: RequestContext, shippingLine: ShippingLine, order: Order, ): OrderLine[] | Promise<OrderLine[]> { return order.lines; } }
import { ConfigArg } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { ShippingMethod, Order } from '../../entity'; export interface ShippingCalculatorConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { calculate: CalculateShippingFn<T>; } /** * @description * The ShippingCalculator is used by a {@link ShippingMethod} to calculate the price of shipping on a given {@link Order}. * * @example * ```ts * const flatRateCalculator = new ShippingCalculator({ * code: 'flat-rate-calculator', * description: [{ languageCode: LanguageCode.en, value: 'Default Flat-Rate Shipping Calculator' }], * args: { * rate: { * type: 'int', * ui: { component: 'currency-form-input' }, * }, * taxRate: { type: 'int', ui: { component: 'number-form-input', suffix: '%' }, }, * }, * calculate: (ctx, order, args) => { * return { * price: args.rate, * taxRate: args.taxRate, * priceIncludesTax: ctx.channel.pricesIncludeTax, * }; * }, * }); * ``` * * @docsCategory shipping * @docsPage ShippingCalculator */ export class ShippingCalculator<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { private readonly calculateFn: CalculateShippingFn<T>; constructor(config: ShippingCalculatorConfig<T>) { super(config); this.calculateFn = config.calculate; } /** * @description * Calculates the price of shipping for the given Order. * * @internal */ calculate( ctx: RequestContext, order: Order, args: ConfigArg[], method: ShippingMethod, ): CalculateShippingFnResult { return this.calculateFn(ctx, order, this.argsArrayToHash(args), method); } } /** * @description * The return value of the {@link CalculateShippingFn}. * * @docsCategory shipping * @docsPage ShippingCalculator */ export interface ShippingCalculationResult { /** * @description * The shipping price without any taxes. */ price: number; /** * @description * Whether or not the given price already includes taxes. */ priceIncludesTax: boolean; /** * @description * The tax rate applied to the shipping price. */ taxRate: number; /** * @description * Arbitrary metadata may be returned from the calculation function. This can be used * e.g. to return data on estimated delivery times or any other data which may be * needed in the storefront application when listing eligible shipping methods. */ metadata?: Record<string, any>; } export type CalculateShippingFnResult = | ShippingCalculationResult | Promise<ShippingCalculationResult | undefined> | undefined; /** * @description * A function which implements the specific shipping calculation logic. It takes an {@link Order} and * an arguments object and should return the shipping price as an integer in cents. * * Should return a {@link ShippingCalculationResult} object. * * @docsCategory shipping * @docsPage ShippingCalculator */ export type CalculateShippingFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, method: ShippingMethod, ) => CalculateShippingFnResult;
import { ConfigArg } from '@vendure/common/lib/generated-types'; import { Json } from '@vendure/common/lib/shared-types'; import { createHash } from 'crypto'; import { RequestContext } from '../../api/common/request-context'; import { ConfigArgs, ConfigArgValues, ConfigurableOperationDef, ConfigurableOperationDefOptions, } from '../../common/configurable-operation'; import { TtlCache } from '../../common/ttl-cache'; import { ShippingMethod, Order } from '../../entity'; /** * @description * Configuration passed into the constructor of a {@link ShippingEligibilityChecker} to * configure its behavior. * * @docsCategory shipping */ export interface ShippingEligibilityCheckerConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { check: CheckShippingEligibilityCheckerFn<T>; shouldRunCheck?: ShouldRunCheckFn<T>; } /** * @description * The ShippingEligibilityChecker class is used to check whether an order qualifies for a * given {@link ShippingMethod}. * * @example * ```ts * const minOrderTotalEligibilityChecker = new ShippingEligibilityChecker({ * code: 'min-order-total-eligibility-checker', * description: [{ languageCode: LanguageCode.en, value: 'Checks that the order total is above some minimum value' }], * args: { * orderMinimum: { type: 'int', ui: { component: 'currency-form-input' } }, * }, * check: (ctx, order, args) => { * return order.totalWithTax >= args.orderMinimum; * }, * }); * ``` * * @docsCategory shipping * @docsPage ShippingEligibilityChecker */ export class ShippingEligibilityChecker< T extends ConfigArgs = ConfigArgs, > extends ConfigurableOperationDef<T> { private readonly checkFn: CheckShippingEligibilityCheckerFn<T>; private readonly shouldRunCheckFn?: ShouldRunCheckFn<T>; private shouldRunCheckCache = new TtlCache({ cacheSize: 5000, ttl: 1000 * 60 * 60 * 5 }); constructor(config: ShippingEligibilityCheckerConfig<T>) { super(config); this.checkFn = config.check; this.shouldRunCheckFn = config.shouldRunCheck; } /** * @description * Check the given Order to determine whether it is eligible. * * @internal */ async check( ctx: RequestContext, order: Order, args: ConfigArg[], method: ShippingMethod, ): Promise<boolean> { const shouldRunCheck = await this.shouldRunCheck(ctx, order, args, method); return shouldRunCheck ? this.checkFn(ctx, order, this.argsArrayToHash(args), method) : true; } /** * Determines whether the check function needs to be run, based on the presence and * result of any defined `shouldRunCheckFn`. */ private async shouldRunCheck( ctx: RequestContext, order: Order, args: ConfigArg[], method: ShippingMethod, ): Promise<boolean> { if (typeof this.shouldRunCheckFn === 'function') { const cacheKey = ctx.session?.id; if (cacheKey) { const checkResult = await this.shouldRunCheckFn( ctx, order, this.argsArrayToHash(args), method, ); const checkResultHash = createHash('sha1') .update(JSON.stringify(checkResult)) .digest('base64'); const lastResultHash = this.shouldRunCheckCache.get(cacheKey); this.shouldRunCheckCache.set(cacheKey, checkResultHash); if (checkResultHash === lastResultHash) { return false; } } } return true; } } /** * @description * A function which implements logic to determine whether a given {@link Order} is eligible for * a particular shipping method. Once a ShippingMethod has been assigned to an Order, this * function will be called on every change to the Order (e.g. updating quantities, adding/removing * items etc). * * If the code running in this function is expensive, then consider also defining * a {@link ShouldRunCheckFn} to avoid unnecessary calls. * * @docsCategory shipping */ export type CheckShippingEligibilityCheckerFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, method: ShippingMethod, ) => boolean | Promise<boolean>; /** * @description * An optional method which is used to decide whether to run the `check()` function. * Returns a JSON-compatible object which is cached and compared between calls. * If the value is the same, then the `check()` function is not called. * * Use of this function is an optimization technique which can be useful when * the `check()` function is expensive and should be kept to an absolute minimum. * * @example * ```ts * const optimizedChecker = new ShippingEligibilityChecker({ * code: 'example', * description: [], * args: {}, * check: async (ctx, order) => { * // some slow, expensive function here * }, * shouldRunCheck: (ctx, order) => { * // Will only run the `check()` function any time * // the shippingAddress object has changed. * return order.shippingAddress; * }, * }); * ``` * * @docsCategory shipping */ export type ShouldRunCheckFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, method: ShippingMethod, ) => Json | Promise<Json>;
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { ShippingLine } from '../../entity/shipping-line/shipping-line.entity'; /** * @description * This strategy is used to assign a given {@link ShippingLine} to one or more {@link OrderLine}s of the Order. * This allows you to set multiple shipping methods for a single order, each assigned a different subset of * OrderLines. * * The {@link DefaultShippingLineAssignmentStrategy} simply assigns _all_ OrderLines, so is suitable for the * most common scenario of a single shipping method per Order. * * :::info * * This is configured via the `shippingOptions.shippingLineAssignmentStrategy` property of * your VendureConfig. * * ::: * * Here's an example of a custom ShippingLineAssignmentStrategy which assigns digital products to a * different ShippingLine to physical products: * * ```ts * import { * Order, * OrderLine, * RequestContext, * ShippingLine, * ShippingLineAssignmentStrategy, * } from '\@vendure/core'; * * export class DigitalShippingLineAssignmentStrategy implements ShippingLineAssignmentStrategy { * assignShippingLineToOrderLines( * ctx: RequestContext, * shippingLine: ShippingLine, * order: Order, * ): OrderLine[] | Promise<OrderLine[]> { * if (shippingLine.shippingMethod.customFields.isDigital) { * return order.lines.filter(l => l.productVariant.customFields.isDigital); * } else { * return order.lines.filter(l => !l.productVariant.customFields.isDigital); * } * } * } * ``` * * @since 2.0.0 * @docsCategory shipping */ export interface ShippingLineAssignmentStrategy extends InjectableStrategy { assignShippingLineToOrderLines( ctx: RequestContext, shippingLine: ShippingLine, order: Order, ): OrderLine[] | Promise<OrderLine[]>; }
import { ArgumentsHost } from '@nestjs/common'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Job } from '../../job-queue/job'; /** * @description * This strategy defines logic for handling errors thrown during on both the server * and the worker. It can be used for additional logging & monitoring, or for sending error * reports to external services. * * :::info * * This is configured via the `systemOptions.errorHandlers` property of * your VendureConfig. * * ::: * * @example * ```ts * import { ArgumentsHost, ExecutionContext } from '\@nestjs/common'; * import { GqlContextType, GqlExecutionContext } from '\@nestjs/graphql'; * import { ErrorHandlerStrategy, I18nError, Injector, Job, LogLevel } from '\@vendure/core'; * * import { MonitoringService } from './monitoring.service'; * * export class CustomErrorHandlerStrategy implements ErrorHandlerStrategy { * private monitoringService: MonitoringService; * * init(injector: Injector) { * this.monitoringService = injector.get(MonitoringService); * } * * handleServerError(error: Error, { host }: { host: ArgumentsHost }) { * const errorContext: any = {}; * if (host?.getType<GqlContextType>() === 'graphql') { * const gqlContext = GqlExecutionContext.create(host as ExecutionContext); * const info = gqlContext.getInfo(); * errorContext.graphQlInfo = { * fieldName: info.fieldName, * path: info.path, * }; * } * this.monitoringService.captureException(error, errorContext); * } * * handleWorkerError(error: Error, { job }: { job: Job }) { * const errorContext = { * queueName: job.queueName, * jobId: job.id, * }; * this.monitoringService.captureException(error, errorContext); * } * } * ``` * * @since 2.2.0 * @docsCategory Errors */ export interface ErrorHandlerStrategy extends InjectableStrategy { /** * @description * This method will be invoked for any error thrown during the execution of the * server. */ handleServerError(exception: Error, context: { host: ArgumentsHost }): void | Promise<void>; /** * @description * This method will be invoked for any error thrown during the execution of a * job on the worker. */ handleWorkerError(exception: Error, context: { job: Job }): void | Promise<void>; }
import { HealthIndicatorFunction } from '@nestjs/terminus'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; /** * @description * This strategy defines health checks which are included as part of the * `/health` endpoint. They should only be used to monitor _critical_ systems * on which proper functioning of the Vendure server depends. * * For more information on the underlying mechanism, see the * [NestJS Terminus module docs](https://docs.nestjs.com/recipes/terminus). * * Custom strategies should be added to the `systemOptions.healthChecks` array. * By default, Vendure includes the `TypeORMHealthCheckStrategy`, so if you set the value of the `healthChecks` * array, be sure to include it manually. * * Vendure also ships with the {@link HttpHealthCheckStrategy}, which is convenient * for adding a health check dependent on an HTTP ping. * * :::info * * This is configured via the `systemOptions.healthChecks` property of * your VendureConfig. * * ::: * * * @example * ```ts * import { HttpHealthCheckStrategy, TypeORMHealthCheckStrategy } from '\@vendure/core'; * import { MyCustomHealthCheckStrategy } from './config/custom-health-check-strategy'; * * export const config = { * // ... * systemOptions: { * healthChecks: [ * new TypeORMHealthCheckStrategy(), * new HttpHealthCheckStrategy({ key: 'my-service', url: 'https://my-service.com' }), * new MyCustomHealthCheckStrategy(), * ], * }, * }; * ``` * * @docsCategory health-check */ export interface HealthCheckStrategy extends InjectableStrategy { /** * @description * Should return a `HealthIndicatorFunction`, as defined by the * [NestJS Terminus module](https://docs.nestjs.com/recipes/terminus). */ getHealthIndicator(): HealthIndicatorFunction; }
import { TaxLine } from '@vendure/common/lib/generated-types'; import { CalculateTaxLinesArgs, TaxLineCalculationStrategy } from './tax-line-calculation-strategy'; /** * @description * The default {@link TaxLineCalculationStrategy} which applies a single TaxLine to the OrderLine * based on the applicable {@link TaxRate}. * * @docsCategory tax */ export class DefaultTaxLineCalculationStrategy implements TaxLineCalculationStrategy { calculate(args: CalculateTaxLinesArgs): TaxLine[] { const { orderLine, applicableTaxRate } = args; return [applicableTaxRate.apply(orderLine.proratedUnitPrice)]; } }
import { RequestContext } from '../../api/common/request-context'; import { Channel, Order, Zone } from '../../entity'; import { TaxZoneStrategy } from './tax-zone-strategy'; /** * @description * A default method of determining Zone for tax calculations. * * @docsCategory tax */ export class DefaultTaxZoneStrategy implements TaxZoneStrategy { determineTaxZone(ctx: RequestContext, zones: Zone[], channel: Channel, order?: Order): Zone { return channel.defaultTaxZone; } }
import { TaxLine } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { TaxRate } from '../../entity/tax-rate/tax-rate.entity'; /** * @description * This strategy defines how the TaxLines on OrderItems are calculated. By default, * the {@link DefaultTaxLineCalculationStrategy} is used, which directly applies * a single TaxLine based on the applicable {@link TaxRate}. * * However, custom strategies may use any suitable method for calculating TaxLines. * For example, a third-party tax API or a lookup of a custom tax table may be used. * * :::info * * This is configured via the `taxOptions.taxLineCalculationStrategy` property of * your VendureConfig. * * ::: * * @docsCategory tax * @docsPage TaxLineCalculationStrategy * @docsWeight 0 */ export interface TaxLineCalculationStrategy extends InjectableStrategy { /** * @description * This method is called when calculating the Order prices. Since it will be called * whenever an Order is modified in some way (adding/removing items, applying promotions, * setting ShippingMethod etc), care should be taken so that calling the function does * not adversely impact overall performance. For example, by using caching and only * calling external APIs when absolutely necessary. */ calculate(args: CalculateTaxLinesArgs): TaxLine[] | Promise<TaxLine[]>; } /** * @description * * @docsCategory tax * @docsPage TaxLineCalculationStrategy */ export interface CalculateTaxLinesArgs { ctx: RequestContext; order: Order; orderLine: OrderLine; applicableTaxRate: TaxRate; }
import { RequestContext } from '../../api/common/request-context'; import { InjectableStrategy } from '../../common/types/injectable-strategy'; import { Channel, Order, Zone } from '../../entity'; /** * @description * Defines how the active {@link Zone} is determined for the purposes of calculating taxes. * * This strategy is used in 2 scenarios: * * 1. To determine the applicable Zone when calculating the taxRate to apply when displaying ProductVariants. In this case the * `order` argument will be undefined, as the request is not related to a specific Order. * 2. To determine the applicable Zone when calculating the taxRate on the contents of a specific Order. In this case the * `order` argument _will_ be defined, and can be used in the logic. For example, the shipping address can be taken into account. * * Note that this method is called very often in a typical user session, so any work it performs should be designed with as little * performance impact as possible. * * :::info * * This is configured via the `taxOptions.taxZoneStrategy` property of * your VendureConfig. * * ::: * * @docsCategory tax */ export interface TaxZoneStrategy extends InjectableStrategy { determineTaxZone( ctx: RequestContext, zones: Zone[], channel: Channel, order?: Order, ): Zone | Promise<Zone> | undefined; }
import { DynamicModule, Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { DataSourceOptions } from 'typeorm'; import { ConfigModule } from '../config/config.module'; import { ConfigService } from '../config/config.service'; import { TypeOrmLogger } from '../config/logger/typeorm-logger'; import { TransactionSubscriber } from './transaction-subscriber'; import { TransactionWrapper } from './transaction-wrapper'; import { TransactionalConnection } from './transactional-connection'; let defaultTypeOrmModule: DynamicModule; @Module({ imports: [ConfigModule], providers: [TransactionalConnection, TransactionSubscriber, TransactionWrapper], exports: [TransactionalConnection, TransactionSubscriber, TransactionWrapper], }) export class ConnectionModule { static forRoot(): DynamicModule { if (!defaultTypeOrmModule) { defaultTypeOrmModule = TypeOrmModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => { const { dbConnectionOptions } = configService; const logger = ConnectionModule.getTypeOrmLogger(dbConnectionOptions); return { ...dbConnectionOptions, logger, }; }, inject: [ConfigService], }); } return { module: ConnectionModule, imports: [defaultTypeOrmModule], }; } static forPlugin(): DynamicModule { return { module: ConnectionModule, imports: [TypeOrmModule.forFeature()], }; } static getTypeOrmLogger(dbConnectionOptions: DataSourceOptions) { if (!dbConnectionOptions.logger) { return new TypeOrmLogger(dbConnectionOptions.logging); } else { return dbConnectionOptions.logger; } } }
import { FindOneOptions } from 'typeorm'; import { FindOptionsRelationByString } from 'typeorm/find-options/FindOptionsRelations'; /** * Some internal APIs depend on the TypeORM FindOptions `relations` property being a string array. * This function converts the new-style FindOptionsRelations object to a string array. */ export function findOptionsObjectToArray<T>( input: NonNullable<FindOneOptions['relations']>, parentKey?: string, ): FindOptionsRelationByString { if (Array.isArray(input)) { return input; } const keys = Object.keys(input); return keys.reduce((acc: string[], key: string) => { const value = input[key as any]; const path = parentKey ? `${parentKey}.${key}` : key; acc.push(path); // Push parent key instead of path if (typeof value === 'object' && value !== null) { const subKeys = findOptionsObjectToArray(value, path); acc.push(...subKeys); } return acc; }, []); }
export * from './transactional-connection'; export * from './transaction-subscriber'; export * from './connection.module'; export * from './types';
import { SelectQueryBuilder } from 'typeorm'; import { Logger } from '../config/logger/vendure-logger'; /** * This is a work-around for this issue: https://github.com/vendure-ecommerce/vendure/issues/1664 * * Explanation: * When calling `FindOptionsUtils.joinEagerRelations()`, there appears to be a bug in TypeORM whereby * it will throw the following error *if* the `options.relations` array contains any customField relations * where the related entity itself has eagerly-loaded relations. * * For example, let's say we define a custom field on the Product entity like this: * ``` * Product: [{ * name: 'featuredFacet', * type: 'relation', * entity: Facet, * }], * ``` * and then we pass into `TransactionalConnection.findOneInChannel()` an options array of: * * ``` * { relations: ['customFields.featuredFacet'] } * ``` * it will throw an error because the `Facet` entity itself has eager relations (namely the `translations` property). * This will cause TypeORM to throw the error: * ``` * TypeORMError: "entity__customFields" alias was not found. Maybe you forgot to join it? * ``` * * So this method introspects the QueryBuilder metadata and checks for any custom field relations which * themselves have eager relations. If found, it removes those items from the `options.relations` array. * * TODO: Ideally create a minimal reproduction case and report in the TypeORM repo for an upstream fix. */ export function removeCustomFieldsWithEagerRelations<T extends string>( qb: SelectQueryBuilder<any>, relations: T[] = [], ): T[] { let resultingRelations = relations; const mainAlias = qb.expressionMap.mainAlias; const customFieldsMetadata = mainAlias?.metadata.embeddeds.find( metadata => metadata.propertyName === 'customFields', ); if (customFieldsMetadata) { const customFieldRelationsWithEagerRelations = customFieldsMetadata.relations.filter(relation => { return ( !!relation.inverseEntityMetadata.ownRelations.find(or => or.isEager === true) || relation.inverseEntityMetadata.embeddeds.find( em => em.propertyName === 'customFields' && em.relations.find(emr => emr.isEager), ) ); }); for (const relation of customFieldRelationsWithEagerRelations) { const propertyName = relation.propertyName; const relationsToRemove = relations.filter(r => r.startsWith(`customFields.${propertyName}`)); if (relationsToRemove.length) { Logger.debug( `TransactionalConnection.findOneInChannel cannot automatically join relation [${ mainAlias?.metadata.name ?? '(unknown)' }.customFields.${propertyName}]`, ); resultingRelations = relations.filter(r => !r.startsWith(`customFields.${propertyName}`)); } } } return resultingRelations; }
import { Injectable } from '@nestjs/common'; import { InjectConnection } from '@nestjs/typeorm'; import { lastValueFrom, merge, ObservableInput, Subject } from 'rxjs'; import { delay, filter, map, take, tap } from 'rxjs/operators'; import { Connection, EntitySubscriberInterface } from 'typeorm'; import { EntityManager } from 'typeorm/entity-manager/EntityManager'; import { QueryRunner } from 'typeorm/query-runner/QueryRunner'; import { TransactionCommitEvent } from 'typeorm/subscriber/event/TransactionCommitEvent'; import { TransactionRollbackEvent } from 'typeorm/subscriber/event/TransactionRollbackEvent'; /** * This error should be thrown by an event subscription if types do not match * * @internal */ export class TransactionSubscriberError extends Error {} export type TransactionSubscriberEventType = 'commit' | 'rollback'; export interface TransactionSubscriberEvent { /** * Event type. Either commit or rollback. */ type: TransactionSubscriberEventType; /** * Connection used in the event. */ connection: Connection; /** * QueryRunner used in the event transaction. * All database operations in the subscribed event listener should be performed using this query runner instance. */ queryRunner: QueryRunner; /** * EntityManager used in the event transaction. * All database operations in the subscribed event listener should be performed using this entity manager instance. */ manager: EntityManager; } /** * This subscriber listens to all transaction commit/rollback events emitted by TypeORM * so that we can be notified as soon as a particular queryRunner's transactions ends. * * This is used by the {@link EventBus} to prevent events from being published until their * associated transactions are complete. */ @Injectable() export class TransactionSubscriber implements EntitySubscriberInterface { private subject$ = new Subject<TransactionSubscriberEvent>(); constructor(@InjectConnection() private connection: Connection) { if (!connection.subscribers.find(subscriber => subscriber.constructor === TransactionSubscriber)) { connection.subscribers.push(this); } } afterTransactionCommit(event: TransactionCommitEvent) { this.subject$.next({ type: 'commit', ...event, }); } afterTransactionRollback(event: TransactionRollbackEvent) { this.subject$.next({ type: 'rollback', ...event, }); } awaitCommit(queryRunner: QueryRunner): Promise<QueryRunner> { return this.awaitTransactionEvent(queryRunner, 'commit'); } awaitRollback(queryRunner: QueryRunner): Promise<QueryRunner> { return this.awaitTransactionEvent(queryRunner, 'rollback'); } awaitRelease(queryRunner: QueryRunner): Promise<QueryRunner> { return this.awaitTransactionEvent(queryRunner); } private awaitTransactionEvent( queryRunner: QueryRunner, type?: TransactionSubscriberEventType, ): Promise<QueryRunner> { if (queryRunner.isTransactionActive) { return lastValueFrom(this.subject$ .pipe( filter( event => !event.queryRunner.isTransactionActive && event.queryRunner === queryRunner, ), take(1), tap(event => { if (type && event.type !== type) { throw new TransactionSubscriberError(`Unexpected event type: ${event.type}. Expected ${type}.`); } }), map(event => event.queryRunner), // This `delay(0)` call appears to be necessary with the upgrade to TypeORM // v0.2.41, otherwise an active queryRunner can still get picked up in an event // subscriber function. This is manifested by the e2e test // "Transaction infrastructure › passing transaction via EventBus" failing // in the database-transactions.e2e-spec.ts suite, and a bunch of errors // in the default-search-plugin.e2e-spec.ts suite when using sqljs. delay(0), ) ); } else { return Promise.resolve(queryRunner); } } }
import { from, lastValueFrom, Observable, of } from 'rxjs'; import { retryWhen, take, tap } from 'rxjs/operators'; import { Connection, EntityManager, QueryRunner } from 'typeorm'; import { TransactionAlreadyStartedError } from 'typeorm/error/TransactionAlreadyStartedError'; import { RequestContext } from '../api/common/request-context'; import { TransactionIsolationLevel, TransactionMode } from '../api/decorators/transaction.decorator'; import { TRANSACTION_MANAGER_KEY } from '../common/constants'; /** * @description * This helper class is used to wrap operations in a TypeORM transaction in order to ensure * atomic operations on the database. */ export class TransactionWrapper { /** * @description * Executes the `work` function within the context of a transaction. If the `work` function * resolves / completes, then all the DB operations it contains will be committed. If it * throws an error or rejects, then all DB operations will be rolled back. * * @note * This function does not mutate your context. Instead, this function makes a copy and passes * context to work function. */ async executeInTransaction<T>( originalCtx: RequestContext, work: (ctx: RequestContext) => Observable<T> | Promise<T>, mode: TransactionMode, isolationLevel: TransactionIsolationLevel | undefined, connection: Connection, ): Promise<T> { // Copy to make sure original context will remain valid after transaction completes const ctx = originalCtx.copy(); const entityManager: EntityManager | undefined = (ctx as any)[TRANSACTION_MANAGER_KEY]; const queryRunner = entityManager ?.queryRunner || connection.createQueryRunner(); if (mode === 'auto') { await this.startTransaction(queryRunner, isolationLevel); } (ctx as any)[TRANSACTION_MANAGER_KEY] = queryRunner.manager; try { const maxRetries = 5; const result = await lastValueFrom( from(work(ctx)).pipe( retryWhen(errors => errors.pipe( tap(err => { if (!this.isRetriableError(err)) { throw err; } }), take(maxRetries), ), ), ), ); if (queryRunner.isTransactionActive) { await queryRunner.commitTransaction(); } return result; } catch (error) { if (queryRunner.isTransactionActive) { await queryRunner.rollbackTransaction(); } throw error; } finally { if (!queryRunner.isTransactionActive && queryRunner.isReleased === false) { // There is a check for an active transaction // because this could be a nested transaction (savepoint). await queryRunner.release(); } } } /** * Attempts to start a DB transaction, with retry logic in the case that a transaction * is already started for the connection (which is mainly a problem with SQLite/Sql.js) */ private async startTransaction(queryRunner: QueryRunner, isolationLevel: TransactionIsolationLevel | undefined) { const maxRetries = 25; let attempts = 0; let lastError: any; // Returns false if a transaction is already in progress async function attemptStartTransaction(): Promise<boolean> { try { await queryRunner.startTransaction(isolationLevel); return true; } catch (err: any) { lastError = err; if (err instanceof TransactionAlreadyStartedError) { return false; } throw err; } } while (attempts < maxRetries) { const result = await attemptStartTransaction(); if (result) { return; } attempts++; // insert an increasing delay before retrying await new Promise(resolve => setTimeout(resolve, attempts * 20)); } throw lastError; } /** * If the resolver function throws an error, there are certain cases in which * we want to retry the whole thing again - notably in the case of a deadlock * situation, which can usually be retried with success. */ private isRetriableError(err: any): boolean { const mysqlDeadlock = err.code === 'ER_LOCK_DEADLOCK'; const postgresDeadlock = err.code === 'deadlock_detected'; return mysqlDeadlock || postgresDeadlock; } }
import { Injectable } from '@nestjs/common'; import { InjectDataSource } from '@nestjs/typeorm/dist/common/typeorm.decorators'; import { ID, Type } from '@vendure/common/lib/shared-types'; import { DataSource, EntityManager, EntitySchema, FindManyOptions, FindOneOptions, ObjectLiteral, ObjectType, Repository, SelectQueryBuilder, } from 'typeorm'; import { RequestContext } from '../api/common/request-context'; import { TransactionIsolationLevel } from '../api/decorators/transaction.decorator'; import { TRANSACTION_MANAGER_KEY } from '../common/constants'; import { EntityNotFoundError } from '../common/error/errors'; import { ChannelAware, SoftDeletable } from '../common/types/common-types'; import { VendureEntity } from '../entity/base/base.entity'; import { joinTreeRelationsDynamically } from '../service/helpers/utils/tree-relations-qb-joiner'; import { findOptionsObjectToArray } from './find-options-object-to-array'; import { TransactionWrapper } from './transaction-wrapper'; import { GetEntityOrThrowOptions } from './types'; /** * @description * The TransactionalConnection is a wrapper around the TypeORM `Connection` object which works in conjunction * with the {@link Transaction} decorator to implement per-request transactions. All services which access the * database should use this class rather than the raw TypeORM connection, to ensure that db changes can be * easily wrapped in transactions when required. * * The service layer does not need to know about the scope of a transaction, as this is covered at the * API by the use of the `Transaction` decorator. * * @docsCategory data-access */ @Injectable() export class TransactionalConnection { constructor( @InjectDataSource() private dataSource: DataSource, private transactionWrapper: TransactionWrapper, ) {} /** * @description * The plain TypeORM Connection object. Should be used carefully as any operations * performed with this connection will not be performed within any outer * transactions. */ get rawConnection(): DataSource { return this.dataSource; } /** * @description * Returns a TypeORM repository. Note that when no RequestContext is supplied, the repository will not * be aware of any existing transaction. Therefore, calling this method without supplying a RequestContext * is discouraged without a deliberate reason. * * @deprecated since 1.7.0: Use {@link TransactionalConnection.rawConnection rawConnection.getRepository()} function instead. */ getRepository<Entity extends ObjectLiteral>( target: ObjectType<Entity> | EntitySchema<Entity> | string, ): Repository<Entity>; /** * @description * Returns a TypeORM repository which is bound to any existing transactions. It is recommended to _always_ pass * the RequestContext argument when possible, otherwise the queries will be executed outside of any * ongoing transactions which have been started by the {@link Transaction} decorator. */ getRepository<Entity extends ObjectLiteral>( ctx: RequestContext | undefined, target: ObjectType<Entity> | EntitySchema<Entity> | string, ): Repository<Entity>; getRepository<Entity extends ObjectLiteral>( ctxOrTarget: RequestContext | ObjectType<Entity> | EntitySchema<Entity> | string | undefined, maybeTarget?: ObjectType<Entity> | EntitySchema<Entity> | string, ): Repository<Entity> { if (ctxOrTarget instanceof RequestContext) { const transactionManager = this.getTransactionManager(ctxOrTarget); if (transactionManager) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return transactionManager.getRepository(maybeTarget!); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.rawConnection.getRepository(maybeTarget!); } } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.rawConnection.getRepository(ctxOrTarget ?? maybeTarget!); } } /** * @description * Allows database operations to be wrapped in a transaction, ensuring that in the event of an error being * thrown at any point, the entire transaction will be rolled back and no changes will be saved. * * In the context of API requests, you should instead use the {@link Transaction} decorator on your resolver or * controller method. * * On the other hand, for code that does not run in the context of a GraphQL/REST request, this method * should be used to protect against non-atomic changes to the data which could leave your data in an * inconsistent state. * * Such situations include function processed by the JobQueue or stand-alone scripts which make use * of Vendure internal services. * * If there is already a {@link RequestContext} object available, you should pass it in as the first * argument in order to create transactional context as the copy. If not, omit the first argument and an empty * RequestContext object will be created, which is then used to propagate the transaction to * all inner method calls. * * @example * ```ts * private async transferCredit(outerCtx: RequestContext, fromId: ID, toId: ID, amount: number) { * await this.connection.withTransaction(outerCtx, async ctx => { * // Note you must not use `outerCtx` here, instead use `ctx`. Otherwise, this query * // will be executed outside of transaction * await this.giftCardService.updateCustomerCredit(ctx, fromId, -amount); * * await this.connection.getRepository(ctx, GiftCard).update(fromId, { transferred: true }) * * // If some intermediate logic here throws an Error, * // then all DB transactions will be rolled back and neither Customer's * // credit balance will have changed. * * await this.giftCardService.updateCustomerCredit(ctx, toId, amount); * }) * } * ``` * * @since 1.3.0 */ async withTransaction<T>(work: (ctx: RequestContext) => Promise<T>): Promise<T>; async withTransaction<T>(ctx: RequestContext, work: (ctx: RequestContext) => Promise<T>): Promise<T>; async withTransaction<T>( ctxOrWork: RequestContext | ((ctx: RequestContext) => Promise<T>), maybeWork?: (ctx: RequestContext) => Promise<T>, ): Promise<T> { let ctx: RequestContext; let work: (ctx: RequestContext) => Promise<T>; if (ctxOrWork instanceof RequestContext) { ctx = ctxOrWork; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion work = maybeWork!; } else { ctx = RequestContext.empty(); work = ctxOrWork; } return this.transactionWrapper.executeInTransaction(ctx, work, 'auto', undefined, this.rawConnection); } /** * @description * Manually start a transaction if one is not already in progress. This method should be used in * conjunction with the `'manual'` mode of the {@link Transaction} decorator. */ async startTransaction(ctx: RequestContext, isolationLevel?: TransactionIsolationLevel) { const transactionManager = this.getTransactionManager(ctx); if (transactionManager?.queryRunner?.isTransactionActive === false) { await transactionManager.queryRunner.startTransaction(isolationLevel); } } /** * @description * Manually commits any open transaction. Should be very rarely needed, since the {@link Transaction} decorator * and the internal TransactionInterceptor take care of this automatically. Use-cases include situations * in which the worker thread needs to access changes made in the current transaction, or when using the * Transaction decorator in manual mode. */ async commitOpenTransaction(ctx: RequestContext) { const transactionManager = this.getTransactionManager(ctx); if (transactionManager?.queryRunner?.isTransactionActive) { await transactionManager.queryRunner.commitTransaction(); } } /** * @description * Manually rolls back any open transaction. Should be very rarely needed, since the {@link Transaction} decorator * and the internal TransactionInterceptor take care of this automatically. Use-cases include when using the * Transaction decorator in manual mode. */ async rollBackTransaction(ctx: RequestContext) { const transactionManager = this.getTransactionManager(ctx); if (transactionManager?.queryRunner?.isTransactionActive) { await transactionManager.queryRunner.rollbackTransaction(); } } /** * @description * Finds an entity of the given type by ID, or throws an `EntityNotFoundError` if none * is found. */ async getEntityOrThrow<T extends VendureEntity>( ctx: RequestContext, entityType: Type<T>, id: ID, options: GetEntityOrThrowOptions<T> = {}, ): Promise<T> { const { retries, retryDelay } = options; if (retries == null || retries <= 0) { return this.getEntityOrThrowInternal(ctx, entityType, id, options); } else { let err: any; const retriesInt = Math.ceil(retries); const delay = Math.ceil(Math.max(retryDelay || 25, 1)); for (let attempt = 0; attempt < retriesInt; attempt++) { try { const result = await this.getEntityOrThrowInternal(ctx, entityType, id, options); return result; } catch (e: any) { err = e; if (attempt < retriesInt - 1) { await new Promise(resolve => setTimeout(resolve, delay)); } } } throw err; } } private async getEntityOrThrowInternal<T extends VendureEntity>( ctx: RequestContext, entityType: Type<T>, id: ID, options: GetEntityOrThrowOptions = {}, ): Promise<T> { let entity: T | undefined; if (options.channelId != null) { const { channelId, ...optionsWithoutChannelId } = options; entity = await this.findOneInChannel( ctx, entityType as Type<T & ChannelAware>, id, options.channelId, optionsWithoutChannelId, ); } else { const optionsWithId = { ...options, where: { ...(options.where || {}), id, }, } as FindOneOptions<T>; entity = await this.getRepository(ctx, entityType) .findOne(optionsWithId) .then(result => result ?? undefined); } if ( !entity || (entity.hasOwnProperty('deletedAt') && (entity as T & SoftDeletable).deletedAt !== null && options.includeSoftDeleted !== true) ) { throw new EntityNotFoundError(entityType.name as any, id); } return entity; } /** * @description * Like the TypeOrm `Repository.findOne()` method, but limits the results to * the given Channel. */ findOneInChannel<T extends ChannelAware & VendureEntity>( ctx: RequestContext, entity: Type<T>, id: ID, channelId: ID, options: FindOneOptions<T> = {}, ) { const qb = this.getRepository(ctx, entity).createQueryBuilder('entity'); if (options.relations) { const joinedRelations = joinTreeRelationsDynamically(qb, entity, options.relations); // Remove any relations which are related to the 'collection' tree, as these are handled separately // to avoid duplicate joins. options.relations = findOptionsObjectToArray(options.relations).filter( relationPath => !joinedRelations.has(relationPath), ); } qb.setFindOptions({ relationLoadStrategy: 'query', // default to query strategy for maximum performance ...options, }); qb.leftJoin('entity.channels', '__channel') .andWhere('entity.id = :id', { id }) .andWhere('__channel.id = :channelId', { channelId }); return qb.getOne().then(result => { return result ?? undefined; }); } /** * @description * Like the TypeOrm `Repository.findByIds()` method, but limits the results to * the given Channel. */ findByIdsInChannel<T extends ChannelAware | VendureEntity>( ctx: RequestContext, entity: Type<T>, ids: ID[], channelId: ID, options: FindManyOptions<T>, ) { // the syntax described in https://github.com/typeorm/typeorm/issues/1239#issuecomment-366955628 // breaks if the array is empty if (ids.length === 0) { return Promise.resolve([]); } const qb = this.getRepository(ctx, entity).createQueryBuilder('entity'); if (Array.isArray(options.relations) && options.relations.length > 0) { const joinedRelations = joinTreeRelationsDynamically( qb as SelectQueryBuilder<VendureEntity>, entity, options.relations, ); // Remove any relations which are related to the 'collection' tree, as these are handled separately // to avoid duplicate joins. options.relations = options.relations.filter(relationPath => !joinedRelations.has(relationPath)); } qb.setFindOptions({ relationLoadStrategy: 'query', // default to query strategy for maximum performance ...options, }); return qb .leftJoin('entity.channels', 'channel') .andWhere('entity.id IN (:...ids)', { ids }) .andWhere('channel.id = :channelId', { channelId }) .getMany(); } private getTransactionManager(ctx: RequestContext): EntityManager | undefined { return (ctx as any)[TRANSACTION_MANAGER_KEY]; } }
import { ID } from '@vendure/common/lib/shared-types'; import { FindOneOptions } from 'typeorm'; /** * @description * Options used by the {@link TransactionalConnection} `getEntityOrThrow` method. * * @docsCategory data-access */ export interface GetEntityOrThrowOptions<T = any> extends FindOneOptions<T> { /** * @description * An optional channelId to limit results to entities assigned to the given Channel. Should * only be used when getting entities that implement the {@link ChannelAware} interface. */ channelId?: ID; /** * @description * If set to a positive integer, it will retry getting the entity in case it is initially not * found. * * @since 1.1.0 * @default 0 */ retries?: number; /** * @description * Specifies the delay in ms to wait between retries. * * @since 1.1.0 * @default 25 */ retryDelay?: number; /** * @description * If set to `true`, soft-deleted entities will be returned. Otherwise they will * throw as if they did not exist. * * @since 1.3.0 * @default false */ includeSoftDeleted?: boolean; }
import { Module } from '@nestjs/common'; import { ConfigModule } from '../config/config.module'; import { ConnectionModule } from '../connection/connection.module'; import { PluginModule } from '../plugin/plugin.module'; import { ServiceModule } from '../service/service.module'; import { AssetImporter } from './providers/asset-importer/asset-importer'; import { ImportParser } from './providers/import-parser/import-parser'; import { FastImporterService } from './providers/importer/fast-importer.service'; import { Importer } from './providers/importer/importer'; import { Populator } from './providers/populator/populator'; @Module({ // Important! PluginModule must be defined before ServiceModule // in order that overrides of Services (e.g. SearchService) are correctly // registered with the injector. imports: [PluginModule.forRoot(), ServiceModule, ConnectionModule.forPlugin(), ConfigModule], exports: [ImportParser, Importer, Populator, FastImporterService, AssetImporter], providers: [ImportParser, Importer, Populator, FastImporterService, AssetImporter], }) export class DataImportModule {}
export * from './providers/populator/populator'; export * from './providers/importer/importer'; export * from './providers/importer/fast-importer.service'; export * from './providers/asset-importer/asset-importer'; export * from './providers/import-parser/import-parser'; export * from './types';
import { ConfigurableOperationInput, LanguageCode, Permission } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { Zone } from '../entity/zone/zone.entity'; export type ZoneMap = Map<string, { entity: Zone; members: ID[] }>; export interface CountryDefinition { code: string; name: string; zone: string; } export interface FacetValueCollectionFilterDefinition { code: 'facet-value-filter'; args: { facetValueNames: string[]; containsAny: boolean; }; } export type CollectionFilterDefinition = FacetValueCollectionFilterDefinition; export interface CollectionDefinition { name: string; description?: string; slug?: string; private?: boolean; filters?: CollectionFilterDefinition[]; inheritFilters?: boolean; parentName?: string; assetPaths?: string[]; } export interface RoleDefinition { code: string; description: string; permissions: Permission[]; } /** * @description * An object defining initial settings for a new Vendure installation. * * @docsCategory import-export */ export interface InitialData { defaultLanguage: LanguageCode; defaultZone: string; roles?: RoleDefinition[]; countries: CountryDefinition[]; taxRates: Array<{ name: string; percentage: number }>; shippingMethods: Array<{ name: string; price: number }>; paymentMethods: Array<{ name: string; handler: ConfigurableOperationInput }>; collections: CollectionDefinition[]; }
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { isGraphQlErrorResult } from '../../../common/index'; import { ConfigService } from '../../../config/config.service'; import { Asset } from '../../../entity/asset/asset.entity'; import { AssetService } from '../../../service/services/asset.service'; /** * @description * This service creates new {@link Asset} entities based on string paths provided in the CSV * import format. The source files are resolved by joining the value of `importExportOptions.importAssetsDir` * with the asset path. This service is used internally by the {@link Importer} service. * * @docsCategory import-export */ @Injectable() export class AssetImporter { private assetMap = new Map<string, Asset>(); /** @internal */ constructor(private configService: ConfigService, private assetService: AssetService) {} /** * @description * Creates Asset entities for the given paths, using the assetMap cache to prevent the * creation of duplicates. */ async getAssets( assetPaths: string[], ctx?: RequestContext, ): Promise<{ assets: Asset[]; errors: string[] }> { const assets: Asset[] = []; const errors: string[] = []; const { assetImportStrategy } = this.configService.importExportOptions; const uniqueAssetPaths = new Set(assetPaths); for (const assetPath of uniqueAssetPaths.values()) { const cachedAsset = this.assetMap.get(assetPath); if (cachedAsset) { assets.push(cachedAsset); } else { try { const stream = await assetImportStrategy.getStreamFromPath(assetPath); if (stream) { const asset = await this.assetService.createFromFileStream(stream, assetPath, ctx); if (isGraphQlErrorResult(asset)) { errors.push(asset.message); } else { this.assetMap.set(assetPath, asset as Asset); assets.push(asset as Asset); } } } catch (e: any) { errors.push(e.message); } } } return { assets, errors }; } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import fs from 'fs-extra'; import path from 'path'; import { beforeAll, describe, expect, it } from 'vitest'; import { ensureConfigLoaded } from '../../../config/config-helpers'; import { ConfigService } from '../../../config/config.service'; import { ImportParser } from './import-parser'; const mockConfigService = { defaultLanguageCode: LanguageCode.en, customFields: { Product: [ { name: 'keywords', type: 'localeString', list: true, }, { name: 'customPage', type: 'string', }, ], ProductVariant: [ { name: 'volumetric', type: 'int', }, ], }, } as ConfigService; describe('ImportParser', () => { beforeAll(async () => { await ensureConfigLoaded(); }); describe('parseProducts', () => { it('single product with a single variant', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('single-product-single-variant.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('single product with a multiple variants', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('single-product-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('multiple products with multiple variants', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('multiple-products-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('custom fields', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('custom-fields.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('works with streamed input', async () => { const importParser = new ImportParser(mockConfigService); const filename = path.join(__dirname, 'test-fixtures', 'multiple-products-multiple-variants.csv'); const input = fs.createReadStream(filename); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('works with multilingual input', async () => { const importParser = new ImportParser(mockConfigService); const filename = path.join(__dirname, 'test-fixtures', 'multiple-languages.csv'); const input = fs.createReadStream(filename); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); describe('error conditions', () => { it('reports errors on invalid option values', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('invalid-option-values.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ "The number of optionValues in column 'optionValues' must match the number of optionGroups on line 2", "The number of optionValues in column 'optionValues' must match the number of optionGroups on line 3", "The number of optionValues in column 'optionValues' must match the number of optionGroups on line 4", "The number of optionValues in column 'optionValues' must match the number of optionGroups on line 5", ]); }); it('reports error on ivalid columns', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('invalid-columns.csv'); const result = await importParser.parseProducts(input); expect(result.results).toEqual([]); expect(result.errors).toEqual([ 'The import file is missing the following columns: "slug", "assets", "variantFacets"', ]); }); it('reports error on ivalid row length', async () => { const importParser = new ImportParser(mockConfigService); const input = await loadTestFixture('invalid-row-length.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'Invalid Record Length: header length is 14, got 12 on line 3', 'Invalid Record Length: header length is 14, got 1 on line 4', ]); expect(result.results.length).toBe(2); }); }); }); }); function loadTestFixture(fileName: string): Promise<string> { return fs.readFile(path.join(__dirname, 'test-fixtures', fileName), 'utf-8'); }
import { Injectable } from '@nestjs/common'; import { GlobalFlag, LanguageCode } from '@vendure/common/lib/generated-types'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { unique } from '@vendure/common/lib/unique'; import { parse, Options } from 'csv-parse'; import { Stream } from 'stream'; import { InternalServerError } from '../../../common/error/errors'; import { ConfigService } from '../../../config/config.service'; import { CustomFieldConfig } from '../../../config/custom-field/custom-field-types'; const baseTranslatableColumns = [ 'name', 'slug', 'description', 'facets', 'optionGroups', 'optionValues', 'variantFacets', ]; const requiredColumns: string[] = [ 'name', 'slug', 'description', 'assets', 'facets', 'optionGroups', 'optionValues', 'sku', 'price', 'taxCategory', 'variantAssets', 'variantFacets', ]; /** * @description * The intermediate representation of an OptionGroup after it has been parsed * by the {@link ImportParser}. * * @docsCategory import-export * @docsPage ImportParser */ export interface ParsedOptionGroup { translations: Array<{ languageCode: LanguageCode; name: string; values: string[]; }>; } /** * @description * The intermediate representation of a Facet after it has been parsed * by the {@link ImportParser}. * * @docsCategory import-export * @docsPage ImportParser */ export interface ParsedFacet { translations: Array<{ languageCode: LanguageCode; facet: string; value: string; }>; } /** * @description * The intermediate representation of a ProductVariant after it has been parsed * by the {@link ImportParser}. * * @docsCategory import-export * @docsPage ImportParser */ export interface ParsedProductVariant { sku: string; price: number; taxCategory: string; stockOnHand: number; trackInventory: GlobalFlag; assetPaths: string[]; facets: ParsedFacet[]; translations: Array<{ languageCode: LanguageCode; optionValues: string[]; customFields: { [name: string]: string; }; }>; } /** * @description * The intermediate representation of a Product after it has been parsed * by the {@link ImportParser}. * * @docsCategory import-export * @docsPage ImportParser */ export interface ParsedProduct { assetPaths: string[]; optionGroups: ParsedOptionGroup[]; facets: ParsedFacet[]; translations: Array<{ languageCode: LanguageCode; name: string; slug: string; description: string; customFields: { [name: string]: string; }; }>; } /** * @description * The data structure into which an import CSV file is parsed by the * {@link ImportParser} `parseProducts()` method. * * @docsCategory import-export * @docsPage ImportParser */ export interface ParsedProductWithVariants { product: ParsedProduct; variants: ParsedProductVariant[]; } /** * @description * The result returned by the {@link ImportParser} `parseProducts()` method. * * @docsCategory import-export * @docsPage ImportParser */ export interface ParseResult<T> { results: T[]; errors: string[]; processed: number; } /** * @description * Validates and parses CSV files into a data structure which can then be used to created new entities. * This is used internally by the {@link Importer}. * * @docsCategory import-export * @docsPage ImportParser * @docsWeight 0 */ @Injectable() export class ImportParser { /** @internal */ constructor(private configService: ConfigService) {} /** * @description * Parses the contents of the [product import CSV file](/guides/developer-guide/importing-data/#product-import-format) and * returns a data structure which can then be used to populate Vendure using the {@link FastImporterService}. */ async parseProducts( input: string | Stream, mainLanguage: LanguageCode = this.configService.defaultLanguageCode, ): Promise<ParseResult<ParsedProductWithVariants>> { const options: Options = { trim: true, relax_column_count: true, }; return new Promise<ParseResult<ParsedProductWithVariants>>((resolve, reject) => { let errors: string[] = []; if (typeof input === 'string') { parse(input, options, (err: any, records: string[][]) => { if (err) { errors = errors.concat(err); } if (records) { const parseResult = this.processRawRecords(records, mainLanguage); errors = errors.concat(parseResult.errors); resolve({ results: parseResult.results, errors, processed: parseResult.processed }); } else { resolve({ results: [], errors, processed: 0 }); } }); } else { const parser = parse(options); const records: string[][] = []; // input.on('open', () => input.pipe(parser)); input.pipe(parser); parser.on('readable', () => { let record; // eslint-disable-next-line no-cond-assign while ((record = parser.read())) { records.push(record); } }); parser.on('error', reject); parser.on('end', () => { const parseResult = this.processRawRecords(records, mainLanguage); errors = errors.concat(parseResult.errors); resolve({ results: parseResult.results, errors, processed: parseResult.processed }); }); } }); } private processRawRecords( records: string[][], mainLanguage: LanguageCode, ): ParseResult<ParsedProductWithVariants> { const results: ParsedProductWithVariants[] = []; const errors: string[] = []; let currentRow: ParsedProductWithVariants | undefined; const headerRow = records[0]; const rest = records.slice(1); const totalProducts = rest.map(row => row[0]).filter(name => name.trim() !== '').length; const customFieldErrors = this.validateCustomFields(headerRow); if (customFieldErrors.length > 0) { return { results: [], errors: customFieldErrors, processed: 0 }; } const translationError = this.validateHeaderTranslations(headerRow); if (translationError) { return { results: [], errors: [translationError], processed: 0 }; } const columnError = validateRequiredColumns(headerRow); if (columnError) { return { results: [], errors: [columnError], processed: 0 }; } const usedLanguages = usedLanguageCodes(headerRow); let line = 1; for (const record of rest) { line++; const columnCountError = validateColumnCount(headerRow, record); if (columnCountError) { errors.push(columnCountError + ` on line ${line}`); continue; } const r = mapRowToObject(headerRow, record); if (getRawMainTranslation(r, 'name', mainLanguage)) { if (currentRow) { populateOptionGroupValues(currentRow); results.push(currentRow); } currentRow = { product: this.parseProductFromRecord(r, usedLanguages, mainLanguage), variants: [this.parseVariantFromRecord(r, usedLanguages, mainLanguage)], }; } else { if (currentRow) { currentRow.variants.push(this.parseVariantFromRecord(r, usedLanguages, mainLanguage)); } } const optionError = validateOptionValueCount(r, currentRow); if (optionError) { errors.push(optionError + ` on line ${line}`); } } if (currentRow) { populateOptionGroupValues(currentRow); results.push(currentRow); } return { results, errors, processed: totalProducts }; } private validateCustomFields(rowKeys: string[]): string[] { const errors: string[] = []; for (const rowKey of rowKeys) { const baseKey = getBaseKey(rowKey); const parts = baseKey.split(':'); if (parts.length === 1) { continue; } if (parts.length === 2) { let customFieldConfigs: CustomFieldConfig[] = []; if (parts[0] === 'product') { customFieldConfigs = this.configService.customFields.Product; } else if (parts[0] === 'variant') { customFieldConfigs = this.configService.customFields.ProductVariant; } else { continue; } const customFieldConfig = customFieldConfigs.find(config => config.name === parts[1]); if (customFieldConfig) { continue; } } errors.push(`Invalid custom field: ${rowKey}`); } return errors; } private isTranslatable(baseKey: string): boolean { const parts = baseKey.split(':'); if (parts.length === 1) { return baseTranslatableColumns.includes(baseKey); } if (parts.length === 2) { let customFieldConfigs: CustomFieldConfig[]; if (parts[0] === 'product') { customFieldConfigs = this.configService.customFields.Product; } else if (parts[0] === 'variant') { customFieldConfigs = this.configService.customFields.ProductVariant; } else { throw new InternalServerError(`Invalid column header '${baseKey}'`); } const customFieldConfig = customFieldConfigs.find(config => config.name === parts[1]); if (!customFieldConfig) { throw new InternalServerError( `Could not find custom field config for column header '${baseKey}'`, ); } return customFieldConfig.type === 'localeString'; } throw new InternalServerError(`Invalid column header '${baseKey}'`); } private validateHeaderTranslations(rowKeys: string[]): string | undefined { const missing: string[] = []; const languageCodes = usedLanguageCodes(rowKeys); const baseKeys = usedBaseKeys(rowKeys); for (const baseKey of baseKeys) { const translatedKeys = languageCodes.map(code => [baseKey, code].join(':')); if (rowKeys.includes(baseKey)) { // Untranslated column header is used -> there should be no translated ones if (rowKeys.some(key => translatedKeys.includes(key))) { return `The import file must not contain both translated and untranslated columns for field '${baseKey}'`; } } else { if (!this.isTranslatable(baseKey) && translatedKeys.some(key => rowKeys.includes(key))) { return `The '${baseKey}' field is not translatable.`; } // All column headers must exist for all translations for (const translatedKey of translatedKeys) { if (!rowKeys.includes(translatedKey)) { missing.push(translatedKey); } } } } if (missing.length) { return `The import file is missing the following translations: ${missing .map(m => `"${m}"`) .join(', ')}`; } } private parseProductFromRecord( r: { [key: string]: string }, usedLanguages: LanguageCode[], mainLanguage: LanguageCode, ): ParsedProduct { const translationCodes = usedLanguages.length === 0 ? [mainLanguage] : usedLanguages; const optionGroups: ParsedOptionGroup[] = []; for (const languageCode of translationCodes) { const rawTranslOptionGroups = r.hasOwnProperty(`optionGroups:${languageCode}`) ? r[`optionGroups:${languageCode}`] : r.optionGroups; const translatedOptionGroups = parseStringArray(rawTranslOptionGroups); if (optionGroups.length === 0) { for (const translatedOptionGroup of translatedOptionGroups) { optionGroups.push({ translations: [] }); } } for (const i of optionGroups.map((optionGroup, index) => index)) { optionGroups[i].translations.push({ languageCode, name: translatedOptionGroups[i], values: [], }); } } const facets: ParsedFacet[] = []; for (const languageCode of translationCodes) { const rawTranslatedFacets = r.hasOwnProperty(`facets:${languageCode}`) ? r[`facets:${languageCode}`] : r.facets; const translatedFacets = parseStringArray(rawTranslatedFacets); if (facets.length === 0) { for (const translatedFacet of translatedFacets) { facets.push({ translations: [] }); } } for (const i of facets.map((facet, index) => index)) { const [facet, value] = translatedFacets[i].split(':'); facets[i].translations.push({ languageCode, facet, value, }); } } const translations = translationCodes.map(languageCode => { const translatedFields = getRawTranslatedFields(r, languageCode); const parsedTranslatedCustomFields = parseCustomFields('product', translatedFields); const parsedUntranslatedCustomFields = parseCustomFields('product', getRawUntranslatedFields(r)); const parsedCustomFields = { ...parsedUntranslatedCustomFields, ...parsedTranslatedCustomFields, }; const name = translatedFields.hasOwnProperty('name') ? parseString(translatedFields.name) : r.name; let slug: string; if (translatedFields.hasOwnProperty('slug')) { slug = parseString(translatedFields.slug); } else { slug = parseString(r.slug); } if (slug.length === 0) { slug = normalizeString(name, '-'); } return { languageCode, name, slug, description: translatedFields.hasOwnProperty('description') ? parseString(translatedFields.description) : r.description, customFields: parsedCustomFields, }; }); const parsedProduct: ParsedProduct = { assetPaths: parseStringArray(r.assets), optionGroups, facets, translations, }; return parsedProduct; } private parseVariantFromRecord( r: { [key: string]: string }, usedLanguages: LanguageCode[], mainLanguage: LanguageCode, ): ParsedProductVariant { const translationCodes = usedLanguages.length === 0 ? [mainLanguage] : usedLanguages; const facets: ParsedFacet[] = []; for (const languageCode of translationCodes) { const rawTranslatedFacets = r.hasOwnProperty(`variantFacets:${languageCode}`) ? r[`variantFacets:${languageCode}`] : r.variantFacets; const translatedFacets = parseStringArray(rawTranslatedFacets); if (facets.length === 0) { for (const translatedFacet of translatedFacets) { facets.push({ translations: [] }); } } for (const i of facets.map((facet, index) => index)) { const [facet, value] = translatedFacets[i].split(':'); facets[i].translations.push({ languageCode, facet, value, }); } } const translations = translationCodes.map(languageCode => { const rawTranslOptionValues = r.hasOwnProperty(`optionValues:${languageCode}`) ? r[`optionValues:${languageCode}`] : r.optionValues; const translatedOptionValues = parseStringArray(rawTranslOptionValues); const translatedFields = getRawTranslatedFields(r, languageCode); const parsedTranslatedCustomFields = parseCustomFields('variant', translatedFields); const parsedUntranslatedCustomFields = parseCustomFields('variant', getRawUntranslatedFields(r)); const parsedCustomFields = { ...parsedUntranslatedCustomFields, ...parsedTranslatedCustomFields, }; return { languageCode, optionValues: translatedOptionValues, customFields: parsedCustomFields, }; }); const parsedVariant: ParsedProductVariant = { sku: parseString(r.sku), price: parseNumber(r.price), taxCategory: parseString(r.taxCategory), stockOnHand: parseNumber(r.stockOnHand), trackInventory: r.trackInventory == null || r.trackInventory === '' ? GlobalFlag.INHERIT : parseBoolean(r.trackInventory) ? GlobalFlag.TRUE : GlobalFlag.FALSE, assetPaths: parseStringArray(r.variantAssets), facets, translations, }; return parsedVariant; } } function populateOptionGroupValues(currentRow: ParsedProductWithVariants) { for (const translation of currentRow.product.translations) { const values = currentRow.variants.map(variant => { const variantTranslation = variant.translations.find( t => t.languageCode === translation.languageCode, ); if (!variantTranslation) { throw new InternalServerError( `No translation '${translation.languageCode}' for variant SKU '${variant.sku}'`, ); } return variantTranslation.optionValues; }); currentRow.product.optionGroups.forEach((og, i) => { const ogTranslation = og.translations.find(t => t.languageCode === translation.languageCode); if (!ogTranslation) { throw new InternalServerError( `No translation '${translation.languageCode}' for option groups'`, ); } ogTranslation.values = unique(values.map(v => v[i])); }); } } function getLanguageCode(rowKey: string): LanguageCode | undefined { const parts = rowKey.split(':'); if (parts.length === 2) { if (parts[1] in LanguageCode) { return parts[1] as LanguageCode; } } if (parts.length === 3) { if (['product', 'productVariant'].includes(parts[0]) && parts[2] in LanguageCode) { return parts[2] as LanguageCode; } } } function getBaseKey(rowKey: string): string { const parts = rowKey.split(':'); if (getLanguageCode(rowKey)) { parts.pop(); return parts.join(':'); } else { return rowKey; } } function usedLanguageCodes(rowKeys: string[]): LanguageCode[] { const languageCodes: LanguageCode[] = []; for (const rowKey of rowKeys) { const languageCode = getLanguageCode(rowKey); if (languageCode && !languageCodes.includes(languageCode)) { languageCodes.push(languageCode); } } return languageCodes; } function usedBaseKeys(rowKeys: string[]): string[] { const baseKeys: string[] = []; for (const rowKey of rowKeys) { const baseKey = getBaseKey(rowKey); if (!baseKeys.includes(baseKey)) { baseKeys.push(baseKey); } } return baseKeys; } function validateRequiredColumns(r: string[]): string | undefined { const rowKeys = r; const missing: string[] = []; const languageCodes = usedLanguageCodes(rowKeys); for (const col of requiredColumns) { if (!rowKeys.includes(col)) { if (languageCodes.length > 0 && rowKeys.includes(`${col}:${languageCodes[0]}`)) { continue; // If one translation is present, they are all present (we did 'validateHeaderTranslations' before) } missing.push(col); } } if (missing.length) { return `The import file is missing the following columns: ${missing.map(m => `"${m}"`).join(', ')}`; } } function validateColumnCount(columns: string[], row: string[]): string | undefined { if (columns.length !== row.length) { return `Invalid Record Length: header length is ${columns.length}, got ${row.length}`; } } function mapRowToObject(columns: string[], row: string[]): { [key: string]: string } { return row.reduce((obj, val, i) => { return { ...obj, [columns[i]]: val }; }, {}); } function validateOptionValueCount( r: { [key: string]: string }, currentRow?: ParsedProductWithVariants, ): string | undefined { if (!currentRow) { return; } const optionValueKeys = Object.keys(r).filter(key => key.startsWith('optionValues')); for (const key of optionValueKeys) { const optionValues = parseStringArray(r[key]); if (currentRow.product.optionGroups.length !== optionValues.length) { return `The number of optionValues in column '${key}' must match the number of optionGroups`; } } } function getRawMainTranslation( r: { [key: string]: string }, field: string, mainLanguage: LanguageCode, ): string { if (r.hasOwnProperty(field)) { return r[field]; } else { return r[`${field}:${mainLanguage}`]; } } function getRawTranslatedFields( r: { [key: string]: string }, languageCode: LanguageCode, ): { [key: string]: string } { return Object.entries(r) .filter(([key, value]) => key.endsWith(`:${languageCode}`)) .reduce((output, [key, value]) => { const fieldName = key.replace(`:${languageCode}`, ''); return { ...output, [fieldName]: value, }; }, {}); } function getRawUntranslatedFields(r: { [key: string]: string }): { [key: string]: string } { return Object.entries(r) .filter(([key, value]) => { return !getLanguageCode(key); }) .reduce((output, [key, value]) => { return { ...output, [key]: value, }; }, {}); } function isRelationObject(value: string) { try { const parsed = JSON.parse(value); return parsed && parsed.hasOwnProperty('id'); } catch (e: any) { return false; } } function parseCustomFields( prefix: 'product' | 'variant', r: { [key: string]: string }, ): { [name: string]: string } { return Object.entries(r) .filter(([key, value]) => { return key.indexOf(`${prefix}:`) === 0; }) .reduce((output, [key, value]) => { const fieldName = key.replace(`${prefix}:`, ''); return { ...output, [fieldName]: isRelationObject(value) ? JSON.parse(value) : value, }; }, {}); } function parseString(input?: string): string { return (input || '').trim(); } function parseNumber(input?: string): number { return +(input || '').trim(); } function parseBoolean(input?: string): boolean { if (input == null) { return false; } switch (input.toLowerCase()) { case 'true': case '1': case 'yes': return true; default: return false; } } function parseStringArray(input?: string, separator = '|'): string[] { return (input || '') .trim() .split(separator) .map(s => s.trim()) .filter(s => s !== ''); }
import { Injectable } from '@nestjs/common'; import { CreateProductInput, CreateProductOptionGroupInput, CreateProductOptionInput, CreateProductVariantInput, } from '@vendure/common/lib/generated-types'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { ID } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { RequestContext } from '../../../api/common/request-context'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Channel } from '../../../entity/channel/channel.entity'; import { ProductAsset } from '../../../entity/product/product-asset.entity'; import { ProductTranslation } from '../../../entity/product/product-translation.entity'; import { Product } from '../../../entity/product/product.entity'; import { ProductOptionTranslation } from '../../../entity/product-option/product-option-translation.entity'; import { ProductOption } from '../../../entity/product-option/product-option.entity'; import { ProductOptionGroupTranslation } from '../../../entity/product-option-group/product-option-group-translation.entity'; import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity'; import { ProductVariantAsset } from '../../../entity/product-variant/product-variant-asset.entity'; import { ProductVariantPrice } from '../../../entity/product-variant/product-variant-price.entity'; import { ProductVariantTranslation } from '../../../entity/product-variant/product-variant-translation.entity'; import { ProductVariant } from '../../../entity/product-variant/product-variant.entity'; import { RequestContextService } from '../../../service/helpers/request-context/request-context.service'; import { TranslatableSaver } from '../../../service/helpers/translatable-saver/translatable-saver'; import { ChannelService } from '../../../service/services/channel.service'; import { StockMovementService } from '../../../service/services/stock-movement.service'; /** * @description * A service to import entities into the database. This replaces the regular `create` methods of the service layer with faster * versions which skip much of the defensive checks and other DB calls which are not needed when running an import. It also * does not publish any events, so e.g. will not trigger search index jobs. * * In testing, the use of the FastImporterService approximately doubled the speed of bulk imports. * * @docsCategory import-export */ @Injectable() export class FastImporterService { private defaultChannel: Channel; private importCtx: RequestContext; /** @internal */ constructor( private connection: TransactionalConnection, private channelService: ChannelService, private stockMovementService: StockMovementService, private translatableSaver: TranslatableSaver, private requestContextService: RequestContextService, ) {} /** * @description * This should be called prior to any of the import methods, as it establishes the * default Channel as well as the context in which the new entities will be created. * * Passing a `channel` argument means that Products and ProductVariants will be assigned * to that Channel. */ async initialize(channel?: Channel) { this.importCtx = channel ? await this.requestContextService.create({ apiType: 'admin', channelOrToken: channel, }) : RequestContext.empty(); this.defaultChannel = await this.channelService.getDefaultChannel(this.importCtx); } async createProduct(input: CreateProductInput): Promise<ID> { this.ensureInitialized(); // https://github.com/vendure-ecommerce/vendure/issues/2053 // normalizes slug without validation for faster performance input.translations.map(translation => { translation.slug = normalizeString(translation.slug as string, '-'); }); const product = await this.translatableSaver.create({ ctx: this.importCtx, input, entityType: Product, translationType: ProductTranslation, beforeSave: async p => { p.channels = unique([this.defaultChannel, this.importCtx.channel], 'id'); if (input.facetValueIds) { p.facetValues = input.facetValueIds.map(id => ({ id } as any)); } if (input.featuredAssetId) { p.featuredAsset = { id: input.featuredAssetId } as any; } }, }); if (input.assetIds) { const productAssets = input.assetIds.map( (id, i) => new ProductAsset({ assetId: id, productId: product.id, position: i, }), ); await this.connection .getRepository(this.importCtx, ProductAsset) .save(productAssets, { reload: false }); } return product.id; } async createProductOptionGroup(input: CreateProductOptionGroupInput): Promise<ID> { this.ensureInitialized(); const group = await this.translatableSaver.create({ ctx: this.importCtx, input, entityType: ProductOptionGroup, translationType: ProductOptionGroupTranslation, }); return group.id; } async createProductOption(input: CreateProductOptionInput): Promise<ID> { this.ensureInitialized(); const option = await this.translatableSaver.create({ ctx: this.importCtx, input, entityType: ProductOption, translationType: ProductOptionTranslation, beforeSave: po => (po.group = { id: input.productOptionGroupId } as any), }); return option.id; } async addOptionGroupToProduct(productId: ID, optionGroupId: ID) { this.ensureInitialized(); await this.connection .getRepository(this.importCtx, Product) .createQueryBuilder() .relation('optionGroups') .of(productId) .add(optionGroupId); } async createProductVariant(input: CreateProductVariantInput): Promise<ID> { this.ensureInitialized(); if (!input.optionIds) { input.optionIds = []; } if (input.price == null) { input.price = 0; } const inputWithoutPrice = { ...input, }; delete inputWithoutPrice.price; const createdVariant = await this.translatableSaver.create({ ctx: this.importCtx, input: inputWithoutPrice, entityType: ProductVariant, translationType: ProductVariantTranslation, beforeSave: async variant => { variant.channels = unique([this.defaultChannel, this.importCtx.channel], 'id'); const { optionIds } = input; if (optionIds && optionIds.length) { variant.options = optionIds.map(id => ({ id } as any)); } if (input.facetValueIds) { variant.facetValues = input.facetValueIds.map(id => ({ id } as any)); } variant.product = { id: input.productId } as any; variant.taxCategory = { id: input.taxCategoryId } as any; if (input.featuredAssetId) { variant.featuredAsset = { id: input.featuredAssetId } as any; } }, }); if (input.assetIds) { const variantAssets = input.assetIds.map( (id, i) => new ProductVariantAsset({ assetId: id, productVariantId: createdVariant.id, position: i, }), ); await this.connection .getRepository(this.importCtx, ProductVariantAsset) .save(variantAssets, { reload: false }); } await this.stockMovementService.adjustProductVariantStock( this.importCtx, createdVariant.id, input.stockOnHand ?? 0, ); const assignedChannelIds = unique([this.defaultChannel, this.importCtx.channel], 'id').map(c => c.id); for (const channelId of assignedChannelIds) { const variantPrice = new ProductVariantPrice({ price: input.price, channelId, currencyCode: this.defaultChannel.defaultCurrencyCode, }); variantPrice.variant = createdVariant; await this.connection .getRepository(this.importCtx, ProductVariantPrice) .save(variantPrice, { reload: false }); } return createdVariant.id; } private ensureInitialized() { if (!this.defaultChannel || !this.importCtx) { throw new Error( "The FastImporterService must be initialized with a call to 'initialize()' before importing data", ); } } }
import { Injectable } from '@nestjs/common'; import { ImportInfo, LanguageCode } from '@vendure/common/lib/generated-types'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { ID } from '@vendure/common/lib/shared-types'; import ProgressBar from 'progress'; import { Observable } from 'rxjs'; import { Stream } from 'stream'; import { RequestContext } from '../../../api/common/request-context'; import { InternalServerError } from '../../../common/error/errors'; import { ConfigService } from '../../../config/config.service'; import { CustomFieldConfig } from '../../../config/custom-field/custom-field-types'; import { Facet } from '../../../entity/facet/facet.entity'; import { FacetValue } from '../../../entity/facet-value/facet-value.entity'; import { TaxCategory } from '../../../entity/tax-category/tax-category.entity'; import { ChannelService } from '../../../service/services/channel.service'; import { FacetValueService } from '../../../service/services/facet-value.service'; import { FacetService } from '../../../service/services/facet.service'; import { TaxCategoryService } from '../../../service/services/tax-category.service'; import { AssetImporter } from '../asset-importer/asset-importer'; import { ImportParser, ParsedFacet, ParsedProductWithVariants } from '../import-parser/import-parser'; import { FastImporterService } from './fast-importer.service'; export interface ImportProgress extends ImportInfo { currentProduct: string; } export type OnProgressFn = (progess: ImportProgress) => void; /** * @description * Parses and imports Products using the CSV import format. * * Internally it is using the {@link ImportParser} to parse the CSV file, and then the * {@link FastImporterService} and the {@link AssetImporter} to actually create the resulting * entities in the Vendure database. * * @docsCategory import-export */ @Injectable() export class Importer { private taxCategoryMatches: { [name: string]: ID } = {}; // These Maps are used to cache newly-created entities and prevent duplicates // from being created. private facetMap = new Map<string, Facet>(); private facetValueMap = new Map<string, FacetValue>(); /** @internal */ constructor( private configService: ConfigService, private importParser: ImportParser, private channelService: ChannelService, private facetService: FacetService, private facetValueService: FacetValueService, private taxCategoryService: TaxCategoryService, private assetImporter: AssetImporter, private fastImporter: FastImporterService, ) {} /** * @description * Parses the contents of the [product import CSV file](/guides/developer-guide/importing-data/#product-import-format) and imports * the resulting Product & ProductVariants, as well as any associated Assets, Facets & FacetValues. * * The `ctxOrLanguageCode` argument is used to specify the languageCode to be used when creating the Products. */ parseAndImport( input: string | Stream, ctxOrLanguageCode: RequestContext | LanguageCode, reportProgress: boolean = false, ): Observable<ImportProgress> { let bar: ProgressBar | undefined; return new Observable(subscriber => { const p = this.doParseAndImport(input, ctxOrLanguageCode, progress => { if (reportProgress) { if (!bar) { bar = new ProgressBar(' importing [:bar] :percent :etas Importing: :prodName', { complete: '=', incomplete: ' ', total: progress.processed, width: 40, }); } bar.tick({ prodName: progress.currentProduct }); } subscriber.next(progress); }).then(value => { subscriber.next({ ...value, currentProduct: 'Complete' }); subscriber.complete(); }); }); } private async doParseAndImport( input: string | Stream, ctxOrLanguageCode: RequestContext | LanguageCode, onProgress: OnProgressFn, ): Promise<ImportInfo> { const ctx = await this.getRequestContext(ctxOrLanguageCode); const parsed = await this.importParser.parseProducts(input, ctx.languageCode); if (parsed && parsed.results.length) { try { const importErrors = await this.importProducts(ctx, parsed.results, progess => { onProgress({ ...progess, processed: parsed.processed, }); }); return { errors: parsed.errors.concat(importErrors), imported: parsed.results.length, processed: parsed.processed, }; } catch (err: any) { return { errors: [err.message], imported: 0, processed: parsed.processed, }; } } else { return { errors: [], imported: 0, processed: parsed.processed, }; } } private async getRequestContext( ctxOrLanguageCode: RequestContext | LanguageCode, ): Promise<RequestContext> { if (ctxOrLanguageCode instanceof RequestContext) { return ctxOrLanguageCode; } else { const channel = await this.channelService.getDefaultChannel(); return new RequestContext({ apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, channel, languageCode: ctxOrLanguageCode, }); } } /** * @description * Imports the products specified in the rows object. Return an array of error messages. */ async importProducts( ctx: RequestContext, rows: ParsedProductWithVariants[], onProgress: OnProgressFn, ): Promise<string[]> { let errors: string[] = []; let imported = 0; const languageCode = ctx.languageCode; const taxCategories = await this.taxCategoryService.findAll(ctx); await this.fastImporter.initialize(ctx.channel); for (const { product, variants } of rows) { const productMainTranslation = this.getTranslationByCodeOrFirst( product.translations, ctx.languageCode, ); const createProductAssets = await this.assetImporter.getAssets(product.assetPaths, ctx); const productAssets = createProductAssets.assets; if (createProductAssets.errors.length) { errors = errors.concat(createProductAssets.errors); } const customFields = this.processCustomFieldValues( product.translations[0].customFields, this.configService.customFields.Product, ); const createdProductId = await this.fastImporter.createProduct({ featuredAssetId: productAssets.length ? productAssets[0].id : undefined, assetIds: productAssets.map(a => a.id), facetValueIds: await this.getFacetValueIds(ctx, product.facets, ctx.languageCode), translations: product.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.name, description: translation.description, slug: translation.slug, customFields: this.processCustomFieldValues( translation.customFields, this.configService.customFields.Product, ), }; }), customFields, }); const optionsMap: { [optionName: string]: ID } = {}; for (const [optionGroup, optionGroupIndex] of product.optionGroups.map( (group, i) => [group, i] as const, )) { const optionGroupMainTranslation = this.getTranslationByCodeOrFirst( optionGroup.translations, ctx.languageCode, ); const code = normalizeString( `${productMainTranslation.name}-${optionGroupMainTranslation.name}`, '-', ); const groupId = await this.fastImporter.createProductOptionGroup({ code, options: optionGroupMainTranslation.values.map(name => ({} as any)), translations: optionGroup.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.name, }; }), }); for (const [optionIndex, value] of optionGroupMainTranslation.values.map( (val, index) => [index, val] as const, )) { const createdOptionId = await this.fastImporter.createProductOption({ productOptionGroupId: groupId, code: normalizeString(value, '-'), translations: optionGroup.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.values[optionIndex], }; }), }); optionsMap[`${optionGroupIndex}_${value}`] = createdOptionId; } await this.fastImporter.addOptionGroupToProduct(createdProductId, groupId); } for (const variant of variants) { const variantMainTranslation = this.getTranslationByCodeOrFirst( variant.translations, ctx.languageCode, ); const createVariantAssets = await this.assetImporter.getAssets(variant.assetPaths); const variantAssets = createVariantAssets.assets; if (createVariantAssets.errors.length) { errors = errors.concat(createVariantAssets.errors); } let facetValueIds: ID[] = []; if (0 < variant.facets.length) { facetValueIds = await this.getFacetValueIds(ctx, variant.facets, languageCode); } const variantCustomFields = this.processCustomFieldValues( variantMainTranslation.customFields, this.configService.customFields.ProductVariant, ); const optionIds = variantMainTranslation.optionValues.map( (v, index) => optionsMap[`${index}_${v}`], ); const createdVariant = await this.fastImporter.createProductVariant({ productId: createdProductId, facetValueIds, featuredAssetId: variantAssets.length ? variantAssets[0].id : undefined, assetIds: variantAssets.map(a => a.id), sku: variant.sku, taxCategoryId: this.getMatchingTaxCategoryId(variant.taxCategory, taxCategories.items), stockOnHand: variant.stockOnHand, trackInventory: variant.trackInventory, optionIds, translations: variant.translations.map(translation => { const productTranslation = product.translations.find( t => t.languageCode === translation.languageCode, ); if (!productTranslation) { throw new InternalServerError( `No translation '${translation.languageCode}' for product with slug '${productMainTranslation.slug}'`, ); } return { languageCode: translation.languageCode, name: [productTranslation.name, ...translation.optionValues].join(' '), customFields: this.processCustomFieldValues( translation.customFields, this.configService.customFields.ProductVariant, ), }; }), price: Math.round(variant.price * 100), customFields: variantCustomFields, }); } imported++; onProgress({ processed: 0, imported, errors, currentProduct: productMainTranslation.name, }); } return errors; } private async getFacetValueIds( ctx: RequestContext, facets: ParsedFacet[], languageCode: LanguageCode, ): Promise<ID[]> { const facetValueIds: ID[] = []; for (const item of facets) { const itemMainTranslation = this.getTranslationByCodeOrFirst(item.translations, languageCode); const facetName = itemMainTranslation.facet; const valueName = itemMainTranslation.value; let facetEntity: Facet; const cachedFacet = this.facetMap.get(facetName); if (cachedFacet) { facetEntity = cachedFacet; } else { const existing = await this.facetService.findByCode( ctx, normalizeString(facetName, '-'), languageCode, ); if (existing) { facetEntity = existing; } else { facetEntity = await this.facetService.create(ctx, { isPrivate: false, code: normalizeString(facetName, '-'), translations: item.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.facet, }; }), }); } this.facetMap.set(facetName, facetEntity); } let facetValueEntity: FacetValue; const facetValueMapKey = `${facetName}:${valueName}`; const cachedFacetValue = this.facetValueMap.get(facetValueMapKey); if (cachedFacetValue) { facetValueEntity = cachedFacetValue; } else { const existing = facetEntity.values.find(v => v.name === valueName); if (existing) { facetValueEntity = existing; } else { facetValueEntity = await this.facetValueService.create(ctx, facetEntity, { code: normalizeString(valueName, '-'), translations: item.translations.map(translation => { return { languageCode: translation.languageCode, name: translation.value, }; }), }); } this.facetValueMap.set(facetValueMapKey, facetValueEntity); } facetValueIds.push(facetValueEntity.id); } return facetValueIds; } private processCustomFieldValues(customFields: { [field: string]: string }, config: CustomFieldConfig[]) { const processed: { [field: string]: string | string[] | boolean | undefined } = {}; for (const fieldDef of config) { const value = customFields[fieldDef.name]; if (fieldDef.list === true) { processed[fieldDef.name] = value?.split('|').filter(val => val.trim() !== ''); } else if (fieldDef.type === 'boolean') { processed[fieldDef.name] = value ? value.toLowerCase() === 'true' : undefined; } else { processed[fieldDef.name] = value ? value : undefined; } } return processed; } /** * Attempts to match a TaxCategory entity against the name supplied in the import table. If no matches * are found, the first TaxCategory id is returned. */ private getMatchingTaxCategoryId(name: string, taxCategories: TaxCategory[]): ID { if (this.taxCategoryMatches[name]) { return this.taxCategoryMatches[name]; } const regex = new RegExp(name, 'i'); const found = taxCategories.find(tc => !!tc.name.match(regex)); const match = found ? found : taxCategories[0]; this.taxCategoryMatches[name] = match.id; return match.id; } private getTranslationByCodeOrFirst<Type extends { languageCode: LanguageCode }>( translations: Type[], languageCode: LanguageCode, ): Type { let translation = translations.find(t => t.languageCode === languageCode); if (!translation) { translation = translations[0]; } return translation; } }
import { Injectable } from '@nestjs/common'; import { ConfigurableOperationInput } from '@vendure/common/lib/generated-types'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { RequestContext } from '../../../api/common/request-context'; import { ConfigService, defaultShippingCalculator, defaultShippingEligibilityChecker, Logger, } from '../../../config'; import { manualFulfillmentHandler } from '../../../config/fulfillment/manual-fulfillment-handler'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Channel, Collection, FacetValue, TaxCategory, User } from '../../../entity'; import { CollectionService, FacetValueService, PaymentMethodService, RequestContextService, RoleService, ShippingMethodService, } from '../../../service'; import { ChannelService } from '../../../service/services/channel.service'; import { CountryService } from '../../../service/services/country.service'; import { SearchService } from '../../../service/services/search.service'; import { TaxCategoryService } from '../../../service/services/tax-category.service'; import { TaxRateService } from '../../../service/services/tax-rate.service'; import { ZoneService } from '../../../service/services/zone.service'; import { CollectionFilterDefinition, CountryDefinition, InitialData, RoleDefinition, ZoneMap, } from '../../types'; import { AssetImporter } from '../asset-importer/asset-importer'; /** * @description * Responsible for populating the database with {@link InitialData}, i.e. non-product data such as countries, tax rates, * shipping methods, payment methods & roles. * * @docsCategory import-export */ @Injectable() export class Populator { /** @internal */ constructor( private countryService: CountryService, private zoneService: ZoneService, private channelService: ChannelService, private taxRateService: TaxRateService, private taxCategoryService: TaxCategoryService, private shippingMethodService: ShippingMethodService, private paymentMethodService: PaymentMethodService, private collectionService: CollectionService, private facetValueService: FacetValueService, private searchService: SearchService, private assetImporter: AssetImporter, private roleService: RoleService, private configService: ConfigService, private connection: TransactionalConnection, private requestContextService: RequestContextService, ) {} /** * @description * Should be run *before* populating the products, so that there are TaxRates by which * product prices can be set. If the `channel` argument is set, then any {@link ChannelAware} * entities will be assigned to that Channel. */ async populateInitialData(data: InitialData, channel?: Channel) { const ctx = await this.createRequestContext(data, channel); let zoneMap: ZoneMap; try { zoneMap = await this.populateCountries(ctx, data.countries); } catch (e: any) { Logger.error('Could not populate countries'); Logger.error(e, 'populator', e.stack); throw e; } try { await this.populateTaxRates(ctx, data.taxRates, zoneMap); } catch (e: any) { Logger.error('Could not populate tax rates'); Logger.error(e, 'populator', e.stack); } try { await this.populateShippingMethods(ctx, data.shippingMethods); } catch (e: any) { Logger.error('Could not populate shipping methods'); Logger.error(e, 'populator', e.stack); } try { await this.populatePaymentMethods(ctx, data.paymentMethods); } catch (e: any) { Logger.error('Could not populate payment methods'); Logger.error(e, 'populator', e.stack); } try { await this.setChannelDefaults(zoneMap, data, ctx.channel); } catch (e: any) { Logger.error('Could not set channel defaults'); Logger.error(e, 'populator', e.stack); } try { await this.populateRoles(ctx, data.roles); } catch (e: any) { Logger.error('Could not populate roles'); Logger.error(e, 'populator', e.stack); } } /** * @description * Should be run *after* the products have been populated, otherwise the expected FacetValues will not * yet exist. */ async populateCollections(data: InitialData, channel?: Channel) { const ctx = await this.createRequestContext(data, channel); const allFacetValues = await this.facetValueService.findAll(ctx, ctx.languageCode); const collectionMap = new Map<string, Collection>(); for (const collectionDef of data.collections) { const parent = collectionDef.parentName && collectionMap.get(collectionDef.parentName); const parentId = parent ? parent.id.toString() : undefined; const { assets } = await this.assetImporter.getAssets(collectionDef.assetPaths || [], ctx); let filters: ConfigurableOperationInput[] = []; try { filters = (collectionDef.filters || []).map(filter => this.processFilterDefinition(filter, allFacetValues), ); } catch (e: any) { Logger.error(e.message); } const collection = await this.collectionService.create(ctx, { translations: [ { languageCode: ctx.languageCode, name: collectionDef.name, description: collectionDef.description || '', slug: collectionDef.slug ?? collectionDef.name, }, ], isPrivate: collectionDef.private || false, parentId, assetIds: assets.map(a => a.id.toString()), featuredAssetId: assets.length ? assets[0].id.toString() : undefined, filters, inheritFilters: collectionDef.inheritFilters ?? true, }); collectionMap.set(collectionDef.name, collection); } // Wait for the created collection operations to complete before running // the reindex of the search index. await new Promise(resolve => setTimeout(resolve, 50)); await this.searchService.reindex(ctx); } private processFilterDefinition( filter: CollectionFilterDefinition, allFacetValues: FacetValue[], ): ConfigurableOperationInput { switch (filter.code) { case 'facet-value-filter': const facetValueIds = filter.args.facetValueNames .map(name => allFacetValues.find(fv => { let facetName; let valueName = name; if (name.includes(':')) { [facetName, valueName] = name.split(':'); return ( (fv.name === valueName || fv.code === valueName) && (fv.facet.name === facetName || fv.facet.code === facetName) ); } else { return fv.name === valueName || fv.code === valueName; } }), ) .filter(notNullOrUndefined) .map(fv => fv.id); return { code: filter.code, arguments: [ { name: 'facetValueIds', value: JSON.stringify(facetValueIds), }, { name: 'containsAny', value: filter.args.containsAny.toString(), }, ], }; default: throw new Error(`Filter with code "${filter.code as string}" is not recognized.`); } } private async createRequestContext(data: InitialData, channel?: Channel) { const { superadminCredentials } = this.configService.authOptions; const superAdminUser = await this.connection.rawConnection.getRepository(User).findOne({ where: { identifier: superadminCredentials.identifier, }, }); const ctx = await this.requestContextService.create({ user: superAdminUser ?? undefined, apiType: 'admin', languageCode: data.defaultLanguage, channelOrToken: channel ?? (await this.channelService.getDefaultChannel()), }); return ctx; } private async setChannelDefaults(zoneMap: ZoneMap, data: InitialData, channel: Channel) { const defaultZone = zoneMap.get(data.defaultZone); if (!defaultZone) { throw new Error( `The defaultZone (${data.defaultZone}) did not match any existing or created zone names`, ); } const defaultZoneId = defaultZone.entity.id; await this.channelService.update(RequestContext.empty(), { id: channel.id, defaultTaxZoneId: defaultZoneId, defaultShippingZoneId: defaultZoneId, }); } private async populateCountries(ctx: RequestContext, countries: CountryDefinition[]): Promise<ZoneMap> { const zoneMap: ZoneMap = new Map(); const existingZones = await this.zoneService.getAllWithMembers(ctx); for (const zone of existingZones) { zoneMap.set(zone.name, { entity: zone, members: zone.members.map(m => m.id) }); } for (const { name, code, zone } of countries) { const countryEntity = await this.countryService.create(ctx, { code, enabled: true, translations: [{ languageCode: ctx.languageCode, name }], }); let zoneItem = zoneMap.get(zone); if (!zoneItem) { const zoneEntity = await this.zoneService.create(ctx, { name: zone }); zoneItem = { entity: zoneEntity, members: [] }; zoneMap.set(zone, zoneItem); } if (!zoneItem.members.includes(countryEntity.id)) { zoneItem.members.push(countryEntity.id); } } // add the countries to the respective zones for (const zoneItem of zoneMap.values()) { await this.zoneService.addMembersToZone(ctx, { zoneId: zoneItem.entity.id, memberIds: zoneItem.members, }); } return zoneMap; } private async populateTaxRates( ctx: RequestContext, taxRates: Array<{ name: string; percentage: number }>, zoneMap: ZoneMap, ) { const taxCategories: TaxCategory[] = []; for (const taxRate of taxRates) { const category = await this.taxCategoryService.create(ctx, { name: taxRate.name }); for (const { entity } of zoneMap.values()) { await this.taxRateService.create(ctx, { zoneId: entity.id, value: taxRate.percentage, categoryId: category.id, name: `${taxRate.name} ${entity.name}`, enabled: true, }); } } } private async populateShippingMethods( ctx: RequestContext, shippingMethods: Array<{ name: string; price: number }>, ) { for (const method of shippingMethods) { await this.shippingMethodService.create(ctx, { fulfillmentHandler: manualFulfillmentHandler.code, checker: { code: defaultShippingEligibilityChecker.code, arguments: [{ name: 'orderMinimum', value: '0' }], }, calculator: { code: defaultShippingCalculator.code, arguments: [ { name: 'rate', value: method.price.toString() }, { name: 'taxRate', value: '0' }, { name: 'includesTax', value: 'auto' }, ], }, code: normalizeString(method.name, '-'), translations: [{ languageCode: ctx.languageCode, name: method.name, description: '' }], }); } } private async populatePaymentMethods(ctx: RequestContext, paymentMethods: InitialData['paymentMethods']) { for (const method of paymentMethods) { await this.paymentMethodService.create(ctx, { code: normalizeString(method.name, '-'), enabled: true, handler: method.handler, translations: [{ languageCode: ctx.languageCode, name: method.name, description: '' }], }); } } private async populateRoles(ctx: RequestContext, roles?: RoleDefinition[]) { if (!roles) { return; } for (const roleDef of roles) { await this.roleService.create(ctx, roleDef); } } }
export class CustomAddressFields {} export class CustomAdministratorFields {} export class CustomAssetFields {} export class CustomChannelFields {} export class CustomCollectionFields {} export class CustomCollectionFieldsTranslation {} export class CustomCustomerFields {} export class CustomCustomerGroupFields {} export class CustomFacetFields {} export class CustomFacetFieldsTranslation {} export class CustomFacetValueFields {} export class CustomFacetValueFieldsTranslation {} export class CustomFulfillmentFields {} export class CustomGlobalSettingsFields {} export class CustomOrderFields {} export class CustomOrderLineFields {} export class CustomPaymentMethodFields {} export class CustomPaymentMethodFieldsTranslation {} export class CustomProductFields {} export class CustomProductFieldsTranslation {} export class CustomProductOptionFields {} export class CustomProductOptionFieldsTranslation {} export class CustomProductOptionGroupFields {} export class CustomProductOptionGroupFieldsTranslation {} export class CustomProductVariantFields {} export class CustomProductVariantFieldsTranslation {} export class CustomProductVariantPriceFields {} export class CustomPromotionFields {} export class CustomPromotionFieldsTranslation {} export class CustomRegionFields {} export class CustomRegionFieldsTranslation {} export class CustomSellerFields {} export class CustomShippingMethodFields {} export class CustomShippingMethodFieldsTranslation {} export class CustomStockLocationFields {} export class CustomTaxCategoryFields {} export class CustomTaxRateFields {} export class CustomUserFields {} export class CustomZoneFields {}
import { Address } from './address/address.entity'; import { Administrator } from './administrator/administrator.entity'; import { Asset } from './asset/asset.entity'; import { AuthenticationMethod } from './authentication-method/authentication-method.entity'; import { ExternalAuthenticationMethod } from './authentication-method/external-authentication-method.entity'; import { NativeAuthenticationMethod } from './authentication-method/native-authentication-method.entity'; import { Channel } from './channel/channel.entity'; import { CollectionAsset } from './collection/collection-asset.entity'; import { CollectionTranslation } from './collection/collection-translation.entity'; import { Collection } from './collection/collection.entity'; import { Customer } from './customer/customer.entity'; import { CustomerGroup } from './customer-group/customer-group.entity'; import { FacetTranslation } from './facet/facet-translation.entity'; import { Facet } from './facet/facet.entity'; import { FacetValueTranslation } from './facet-value/facet-value-translation.entity'; import { FacetValue } from './facet-value/facet-value.entity'; import { Fulfillment } from './fulfillment/fulfillment.entity'; import { GlobalSettings } from './global-settings/global-settings.entity'; import { CustomerHistoryEntry } from './history-entry/customer-history-entry.entity'; import { HistoryEntry } from './history-entry/history-entry.entity'; import { OrderHistoryEntry } from './history-entry/order-history-entry.entity'; import { Order } from './order/order.entity'; import { OrderLine } from './order-line/order-line.entity'; import { FulfillmentLine } from './order-line-reference/fulfillment-line.entity'; import { OrderLineReference } from './order-line-reference/order-line-reference.entity'; import { OrderModificationLine } from './order-line-reference/order-modification-line.entity'; import { RefundLine } from './order-line-reference/refund-line.entity'; import { OrderModification } from './order-modification/order-modification.entity'; import { Payment } from './payment/payment.entity'; import { PaymentMethodTranslation } from './payment-method/payment-method-translation.entity'; import { PaymentMethod } from './payment-method/payment-method.entity'; import { ProductAsset } from './product/product-asset.entity'; import { ProductTranslation } from './product/product-translation.entity'; import { Product } from './product/product.entity'; import { ProductOptionTranslation } from './product-option/product-option-translation.entity'; import { ProductOption } from './product-option/product-option.entity'; import { ProductOptionGroupTranslation } from './product-option-group/product-option-group-translation.entity'; import { ProductOptionGroup } from './product-option-group/product-option-group.entity'; import { ProductVariantAsset } from './product-variant/product-variant-asset.entity'; import { ProductVariantPrice } from './product-variant/product-variant-price.entity'; import { ProductVariantTranslation } from './product-variant/product-variant-translation.entity'; import { ProductVariant } from './product-variant/product-variant.entity'; import { PromotionTranslation } from './promotion/promotion-translation.entity'; import { Promotion } from './promotion/promotion.entity'; import { Refund } from './refund/refund.entity'; import { Country } from './region/country.entity'; import { Province } from './region/province.entity'; import { RegionTranslation } from './region/region-translation.entity'; import { Region } from './region/region.entity'; import { Role } from './role/role.entity'; import { Seller } from './seller/seller.entity'; import { AnonymousSession } from './session/anonymous-session.entity'; import { AuthenticatedSession } from './session/authenticated-session.entity'; import { Session } from './session/session.entity'; import { ShippingLine } from './shipping-line/shipping-line.entity'; import { ShippingMethodTranslation } from './shipping-method/shipping-method-translation.entity'; import { ShippingMethod } from './shipping-method/shipping-method.entity'; import { StockLevel } from './stock-level/stock-level.entity'; import { StockLocation } from './stock-location/stock-location.entity'; import { Allocation } from './stock-movement/allocation.entity'; import { Cancellation } from './stock-movement/cancellation.entity'; import { Release } from './stock-movement/release.entity'; import { Sale } from './stock-movement/sale.entity'; import { StockAdjustment } from './stock-movement/stock-adjustment.entity'; import { StockMovement } from './stock-movement/stock-movement.entity'; import { Surcharge } from './surcharge/surcharge.entity'; import { Tag } from './tag/tag.entity'; import { TaxCategory } from './tax-category/tax-category.entity'; import { TaxRate } from './tax-rate/tax-rate.entity'; import { User } from './user/user.entity'; import { Zone } from './zone/zone.entity'; /** * A map of all the core database entities. */ export const coreEntitiesMap = { Address, Administrator, Allocation, AnonymousSession, Asset, AuthenticatedSession, AuthenticationMethod, Cancellation, Channel, Collection, CollectionAsset, CollectionTranslation, Country, Customer, CustomerGroup, CustomerHistoryEntry, ExternalAuthenticationMethod, Facet, FacetTranslation, FacetValue, FacetValueTranslation, Fulfillment, FulfillmentLine, GlobalSettings, HistoryEntry, OrderModificationLine, NativeAuthenticationMethod, Order, OrderHistoryEntry, OrderLine, OrderLineReference, OrderModification, Payment, PaymentMethod, PaymentMethodTranslation, Product, ProductAsset, ProductOption, ProductOptionGroup, ProductOptionGroupTranslation, ProductOptionTranslation, ProductTranslation, ProductVariant, ProductVariantAsset, ProductVariantPrice, ProductVariantTranslation, Promotion, PromotionTranslation, Province, Refund, RefundLine, Region, RegionTranslation, Release, Role, Sale, Session, ShippingLine, ShippingMethod, ShippingMethodTranslation, StockAdjustment, StockLevel, StockLocation, StockMovement, Surcharge, Tag, TaxCategory, TaxRate, User, Seller, Zone, };
import { Type } from '@vendure/common/lib/shared-types'; interface IdColumnOptions { /** Whether the field is nullable. Defaults to false */ nullable?: boolean; /** Whether this is a primary key. Defaults to false */ primary?: boolean; } interface IdColumnConfig { name: string; entity: any; options?: IdColumnOptions; } const idColumnRegistry = new Map<any, IdColumnConfig[]>(); let primaryGeneratedColumn: { entity: any; name: string } | undefined; /** * Decorates a property which should be marked as a generated primary key. * Designed to be applied to the VendureEntity id property. */ export function PrimaryGeneratedId() { return (entity: any, propertyName: string) => { primaryGeneratedColumn = { entity, name: propertyName, }; }; } /** * @description * Decorates a property which points to another entity by ID. This custom decorator is needed * because we do not know the data type of the ID column until runtime, when we have access * to the configured EntityIdStrategy. * * @docsCategory configuration * @docsPage EntityId Decorator */ export function EntityId(options?: IdColumnOptions) { return (entity: any, propertyName: string) => { const idColumns = idColumnRegistry.get(entity); const entry = { name: propertyName, entity, options }; if (idColumns) { idColumns.push(entry); } else { idColumnRegistry.set(entity, [entry]); } }; } /** * Returns any columns on the entity which have been decorated with the {@link EntityId} * decorator. */ export function getIdColumnsFor(entityType: Type<any>): IdColumnConfig[] { const match = Array.from(idColumnRegistry.entries()).find( ([entity, columns]) => entity.constructor === entityType, ); return match ? match[1] : []; } /** * Returns the entity and property name that was decorated with the {@link PrimaryGeneratedId} * decorator. */ export function getPrimaryGeneratedIdColumn(): { entity: any; name: string } { if (!primaryGeneratedColumn) { throw new Error( 'primaryGeneratedColumn is undefined. The base VendureEntity must have the @PrimaryGeneratedId() decorator set on its id property.', ); } return primaryGeneratedColumn; }
export * from './address/address.entity'; export * from './administrator/administrator.entity'; export * from './asset/asset.entity'; export * from './authentication-method/authentication-method.entity'; export * from './authentication-method/external-authentication-method.entity'; export * from './authentication-method/native-authentication-method.entity'; export * from './base/base.entity'; export * from './channel/channel.entity'; export * from './collection/collection-asset.entity'; export * from './collection/collection-translation.entity'; export * from './collection/collection.entity'; export * from './region/country.entity'; export * from './custom-entity-fields'; export * from './customer-group/customer-group.entity'; export * from './customer/customer.entity'; export * from './facet-value/facet-value-translation.entity'; export * from './facet-value/facet-value.entity'; export * from './facet/facet-translation.entity'; export * from './facet/facet.entity'; export * from './fulfillment/fulfillment.entity'; export * from './global-settings/global-settings.entity'; export * from './order/order.entity'; export * from './order-line/order-line.entity'; export * from './order-line-reference/fulfillment-line.entity'; export * from './order-line-reference/order-modification-line.entity'; export * from './order-line-reference/order-line-reference.entity'; export * from './order-line-reference/refund-line.entity'; export * from './payment/payment.entity'; export * from './payment-method/payment-method.entity'; export * from './payment/payment.entity'; export * from './product-option-group/product-option-group-translation.entity'; export * from './product-option-group/product-option-group.entity'; export * from './product-option/product-option-translation.entity'; export * from './product-option/product-option.entity'; export * from './product-variant/product-variant-asset.entity'; export * from './product-variant/product-variant-price.entity'; export * from './product-variant/product-variant-translation.entity'; export * from './product-variant/product-variant.entity'; export * from './product/product-asset.entity'; export * from './product/product-translation.entity'; export * from './product/product.entity'; export * from './promotion/promotion.entity'; export * from './refund/refund.entity'; export * from './role/role.entity'; export * from './seller/seller.entity'; export * from './session/anonymous-session.entity'; export * from './session/authenticated-session.entity'; export * from './session/session.entity'; export * from './shipping-line/shipping-line.entity'; export * from './shipping-method/shipping-method.entity'; export * from './stock-level/stock-level.entity'; export * from './stock-location/stock-location.entity'; export * from './stock-movement/allocation.entity'; export * from './stock-movement/cancellation.entity'; export * from './stock-movement/release.entity'; export * from './stock-movement/sale.entity'; export * from './stock-movement/stock-adjustment.entity'; export * from './stock-movement/stock-movement.entity'; export * from './surcharge/surcharge.entity'; export * from './tag/tag.entity'; export * from './tax-category/tax-category.entity'; export * from './tax-rate/tax-rate.entity'; export * from './user/user.entity'; export * from './zone/zone.entity'; export * from './entity-id.decorator'; export * from './money.decorator';
import { Type } from '@vendure/common/lib/shared-types'; interface MoneyColumnOptions { default?: number; /** Whether the field is nullable. Defaults to false */ nullable?: boolean; } interface MoneyColumnConfig { name: string; entity: any; options?: MoneyColumnOptions; } const moneyColumnRegistry = new Map<any, MoneyColumnConfig[]>(); /** * @description * Use this decorator for any entity field that is storing a monetary value. * This allows the column type to be defined by the configured {@link MoneyStrategy}. * * @docsCategory money * @docsPage Money Decorator * @since 2.0.0 */ export function Money(options?: MoneyColumnOptions) { return (entity: any, propertyName: string) => { const idColumns = moneyColumnRegistry.get(entity); const entry = { name: propertyName, entity, options }; if (idColumns) { idColumns.push(entry); } else { moneyColumnRegistry.set(entity, [entry]); } }; } /** * @description * Returns any columns on the entity which have been decorated with the {@link EntityId} * decorator. */ export function getMoneyColumnsFor(entityType: Type<any>): MoneyColumnConfig[] { const match = Array.from(moneyColumnRegistry.entries()).find( ([entity, columns]) => entity.constructor === entityType, ); return match ? match[1] : []; }
/* eslint-disable @typescript-eslint/ban-types */ import { CustomFieldType } from '@vendure/common/lib/shared-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { Column, ColumnOptions, ColumnType, DataSourceOptions, getMetadataArgsStorage, Index, JoinColumn, JoinTable, ManyToMany, ManyToOne, } from 'typeorm'; import { EmbeddedMetadataArgs } from 'typeorm/metadata-args/EmbeddedMetadataArgs'; import { DateUtils } from 'typeorm/util/DateUtils'; import { CustomFieldConfig, CustomFields } from '../config/custom-field/custom-field-types'; import { Logger } from '../config/logger/vendure-logger'; import { VendureConfig } from '../config/vendure-config'; /** * The maximum length of the "length" argument of a MySQL varchar column. */ const MAX_STRING_LENGTH = 65535; /** * Dynamically add columns to the custom field entity based on the CustomFields config. */ function registerCustomFieldsForEntity( config: VendureConfig, entityName: keyof CustomFields, // eslint-disable-next-line @typescript-eslint/prefer-function-type ctor: { new (): any }, translation = false, ) { const customFields = config.customFields && config.customFields[entityName]; const dbEngine = config.dbConnectionOptions.type; if (customFields) { for (const customField of customFields) { const { name, list, defaultValue, nullable } = customField; const instance = new ctor(); const registerColumn = () => { if (customField.type === 'relation') { if (customField.list) { ManyToMany(type => customField.entity, customField.inverseSide, { eager: customField.eager, })(instance, name); JoinTable()(instance, name); } else { ManyToOne(type => customField.entity, customField.inverseSide, { eager: customField.eager, })(instance, name); JoinColumn()(instance, name); } } else { const options: ColumnOptions = { type: list ? 'simple-json' : getColumnType(dbEngine, customField.type), default: getDefault(customField, dbEngine), name, nullable: nullable === false ? false : true, unique: customField.unique ?? false, }; if ((customField.type === 'string' || customField.type === 'localeString') && !list) { const length = customField.length || 255; if (MAX_STRING_LENGTH < length) { throw new Error( `ERROR: The "length" property of the custom field "${customField.name}" is ` + `greater than the maximum allowed value of ${MAX_STRING_LENGTH}`, ); } options.length = length; } if ( customField.type === 'float' && typeof customField.defaultValue === 'number' && (dbEngine === 'mariadb' || dbEngine === 'mysql') ) { // In the MySQL driver, a default float value will get rounded to the nearest integer. // unless you specify the precision. const defaultValueDecimalPlaces = customField.defaultValue.toString().split('.')[1]; if (defaultValueDecimalPlaces) { options.scale = defaultValueDecimalPlaces.length; } } if ( customField.type === 'datetime' && options.precision == null && // Setting precision on an sqlite datetime will cause // spurious migration commands. See https://github.com/typeorm/typeorm/issues/2333 dbEngine !== 'sqljs' && dbEngine !== 'sqlite' && !list ) { options.precision = 6; } Column(options)(instance, name); if ((dbEngine === 'mysql' || dbEngine === 'mariadb') && customField.unique === true) { // The MySQL driver seems to work differently and will only apply a unique // constraint if an index is defined on the column. For postgres/sqlite it is // sufficient to add the `unique: true` property to the column options. Index({ unique: true })(instance, name); } } }; if (translation) { if (customField.type === 'localeString' || customField.type === 'localeText') { registerColumn(); } } else { if (customField.type !== 'localeString' && customField.type !== 'localeText') { registerColumn(); } } const relationFieldsCount = customFields.filter(f => f.type === 'relation').length; const nonLocaleStringFieldsCount = customFields.filter( f => f.type !== 'localeString' && f.type !== 'localeText' && f.type !== 'relation', ).length; if (0 < relationFieldsCount && nonLocaleStringFieldsCount === 0) { // if (customFields.filter(f => f.type === 'relation').length === customFields.length) { // If there are _only_ relational customFields defined for an Entity, then TypeORM // errors when attempting to load that entity ("Cannot set property <fieldName> of undefined"). // Therefore as a work-around we will add a "fake" column to the customFields embedded type // to prevent this error from occurring. Column({ type: 'boolean', nullable: true, comment: 'A work-around needed when only relational custom fields are defined on an entity', })(instance, '__fix_relational_custom_fields__'); } } } } function formatDefaultDatetime(dbEngine: DataSourceOptions['type'], datetime: any): Date | string { if (!datetime) { return datetime; } switch (dbEngine) { case 'sqlite': case 'sqljs': return DateUtils.mixedDateToUtcDatetimeString(datetime); case 'mysql': case 'postgres': default: return DateUtils.mixedDateToUtcDatetimeString(datetime); // return DateUtils.mixedDateToDate(datetime, true, true); } } function getColumnType( dbEngine: DataSourceOptions['type'], type: Exclude<CustomFieldType, 'relation'>, ): ColumnType { switch (type) { case 'string': case 'localeString': return 'varchar'; case 'text': case 'localeText': switch (dbEngine) { case 'mysql': case 'mariadb': return 'longtext'; default: return 'text'; } case 'boolean': switch (dbEngine) { case 'mysql': return 'tinyint'; case 'postgres': return 'bool'; case 'sqlite': case 'sqljs': default: return 'boolean'; } case 'int': return 'int'; case 'float': return 'double precision'; case 'datetime': switch (dbEngine) { case 'postgres': return 'timestamp'; case 'mysql': case 'sqlite': case 'sqljs': default: return 'datetime'; } default: assertNever(type); } return 'varchar'; } function getDefault(customField: CustomFieldConfig, dbEngine: DataSourceOptions['type']) { const { name, type, list, defaultValue, nullable } = customField; if (list && defaultValue) { if (dbEngine === 'mysql') { // MySQL does not support defaults on TEXT fields, which is what "simple-json" uses // internally. See https://stackoverflow.com/q/3466872/772859 Logger.warn( `MySQL does not support default values on list fields (${name}). No default will be set.`, ); return undefined; } return JSON.stringify(defaultValue); } return type === 'datetime' ? formatDefaultDatetime(dbEngine, defaultValue) : defaultValue; } function assertLocaleFieldsNotSpecified(config: VendureConfig, entityName: keyof CustomFields) { const customFields = config.customFields && config.customFields[entityName]; if (customFields) { for (const customField of customFields) { if (customField.type === 'localeString' || customField.type === 'localeText') { Logger.error( `Custom field "${customField.name}" on entity "${entityName}" cannot be of type "localeString" or "localeText". ` + `This entity does not support localization.`, ); } } } } /** * Dynamically registers any custom fields with TypeORM. This function should be run at the bootstrap * stage of the app lifecycle, before the AppModule is initialized. */ export function registerCustomEntityFields(config: VendureConfig) { // In order to determine the classes used for the custom field embedded types, we need // to introspect the metadata args storage. const metadataArgsStorage = getMetadataArgsStorage(); for (const [entityName, customFieldsConfig] of Object.entries(config.customFields ?? {})) { if (customFieldsConfig && customFieldsConfig.length) { const customFieldsMetadata = getCustomFieldsMetadata(entityName); const customFieldsClass = customFieldsMetadata.type(); if (customFieldsClass && typeof customFieldsClass !== 'string') { registerCustomFieldsForEntity(config, entityName, customFieldsClass as any); } const translationsMetadata = metadataArgsStorage .filterRelations(customFieldsMetadata.target) .find(m => m.propertyName === 'translations'); if (translationsMetadata) { // This entity is translatable, which means that we should // also register any localized custom fields on the related // EntityTranslation entity. const translationType: Function = (translationsMetadata.type as Function)(); const customFieldsTranslationsMetadata = getCustomFieldsMetadata(translationType); const customFieldsTranslationClass = customFieldsTranslationsMetadata.type(); if (customFieldsTranslationClass && typeof customFieldsTranslationClass !== 'string') { registerCustomFieldsForEntity( config, entityName, customFieldsTranslationClass as any, true, ); } } else { assertLocaleFieldsNotSpecified(config, entityName); } } } function getCustomFieldsMetadata(entity: Function | string): EmbeddedMetadataArgs { const entityName = typeof entity === 'string' ? entity : entity.name; const metadataArgs = metadataArgsStorage.embeddeds.find(item => { if (item.propertyName === 'customFields') { const targetName = typeof item.target === 'string' ? item.target : item.target.name; return targetName === entityName; } }); if (!metadataArgs) { throw new Error(`Could not find embedded CustomFields property on entity "${entityName}"`); } return metadataArgs; } }
import { getMetadataArgsStorage } from 'typeorm'; import { VendureConfig } from '../config/vendure-config'; export async function runEntityMetadataModifiers(config: VendureConfig) { if (config.entityOptions?.metadataModifiers?.length) { const metadataArgsStorage = getMetadataArgsStorage(); for (const modifier of config.entityOptions.metadataModifiers) { await modifier(metadataArgsStorage); } } }
import { Type } from '@vendure/common/lib/shared-types'; import { Column, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm'; import { EntityIdStrategy } from '../config/entity/entity-id-strategy'; import { getIdColumnsFor, getPrimaryGeneratedIdColumn } from './entity-id.decorator'; export function setEntityIdStrategy(entityIdStrategy: EntityIdStrategy<any>, entities: Array<Type<any>>) { setBaseEntityIdType(entityIdStrategy); setEntityIdColumnTypes(entityIdStrategy, entities); } function setEntityIdColumnTypes(entityIdStrategy: EntityIdStrategy<any>, entities: Array<Type<any>>) { const columnDataType = entityIdStrategy.primaryKeyType === 'increment' ? 'int' : 'varchar'; for (const EntityCtor of entities) { const columnConfig = getIdColumnsFor(EntityCtor); for (const { name, options, entity } of columnConfig) { Column({ type: columnDataType, nullable: (options && options.nullable) || false, primary: (options && options.primary) || false, })(entity, name); } } } function setBaseEntityIdType(entityIdStrategy: EntityIdStrategy<any>) { const { entity, name } = getPrimaryGeneratedIdColumn(); PrimaryGeneratedColumn(entityIdStrategy.primaryKeyType)(entity, name); }
import { Type } from '@vendure/common/lib/shared-types'; import { Column } from 'typeorm'; import { MoneyStrategy } from '../config/entity/money-strategy'; import { getMoneyColumnsFor } from './money.decorator'; export function setMoneyStrategy(moneyStrategy: MoneyStrategy, entities: Array<Type<any>>) { for (const EntityCtor of entities) { const columnConfig = getMoneyColumnsFor(EntityCtor); for (const { name, options, entity } of columnConfig) { Column({ ...moneyStrategy.moneyColumnOptions, nullable: options?.nullable ?? false, default: options?.default, })(entity, name); } } }
import { EntitySubscriberInterface, EventSubscriber, InsertEvent } from 'typeorm'; import { CalculatedColumnDefinition, CALCULATED_PROPERTIES } from '../common/calculated-decorator'; interface EntityPrototype { [CALCULATED_PROPERTIES]: CalculatedColumnDefinition[]; } @EventSubscriber() export class CalculatedPropertySubscriber implements EntitySubscriberInterface { afterLoad(event: any) { this.moveCalculatedGettersToInstance(event); } afterInsert(event: InsertEvent<any>): Promise<any> | void { this.moveCalculatedGettersToInstance(event.entity); } /** * For any entity properties decorated with @Calculated(), this subscriber transfers * the getter from the entity prototype to the entity instance, so that it can be * correctly enumerated and serialized in the API response. */ private moveCalculatedGettersToInstance(entity: any) { if (entity) { const prototype: EntityPrototype = Object.getPrototypeOf(entity); if (prototype.hasOwnProperty(CALCULATED_PROPERTIES)) { for (const calculatedPropertyDef of prototype[CALCULATED_PROPERTIES]) { const getterDescriptor = Object.getOwnPropertyDescriptor( prototype, calculatedPropertyDef.name, ); // eslint-disable-next-line @typescript-eslint/unbound-method const getFn = getterDescriptor && getterDescriptor.get; if (getFn && !entity.hasOwnProperty(calculatedPropertyDef.name)) { const boundGetFn = getFn.bind(entity); Object.defineProperties(entity, { [calculatedPropertyDef.name]: { get: () => boundGetFn(), enumerable: true, }, }); } } } } } } /** * A map of the core TypeORM Subscribers. */ export const coreSubscribersMap = { CalculatedPropertySubscriber, };
import { Type } from '@vendure/common/lib/shared-types'; import { describe, expect, it } from 'vitest'; import { CustomFields } from '../config/custom-field/custom-field-types'; import { coreEntitiesMap } from './entities'; import { validateCustomFieldsConfig } from './validate-custom-fields-config'; describe('validateCustomFieldsConfig()', () => { const allEntities = Object.values(coreEntitiesMap) as Array<Type<any>>; it('valid config', () => { const config: CustomFields = { Product: [ { name: 'foo', type: 'string' }, { name: 'bar', type: 'localeString' }, ], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(true); expect(result.errors.length).toBe(0); }); it('invalid localeString', () => { const config: CustomFields = { User: [ { name: 'foo', type: 'string' }, { name: 'bar', type: 'localeString' }, ], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual(['User entity does not support custom fields of type "localeString"']); }); it('valid names', () => { const config: CustomFields = { User: [ { name: 'love2code', type: 'string' }, { name: 'snake_case', type: 'string' }, { name: 'camelCase', type: 'string' }, { name: 'SHOUTY', type: 'string' }, ], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(true); expect(result.errors).toEqual([]); }); it('invalid names', () => { const config: CustomFields = { User: [ { name: '2cool', type: 'string' }, { name: 'has space', type: 'string' }, { name: 'speci@alChar', type: 'string' }, { name: 'has-dash', type: 'string' }, ], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual([ 'User entity has an invalid custom field name: "2cool"', 'User entity has an invalid custom field name: "has space"', 'User entity has an invalid custom field name: "speci@alChar"', 'User entity has an invalid custom field name: "has-dash"', ]); }); it('duplicate names', () => { const config: CustomFields = { User: [ { name: 'foo', type: 'string' }, { name: 'bar', type: 'string' }, { name: 'baz', type: 'string' }, { name: 'foo', type: 'boolean' }, { name: 'bar', type: 'boolean' }, ], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual([ 'User entity has duplicated custom field name: "foo"', 'User entity has duplicated custom field name: "bar"', ]); }); it('duplicate names in translation', () => { const config: CustomFields = { Product: [ { name: 'foo', type: 'string' }, { name: 'bar', type: 'string' }, { name: 'baz', type: 'string' }, { name: 'foo', type: 'localeString' }, { name: 'bar', type: 'boolean' }, ], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual([ 'Product entity has duplicated custom field name: "foo"', 'Product entity has duplicated custom field name: "bar"', ]); }); it('name conflict with existing fields', () => { const config: CustomFields = { Product: [{ name: 'createdAt', type: 'string' }], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual(['Product entity already has a field named "createdAt"']); }); it('name conflict with existing fields in translation', () => { const config: CustomFields = { Product: [{ name: 'name', type: 'string' }], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual(['Product entity already has a field named "name"']); }); it('non-nullable must have defaultValue', () => { const config: CustomFields = { Product: [{ name: 'foo', type: 'string', nullable: false }], }; const result = validateCustomFieldsConfig(config, allEntities); expect(result.valid).toBe(false); expect(result.errors).toEqual([ 'Product entity custom field "foo" is non-nullable and must have a defaultValue', ]); }); });
import { Type } from '@vendure/common/lib/shared-types'; import { getMetadataArgsStorage } from 'typeorm'; import { CustomFieldConfig, CustomFields } from '../config/custom-field/custom-field-types'; import { VendureEntity } from './base/base.entity'; function validateCustomFieldsForEntity( entity: Type<VendureEntity>, customFields: CustomFieldConfig[], ): string[] { return [ ...assertValidFieldNames(entity.name, customFields), ...assertNoNameConflictsWithEntity(entity, customFields), ...assertNoDuplicatedCustomFieldNames(entity.name, customFields), ...assetNonNullablesHaveDefaults(entity.name, customFields), ...(isTranslatable(entity) ? [] : assertNoLocaleStringFields(entity.name, customFields)), ]; } /** * Assert that the custom entity names are valid */ function assertValidFieldNames(entityName: string, customFields: CustomFieldConfig[]): string[] { const errors: string[] = []; const validNameRe = /^[a-zA-Z_]+[a-zA-Z0-9_]*$/; for (const field of customFields) { if (!validNameRe.test(field.name)) { errors.push(`${entityName} entity has an invalid custom field name: "${field.name}"`); } } return errors; } function assertNoNameConflictsWithEntity(entity: Type<any>, customFields: CustomFieldConfig[]): string[] { const errors: string[] = []; for (const field of customFields) { const conflicts = (e: Type<any>): boolean => { return -1 < getAllColumnNames(e).findIndex(name => name === field.name); }; const translation = getEntityTranslation(entity); if (conflicts(entity) || (translation && conflicts(translation))) { errors.push(`${entity.name} entity already has a field named "${field.name}"`); } } return errors; } /** * Assert that none of the custom field names conflict with one another. */ function assertNoDuplicatedCustomFieldNames(entityName: string, customFields: CustomFieldConfig[]): string[] { const nameCounts = customFields .map(f => f.name) .reduce((hash, name) => { // eslint-disable-next-line @typescript-eslint/no-unused-expressions hash[name] ? hash[name]++ : (hash[name] = 1); return hash; }, {} as { [name: string]: number }); return Object.entries(nameCounts) .filter(([name, count]) => 1 < count) .map(([name, count]) => `${entityName} entity has duplicated custom field name: "${name}"`); } /** * For entities which are not localized (Address, Customer), we assert that none of the custom fields * have a type "localeString". */ function assertNoLocaleStringFields(entityName: string, customFields: CustomFieldConfig[]): string[] { if (!!customFields.find(f => f.type === 'localeString')) { return [`${entityName} entity does not support custom fields of type "localeString"`]; } return []; } /** * Assert that any non-nullable field must have a defaultValue specified. */ function assetNonNullablesHaveDefaults(entityName: string, customFields: CustomFieldConfig[]): string[] { const errors: string[] = []; for (const field of customFields) { if (field.nullable === false && field.defaultValue === undefined) { errors.push( `${entityName} entity custom field "${field.name}" is non-nullable and must have a defaultValue`, ); } } return errors; } function isTranslatable(entity: Type<any>): boolean { return !!getEntityTranslation(entity); } function getEntityTranslation(entity: Type<any>): Type<any> | undefined { const metadata = getMetadataArgsStorage(); const translation = metadata.filterRelations(entity).find(r => r.propertyName === 'translations'); if (translation) { const type = translation.type; if (typeof type === 'function') { // See https://github.com/microsoft/TypeScript/issues/37663 return (type as any)(); } } } function getAllColumnNames(entity: Type<any>): string[] { const metadata = getMetadataArgsStorage(); const ownColumns = metadata.filterColumns(entity); const relationColumns = metadata.filterRelations(entity); const embeddedColumns = metadata.filterEmbeddeds(entity); const baseColumns = metadata.filterColumns(VendureEntity); return [...ownColumns, ...relationColumns, ...embeddedColumns, ...baseColumns].map(c => c.propertyName); } /** * Validates the custom fields config, e.g. by ensuring that there are no naming conflicts with the built-in fields * of each entity. */ export function validateCustomFieldsConfig( customFieldConfig: CustomFields, entities: Array<Type<any>>, ): { valid: boolean; errors: string[] } { let errors: string[] = []; getMetadataArgsStorage(); for (const key of Object.keys(customFieldConfig)) { const entityName = key as keyof CustomFields; const customEntityFields = customFieldConfig[entityName] || []; const entity = entities.find(e => e.name === entityName); if (entity && customEntityFields.length) { errors = errors.concat(validateCustomFieldsForEntity(entity, customEntityFields)); } } return { valid: errors.length === 0, errors, }; }