content
stringlengths
28
1.34M
import { Coordinate, CurrencyCode, LanguageCode, PriceRange, SearchResult, SearchResultAsset, SinglePrice, } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { Brackets, QueryBuilder, SelectQueryBuilder } from 'typeorm'; import { SearchIndexItem } from '../entities/search-index-item.entity'; /** * Maps a raw database result to a SearchResult. */ export function mapToSearchResult(raw: any, currencyCode: CurrencyCode): SearchResult { const price = raw.minPrice !== undefined ? ({ min: raw.minPrice, max: raw.maxPrice } as PriceRange) : ({ value: raw.si_price } as SinglePrice); const priceWithTax = raw.minPriceWithTax !== undefined ? ({ min: raw.minPriceWithTax, max: raw.maxPriceWithTax } as PriceRange) : ({ value: raw.si_priceWithTax } as SinglePrice); const productAsset: SearchResultAsset | undefined = !raw.si_productAssetId ? undefined : { id: raw.si_productAssetId, preview: raw.si_productPreview, focalPoint: parseFocalPoint(raw.si_productPreviewFocalPoint), }; const productVariantAsset: SearchResultAsset | undefined = !raw.si_productVariantAssetId ? undefined : { id: raw.si_productVariantAssetId, preview: raw.si_productVariantPreview, focalPoint: parseFocalPoint(raw.si_productVariantPreviewFocalPoint), }; const enabled = raw.productEnabled != null ? !!Number(raw.productEnabled) : raw.si_enabled; return { sku: raw.si_sku, slug: raw.si_slug, price, enabled, priceWithTax, currencyCode, productVariantId: raw.si_productVariantId, productId: raw.si_productId, productName: raw.si_productName, productVariantName: raw.si_productVariantName, description: raw.si_description, facetIds: raw.si_facetIds.split(',').map((x: string) => x.trim()), facetValueIds: raw.si_facetValueIds.split(',').map((x: string) => x.trim()), collectionIds: raw.si_collectionIds.split(',').map((x: string) => x.trim()), channelIds: raw.si_channelIds.split(',').map((x: string) => x.trim()), productAsset, productVariantAsset, score: raw.score || 0, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore inStock: raw.si_inStock, }; } /** * Given the raw query results containing rows with a `facetValues` property line "1,2,1,2", * this function returns a map of FacetValue ids => count of how many times they occur. */ export function createFacetIdCountMap(facetValuesResult: Array<{ facetValues: string }>) { const result = new Map<ID, number>(); for (const res of facetValuesResult) { const facetValueIds: ID[] = unique(res.facetValues.split(',').filter(x => x !== '')); for (const id of facetValueIds) { const count = result.get(id); const newCount = count ? count + 1 : 1; result.set(id, newCount); } } return result; } /** * Given the raw query results containing rows with a `collections` property line "1,2,1,2", * this function returns a map of Collection ids => count of how many times they occur. */ export function createCollectionIdCountMap(collectionsResult: Array<{ collections: string }>) { const result = new Map<ID, number>(); for (const res of collectionsResult) { const collectionIds: ID[] = unique(res.collections.split(',').filter(x => x !== '')); for (const id of collectionIds) { const count = result.get(id); const newCount = count ? count + 1 : 1; result.set(id, newCount); } } return result; } function parseFocalPoint(focalPoint: any): Coordinate | undefined { if (focalPoint && typeof focalPoint === 'string') { try { return JSON.parse(focalPoint); } catch (e: any) { // fall though } } return; } export function createPlaceholderFromId(id: ID): string { return '_' + id.toString().replace(/-/g, '_'); } /** * Applies language constraints for {@link SearchIndexItem} query. * * @param qb QueryBuilder instance * @param languageCode Preferred language code * @param defaultLanguageCode Default language code that is used if {@link SearchIndexItem} is not available in preferred language */ export function applyLanguageConstraints( qb: SelectQueryBuilder<SearchIndexItem>, languageCode: LanguageCode, defaultLanguageCode: LanguageCode, ) { const lcEscaped = qb.escape('languageCode'); const ciEscaped = qb.escape('channelId'); const pviEscaped = qb.escape('productVariantId'); if (languageCode === defaultLanguageCode) { qb.andWhere(`si.${lcEscaped} = :languageCode`, { languageCode, }); } else { qb.andWhere(`si.${lcEscaped} IN (:...languageCodes)`, { languageCodes: [languageCode, defaultLanguageCode], }); qb.leftJoin( SearchIndexItem, 'sil', `sil.${lcEscaped} = :languageCode AND sil.${ciEscaped} = si.${ciEscaped} AND sil.${pviEscaped} = si.${pviEscaped}`, { languageCode, }, ); qb.andWhere( new Brackets(qb1 => { qb1.where(`si.${lcEscaped} = :languageCode1`, { languageCode1: languageCode, }).orWhere(`sil.${lcEscaped} IS NULL`); }), ); } return qb; }
import { SearchInput, SearchResult } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../../api'; import { InjectableStrategy } from '../../../common'; /** * This interface defines the contract that any database-specific search implementations * should follow. * * :::info * * This is configured via the `searchStrategy` property of * the {@link DefaultSearchPluginInitOptions}. * * ::: */ export interface SearchStrategy extends InjectableStrategy { getSearchResults(ctx: RequestContext, input: SearchInput, enabledOnly: boolean): Promise<SearchResult[]>; getTotalCount(ctx: RequestContext, input: SearchInput, enabledOnly: boolean): Promise<number>; /** * Returns a map of `facetValueId` => `count`, providing the number of times that * facetValue occurs in the result set. */ getFacetValueIds(ctx: RequestContext, input: SearchInput, enabledOnly: boolean): Promise<Map<ID, number>>; /** * Returns a map of `collectionId` => `count`, providing the number of times that * collection occurs in the result set. */ getCollectionIds(ctx: RequestContext, input: SearchInput, enabledOnly: boolean): Promise<Map<ID, number>>; }
import { LogicalOperator, SearchResult } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { Brackets, SelectQueryBuilder } from 'typeorm'; import { RequestContext } from '../../../api/common/request-context'; import { Injector } from '../../../common'; import { UserInputError } from '../../../common/error/errors'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { PLUGIN_INIT_OPTIONS } from '../constants'; import { SearchIndexItem } from '../entities/search-index-item.entity'; import { DefaultSearchPluginInitOptions, SearchInput } from '../types'; import { SearchStrategy } from './search-strategy'; import { applyLanguageConstraints, createCollectionIdCountMap, createFacetIdCountMap, createPlaceholderFromId, mapToSearchResult, } from './search-strategy-utils'; /** * A rather naive search for SQLite / SQL.js. Rather than proper * full-text searching, it uses a weighted `LIKE "%term%"` operator instead. */ export class SqliteSearchStrategy implements SearchStrategy { private readonly minTermLength = 2; private connection: TransactionalConnection; private options: DefaultSearchPluginInitOptions; async init(injector: Injector) { this.connection = injector.get(TransactionalConnection); this.options = injector.get(PLUGIN_INIT_OPTIONS); } async getFacetValueIds( ctx: RequestContext, input: SearchInput, enabledOnly: boolean, ): Promise<Map<ID, number>> { const facetValuesQb = this.connection .getRepository(ctx, SearchIndexItem) .createQueryBuilder('si') .select(['si.productId', 'si.productVariantId']) .addSelect('GROUP_CONCAT(si.facetValueIds)', 'facetValues'); this.applyTermAndFilters(ctx, facetValuesQb, input); if (!input.groupByProduct) { facetValuesQb.groupBy('si.productVariantId'); } if (enabledOnly) { facetValuesQb.andWhere('si.enabled = :enabled', { enabled: true }); } const facetValuesResult = await facetValuesQb.getRawMany(); return createFacetIdCountMap(facetValuesResult); } async getCollectionIds( ctx: RequestContext, input: SearchInput, enabledOnly: boolean, ): Promise<Map<ID, number>> { const collectionsQb = this.connection .getRepository(ctx, SearchIndexItem) .createQueryBuilder('si') .select(['si.productId', 'si.productVariantId']) .addSelect('GROUP_CONCAT(si.collectionIds)', 'collections'); this.applyTermAndFilters(ctx, collectionsQb, input); if (!input.groupByProduct) { collectionsQb.groupBy('si.productVariantId'); } if (enabledOnly) { collectionsQb.andWhere('si.enabled = :enabled', { enabled: true }); } const collectionsResult = await collectionsQb.getRawMany(); return createCollectionIdCountMap(collectionsResult); } async getSearchResults( ctx: RequestContext, input: SearchInput, enabledOnly: boolean, ): Promise<SearchResult[]> { const take = input.take || 25; const skip = input.skip || 0; const sort = input.sort; const qb = this.connection.getRepository(ctx, SearchIndexItem).createQueryBuilder('si'); if (input.groupByProduct) { qb.addSelect('MIN(si.price)', 'minPrice'); qb.addSelect('MAX(si.price)', 'maxPrice'); qb.addSelect('MIN(si.priceWithTax)', 'minPriceWithTax'); qb.addSelect('MAX(si.priceWithTax)', 'maxPriceWithTax'); } this.applyTermAndFilters(ctx, qb, input); if (sort) { if (sort.name) { // TODO: v3 - set the collation on the SearchIndexItem entity qb.addOrderBy('si.productName COLLATE NOCASE', sort.name); } if (sort.price) { qb.addOrderBy('si.price', sort.price); } } else if (input.term && input.term.length > this.minTermLength) { qb.addOrderBy('score', 'DESC'); } // Required to ensure deterministic sorting. // E.g. in case of sorting products with duplicate name, price or score results. qb.addOrderBy('si.productVariantId', 'ASC'); if (enabledOnly) { qb.andWhere('si.enabled = :enabled', { enabled: true }); } return await qb .limit(take) .offset(skip) .getRawMany() .then(res => res.map(r => mapToSearchResult(r, ctx.channel.defaultCurrencyCode))); } async getTotalCount(ctx: RequestContext, input: SearchInput, enabledOnly: boolean): Promise<number> { const innerQb = this.applyTermAndFilters( ctx, this.connection.getRepository(ctx, SearchIndexItem).createQueryBuilder('si'), input, ); if (enabledOnly) { innerQb.andWhere('si.enabled = :enabled', { enabled: true }); } const totalItemsQb = this.connection.rawConnection .createQueryBuilder() .select('COUNT(*) as total') .from(`(${innerQb.getQuery()})`, 'inner') .setParameters(innerQb.getParameters()); return totalItemsQb.getRawOne().then(res => res.total); } private applyTermAndFilters( ctx: RequestContext, qb: SelectQueryBuilder<SearchIndexItem>, input: SearchInput, ): SelectQueryBuilder<SearchIndexItem> { const { term, facetValueFilters, facetValueIds, facetValueOperator, collectionId, collectionSlug } = input; qb.where('1 = 1'); if (term && term.length > this.minTermLength) { // Note: SQLite does not natively have fulltext search capabilities, // so we just use a weighted LIKE match qb.addSelect( ` CASE WHEN si.sku LIKE :like_term THEN 10 ELSE 0 END + CASE WHEN si.productName LIKE :like_term THEN 3 ELSE 0 END + CASE WHEN si.productVariantName LIKE :like_term THEN 2 ELSE 0 END + CASE WHEN si.description LIKE :like_term THEN 1 ELSE 0 END`, 'score', ) .andWhere( new Brackets(qb1 => { qb1.where('si.sku LIKE :like_term') .orWhere('si.productName LIKE :like_term') .orWhere('si.productVariantName LIKE :like_term') .orWhere('si.description LIKE :like_term'); }), ) .setParameters({ term, like_term: `%${term}%` }); } if (input.inStock != null) { if (input.groupByProduct) { qb.andWhere('si.productInStock = :inStock', { inStock: input.inStock }); } else { qb.andWhere('si.inStock = :inStock', { inStock: input.inStock }); } } if (facetValueIds?.length) { qb.andWhere( new Brackets(qb1 => { for (const id of facetValueIds) { const placeholder = createPlaceholderFromId(id); const clause = `(',' || si.facetValueIds || ',') LIKE :${placeholder}`; const params = { [placeholder]: `%,${id},%` }; if (facetValueOperator === LogicalOperator.AND) { qb1.andWhere(clause, params); } else { qb1.orWhere(clause, params); } } }), ); } if (facetValueFilters?.length) { qb.andWhere( new Brackets(qb1 => { for (const facetValueFilter of facetValueFilters) { qb1.andWhere( new Brackets(qb2 => { if (facetValueFilter.and && facetValueFilter.or?.length) { throw new UserInputError('error.facetfilterinput-invalid-input'); } if (facetValueFilter.and) { const placeholder = createPlaceholderFromId(facetValueFilter.and); const clause = `(',' || si.facetValueIds || ',') LIKE :${placeholder}`; const params = { [placeholder]: `%,${facetValueFilter.and},%` }; qb2.where(clause, params); } if (facetValueFilter.or?.length) { for (const id of facetValueFilter.or) { const placeholder = createPlaceholderFromId(id); const clause = `(',' || si.facetValueIds || ',') LIKE :${placeholder}`; const params = { [placeholder]: `%,${id},%` }; qb2.orWhere(clause, params); } } }), ); } }), ); } if (collectionId) { qb.andWhere("(',' || si.collectionIds || ',') LIKE :collectionId", { collectionId: `%,${collectionId},%`, }); } if (collectionSlug) { qb.andWhere("(',' || si.collectionSlugs || ',') LIKE :collectionSlug", { collectionSlug: `%,${collectionSlug},%`, }); } qb.andWhere('si.channelId = :channelId', { channelId: ctx.channelId }); applyLanguageConstraints(qb, ctx.languageCode, ctx.channel.defaultLanguageCode); if (input.groupByProduct === true) { qb.groupBy('si.productId'); } return qb; } }
export { ProcessContext } from './process-context';
import { DynamicModule, Global, Module } from '@nestjs/common'; import { ProcessContext } from './process-context'; @Global() @Module({ providers: [ProcessContext], exports: [ProcessContext], }) export class ProcessContextModule {}
import { Injectable } from '@nestjs/common'; type ProcessContextType = 'server' | 'worker'; let currentContext: ProcessContextType = 'server'; /** * @description * The ProcessContext can be injected into your providers & modules in order to know whether it * is being executed in the context of the main Vendure server or the worker. * * @example * ```ts * import { Injectable, OnApplicationBootstrap } from '\@nestjs/common'; * import { ProcessContext } from '\@vendure/core'; * * \@Injectable() * export class MyService implements OnApplicationBootstrap { * constructor(private processContext: ProcessContext) {} * * onApplicationBootstrap() { * if (this.processContext.isServer) { * // code which will only execute when running in * // the server process * } * } * } * ``` * * @docsCategory common */ export class ProcessContext { get isServer(): boolean { return currentContext === 'server'; } get isWorker(): boolean { return currentContext === 'worker'; } } /** * @description * Should only be called in the core bootstrap functions in order to establish * the current process context. * * @internal */ export function setProcessContext(context: ProcessContextType) { currentContext = context; }
export * from './helpers/active-order/active-order.service'; export * from './helpers/config-arg/config-arg.service'; export * from './helpers/custom-field-relation/custom-field-relation.service'; export * from './helpers/entity-duplicator/entity-duplicator.service'; export * from './helpers/entity-hydrator/entity-hydrator.service'; export * from './helpers/external-authentication/external-authentication.service'; export * from './helpers/fulfillment-state-machine/fulfillment-state'; export * from './helpers/list-query-builder/list-query-builder'; export * from './helpers/locale-string-hydrator/locale-string-hydrator'; export * from './helpers/order-calculator/order-calculator'; export * from './helpers/order-calculator/prorate'; export * from './helpers/order-merger/order-merger'; export * from './helpers/order-modifier/order-modifier'; export * from './helpers/order-splitter/order-splitter'; export * from './helpers/order-state-machine/order-state'; export * from './helpers/order-state-machine/order-state-machine'; export * from './helpers/password-cipher/password-cipher'; export * from './helpers/payment-state-machine/payment-state'; export * from './helpers/product-price-applicator/product-price-applicator'; export * from './helpers/refund-state-machine/refund-state'; export * from './helpers/request-context/request-context.service'; export * from './helpers/translatable-saver/translatable-saver'; export * from './helpers/translator/translator.service'; export * from './helpers/utils/order-utils'; export * from './helpers/utils/patch-entity'; export * from './helpers/utils/translate-entity'; export * from './helpers/verification-token-generator/verification-token-generator'; export * from './services/administrator.service'; export * from './services/asset.service'; export * from './services/auth.service'; export * from './services/channel.service'; export * from './services/collection.service'; export * from './services/country.service'; export * from './services/customer-group.service'; export * from './services/customer.service'; export * from './services/facet-value.service'; export * from './services/facet.service'; export * from './services/fulfillment.service'; export * from './services/global-settings.service'; export * from './services/history.service'; export * from './services/order-testing.service'; export * from './services/order.service'; export * from './services/payment-method.service'; export * from './services/payment.service'; export * from './services/product-option-group.service'; export * from './services/product-option.service'; export * from './services/product-variant.service'; export * from './services/product.service'; export * from './services/promotion.service'; export * from './services/role.service'; export * from './services/search.service'; export * from './services/seller.service'; export * from './services/session.service'; export * from './services/shipping-method.service'; export * from './services/stock-level.service'; export * from './services/stock-location.service'; export * from './services/stock-movement.service'; export * from './services/tag.service'; export * from './services/tax-category.service'; export * from './services/tax-rate.service'; export * from './services/user.service'; export * from './services/zone.service';
import { Injectable } from '@nestjs/common'; import { Logger } from '../config/logger/vendure-logger'; import { TransactionalConnection } from '../connection/transactional-connection'; import { Administrator } from '../entity/administrator/administrator.entity'; import { EventBus } from '../event-bus'; import { InitializerEvent } from '../event-bus/events/initializer-event'; import { AdministratorService } from './services/administrator.service'; import { ChannelService } from './services/channel.service'; import { GlobalSettingsService } from './services/global-settings.service'; import { RoleService } from './services/role.service'; import { SellerService } from './services/seller.service'; import { ShippingMethodService } from './services/shipping-method.service'; import { StockLocationService } from './services/stock-location.service'; import { TaxRateService } from './services/tax-rate.service'; import { ZoneService } from './services/zone.service'; /** * Only used internally to run the various service init methods in the correct * sequence on bootstrap. */ @Injectable() export class InitializerService { constructor( private connection: TransactionalConnection, private zoneService: ZoneService, private channelService: ChannelService, private roleService: RoleService, private administratorService: AdministratorService, private shippingMethodService: ShippingMethodService, private globalSettingsService: GlobalSettingsService, private taxRateService: TaxRateService, private sellerService: SellerService, private eventBus: EventBus, private stockLocationService: StockLocationService, ) {} async onModuleInit() { await this.awaitDbSchemaGeneration(); // IMPORTANT - why manually invoke these init methods rather than just relying on // Nest's "onModuleInit" lifecycle hook within each individual service class? // The reason is that the order of invocation matters. By explicitly invoking the // methods below, we can e.g. guarantee that the default channel exists // (channelService.initChannels()) before we try to create any roles (which assume that // there is a default Channel to work with. await this.zoneService.initZones(); await this.globalSettingsService.initGlobalSettings(); await this.sellerService.initSellers(); await this.channelService.initChannels(); await this.roleService.initRoles(); await this.administratorService.initAdministrators(); await this.shippingMethodService.initShippingMethods(); await this.taxRateService.initTaxRates(); await this.stockLocationService.initStockLocations(); await this.eventBus.publish(new InitializerEvent()); } /** * On the first run of the server & worker, when dbConnectionOptions.synchronize = true, there can be * a race condition where the worker starts up before the server process has had a chance to generate * the DB schema. This results in a fatal error as the worker is not able to run its initialization * tasks which interact with the DB. * * This method applies retry logic to give the server time to populate the schema before the worker * continues with its bootstrap process. */ private async awaitDbSchemaGeneration() { const retries = 20; const delayMs = 100; for (let attempt = 0; attempt < retries; attempt++) { try { const result = await this.connection.rawConnection.getRepository(Administrator).find(); return; } catch (e: any) { if (attempt < retries - 1) { Logger.warn(`Awaiting DB schema creation... (attempt ${attempt})`); await new Promise(resolve => setTimeout(resolve, delayMs)); } else { Logger.error('Timed out when awaiting the DB schema to be ready!', undefined, e.stack); } } } } }
import { Module } from '@nestjs/common'; import { CacheModule } from '../cache/cache.module'; import { ConfigModule } from '../config/config.module'; import { ConnectionModule } from '../connection/connection.module'; import { EventBusModule } from '../event-bus/event-bus.module'; import { JobQueueModule } from '../job-queue/job-queue.module'; import { ActiveOrderService } from './helpers/active-order/active-order.service'; import { ConfigArgService } from './helpers/config-arg/config-arg.service'; import { CustomFieldRelationService } from './helpers/custom-field-relation/custom-field-relation.service'; import { EntityDuplicatorService } from './helpers/entity-duplicator/entity-duplicator.service'; import { EntityHydrator } from './helpers/entity-hydrator/entity-hydrator.service'; import { ExternalAuthenticationService } from './helpers/external-authentication/external-authentication.service'; import { FulfillmentStateMachine } from './helpers/fulfillment-state-machine/fulfillment-state-machine'; import { ListQueryBuilder } from './helpers/list-query-builder/list-query-builder'; import { LocaleStringHydrator } from './helpers/locale-string-hydrator/locale-string-hydrator'; import { OrderCalculator } from './helpers/order-calculator/order-calculator'; import { OrderMerger } from './helpers/order-merger/order-merger'; import { OrderModifier } from './helpers/order-modifier/order-modifier'; import { OrderSplitter } from './helpers/order-splitter/order-splitter'; import { OrderStateMachine } from './helpers/order-state-machine/order-state-machine'; import { PasswordCipher } from './helpers/password-cipher/password-cipher'; import { PaymentStateMachine } from './helpers/payment-state-machine/payment-state-machine'; import { ProductPriceApplicator } from './helpers/product-price-applicator/product-price-applicator'; import { RefundStateMachine } from './helpers/refund-state-machine/refund-state-machine'; import { RequestContextService } from './helpers/request-context/request-context.service'; import { ShippingCalculator } from './helpers/shipping-calculator/shipping-calculator'; import { SlugValidator } from './helpers/slug-validator/slug-validator'; import { TranslatableSaver } from './helpers/translatable-saver/translatable-saver'; import { TranslatorService } from './helpers/translator/translator.service'; import { VerificationTokenGenerator } from './helpers/verification-token-generator/verification-token-generator'; import { InitializerService } from './initializer.service'; import { AdministratorService } from './services/administrator.service'; import { AssetService } from './services/asset.service'; import { AuthService } from './services/auth.service'; import { ChannelService } from './services/channel.service'; import { CollectionService } from './services/collection.service'; import { CountryService } from './services/country.service'; import { CustomerGroupService } from './services/customer-group.service'; import { CustomerService } from './services/customer.service'; import { FacetValueService } from './services/facet-value.service'; import { FacetService } from './services/facet.service'; import { FulfillmentService } from './services/fulfillment.service'; import { GlobalSettingsService } from './services/global-settings.service'; import { HistoryService } from './services/history.service'; import { OrderTestingService } from './services/order-testing.service'; import { OrderService } from './services/order.service'; import { PaymentMethodService } from './services/payment-method.service'; import { PaymentService } from './services/payment.service'; import { ProductOptionGroupService } from './services/product-option-group.service'; import { ProductOptionService } from './services/product-option.service'; import { ProductVariantService } from './services/product-variant.service'; import { ProductService } from './services/product.service'; import { PromotionService } from './services/promotion.service'; import { RoleService } from './services/role.service'; import { SearchService } from './services/search.service'; import { SellerService } from './services/seller.service'; import { SessionService } from './services/session.service'; import { ShippingMethodService } from './services/shipping-method.service'; import { StockLevelService } from './services/stock-level.service'; import { StockLocationService } from './services/stock-location.service'; import { StockMovementService } from './services/stock-movement.service'; import { TagService } from './services/tag.service'; import { TaxCategoryService } from './services/tax-category.service'; import { TaxRateService } from './services/tax-rate.service'; import { UserService } from './services/user.service'; import { ZoneService } from './services/zone.service'; const services = [ AdministratorService, AssetService, AuthService, ChannelService, CollectionService, CountryService, CustomerGroupService, CustomerService, FacetService, FacetValueService, FulfillmentService, GlobalSettingsService, HistoryService, OrderService, OrderTestingService, PaymentService, PaymentMethodService, ProductOptionGroupService, ProductOptionService, ProductService, ProductVariantService, PromotionService, RoleService, SearchService, SellerService, SessionService, ShippingMethodService, StockLevelService, StockLocationService, StockMovementService, TagService, TaxCategoryService, TaxRateService, UserService, ZoneService, ]; const helpers = [ TranslatableSaver, PasswordCipher, OrderCalculator, OrderStateMachine, FulfillmentStateMachine, OrderMerger, OrderModifier, OrderSplitter, PaymentStateMachine, ListQueryBuilder, ShippingCalculator, VerificationTokenGenerator, RefundStateMachine, ConfigArgService, SlugValidator, ExternalAuthenticationService, CustomFieldRelationService, LocaleStringHydrator, ActiveOrderService, ProductPriceApplicator, EntityHydrator, RequestContextService, TranslatorService, EntityDuplicatorService, ]; /** * The ServiceCoreModule is imported internally by the ServiceModule. It is arranged in this way so that * there is only a single instance of this module being instantiated, and thus the lifecycle hooks will * only run a single time. */ @Module({ imports: [ConnectionModule, ConfigModule, EventBusModule, CacheModule, JobQueueModule], providers: [...services, ...helpers, InitializerService], exports: [...services, ...helpers], }) export class ServiceCoreModule {} /** * The ServiceModule is responsible for the service layer, i.e. accessing the database * and implementing the main business logic of the application. * * The exported providers are used in the ApiModule, which is responsible for parsing requests * into a format suitable for the service layer logic. */ @Module({ imports: [ServiceCoreModule], exports: [ServiceCoreModule], }) export class ServiceModule {}
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { InternalServerError, UserInputError } from '../../../common/error/errors'; import { ConfigService } from '../../../config/config.service'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Order } from '../../../entity/order/order.entity'; import { OrderService } from '../../services/order.service'; import { SessionService } from '../../services/session.service'; /** * @description * This helper class is used to get a reference to the active Order from the current RequestContext. * * @docsCategory orders */ @Injectable() export class ActiveOrderService { constructor( private sessionService: SessionService, private orderService: OrderService, private connection: TransactionalConnection, private configService: ConfigService, ) {} /** * @description * Gets the active Order object from the current Session. Optionally can create a new Order if * no active Order exists. * * Intended to be used at the Resolver layer for those resolvers that depend upon an active Order * being present. * * @deprecated From v1.9.0, use the `getActiveOrder` method which uses any configured ActiveOrderStrategies */ async getOrderFromContext(ctx: RequestContext): Promise<Order | undefined>; async getOrderFromContext(ctx: RequestContext, createIfNotExists: true): Promise<Order>; async getOrderFromContext(ctx: RequestContext, createIfNotExists = false): Promise<Order | undefined> { 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); } if (!order && createIfNotExists) { order = await this.orderService.create(ctx, ctx.activeUserId); } if (order) { await this.sessionService.setActiveOrder(ctx, ctx.session, order); } } return order || undefined; } /** * @description * Retrieves the active Order based on the configured {@link ActiveOrderStrategy}. * * @since 1.9.0 */ async getActiveOrder( ctx: RequestContext, input: { [strategyName: string]: any } | undefined, ): Promise<Order | undefined>; async getActiveOrder( ctx: RequestContext, input: { [strategyName: string]: any } | undefined, createIfNotExists: true, ): Promise<Order>; async getActiveOrder( ctx: RequestContext, input: { [strategyName: string]: Record<string, any> | undefined } | undefined, createIfNotExists = false, ): Promise<Order | undefined> { let order: any; if (!order) { const { activeOrderStrategy } = this.configService.orderOptions; const strategyArray = Array.isArray(activeOrderStrategy) ? activeOrderStrategy : [activeOrderStrategy]; for (const strategy of strategyArray) { const strategyInput = input?.[strategy.name] ?? {}; order = await strategy.determineActiveOrder(ctx, strategyInput); if (order) { break; } if (createIfNotExists && typeof strategy.createActiveOrder === 'function') { order = await strategy.createActiveOrder(ctx, strategyInput); } if (order) { break; } } if (!order && createIfNotExists) { // No order has been found, and none could be created, which indicates that // none of the configured strategies have a `createActiveOrder` method defined. // In this case, we should throw an error because it is assumed that such a configuration // indicates that an external order creation mechanism should be defined. throw new UserInputError('error.order-could-not-be-determined-or-created'); } if (order && ctx.session) { await this.sessionService.setActiveOrder(ctx, ctx.session, order); } } return order || undefined; } }
import { Injectable } from '@nestjs/common'; import { ConfigurableOperation, ConfigurableOperationInput } from '@vendure/common/lib/generated-types'; import { ConfigurableOperationDef } from '../../../common/configurable-operation'; import { UserInputError } from '../../../common/error/errors'; import { CollectionFilter } from '../../../config/catalog/collection-filter'; import { ConfigService } from '../../../config/config.service'; import { EntityDuplicator } from '../../../config/entity/entity-duplicator'; import { FulfillmentHandler } from '../../../config/fulfillment/fulfillment-handler'; import { PaymentMethodEligibilityChecker } from '../../../config/payment/payment-method-eligibility-checker'; import { PaymentMethodHandler } from '../../../config/payment/payment-method-handler'; import { PromotionAction } from '../../../config/promotion/promotion-action'; import { PromotionCondition } from '../../../config/promotion/promotion-condition'; import { ShippingCalculator } from '../../../config/shipping-method/shipping-calculator'; import { ShippingEligibilityChecker } from '../../../config/shipping-method/shipping-eligibility-checker'; export type ConfigDefTypeMap = { CollectionFilter: CollectionFilter; EntityDuplicator: EntityDuplicator; FulfillmentHandler: FulfillmentHandler; PaymentMethodEligibilityChecker: PaymentMethodEligibilityChecker; PaymentMethodHandler: PaymentMethodHandler; PromotionAction: PromotionAction; PromotionCondition: PromotionCondition; ShippingCalculator: ShippingCalculator; ShippingEligibilityChecker: ShippingEligibilityChecker; }; export type ConfigDefType = keyof ConfigDefTypeMap; /** * This helper class provides methods relating to ConfigurableOperationDef instances. */ @Injectable() export class ConfigArgService { private readonly definitionsByType: { [K in ConfigDefType]: Array<ConfigDefTypeMap[K]> }; constructor(private configService: ConfigService) { this.definitionsByType = { CollectionFilter: this.configService.catalogOptions.collectionFilters, EntityDuplicator: this.configService.entityOptions.entityDuplicators, FulfillmentHandler: this.configService.shippingOptions.fulfillmentHandlers, PaymentMethodEligibilityChecker: this.configService.paymentOptions.paymentMethodEligibilityCheckers || [], PaymentMethodHandler: this.configService.paymentOptions.paymentMethodHandlers, PromotionAction: this.configService.promotionOptions.promotionActions, PromotionCondition: this.configService.promotionOptions.promotionConditions, ShippingCalculator: this.configService.shippingOptions.shippingCalculators, ShippingEligibilityChecker: this.configService.shippingOptions.shippingEligibilityCheckers, }; } getDefinitions<T extends ConfigDefType>(defType: T): Array<ConfigDefTypeMap[T]> { return this.definitionsByType[defType] as Array<ConfigDefTypeMap[T]>; } getByCode<T extends ConfigDefType>(defType: T, code: string): ConfigDefTypeMap[T] { const defsOfType = this.getDefinitions(defType); const match = defsOfType.find(def => def.code === code); if (!match) { throw new UserInputError('error.no-configurable-operation-def-with-code-found', { code, type: defType, }); } return match; } /** * Parses and validates the input to a ConfigurableOperation. */ parseInput(defType: ConfigDefType, input: ConfigurableOperationInput): ConfigurableOperation { const match = this.getByCode(defType, input.code); this.validateRequiredFields(input, match); const orderedArgs = this.orderArgsToMatchDef(match, input.arguments); return { code: input.code, args: orderedArgs, }; } private orderArgsToMatchDef<T extends ConfigDefType>( def: ConfigDefTypeMap[T], args: ConfigurableOperation['args'], ) { const output: ConfigurableOperation['args'] = []; for (const name of Object.keys(def.args)) { const match = args.find(arg => arg.name === name); if (match) { output.push(match); } } return output; } private validateRequiredFields(input: ConfigurableOperationInput, def: ConfigurableOperationDef) { for (const [name, argDef] of Object.entries(def.args)) { if (argDef.required) { const inputArg = input.arguments.find(a => a.name === name); let valid = false; try { if (['string', 'ID', 'datetime'].includes(argDef.type)) { valid = !!inputArg && inputArg.value !== '' && inputArg.value != null; } else { valid = !!inputArg && JSON.parse(inputArg.value) != null; } } catch (e: any) { // ignore } if (!valid) { throw new UserInputError('error.configurable-argument-is-required', { name, }); } } } } }
import { Injectable } from '@nestjs/common'; import { pick } from '@vendure/common/lib/pick'; import { ID, Type } from '@vendure/common/lib/shared-types'; import { getGraphQlInputName } from '@vendure/common/lib/shared-utils'; import { In } from 'typeorm'; import { RequestContext } from '../../../api/common/request-context'; import { ConfigService } from '../../../config/config.service'; import { CustomFieldConfig, CustomFields, HasCustomFields, RelationCustomFieldConfig, } from '../../../config/custom-field/custom-field-types'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { VendureEntity } from '../../../entity/base/base.entity'; @Injectable() export class CustomFieldRelationService { constructor(private connection: TransactionalConnection, private configService: ConfigService) {} /** * @description * If the entity being created or updated has any custom fields of type `relation`, this * method will get the values from the input object and persist those relations in the * database. */ async updateRelations<T extends HasCustomFields & VendureEntity>( ctx: RequestContext, entityType: Type<T>, input: { customFields?: { [key: string]: any } }, entity: T, ) { if (input.customFields) { const relationCustomFields = this.configService.customFields[ entityType.name as keyof CustomFields ].filter(this.isRelationalType); for (const field of relationCustomFields) { const inputIdName = getGraphQlInputName(field); const idOrIds = input.customFields[inputIdName]; if (idOrIds !== undefined) { let relations: VendureEntity | VendureEntity[] | undefined | null; if (idOrIds === null) { // an explicitly `null` value means remove the relation relations = null; } else if (field.list && Array.isArray(idOrIds) && idOrIds.every(id => this.isId(id))) { relations = await this.connection .getRepository(ctx, field.entity) .findBy({ id: In(idOrIds) }); } else if (!field.list && this.isId(idOrIds)) { relations = await this.connection .getRepository(ctx, field.entity) .findOne({ where: { id: idOrIds } }); } if (relations !== undefined) { entity.customFields = { ...entity.customFields, [field.name]: relations }; await this.connection .getRepository(ctx, entityType) .save(pick(entity, ['id', 'customFields']) as any, { reload: false }); } } } } return entity; } private isRelationalType(this: void, input: CustomFieldConfig): input is RelationCustomFieldConfig { return input.type === 'relation'; } private isId(input: unknown): input is ID { return typeof input === 'string' || typeof input === 'number'; } }
import { Injectable } from '@nestjs/common'; import { DuplicateEntityInput, DuplicateEntityResult, EntityDuplicatorDefinition, } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../../api/common/request-context'; import { DuplicateEntityError } from '../../../common/error/generated-graphql-admin-errors'; import { ConfigService } from '../../../config/config.service'; import { Logger } from '../../../config/logger/vendure-logger'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { ConfigArgService } from '../config-arg/config-arg.service'; /** * @description * This service is used to duplicate entities using one of the configured * {@link EntityDuplicator} functions. * * @docsCategory service-helpers * @since 2.2.0 */ @Injectable() export class EntityDuplicatorService { constructor( private configService: ConfigService, private configArgService: ConfigArgService, private connection: TransactionalConnection, ) {} /** * @description * Returns all configured {@link EntityDuplicator} definitions. */ getEntityDuplicators(ctx: RequestContext): EntityDuplicatorDefinition[] { return this.configArgService.getDefinitions('EntityDuplicator').map(x => ({ ...x.toGraphQlType(ctx), __typename: 'EntityDuplicatorDefinition', forEntities: x.forEntities, requiresPermission: x.requiresPermission, })); } /** * @description * Duplicates an entity using the specified {@link EntityDuplicator}. The duplication is performed * within a transaction, so if an error occurs, the transaction will be rolled back. */ async duplicateEntity(ctx: RequestContext, input: DuplicateEntityInput): Promise<DuplicateEntityResult> { const duplicator = this.configService.entityOptions.entityDuplicators.find( s => s.forEntities.includes(input.entityName) && s.code === input.duplicatorInput.code, ); if (!duplicator) { return new DuplicateEntityError({ duplicationError: ctx.translate(`message.entity-duplication-no-strategy-found`, { entityName: input.entityName, code: input.duplicatorInput.code, }), }); } // Check permissions if ( duplicator.requiresPermission.length === 0 || !ctx.userHasPermissions(duplicator.requiresPermission) ) { return new DuplicateEntityError({ duplicationError: ctx.translate(`message.entity-duplication-no-permission`), }); } const parsedInput = this.configArgService.parseInput('EntityDuplicator', input.duplicatorInput); return await this.connection.withTransaction(ctx, async innerCtx => { try { const newEntity = await duplicator.duplicate({ ctx: innerCtx, entityName: input.entityName, id: input.entityId, args: parsedInput.args, }); return { newEntityId: newEntity.id }; } catch (e: any) { await this.connection.rollBackTransaction(innerCtx); Logger.error(e.message, undefined, e.stack); return new DuplicateEntityError({ duplicationError: e.message ?? e.toString(), }); } }); } }
import { EntityRelationPaths } from '../../../common/types/entity-relation-paths'; import { VendureEntity } from '../../../entity/base/base.entity'; /** * @description * Options used to control which relations of the entity get hydrated * when using the {@link EntityHydrator} helper. * * @since 1.3.0 * @docsCategory data-access */ export interface HydrateOptions<Entity extends VendureEntity> { /** * @description * Defines the relations to hydrate, using strings with dot notation to indicate * nested joins. If the entity already has a particular relation available, that relation * will be skipped (no extra DB join will be added). */ relations: Array<EntityRelationPaths<Entity>>; /** * @description * If set to `true`, any ProductVariants will also have their `price` and `priceWithTax` fields * applied based on the current context. If prices are not required, this can be left `false` which * will be slightly more efficient. * * @default false */ applyProductVariantPrices?: boolean; }
import { Injectable } from '@nestjs/common'; import { Type } from '@vendure/common/lib/shared-types'; import { isObject } from '@vendure/common/lib/shared-utils'; import { unique } from '@vendure/common/lib/unique'; import { SelectQueryBuilder } from 'typeorm'; import { RequestContext } from '../../../api/common/request-context'; import { InternalServerError } from '../../../common/error/errors'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { VendureEntity } from '../../../entity/base/base.entity'; import { ProductVariant } from '../../../entity/product-variant/product-variant.entity'; import { ProductPriceApplicator } from '../product-price-applicator/product-price-applicator'; import { TranslatorService } from '../translator/translator.service'; import { joinTreeRelationsDynamically } from '../utils/tree-relations-qb-joiner'; import { HydrateOptions } from './entity-hydrator-types'; /** * @description * This is a helper class which is used to "hydrate" entity instances, which means to populate them * with the specified relations. This is useful when writing plugin code which receives an entity, * and you need to ensure that one or more relations are present. * * @example * ```ts * import { Injectable } from '\@nestjs/common'; * import { ID, RequestContext, EntityHydrator, ProductVariantService } from '\@vendure/core'; * * \@Injectable() * export class MyService { * * constructor( * // highlight-next-line * private entityHydrator: EntityHydrator, * private productVariantService: ProductVariantService, * ) {} * * myMethod(ctx: RequestContext, variantId: ID) { * const product = await this.productVariantService * .getProductForVariant(ctx, variantId); * * // at this stage, we don't know which of the Product relations * // will be joined at runtime. * * // highlight-start * await this.entityHydrator * .hydrate(ctx, product, { relations: ['facetValues.facet' ]}); * * // You can be sure now that the `facetValues` & `facetValues.facet` relations are populated * // highlight-end * } * } *``` * * In this above example, the `product` instance will now have the `facetValues` relation * available, and those FacetValues will have their `facet` relations joined too. * * This `hydrate` method will _also_ automatically take care or translating any * translatable entities (e.g. Product, Collection, Facet), and if the `applyProductVariantPrices` * options is used (see {@link HydrateOptions}), any related ProductVariant will have the correct * Channel-specific prices applied to them. * * Custom field relations may also be hydrated: * * @example * ```ts * const customer = await this.customerService * .findOne(ctx, id); * * await this.entityHydrator * .hydrate(ctx, customer, { relations: ['customFields.avatar' ]}); * ``` * * @docsCategory data-access * @since 1.3.0 */ @Injectable() export class EntityHydrator { constructor( private connection: TransactionalConnection, private productPriceApplicator: ProductPriceApplicator, private translator: TranslatorService, ) {} /** * @description * Hydrates (joins) the specified relations to the target entity instance. This method * mutates the `target` entity. * * @example * ```ts * await this.entityHydrator.hydrate(ctx, product, { * relations: [ * 'variants.stockMovements' * 'optionGroups.options', * 'featuredAsset', * ], * applyProductVariantPrices: true, * }); * ``` * * @since 1.3.0 */ async hydrate<Entity extends VendureEntity>( ctx: RequestContext, target: Entity, options: HydrateOptions<Entity>, ): Promise<Entity> { if (options.relations) { let missingRelations = this.getMissingRelations(target, options); if (options.applyProductVariantPrices === true) { const productVariantPriceRelations = this.getRequiredProductVariantRelations( target, missingRelations, ); missingRelations = unique([...missingRelations, ...productVariantPriceRelations]); } if (missingRelations.length) { const hydratedQb: SelectQueryBuilder<any> = this.connection .getRepository(ctx, target.constructor) .createQueryBuilder(target.constructor.name); const joinedRelations = joinTreeRelationsDynamically( hydratedQb, target.constructor, missingRelations, ); hydratedQb.setFindOptions({ relationLoadStrategy: 'query', where: { id: target.id }, relations: missingRelations.filter(relationPath => !joinedRelations.has(relationPath)), }); const hydrated = await hydratedQb.getOne(); const propertiesToAdd = unique(missingRelations.map(relation => relation.split('.')[0])); for (const prop of propertiesToAdd) { (target as any)[prop] = this.mergeDeep((target as any)[prop], hydrated[prop]); } const relationsWithEntities = missingRelations.map(relation => ({ entity: this.getRelationEntityAtPath(target, relation.split('.')), relation, })); if (options.applyProductVariantPrices === true) { for (const relationWithEntities of relationsWithEntities) { const entity = relationWithEntities.entity; if (entity) { if (Array.isArray(entity)) { if (entity[0] instanceof ProductVariant) { await Promise.all( entity.map((e: any) => this.productPriceApplicator.applyChannelPriceAndTax(e, ctx), ), ); } } else { if (entity instanceof ProductVariant) { await this.productPriceApplicator.applyChannelPriceAndTax(entity, ctx); } } } } } const translateDeepRelations = relationsWithEntities .filter(item => this.isTranslatable(item.entity)) .map(item => item.relation.split('.')); this.assignSettableProperties( target, this.translator.translate(target as any, ctx, translateDeepRelations as any), ); } } return target; } private assignSettableProperties<Entity extends VendureEntity>(target: Entity, source: Entity) { for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(target))) { if (typeof descriptor.get === 'function' && typeof descriptor.set !== 'function') { // If the entity property has a getter only, we will skip it otherwise // we will get an error of the form: // `Cannot set property <name> of #<Entity> which has only a getter` continue; } target[key as keyof Entity] = source[key as keyof Entity]; } return target; } /** * Compares the requested relations against the actual existing relations on the target entity, * and returns an array of all missing relation paths that would need to be fetched. */ private getMissingRelations<Entity extends VendureEntity>( target: Entity, options: HydrateOptions<Entity>, ) { const missingRelations: string[] = []; for (const relation of options.relations.slice().sort()) { if (typeof relation === 'string') { const parts = !relation.startsWith('customFields') ? relation.split('.') : [relation]; let entity: Record<string, any> | undefined = target; const path = []; for (const part of parts) { path.push(part); if (entity && entity[part]) { entity = Array.isArray(entity[part]) ? entity[part][0] : entity[part]; } else { const allParts = path.reduce((result, p, i) => { if (i === 0) { return [p]; } else { return [...result, [result[result.length - 1], p].join('.')]; } }, [] as string[]); missingRelations.push(...allParts); entity = undefined; } } } } return unique(missingRelations.filter(relation => !relation.endsWith('.customFields'))); } private getRequiredProductVariantRelations<Entity extends VendureEntity>( target: Entity, missingRelations: string[], ): string[] { const relationsToAdd: string[] = []; for (const relation of missingRelations) { const entityType = this.getRelationEntityTypeAtPath(target, relation); if (entityType === ProductVariant) { relationsToAdd.push([relation, 'taxCategory'].join('.')); relationsToAdd.push([relation, 'productVariantPrices'].join('.')); } } return relationsToAdd; } /** * Returns an instance of the related entity at the given path. E.g. a path of `['variants', 'featuredAsset']` * will return an Asset instance. */ private getRelationEntityAtPath( entity: VendureEntity, path: string[], ): VendureEntity | VendureEntity[] | undefined { let isArrayResult = false; const result: VendureEntity[] = []; function visit(parent: any, parts: string[]): any { if (parts.length === 0) { return; } const part = parts.shift() as string; const target = parent[part]; if (Array.isArray(target)) { isArrayResult = true; if (parts.length === 0) { result.push(...target); } else { for (const item of target) { visit(item, parts.slice()); } } } else if (target === null) { result.push(target); } else { if (parts.length === 0) { result.push(target); } else { visit(target, parts.slice()); } } } visit(entity, path.slice()); return isArrayResult ? result : result[0]; } private getRelationEntityTypeAtPath(entity: VendureEntity, path: string): Type<VendureEntity> { const { entityMetadatas } = this.connection.rawConnection; const targetMetadata = entityMetadatas.find(m => m.target === entity.constructor); if (!targetMetadata) { throw new InternalServerError( `Cannot find entity metadata for entity "${entity.constructor.name}"`, ); } let currentMetadata = targetMetadata; for (const pathPart of path.split('.')) { const relationMetadata = currentMetadata.findRelationWithPropertyPath(pathPart); if (relationMetadata) { currentMetadata = relationMetadata.inverseEntityMetadata; } else { throw new InternalServerError( `Cannot find relation metadata for entity "${currentMetadata.targetName}" at path "${pathPart}"`, ); } } return currentMetadata.target as Type<VendureEntity>; } private isTranslatable<T extends VendureEntity>(input: T | T[] | undefined): boolean { return Array.isArray(input) ? input[0]?.hasOwnProperty('translations') ?? false : input?.hasOwnProperty('translations') ?? false; } /** * Merges properties into a target entity. This is needed for the cases in which a * property already exists on the target, but the hydrated version also contains that * property with a different set of properties. This prevents the original target * entity from having data overwritten. */ private mergeDeep<T extends { [key: string]: any }>(a: T | undefined, b: T): T { if (!a) { return b; } if (Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.length > 1) { if (a[0].hasOwnProperty('id')) { // If the array contains entities, we can use the id to match them up // so that we ensure that we don't merge properties from different entities // with the same index. const aIds = a.map(e => e.id); const bIds = b.map(e => e.id); if (JSON.stringify(aIds) !== JSON.stringify(bIds)) { // The entities in the arrays are not in the same order, so we can't // safely merge them. We need to sort the `b` array so that the entities // are in the same order as the `a` array. const idToIndexMap = new Map(); a.forEach((item, index) => { idToIndexMap.set(item.id, index); }); b.sort((_a, _b) => { return idToIndexMap.get(_a.id) - idToIndexMap.get(_b.id); }); } } } for (const [key, value] of Object.entries(b)) { if (Object.getOwnPropertyDescriptor(b, key)?.writable) { if (Array.isArray(value)) { (a as any)[key] = value.map((v, index) => this.mergeDeep(a?.[key]?.[index], b[key][index]), ); } else if (isObject(value)) { (a as any)[key] = this.mergeDeep(a?.[key], b[key]); } else { (a as any)[key] = b[key]; } } } return a ?? b; } }
import { Injectable } from '@nestjs/common'; import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../../api/common/request-context'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Administrator } from '../../../entity/administrator/administrator.entity'; import { ExternalAuthenticationMethod } from '../../../entity/authentication-method/external-authentication-method.entity'; import { Customer } from '../../../entity/customer/customer.entity'; import { Role } from '../../../entity/role/role.entity'; import { User } from '../../../entity/user/user.entity'; import { AdministratorService } from '../../services/administrator.service'; import { ChannelService } from '../../services/channel.service'; import { CustomerService } from '../../services/customer.service'; import { HistoryService } from '../../services/history.service'; import { RoleService } from '../../services/role.service'; /** * @description * This is a helper service which exposes methods related to looking up and creating Users based on an * external {@link AuthenticationStrategy}. * * @docsCategory auth */ @Injectable() export class ExternalAuthenticationService { constructor( private connection: TransactionalConnection, private roleService: RoleService, private historyService: HistoryService, private customerService: CustomerService, private administratorService: AdministratorService, private channelService: ChannelService, ) {} /** * @description * Looks up a User based on their identifier from an external authentication * provider, ensuring this User is associated with a Customer account. * * By default, only customers in the currently-active Channel will be checked. * By passing `false` as the `checkCurrentChannelOnly` argument, _all_ channels * will be checked. */ async findCustomerUser( ctx: RequestContext, strategy: string, externalIdentifier: string, checkCurrentChannelOnly = true, ): Promise<User | undefined> { const user = await this.findUser(ctx, strategy, externalIdentifier); if (user) { // Ensure this User is associated with a Customer const customer = await this.customerService.findOneByUserId( ctx, user.id, checkCurrentChannelOnly, ); if (customer) { return user; } } } /** * @description * Looks up a User based on their identifier from an external authentication * provider, ensuring this User is associated with an Administrator account. */ async findAdministratorUser( ctx: RequestContext, strategy: string, externalIdentifier: string, ): Promise<User | undefined> { const user = await this.findUser(ctx, strategy, externalIdentifier); if (user) { // Ensure this User is associated with an Administrator const administrator = await this.administratorService.findOneByUserId(ctx, user.id); if (administrator) { return user; } } } /** * @description * If a customer has been successfully authenticated by an external authentication provider, yet cannot * be found using `findCustomerUser`, then we need to create a new User and * Customer record in Vendure for that user. This method encapsulates that logic as well as additional * housekeeping such as adding a record to the Customer's history. */ async createCustomerAndUser( ctx: RequestContext, config: { strategy: string; externalIdentifier: string; verified: boolean; emailAddress: string; firstName?: string; lastName?: string; }, ): Promise<User> { let user: User; const existingUser = await this.findExistingCustomerUserByEmailAddress(ctx, config.emailAddress); if (existingUser) { user = existingUser; } else { const customerRole = await this.roleService.getCustomerRole(ctx); user = new User({ identifier: config.emailAddress, roles: [customerRole], verified: config.verified || false, authenticationMethods: [], }); } const authMethod = await this.connection.getRepository(ctx, ExternalAuthenticationMethod).save( new ExternalAuthenticationMethod({ externalIdentifier: config.externalIdentifier, strategy: config.strategy, }), ); user.authenticationMethods = [...(user.authenticationMethods || []), authMethod]; const savedUser = await this.connection.getRepository(ctx, User).save(user); let customer: Customer; const existingCustomer = await this.customerService.findOneByUserId(ctx, savedUser.id); if (existingCustomer) { customer = existingCustomer; } else { customer = new Customer({ emailAddress: config.emailAddress, firstName: config.firstName, lastName: config.lastName, user: savedUser, }); } await this.channelService.assignToCurrentChannel(customer, ctx); await this.connection.getRepository(ctx, Customer).save(customer); await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_REGISTERED, data: { strategy: config.strategy, }, }); if (config.verified) { await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_VERIFIED, data: { strategy: config.strategy, }, }); } return savedUser; } /** * @description * If an administrator has been successfully authenticated by an external authentication provider, yet cannot * be found using `findAdministratorUser`, then we need to create a new User and * Administrator record in Vendure for that user. */ async createAdministratorAndUser( ctx: RequestContext, config: { strategy: string; externalIdentifier: string; identifier: string; emailAddress?: string; firstName?: string; lastName?: string; roles: Role[]; }, ) { const newUser = new User({ identifier: config.identifier, roles: config.roles, verified: true, }); const authMethod = await this.connection.getRepository(ctx, ExternalAuthenticationMethod).save( new ExternalAuthenticationMethod({ externalIdentifier: config.externalIdentifier, strategy: config.strategy, }), ); newUser.authenticationMethods = [authMethod]; const savedUser = await this.connection.getRepository(ctx, User).save(newUser); const administrator = await this.connection.getRepository(ctx, Administrator).save( new Administrator({ emailAddress: config.emailAddress, firstName: config.firstName, lastName: config.lastName, user: savedUser, }), ); return newUser; } async findUser( ctx: RequestContext, strategy: string, externalIdentifier: string, ): Promise<User | undefined> { const user = await this.connection .getRepository(ctx, User) .createQueryBuilder('user') .leftJoinAndSelect('user.authenticationMethods', 'aums') .leftJoin('user.authenticationMethods', 'authMethod') .andWhere('authMethod.externalIdentifier = :externalIdentifier', { externalIdentifier }) .andWhere('authMethod.strategy = :strategy', { strategy }) .andWhere('user.deletedAt IS NULL') .getOne(); return user || undefined; } private async findExistingCustomerUserByEmailAddress(ctx: RequestContext, emailAddress: string) { const customer = await this.connection .getRepository(ctx, Customer) .createQueryBuilder('customer') .leftJoinAndSelect('customer.user', 'user') .leftJoin('customer.channels', 'channel') .leftJoinAndSelect('user.authenticationMethods', 'authMethod') .andWhere('customer.emailAddress = :emailAddress', { emailAddress }) .andWhere('user.deletedAt IS NULL') .getOne(); return customer?.user; } }
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { IllegalOperationError } from '../../../common/error/errors'; import { FSM } from '../../../common/finite-state-machine/finite-state-machine'; import { mergeTransitionDefinitions } from '../../../common/finite-state-machine/merge-transition-definitions'; import { StateMachineConfig, Transitions } from '../../../common/finite-state-machine/types'; import { validateTransitionDefinition } from '../../../common/finite-state-machine/validate-transition-definition'; import { awaitPromiseOrObservable } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { Logger } from '../../../config/logger/vendure-logger'; import { Fulfillment } from '../../../entity/fulfillment/fulfillment.entity'; import { Order } from '../../../entity/order/order.entity'; import { FulfillmentState, FulfillmentTransitionData } from './fulfillment-state'; @Injectable() export class FulfillmentStateMachine { readonly config: StateMachineConfig<FulfillmentState, FulfillmentTransitionData>; private readonly initialState: FulfillmentState = 'Created'; constructor(private configService: ConfigService) { this.config = this.initConfig(); } getInitialState(): FulfillmentState { return this.initialState; } canTransition(currentState: FulfillmentState, newState: FulfillmentState): boolean { return new FSM(this.config, currentState).canTransitionTo(newState); } getNextStates(fulfillment: Fulfillment): readonly FulfillmentState[] { const fsm = new FSM(this.config, fulfillment.state); return fsm.getNextStates(); } async transition( ctx: RequestContext, fulfillment: Fulfillment, orders: Order[], state: FulfillmentState, ) { const fsm = new FSM(this.config, fulfillment.state); const result = await fsm.transitionTo(state, { ctx, orders, fulfillment }); fulfillment.state = fsm.currentState; return result; } private initConfig(): StateMachineConfig<FulfillmentState, FulfillmentTransitionData> { // TODO: remove once the customFulfillmentProcess option is removed const customProcesses = this.configService.shippingOptions.customFulfillmentProcess ?? []; const processes = [...customProcesses, ...(this.configService.shippingOptions.process ?? [])]; const allTransitions = processes.reduce( (transitions, process) => mergeTransitionDefinitions(transitions, process.transitions as Transitions<any>), {} as Transitions<FulfillmentState>, ); const validationResult = validateTransitionDefinition(allTransitions, this.initialState); if (!validationResult.valid && validationResult.error) { Logger.error(`The fulfillment process has an invalid configuration:`); throw new Error(validationResult.error); } if (validationResult.valid && validationResult.error) { Logger.warn(`Fulfillment process: ${validationResult.error}`); } return { transitions: allTransitions, onTransitionStart: async (fromState, toState, data) => { for (const process of processes) { if (typeof process.onTransitionStart === 'function') { const result = await awaitPromiseOrObservable( process.onTransitionStart(fromState, toState, data), ); if (result === false || typeof result === 'string') { return result; } } } }, onTransitionEnd: async (fromState, toState, data) => { for (const process of processes) { if (typeof process.onTransitionEnd === 'function') { await awaitPromiseOrObservable(process.onTransitionEnd(fromState, toState, data)); } } }, onError: async (fromState, toState, message) => { for (const process of processes) { if (typeof process.onTransitionError === 'function') { await awaitPromiseOrObservable( process.onTransitionError(fromState, toState, message), ); } } throw new IllegalOperationError(message || 'error.cannot-transition-fulfillment-from-to', { fromState, toState, }); }, }; } }
import { RequestContext } from '../../../api/common/request-context'; import { Fulfillment } from '../../../entity/fulfillment/fulfillment.entity'; import { Order } from '../../../entity/order/order.entity'; /** * @description * An interface to extend standard {@link FulfillmentState}. * * @deprecated use FulfillmentStates */ export interface CustomFulfillmentStates {} /** * @description * An interface to extend standard {@link FulfillmentState}. * * @docsCategory fulfillment */ export interface FulfillmentStates {} /** * @description * These are the default states of the fulfillment process. By default, they will be extended * by the {@link defaultFulfillmentProcess} to also include `Shipped` and `Delivered`. * * * @docsCategory fulfillment */ export type FulfillmentState = | 'Created' | 'Pending' | 'Cancelled' | keyof CustomFulfillmentStates | keyof FulfillmentStates; /** * @description * The data which is passed to the state transition handler of the FulfillmentStateMachine. * * @docsCategory fulfillment */ export interface FulfillmentTransitionData { ctx: RequestContext; orders: Order[]; fulfillment: Fulfillment; }
import { Type } from '@vendure/common/lib/shared-types'; import { DataSource } from 'typeorm'; import { ColumnMetadata } from 'typeorm/metadata/ColumnMetadata'; import { Translation } from '../../../common/types/locale-types'; import { VendureEntity } from '../../../entity/base/base.entity'; /** * @description * Returns TypeORM ColumnMetadata for the given entity type. */ export function getColumnMetadata<T>(connection: DataSource, entity: Type<T>) { const metadata = connection.getMetadata(entity); const columns = metadata.columns; let translationColumns: ColumnMetadata[] = []; const relations = metadata.relations; const translationRelation = relations.find(r => r.propertyName === 'translations'); if (translationRelation) { const commonFields: Array<keyof (Translation<T> & VendureEntity)> = [ 'id', 'createdAt', 'updatedAt', 'languageCode', ]; const translationMetadata = connection.getMetadata(translationRelation.type); translationColumns = translationColumns.concat( translationMetadata.columns.filter( c => !c.relationMetadata && !commonFields.includes(c.propertyName as any), ), ); } const alias = metadata.name.toLowerCase(); return { columns, translationColumns, alias }; } export function getEntityAlias<T>(connection: DataSource, entity: Type<T>): string { return connection.getMetadata(entity).name.toLowerCase(); } /** * @description * Escapes identifiers in an expression according to the current database driver. */ export function escapeCalculatedColumnExpression(connection: DataSource, expression: string): string { return expression.replace(/\b([a-z]+[A-Z]\w+)\b/g, substring => connection.driver.escape(substring)); }
import { Type } from '@vendure/common/lib/shared-types'; import { CalculatedColumnDefinition, CALCULATED_PROPERTIES } from '../../../common/calculated-decorator'; /** * @description * Returns calculated columns definitions for the given entity type. */ export function getCalculatedColumns(entity: Type<any>) { const calculatedColumns: CalculatedColumnDefinition[] = []; const prototype = entity.prototype; if (prototype.hasOwnProperty(CALCULATED_PROPERTIES)) { for (const property of prototype[CALCULATED_PROPERTIES]) { calculatedColumns.push(property); } } return calculatedColumns; }
import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; import { LogicalOperator } from '@vendure/common/lib/generated-types'; import { ID, Type } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { Brackets, FindOneOptions, FindOptionsWhere, Repository, SelectQueryBuilder, WhereExpressionBuilder, } from 'typeorm'; import { BetterSqlite3Driver } from 'typeorm/driver/better-sqlite3/BetterSqlite3Driver'; import { SqljsDriver } from 'typeorm/driver/sqljs/SqljsDriver'; import { ApiType, RequestContext } from '../../../api'; import { FilterParameter, ListQueryOptions, NullOptionals, SortParameter, UserInputError, } from '../../../common'; import { ConfigService, CustomFields, Logger } from '../../../config'; import { TransactionalConnection } from '../../../connection'; import { VendureEntity } from '../../../entity'; import { joinTreeRelationsDynamically } from '../utils/tree-relations-qb-joiner'; import { getColumnMetadata, getEntityAlias } from './connection-utils'; import { getCalculatedColumns } from './get-calculated-columns'; import { parseFilterParams, WhereGroup } from './parse-filter-params'; import { parseSortParams } from './parse-sort-params'; /** * @description * Options which can be passed to the ListQueryBuilder's `build()` method. * * @docsCategory data-access * @docsPage ListQueryBuilder */ export type ExtendedListQueryOptions<T extends VendureEntity> = { relations?: string[]; channelId?: ID; where?: FindOptionsWhere<T>; orderBy?: FindOneOptions<T>['order']; /** * @description * Allows you to specify the alias used for the entity `T` in the generated SQL query. * Defaults to the entity class name lower-cased, i.e. `ProductVariant` -> `'productvariant'`. * * @since 1.6.0 */ entityAlias?: string; /** * @description * When a RequestContext is passed, then the query will be * executed as part of any outer transaction. */ ctx?: RequestContext; /** * @description * One of the main tasks of the ListQueryBuilder is to auto-generate filter and sort queries based on the * available columns of a given entity. However, it may also be sometimes desirable to allow filter/sort * on a property of a relation. In this case, the `customPropertyMap` can be used to define a property * of the `options.sort` or `options.filter` which does not correspond to a direct column of the current * entity, and then provide a mapping to the related property to be sorted/filtered. * * Example: we want to allow sort/filter by and Order's `customerLastName`. The actual lastName property is * not a column in the Order table, it exists on the Customer entity, and Order has a relation to Customer via * `Order.customer`. Therefore, we can define a customPropertyMap like this: * * @example * ```GraphQL * """ * Manually extend the filter & sort inputs to include the new * field that we want to be able to use in building list queries. * """ * input OrderFilterParameter { * customerLastName: StringOperators * } * * input OrderSortParameter { * customerLastName: SortOrder * } * ``` * * @example * ```ts * const qb = this.listQueryBuilder.build(Order, options, { * relations: ['customer'], * customPropertyMap: { * // Tell TypeORM how to map that custom * // sort/filter field to the property on a * // related entity. * customerLastName: 'customer.lastName', * }, * }; * ``` * We can now use the `customerLastName` property to filter or sort * on the list query: * * @example * ```GraphQL * query { * myOrderQuery(options: { * filter: { * customerLastName: { contains: "sm" } * } * }) { * # ... * } * } * ``` */ customPropertyMap?: { [name: string]: string }; /** * @description * When set to `true`, the configured `shopListQueryLimit` and `adminListQueryLimit` values will be ignored, * allowing unlimited results to be returned. Use caution when exposing an unlimited list query to the public, * as it could become a vector for a denial of service attack if an attacker requests a very large list. * * @since 2.0.2 * @default false */ ignoreQueryLimits?: boolean; }; /** * @description * This helper class is used when fetching entities the database from queries which return a {@link PaginatedList} type. * These queries all follow the same format: * * In the GraphQL definition, they return a type which implements the `Node` interface, and the query returns a * type which implements the `PaginatedList` interface: * * ```GraphQL * type BlogPost implements Node { * id: ID! * published: DateTime! * title: String! * body: String! * } * * type BlogPostList implements PaginatedList { * items: [BlogPost!]! * totalItems: Int! * } * * # Generated at run-time by Vendure * input BlogPostListOptions * * extend type Query { * blogPosts(options: BlogPostListOptions): BlogPostList! * } * ``` * When Vendure bootstraps, it will find the `BlogPostListOptions` input and, because it is used in a query * returning a `PaginatedList` type, it knows that it should dynamically generate this input. This means * all primitive field of the `BlogPost` type (namely, "published", "title" and "body") will have `filter` and * `sort` inputs created for them, as well a `skip` and `take` fields for pagination. * * Your resolver function will then look like this: * * ```ts * \@Resolver() * export class BlogPostResolver * constructor(private blogPostService: BlogPostService) {} * * \@Query() * async blogPosts( * \@Ctx() ctx: RequestContext, * \@Args() args: any, * ): Promise<PaginatedList<BlogPost>> { * return this.blogPostService.findAll(ctx, args.options || undefined); * } * } * ``` * * and the corresponding service will use the ListQueryBuilder: * * ```ts * \@Injectable() * export class BlogPostService { * constructor(private listQueryBuilder: ListQueryBuilder) {} * * findAll(ctx: RequestContext, options?: ListQueryOptions<BlogPost>) { * return this.listQueryBuilder * .build(BlogPost, options) * .getManyAndCount() * .then(async ([items, totalItems]) => { * return { items, totalItems }; * }); * } * } * ``` * * @docsCategory data-access * @docsPage ListQueryBuilder * @docsWeight 0 */ @Injectable() export class ListQueryBuilder implements OnApplicationBootstrap { constructor( private connection: TransactionalConnection, private configService: ConfigService, ) {} /** @internal */ onApplicationBootstrap(): any { this.registerSQLiteRegexpFunction(); } /** * @description * Used to determine whether a list query `filter` object contains the * given property, either at the top level or nested inside a boolean * `_and` or `_or` expression. * * This is useful when a custom property map is used to map a filter * field to a related entity, and we need to determine whether the * filter object contains that property, which then means we would need * to join that relation. */ filterObjectHasProperty<FP extends FilterParameter<VendureEntity>>( filterObject: FP | NullOptionals<FP> | null | undefined, property: keyof FP, ): boolean { if (!filterObject) { return false; } for (const key in filterObject) { if (!filterObject[key]) { continue; } if (key === property) { return true; } if (key === '_and' || key === '_or') { const value = filterObject[key] as FP[]; for (const condition of value) { if (this.filterObjectHasProperty(condition, property)) { return true; } } } } return false; } /* * @description * Creates and configures a SelectQueryBuilder for queries that return paginated lists of entities. */ build<T extends VendureEntity>( entity: Type<T>, options: ListQueryOptions<T> = {}, extendedOptions: ExtendedListQueryOptions<T> = {}, ): SelectQueryBuilder<T> { const apiType = extendedOptions.ctx?.apiType ?? 'shop'; const { take, skip } = this.parseTakeSkipParams(apiType, options, extendedOptions.ignoreQueryLimits); const repo = extendedOptions.ctx ? this.connection.getRepository(extendedOptions.ctx, entity) : this.connection.rawConnection.getRepository(entity); const alias = extendedOptions.entityAlias || entity.name.toLowerCase(); const minimumRequiredRelations = this.getMinimumRequiredRelations(repo, options, extendedOptions); const qb = repo.createQueryBuilder(alias); let relations = unique([...minimumRequiredRelations, ...(extendedOptions?.relations ?? [])]); // Special case for the 'collection' entity, which has a complex nested structure // and requires special handling to ensure that only the necessary relations are joined. // This is bypassed an issue in TypeORM where it would join the same relation multiple times. // See https://github.com/typeorm/typeorm/issues/9936 for more context. const processedRelations = joinTreeRelationsDynamically(qb, entity, relations); // Remove any relations which are related to the 'collection' tree, as these are handled separately // to avoid duplicate joins. relations = relations.filter(relationPath => !processedRelations.has(relationPath)); qb.setFindOptions({ relations, take, skip, where: extendedOptions.where || {}, relationLoadStrategy: 'query', }); // join the tables required by calculated columns this.joinCalculatedColumnRelations(qb, entity, options); const { customPropertyMap } = extendedOptions; if (customPropertyMap) { this.normalizeCustomPropertyMap(customPropertyMap, options, qb); } const customFieldsForType = this.configService.customFields[entity.name as keyof CustomFields]; const sortParams = Object.assign({}, options.sort, extendedOptions.orderBy); this.applyTranslationConditions(qb, entity, sortParams, extendedOptions.ctx); const sort = parseSortParams( qb.connection, entity, sortParams, customPropertyMap, qb.alias, customFieldsForType, ); const filter = parseFilterParams(qb.connection, entity, options.filter, customPropertyMap, qb.alias); if (filter.length) { const filterOperator = options.filterOperator ?? LogicalOperator.AND; qb.andWhere( new Brackets(qb1 => { for (const condition of filter) { if ('conditions' in condition) { this.addNestedWhereClause(qb1, condition, filterOperator); } else { if (filterOperator === LogicalOperator.AND) { qb1.andWhere(condition.clause, condition.parameters); } else { qb1.orWhere(condition.clause, condition.parameters); } } } }), ); } if (extendedOptions.channelId) { qb.innerJoin(`${qb.alias}.channels`, 'lqb__channel', 'lqb__channel.id = :channelId', { channelId: extendedOptions.channelId, }); } qb.orderBy(sort); return qb; } private addNestedWhereClause( qb: WhereExpressionBuilder, whereGroup: WhereGroup, parentOperator: LogicalOperator, ) { if (whereGroup.conditions.length) { const subQb = new Brackets(qb1 => { whereGroup.conditions.forEach(condition => { if ('conditions' in condition) { this.addNestedWhereClause(qb1, condition, whereGroup.operator); } else { if (whereGroup.operator === LogicalOperator.AND) { qb1.andWhere(condition.clause, condition.parameters); } else { qb1.orWhere(condition.clause, condition.parameters); } } }); }); if (parentOperator === LogicalOperator.AND) { qb.andWhere(subQb); } else { qb.orWhere(subQb); } } } private parseTakeSkipParams( apiType: ApiType, options: ListQueryOptions<any>, ignoreQueryLimits = false, ): { take: number; skip: number } { const { shopListQueryLimit, adminListQueryLimit } = this.configService.apiOptions; const takeLimit = ignoreQueryLimits ? Number.MAX_SAFE_INTEGER : apiType === 'admin' ? adminListQueryLimit : shopListQueryLimit; if (options.take && options.take > takeLimit) { throw new UserInputError('error.list-query-limit-exceeded', { limit: takeLimit }); } const rawConnection = this.connection.rawConnection; const skip = Math.max(options.skip ?? 0, 0); // `take` must not be negative, and must not be greater than takeLimit let take = options.take == null ? takeLimit : Math.min(Math.max(options.take, 0), takeLimit); if (options.skip !== undefined && options.take === undefined) { take = takeLimit; } return { take, skip }; } /** * @description * As part of list optimization, we only join the minimum required relations which are needed to * get the base list query. Other relations are then joined individually in the patched `getManyAndCount()` * method. */ private getMinimumRequiredRelations<T extends VendureEntity>( repository: Repository<T>, options: ListQueryOptions<T>, extendedOptions: ExtendedListQueryOptions<T>, ): string[] { const requiredRelations: string[] = []; if (extendedOptions.channelId) { requiredRelations.push('channels'); } if (extendedOptions.customPropertyMap) { const metadata = repository.metadata; for (const [property, path] of Object.entries(extendedOptions.customPropertyMap)) { if (!this.customPropertyIsBeingUsed(property, options)) { // If the custom property is not being used to filter or sort, then we don't need // to join the associated relations. continue; } const relationPath = path.split('.').slice(0, -1); let targetMetadata = metadata; const recontructedPath = []; for (const relationPathPart of relationPath) { const relationMetadata = targetMetadata.findRelationWithPropertyPath(relationPathPart); if (relationMetadata) { recontructedPath.push(relationMetadata.propertyName); requiredRelations.push(recontructedPath.join('.')); targetMetadata = relationMetadata.inverseEntityMetadata; } } } } return unique(requiredRelations); } private customPropertyIsBeingUsed(property: string, options: ListQueryOptions<any>): boolean { return !!(options.sort?.[property] || options.filter?.[property]); } /** * If a customPropertyMap is provided, we need to take the path provided and convert it to the actual * relation aliases being used by the SelectQueryBuilder. * * This method mutates the customPropertyMap object. */ private normalizeCustomPropertyMap<T extends VendureEntity>( customPropertyMap: { [name: string]: string }, options: ListQueryOptions<any>, qb: SelectQueryBuilder<any>, ) { for (const [property, value] of Object.entries(customPropertyMap)) { if (!this.customPropertyIsBeingUsed(property, options)) { continue; } let parts = customPropertyMap[property].split('.'); const normalizedRelationPath: string[] = []; let entityMetadata = qb.expressionMap.mainAlias?.metadata; let entityAlias = qb.alias; while (parts.length > 1) { const entityPart = 2 <= parts.length ? parts[0] : qb.alias; const columnPart = parts[parts.length - 1]; if (!entityMetadata) { Logger.error(`Could not get metadata for entity ${qb.alias}`); continue; } const relationMetadata = entityMetadata.findRelationWithPropertyPath(entityPart); if (!relationMetadata ?? !relationMetadata?.propertyName) { Logger.error( `The customPropertyMap entry "${property}:${value}" could not be resolved to a related table`, ); delete customPropertyMap[property]; return; } const alias = `${entityMetadata.tableName}_${relationMetadata.propertyName}`; if (!this.isRelationAlreadyJoined(qb, alias)) { qb.leftJoinAndSelect(`${entityAlias}.${relationMetadata.propertyName}`, alias); } parts = parts.slice(1); entityMetadata = relationMetadata?.inverseEntityMetadata; normalizedRelationPath.push(entityAlias); if (parts.length === 1) { normalizedRelationPath.push(alias, columnPart); } else { entityAlias = alias; } } customPropertyMap[property] = normalizedRelationPath.slice(-2).join('.'); } } /** * Some calculated columns (those with the `@Calculated()` decorator) require extra joins in order * to derive the data needed for their expressions. */ private joinCalculatedColumnRelations<T extends VendureEntity>( qb: SelectQueryBuilder<T>, entity: Type<T>, options: ListQueryOptions<T>, ) { const calculatedColumns = getCalculatedColumns(entity); const filterAndSortFields = unique([ ...Object.keys(options.filter || {}), ...Object.keys(options.sort || {}), ]); const alias = getEntityAlias(this.connection.rawConnection, entity); for (const field of filterAndSortFields) { const calculatedColumnDef = calculatedColumns.find(c => c.name === field); const instruction = calculatedColumnDef?.listQuery; if (instruction) { const relations = instruction.relations || []; for (const relation of relations) { const relationIsAlreadyJoined = qb.expressionMap.joinAttributes.find( ja => ja.entityOrProperty === `${alias}.${relation}`, ); if (!relationIsAlreadyJoined) { const propertyPath = relation.includes('.') ? relation : `${alias}.${relation}`; const relationAlias = relation.includes('.') ? relation.split('.').reverse()[0] : relation; qb.innerJoinAndSelect(propertyPath, relationAlias); } } if (typeof instruction.query === 'function') { instruction.query(qb); } } } } /** * @description * If this entity is Translatable, and we are sorting on one of the translatable fields, * then we need to apply appropriate WHERE clauses to limit * the joined translation relations. */ private applyTranslationConditions<T extends VendureEntity>( qb: SelectQueryBuilder<any>, entity: Type<T>, sortParams: NullOptionals<SortParameter<T>> & FindOneOptions<T>['order'], ctx?: RequestContext, ) { const languageCode = ctx?.languageCode || this.configService.defaultLanguageCode; const { translationColumns } = getColumnMetadata(qb.connection, entity); const alias = qb.alias; const sortKeys = Object.keys(sortParams); let sortingOnTranslatableKey = false; for (const translationColumn of translationColumns) { if (sortKeys.includes(translationColumn.propertyName)) { sortingOnTranslatableKey = true; } } if (translationColumns.length && sortingOnTranslatableKey) { const translationsAlias = qb.connection.namingStrategy.joinTableName( alias, 'translations', '', '', ); if (!this.isRelationAlreadyJoined(qb, translationsAlias)) { qb.leftJoinAndSelect(`${alias}.translations`, translationsAlias); } qb.andWhere( new Brackets(qb1 => { qb1.where(`${translationsAlias}.languageCode = :languageCode`, { languageCode }); const defaultLanguageCode = ctx?.channel.defaultLanguageCode ?? this.configService.defaultLanguageCode; const translationEntity = translationColumns[0].entityMetadata.target; if (languageCode !== defaultLanguageCode) { // If the current languageCode is not the default, then we create a more // complex WHERE clause to allow us to use the non-default translations and // fall back to the default language if no translation exists. qb1.orWhere( new Brackets(qb2 => { const subQb1 = this.connection.rawConnection .createQueryBuilder(translationEntity, 'translation') .where(`translation.base = ${alias}.id`) .andWhere('translation.languageCode = :defaultLanguageCode'); const subQb2 = this.connection.rawConnection .createQueryBuilder(translationEntity, 'translation') .where(`translation.base = ${alias}.id`) .andWhere('translation.languageCode = :nonDefaultLanguageCode'); qb2.where(`EXISTS (${subQb1.getQuery()})`).andWhere( `NOT EXISTS (${subQb2.getQuery()})`, ); }), ); } else { qb1.orWhere( new Brackets(qb2 => { const subQb1 = this.connection.rawConnection .createQueryBuilder(translationEntity, 'translation') .where(`translation.base = ${alias}.id`) .andWhere('translation.languageCode = :defaultLanguageCode'); const subQb2 = this.connection.rawConnection .createQueryBuilder(translationEntity, 'translation') .where(`translation.base = ${alias}.id`) .andWhere('translation.languageCode != :defaultLanguageCode'); qb2.where(`NOT EXISTS (${subQb1.getQuery()})`).andWhere( `EXISTS (${subQb2.getQuery()})`, ); }), ); } qb.setParameters({ nonDefaultLanguageCode: languageCode, defaultLanguageCode, }); }), ); } } /** * Registers a user-defined function (for flavors of SQLite driver that support it) * so that we can run regex filters on string fields. */ private registerSQLiteRegexpFunction() { const regexpFn = (pattern: string, value: string) => { const result = new RegExp(`${pattern}`, 'i').test(value); return result ? 1 : 0; }; const dbType = this.connection.rawConnection.options.type; if (dbType === 'better-sqlite3') { const driver = this.connection.rawConnection.driver as BetterSqlite3Driver; driver.databaseConnection.function('regexp', regexpFn); } if (dbType === 'sqljs') { const driver = this.connection.rawConnection.driver as SqljsDriver; driver.databaseConnection.create_function('regexp', regexpFn); } } private isRelationAlreadyJoined<T extends VendureEntity>( qb: SelectQueryBuilder<T>, alias: string, ): boolean { return qb.expressionMap.joinAttributes.some(ja => ja.alias.name === alias); } }
import { describe, expect, it } from 'vitest'; import { Channel } from '../../../entity/channel/channel.entity'; import { Customer } from '../../../entity/customer/customer.entity'; import { Product } from '../../../entity/product/product.entity'; import { parseChannelParam } from './parse-channel-param'; import { MockConnection } from './parse-sort-params.spec'; describe('parseChannelParam()', () => { it('works with a channel-aware entity', () => { const connection = new MockConnection(); connection.setRelations(Product, [{ propertyName: 'channels', type: Channel }]); const result = parseChannelParam(connection as any, Product, 123); if (!result) { fail('Result should be defined'); return; } expect(result.clause).toEqual('product__channels.id = :channelId'); expect(result.parameters).toEqual({ channelId: 123 }); }); it('returns undefined for a non-channel-aware entity', () => { const connection = new MockConnection(); const result = parseChannelParam(connection as any, Customer, 123); expect(result).toBeUndefined(); }); });
import { ID, Type } from '@vendure/common/lib/shared-types'; import { Connection } from 'typeorm'; import { VendureEntity } from '../../../entity/base/base.entity'; import { WhereCondition } from './parse-filter-params'; /** * Creates a WhereCondition for a channel-aware entity, filtering for only those entities * which are assigned to the channel specified by channelId, */ export function parseChannelParam<T extends VendureEntity>( connection: Connection, entity: Type<T>, channelId: ID, entityAlias?: string, ): WhereCondition | undefined { const metadata = connection.getMetadata(entity); const alias = entityAlias ?? metadata.name.toLowerCase(); const relations = metadata.relations; const channelRelation = relations.find(r => r.propertyName === 'channels'); if (!channelRelation) { return; } return { clause: `${alias}__channels.id = :channelId`, parameters: { channelId }, }; }
import { LogicalOperator } from '@vendure/common/lib/generated-types'; import { describe, expect, it } from 'vitest'; import { FilterParameter } from '../../../common/types/common-types'; import { ProductTranslation } from '../../../entity/product/product-translation.entity'; import { Product } from '../../../entity/product/product.entity'; import { parseFilterParams } from './parse-filter-params'; import { MockConnection } from './parse-sort-params.spec'; describe('parseFilterParams()', () => { it('works with no params', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'image' }]); const result = parseFilterParams(connection as any, Product, {}); expect(result).toEqual([]); }); it('works with single param', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'name' }]); const filterParams: FilterParameter<Product> = { name: { eq: 'foo', }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.name = :arg1'); expect(result[0].parameters).toEqual({ arg1: 'foo' }); }); it('works with multiple params', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'name' }]); const filterParams: FilterParameter<Product> = { name: { eq: 'foo', }, id: { eq: '123', }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.name = :arg1'); expect(result[0].parameters).toEqual({ arg1: 'foo' }); expect(result[1].clause).toBe('product.id = :arg2'); expect(result[1].parameters).toEqual({ arg2: '123' }); }); it('works with localized fields', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'image' }]); connection.setRelations(Product, [{ propertyName: 'translations', type: ProductTranslation }]); connection.setColumns(ProductTranslation, [ { propertyName: 'id' }, { propertyName: 'name' }, { propertyName: 'base', relationMetadata: {} as any }, ]); const filterParams: FilterParameter<Product> = { name: { eq: 'foo', }, id: { eq: '123', }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product__translations.name = :arg1'); expect(result[0].parameters).toEqual({ arg1: 'foo' }); expect(result[1].clause).toBe('product.id = :arg2'); expect(result[1].parameters).toEqual({ arg2: '123' }); }); describe('string operators', () => { it('eq', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'name', type: String }]); const filterParams: FilterParameter<Product> = { name: { eq: 'foo', }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.name = :arg1'); expect(result[0].parameters).toEqual({ arg1: 'foo' }); }); it('contains', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'name', type: String }]); const filterParams: FilterParameter<Product> = { name: { contains: 'foo', }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.name LIKE :arg1'); expect(result[0].parameters).toEqual({ arg1: '%foo%' }); }); }); describe('number operators', () => { it('eq', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'price', type: Number }]); const filterParams: FilterParameter<Product & { price: number }> = { price: { eq: 123, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.price = :arg1'); expect(result[0].parameters).toEqual({ arg1: 123 }); }); it('lt', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'price', type: Number }]); const filterParams: FilterParameter<Product & { price: number }> = { price: { lt: 123, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.price < :arg1'); expect(result[0].parameters).toEqual({ arg1: 123 }); }); it('lte', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'price', type: Number }]); const filterParams: FilterParameter<Product & { price: number }> = { price: { lte: 123, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.price <= :arg1'); expect(result[0].parameters).toEqual({ arg1: 123 }); }); it('gt', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'price', type: Number }]); const filterParams: FilterParameter<Product & { price: number }> = { price: { gt: 123, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.price > :arg1'); expect(result[0].parameters).toEqual({ arg1: 123 }); }); it('gte', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'price', type: Number }]); const filterParams: FilterParameter<Product & { price: number }> = { price: { gte: 123, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.price >= :arg1'); expect(result[0].parameters).toEqual({ arg1: 123 }); }); it('between', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'price', type: Number }]); const filterParams: FilterParameter<Product & { price: number }> = { price: { between: { start: 10, end: 50, }, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.price BETWEEN :arg1_a AND :arg1_b'); expect(result[0].parameters).toEqual({ arg1_a: 10, arg1_b: 50 }); }); }); describe('date operators', () => { it('eq', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'createdAt', type: 'datetime' }]); const filterParams: FilterParameter<Product> = { createdAt: { eq: new Date('2018-01-01T10:00:00.000Z'), }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.createdAt = :arg1'); expect(result[0].parameters).toEqual({ arg1: '2018-01-01 10:00:00.000' }); }); it('before', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'createdAt', type: 'datetime' }]); const filterParams: FilterParameter<Product> = { createdAt: { before: new Date('2018-01-01T10:00:00.000Z'), }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.createdAt < :arg1'); expect(result[0].parameters).toEqual({ arg1: '2018-01-01 10:00:00.000' }); }); it('after', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'createdAt', type: 'datetime' }]); const filterParams: FilterParameter<Product> = { createdAt: { after: new Date('2018-01-01T10:00:00.000Z'), }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.createdAt > :arg1'); expect(result[0].parameters).toEqual({ arg1: '2018-01-01 10:00:00.000' }); }); it('between', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'createdAt', type: 'datetime' }]); const filterParams: FilterParameter<Product> = { createdAt: { between: { start: new Date('2018-01-01T10:00:00.000Z'), end: new Date('2018-02-01T10:00:00.000Z'), }, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.createdAt BETWEEN :arg1_a AND :arg1_b'); expect(result[0].parameters).toEqual({ arg1_a: '2018-01-01 10:00:00.000', arg1_b: '2018-02-01 10:00:00.000', }); }); }); describe('boolean operators', () => { it('eq', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'available', type: 'tinyint' }]); const filterParams: FilterParameter<Product & { available: boolean }> = { available: { eq: true, }, }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].clause).toBe('product.available = :arg1'); expect(result[0].parameters).toEqual({ arg1: true }); }); }); describe('nested boolean expressions', () => { it('simple _and', () => { const connection = new MockConnection(); connection.setColumns(Product, [ { propertyName: 'name', type: String }, { propertyName: 'slug', type: String }, ]); const filterParams = { _and: [ { name: { eq: 'foo' }, }, { slug: { eq: 'bar' }, }, ], }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].operator).toBe(LogicalOperator.AND); expect(result[0].conditions).toEqual([ { clause: 'product.name = :arg1', parameters: { arg1: 'foo' } }, { clause: 'product.slug = :arg2', parameters: { arg2: 'bar' } }, ]); }); it('simple _or', () => { const connection = new MockConnection(); connection.setColumns(Product, [ { propertyName: 'name', type: String }, { propertyName: 'slug', type: String }, ]); const filterParams = { _or: [ { name: { eq: 'foo' }, }, { slug: { eq: 'bar' }, }, ], }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result[0].operator).toBe(LogicalOperator.OR); expect(result[0].conditions).toEqual([ { clause: 'product.name = :arg1', parameters: { arg1: 'foo' } }, { clause: 'product.slug = :arg2', parameters: { arg2: 'bar' } }, ]); }); it('nested _or and _and', () => { const connection = new MockConnection(); connection.setColumns(Product, [ { propertyName: 'name', type: String }, { propertyName: 'slug', type: String }, ]); const filterParams = { _and: [ { name: { eq: 'foo' }, }, { _or: [{ slug: { eq: 'bar' } }, { slug: { eq: 'baz' } }], }, ], }; const result = parseFilterParams(connection as any, Product, filterParams); expect(result).toEqual([ { operator: LogicalOperator.AND, conditions: [ { clause: 'product.name = :arg1', parameters: { arg1: 'foo' } }, { operator: LogicalOperator.OR, conditions: [ { clause: 'product.slug = :arg2', parameters: { arg2: 'bar' } }, { clause: 'product.slug = :arg3', parameters: { arg3: 'baz' } }, ], }, ], }, ]); }); }); });
import { LogicalOperator } from '@vendure/common/lib/generated-types'; import { Type } from '@vendure/common/lib/shared-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { DataSource, DataSourceOptions } from 'typeorm'; import { DateUtils } from 'typeorm/util/DateUtils'; import { InternalServerError, UserInputError } from '../../../common/error/errors'; import { BooleanOperators, DateOperators, FilterParameter, ListOperators, NullOptionals, NumberOperators, StringOperators, } from '../../../common/types/common-types'; import { VendureEntity } from '../../../entity/base/base.entity'; import { escapeCalculatedColumnExpression, getColumnMetadata } from './connection-utils'; import { getCalculatedColumns } from './get-calculated-columns'; export interface WhereGroup { operator: LogicalOperator; conditions: Array<WhereCondition | WhereGroup>; } export interface WhereCondition { clause: string; parameters: { [param: string]: string | number | string[] }; } type AllOperators = StringOperators & BooleanOperators & NumberOperators & DateOperators & ListOperators; type Operator = { [K in keyof AllOperators]-?: K }[keyof AllOperators]; export function parseFilterParams< T extends VendureEntity, FP extends NullOptionals<FilterParameter<T>>, R extends FP extends { _and: Array<FilterParameter<T>> } ? WhereGroup[] : FP extends { _or: Array<FilterParameter<T>> } ? WhereGroup[] : WhereCondition[], >( connection: DataSource, entity: Type<T>, filterParams?: FP | null, customPropertyMap?: { [name: string]: string }, entityAlias?: string, ): R { if (!filterParams) { return [] as unknown as R; } const { columns, translationColumns, alias: defaultAlias } = getColumnMetadata(connection, entity); const alias = entityAlias ?? defaultAlias; const calculatedColumns = getCalculatedColumns(entity); const dbType = connection.options.type; let argIndex = 1; function buildConditionsForField(key: string, operation: FilterParameter<T>): WhereCondition[] { const output: WhereCondition[] = []; const calculatedColumnDef = calculatedColumns.find(c => c.name === key); const instruction = calculatedColumnDef?.listQuery; const calculatedColumnExpression = instruction?.expression; for (const [operator, operand] of Object.entries(operation as object)) { let fieldName: string; if (columns.find(c => c.propertyName === key)) { fieldName = `${alias}.${key}`; } else if (translationColumns.find(c => c.propertyName === key)) { const translationsAlias = connection.namingStrategy.joinTableName( alias, 'translations', '', '', ); fieldName = `${translationsAlias}.${key}`; } else if (calculatedColumnExpression) { fieldName = escapeCalculatedColumnExpression(connection, calculatedColumnExpression); } else if (customPropertyMap?.[key]) { fieldName = customPropertyMap[key]; } else { throw new UserInputError('error.invalid-filter-field'); } const condition = buildWhereCondition(fieldName, operator as Operator, operand, argIndex, dbType); output.push(condition); argIndex++; } return output; } function processFilterParameter(param: FilterParameter<T>) { const result: Array<WhereCondition | WhereGroup> = []; for (const [key, operation] of Object.entries(param)) { if (key === '_and' || key === '_or') { result.push({ operator: key === '_and' ? LogicalOperator.AND : LogicalOperator.OR, conditions: operation.map(o => processFilterParameter(o)).flat(), }); } else if (operation && !Array.isArray(operation)) { result.push(...buildConditionsForField(key, operation)); } } return result; } const conditions = processFilterParameter(filterParams as FilterParameter<T>); return conditions as R; } function buildWhereCondition( fieldName: string, operator: Operator, operand: any, argIndex: number, dbType: DataSourceOptions['type'], ): WhereCondition { switch (operator) { case 'eq': return { clause: `${fieldName} = :arg${argIndex}`, parameters: { [`arg${argIndex}`]: convertDate(operand) }, }; case 'notEq': return { clause: `${fieldName} != :arg${argIndex}`, parameters: { [`arg${argIndex}`]: convertDate(operand) }, }; case 'inList': case 'contains': { const LIKE = dbType === 'postgres' ? 'ILIKE' : 'LIKE'; return { clause: `${fieldName} ${LIKE} :arg${argIndex}`, parameters: { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions [`arg${argIndex}`]: `%${typeof operand === 'string' ? operand.trim() : operand}%`, }, }; } case 'notContains': { const LIKE = dbType === 'postgres' ? 'ILIKE' : 'LIKE'; return { clause: `${fieldName} NOT ${LIKE} :arg${argIndex}`, // eslint-disable-next-line @typescript-eslint/restrict-template-expressions parameters: { [`arg${argIndex}`]: `%${operand.trim()}%` }, }; } case 'in': { if (Array.isArray(operand) && operand.length) { return { clause: `${fieldName} IN (:...arg${argIndex})`, parameters: { [`arg${argIndex}`]: operand }, }; } else { // "in" with an empty set should always return nothing return { clause: '1 = 0', parameters: {}, }; } } case 'notIn': { if (Array.isArray(operand) && operand.length) { return { clause: `${fieldName} NOT IN (:...arg${argIndex})`, parameters: { [`arg${argIndex}`]: operand }, }; } else { // "notIn" with an empty set should always return all return { clause: '1 = 1', parameters: {}, }; } } case 'regex': return { clause: getRegexpClause(fieldName, argIndex, dbType), parameters: { [`arg${argIndex}`]: operand }, }; case 'lt': case 'before': return { clause: `${fieldName} < :arg${argIndex}`, parameters: { [`arg${argIndex}`]: convertDate(operand) }, }; case 'gt': case 'after': return { clause: `${fieldName} > :arg${argIndex}`, parameters: { [`arg${argIndex}`]: convertDate(operand) }, }; case 'lte': return { clause: `${fieldName} <= :arg${argIndex}`, parameters: { [`arg${argIndex}`]: operand }, }; case 'gte': return { clause: `${fieldName} >= :arg${argIndex}`, parameters: { [`arg${argIndex}`]: operand }, }; case 'between': return { clause: `${fieldName} BETWEEN :arg${argIndex}_a AND :arg${argIndex}_b`, parameters: { [`arg${argIndex}_a`]: convertDate(operand.start), [`arg${argIndex}_b`]: convertDate(operand.end), }, }; case 'isNull': return { clause: operand === true ? `${fieldName} IS NULL` : `${fieldName} IS NOT NULL`, parameters: {}, }; default: assertNever(operator); } return { clause: '1', parameters: {}, }; } /** * Converts a JS Date object to a string format recognized by all DB engines. * See https://github.com/vendure-ecommerce/vendure/issues/251 */ function convertDate(input: Date | string | number): string | number { if (input instanceof Date) { return DateUtils.mixedDateToUtcDatetimeString(input); } return input; } /** * Returns a valid regexp clause based on the current DB driver type. */ function getRegexpClause(fieldName: string, argIndex: number, dbType: DataSourceOptions['type']): string { switch (dbType) { case 'mariadb': case 'mysql': case 'sqljs': case 'better-sqlite3': case 'aurora-mysql': return `${fieldName} REGEXP :arg${argIndex}`; case 'postgres': case 'aurora-postgres': case 'cockroachdb': return `${fieldName} ~* :arg${argIndex}`; // The node-sqlite3 driver does not support user-defined functions // and therefore we are unable to define a custom regexp // function. See https://github.com/mapbox/node-sqlite3/issues/140 case 'sqlite': default: throw new InternalServerError( `The 'regex' filter is not available when using the '${dbType}' driver`, ); } }
import { Type } from '@vendure/common/lib/shared-types'; import { fail } from 'assert'; import { DefaultNamingStrategy } from 'typeorm'; import { ColumnMetadata } from 'typeorm/metadata/ColumnMetadata'; import { RelationMetadata } from 'typeorm/metadata/RelationMetadata'; import { describe, expect, it } from 'vitest'; import { SortParameter } from '../../../common/types/common-types'; import { CustomFieldConfig } from '../../../config/custom-field/custom-field-types'; import { ProductTranslation } from '../../../entity/product/product-translation.entity'; import { Product } from '../../../entity/product/product.entity'; import { I18nError } from '../../../i18n/i18n-error'; import { parseSortParams } from './parse-sort-params'; describe('parseSortParams()', () => { it('works with no params', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'image' }]); const result = parseSortParams(connection as any, Product, {}); expect(result).toEqual({}); }); it('works with a single param', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'image' }]); const sortParams: SortParameter<Product> = { id: 'ASC', }; const result = parseSortParams(connection as any, Product, sortParams); expect(result).toEqual({ 'product.id': 'ASC', }); }); it('works with multiple params', () => { const connection = new MockConnection(); connection.setColumns(Product, [ { propertyName: 'id' }, { propertyName: 'image' }, { propertyName: 'createdAt' }, ]); const sortParams: SortParameter<Product> = { id: 'ASC', createdAt: 'DESC', }; const result = parseSortParams(connection as any, Product, sortParams); expect(result).toEqual({ 'product.id': 'ASC', 'product.createdAt': 'DESC', }); }); it('works with localized fields', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'image' }]); connection.setRelations(Product, [{ propertyName: 'translations', type: ProductTranslation }]); connection.setColumns(ProductTranslation, [ { propertyName: 'id' }, { propertyName: 'name' }, { propertyName: 'base', relationMetadata: {} as any }, ]); const sortParams: SortParameter<Product> = { id: 'ASC', name: 'DESC', }; const result = parseSortParams(connection as any, Product, sortParams); expect(result).toEqual({ 'product.id': 'ASC', 'product__translations.name': 'DESC', }); }); it('works with custom fields', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'infoUrl' }]); const sortParams: SortParameter<Product & { infoUrl: any }> = { infoUrl: 'ASC', }; const result = parseSortParams(connection as any, Product, sortParams); expect(result).toEqual({ 'product.infoUrl': 'ASC', }); }); it('works with localized custom fields', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }]); connection.setRelations(Product, [{ propertyName: 'translations', type: ProductTranslation }]); connection.setColumns(ProductTranslation, [{ propertyName: 'id' }, { propertyName: 'shortName' }]); const sortParams: SortParameter<Product & { shortName: any }> = { shortName: 'ASC', }; const productCustomFields: CustomFieldConfig[] = [{ name: 'shortName', type: 'localeString' }]; const result = parseSortParams( connection as any, Product, sortParams, {}, undefined, productCustomFields, ); expect(result).toEqual({ 'product__translations.customFields.shortName': 'ASC', }); }); it('throws if an invalid field is passed', () => { const connection = new MockConnection(); connection.setColumns(Product, [{ propertyName: 'id' }, { propertyName: 'image' }]); connection.setRelations(Product, [{ propertyName: 'translations', type: ProductTranslation }]); connection.setColumns(ProductTranslation, [ { propertyName: 'id' }, { propertyName: 'name' }, { propertyName: 'base', relationMetadata: {} as any }, ]); const sortParams: SortParameter<Product & { invalid: any }> = { invalid: 'ASC', }; try { parseSortParams(connection as any, Product, sortParams); fail('should not get here'); } catch (e: any) { expect(e instanceof I18nError).toBe(true); expect(e.message).toBe('error.invalid-sort-field'); expect(e.variables.fieldName).toBe('invalid'); expect(e.variables.validFields).toEqual('id, image, name'); } }); }); export class MockConnection { private columnsMap = new Map<Type<any>, Array<Partial<ColumnMetadata>>>(); private relationsMap = new Map<Type<any>, Array<Partial<RelationMetadata>>>(); setColumns(entity: Type<any>, value: Array<Partial<ColumnMetadata>>) { value.forEach(v => (v.propertyPath = v.propertyName)); this.columnsMap.set(entity, value); } setRelations(entity: Type<any>, value: Array<Partial<RelationMetadata>>) { this.relationsMap.set(entity, value); } getMetadata = (entity: Type<any>) => { return { name: entity.name, columns: this.columnsMap.get(entity) || [], relations: this.relationsMap.get(entity) || [], }; }; namingStrategy = new DefaultNamingStrategy(); readonly options = { type: 'sqljs', }; }
import { Type } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { OrderByCondition } from 'typeorm'; import { DataSource } from 'typeorm/data-source/DataSource'; import { ColumnMetadata } from 'typeorm/metadata/ColumnMetadata'; import { UserInputError } from '../../../common/error/errors'; import { NullOptionals, SortParameter } from '../../../common/types/common-types'; import { CustomFieldConfig } from '../../../config/custom-field/custom-field-types'; import { VendureEntity } from '../../../entity/base/base.entity'; import { escapeCalculatedColumnExpression, getColumnMetadata } from './connection-utils'; import { getCalculatedColumns } from './get-calculated-columns'; /** * Parses the provided SortParameter array against the metadata of the given entity, ensuring that only * valid fields are being sorted against. The output assumes * @param connection * @param entity * @param sortParams * @param customPropertyMap * @param entityAlias * @param customFields */ export function parseSortParams<T extends VendureEntity>( connection: DataSource, entity: Type<T>, sortParams?: NullOptionals<SortParameter<T>> | null, customPropertyMap?: { [name: string]: string }, entityAlias?: string, customFields?: CustomFieldConfig[], ): OrderByCondition { if (!sortParams || Object.keys(sortParams).length === 0) { return {}; } const { columns, translationColumns, alias: defaultAlias } = getColumnMetadata(connection, entity); const alias = entityAlias ?? defaultAlias; const calculatedColumns = getCalculatedColumns(entity); const output: OrderByCondition = {}; for (const [key, order] of Object.entries(sortParams)) { const calculatedColumnDef = calculatedColumns.find(c => c.name === key); const matchingColumn = columns.find(c => c.propertyName === key); if (matchingColumn) { output[`${alias}.${matchingColumn.propertyPath}`] = order as any; } else if (translationColumns.find(c => c.propertyName === key)) { const translationsAlias = connection.namingStrategy.joinTableName(alias, 'translations', '', ''); const pathParts = [translationsAlias]; const isLocaleStringCustomField = customFields?.find(f => f.name === key)?.type === 'localeString'; if (isLocaleStringCustomField) { pathParts.push('customFields'); } pathParts.push(key); output[pathParts.join('.')] = order as any; } else if (calculatedColumnDef) { const instruction = calculatedColumnDef.listQuery; if (instruction && instruction.expression) { output[escapeCalculatedColumnExpression(connection, instruction.expression)] = order as any; } } else if (customPropertyMap?.[key]) { output[customPropertyMap[key]] = order as any; } else { throw new UserInputError('error.invalid-sort-field', { fieldName: key, validFields: [ ...getValidSortFields([...columns, ...translationColumns]), ...calculatedColumns.map(c => c.name.toString()), ].join(', '), }); } } return output; } function getValidSortFields(columns: ColumnMetadata[]): string[] { return unique(columns.map(c => c.propertyName)); }
import { Injectable } from '@nestjs/common'; import { LanguageCode } from '@vendure/common/lib/generated-types'; import { FindOneOptions } from 'typeorm'; import { RequestContext } from '../../../api/common/request-context'; import { RequestContextCacheService } from '../../../cache/request-context-cache.service'; import { Translatable, TranslatableKeys, Translated } from '../../../common/types/locale-types'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { VendureEntity } from '../../../entity/base/base.entity'; import { TranslatorService } from '../translator/translator.service'; /** * This helper class is to be used in GraphQL entity resolvers, to resolve fields which depend on being * translated (i.e. the corresponding entity field is of type `LocaleString`). */ @Injectable() export class LocaleStringHydrator { constructor( private connection: TransactionalConnection, private requestCache: RequestContextCacheService, private translator: TranslatorService, ) {} async hydrateLocaleStringField<T extends VendureEntity & Translatable & { languageCode?: LanguageCode }>( ctx: RequestContext, entity: T, fieldName: TranslatableKeys<T> | 'languageCode', ): Promise<string> { if (entity[fieldName]) { // Already hydrated, so return the value return entity[fieldName] as any; } await this.hydrateLocaleStrings(ctx, entity); return entity[fieldName] as any; } /** * Takes a translatable entity and populates all the LocaleString fields * by fetching the translations from the database (they will be eagerly loaded). * * This method includes a caching optimization to prevent multiple DB calls when many * translatable fields are needed on the same entity in a resolver. */ private async hydrateLocaleStrings<T extends VendureEntity & Translatable>( ctx: RequestContext, entity: T, ): Promise<Translated<T>> { const entityType = entity.constructor.name; if (!entity.translations?.length) { const cacheKey = `hydrate-${entityType}-${entity.id}`; let dbCallPromise = this.requestCache.get<Promise<T | null>>(ctx, cacheKey); if (!dbCallPromise) { dbCallPromise = this.connection .getRepository<T>(ctx, entityType) .findOne({ where: { id: entity.id } } as FindOneOptions<T>); this.requestCache.set(ctx, cacheKey, dbCallPromise); } await dbCallPromise.then(withTranslations => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion entity.translations = withTranslations!.translations; }); } if (entity.translations.length) { const translated = this.translator.translate(entity, ctx); for (const localeStringProp of Object.keys(entity.translations[0])) { if ( localeStringProp === 'base' || localeStringProp === 'id' || localeStringProp === 'createdAt' || localeStringProp === 'updatedAt' ) { continue; } if (localeStringProp === 'customFields') { (entity as any)[localeStringProp] = Object.assign( (entity as any)[localeStringProp] ?? {}, (translated as any)[localeStringProp] ?? {}, ); } else { (entity as any)[localeStringProp] = (translated as any)[localeStringProp]; } } } return entity as Translated<T>; } }
import { Test } from '@nestjs/testing'; import { AdjustmentType, LanguageCode, TaxLine } from '@vendure/common/lib/generated-types'; import { summate } from '@vendure/common/lib/shared-utils'; import { beforeAll, describe, expect, it } from 'vitest'; import { RequestContext } from '../../../api/common/request-context'; import { RequestContextCacheService } from '../../../cache/request-context-cache.service'; import { PromotionItemAction, PromotionOrderAction, PromotionShippingAction } from '../../../config'; import { ensureConfigLoaded } from '../../../config/config-helpers'; import { ConfigService } from '../../../config/config.service'; import { MockConfigService } from '../../../config/config.service.mock'; import { PromotionCondition } from '../../../config/promotion/promotion-condition'; import { DefaultTaxLineCalculationStrategy } from '../../../config/tax/default-tax-line-calculation-strategy'; import { DefaultTaxZoneStrategy } from '../../../config/tax/default-tax-zone-strategy'; import { CalculateTaxLinesArgs, TaxLineCalculationStrategy, } from '../../../config/tax/tax-line-calculation-strategy'; import { Promotion } from '../../../entity'; import { Order } from '../../../entity/order/order.entity'; import { ShippingLine } from '../../../entity/shipping-line/shipping-line.entity'; import { Surcharge } from '../../../entity/surcharge/surcharge.entity'; import { EventBus } from '../../../event-bus/event-bus'; import { createOrder, createRequestContext, MockTaxRateService, taxCategoryReduced, taxCategoryStandard, taxCategoryZero, } from '../../../testing/order-test-utils'; import { ShippingMethodService } from '../../services/shipping-method.service'; import { TaxRateService } from '../../services/tax-rate.service'; import { ZoneService } from '../../services/zone.service'; import { ListQueryBuilder } from '../list-query-builder/list-query-builder'; import { ShippingCalculator } from '../shipping-calculator/shipping-calculator'; import { OrderCalculator } from './order-calculator'; const mockShippingMethodId = 'T_1'; describe('OrderCalculator', () => { let orderCalculator: OrderCalculator; beforeAll(async () => { await ensureConfigLoaded(); const module = await createTestModule(); orderCalculator = module.get(OrderCalculator); const mockConfigService = module.get<ConfigService, MockConfigService>(ConfigService); mockConfigService.taxOptions = { taxZoneStrategy: new DefaultTaxZoneStrategy(), taxLineCalculationStrategy: new DefaultTaxLineCalculationStrategy(), }; }); describe('taxes', () => { it('single line', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 123, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(123); expect(order.subTotalWithTax).toBe(148); }); it('single line, multiple items', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 123, taxCategory: taxCategoryStandard, quantity: 3, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(369); expect(order.subTotalWithTax).toBe(444); }); it('resets totals when lines array is empty', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [], subTotal: 148, }); await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(0); }); }); describe('shipping', () => { it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.shippingLines = [ new ShippingLine({ shippingMethodId: mockShippingMethodId, }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(100); expect(order.shipping).toBe(500); expect(order.shippingWithTax).toBe(600); expect(order.total).toBe(order.subTotal + 500); expect(order.totalWithTax).toBe(order.subTotalWithTax + 600); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.shippingLines = [ new ShippingLine({ shippingMethodId: mockShippingMethodId, }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(83); expect(order.shipping).toBe(417); expect(order.shippingWithTax).toBe(500); expect(order.total).toBe(order.subTotal + 417); expect(order.totalWithTax).toBe(order.subTotalWithTax + 500); assertOrderTotalsAddUp(order); }); it('multiple shipping lines', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.shippingLines = [ new ShippingLine({ shippingMethodId: mockShippingMethodId, }), new ShippingLine({ shippingMethodId: mockShippingMethodId, }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.shippingLines.length).toBe(2); expect(order.subTotal).toBe(100); expect(order.shipping).toBe(1000); expect(order.shippingWithTax).toBe(1200); expect(order.total).toBe(order.subTotal + 1000); expect(order.totalWithTax).toBe(order.subTotalWithTax + 1200); assertOrderTotalsAddUp(order); }); }); describe('promotions', () => { const alwaysTrueCondition = new PromotionCondition({ args: {}, code: 'always_true_condition', description: [{ languageCode: LanguageCode.en, value: '' }], check() { return true; }, }); const orderTotalCondition = new PromotionCondition({ args: { minimum: { type: 'int' } }, code: 'order_total_condition', description: [{ languageCode: LanguageCode.en, value: '' }], check(ctx, order, args) { const threshold = ctx.channel.pricesIncludeTax ? order.subTotalWithTax : order.subTotal; return args.minimum <= threshold; }, }); const fixedPriceItemAction = new PromotionItemAction({ code: 'fixed_price_item_action', description: [{ languageCode: LanguageCode.en, value: '' }], args: {}, execute(ctx, item) { return -item.unitPrice + 42; }, }); const fixedPriceOrderAction = new PromotionOrderAction({ code: 'fixed_price_order_action', description: [{ languageCode: LanguageCode.en, value: '' }], args: {}, execute(ctx, order) { return (ctx.channel.pricesIncludeTax ? -order.subTotalWithTax : -order.subTotal) + 420; }, }); const fixedDiscountOrderAction = new PromotionOrderAction({ code: 'fixed_discount_order_action', description: [{ languageCode: LanguageCode.en, value: '' }], args: {}, execute(ctx, order) { const discount = -500; return discount; }, }); const percentageItemAction = new PromotionItemAction({ code: 'percentage_item_action', description: [{ languageCode: LanguageCode.en, value: '' }], args: { discount: { type: 'int' } }, async execute(ctx, orderLine, args) { const unitPrice = ctx.channel.pricesIncludeTax ? orderLine.unitPriceWithTax : orderLine.unitPrice; return -unitPrice * (args.discount / 100); }, }); const percentageOrderAction = new PromotionOrderAction({ code: 'percentage_order_action', description: [{ languageCode: LanguageCode.en, value: '' }], args: { discount: { type: 'int' } }, execute(ctx, order, args) { const orderTotal = ctx.channel.pricesIncludeTax ? order.subTotalWithTax : order.subTotal; return -orderTotal * (args.discount / 100); }, }); const freeShippingAction = new PromotionShippingAction({ code: 'free_shipping', description: [{ languageCode: LanguageCode.en, value: 'Free shipping' }], args: {}, execute(ctx, shippingLine, order, args) { return ctx.channel.pricesIncludeTax ? -shippingLine.priceWithTax : -shippingLine.price; }, }); it('empty string couponCode does not prevent promotion being applied', async () => { const hasEmptyStringCouponCode = new Promotion({ id: 2, name: 'Has empty string couponCode', couponCode: '', conditions: [ { code: orderTotalCondition.code, args: [{ name: 'minimum', value: '10' }], }, ], promotionConditions: [orderTotalCondition], actions: [ { code: percentageOrderAction.code, args: [{ name: 'discount', value: '10' }], }, ], promotionActions: [percentageOrderAction], }); const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [hasEmptyStringCouponCode]); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe(hasEmptyStringCouponCode.name); }); describe('OrderItem-level discounts', () => { describe('percentage items discount', () => { const promotion = new Promotion({ id: 1, name: '50% off each item', conditions: [{ code: alwaysTrueCondition.code, args: [] }], promotionConditions: [alwaysTrueCondition], actions: [ { code: percentageItemAction.code, args: [{ name: 'discount', value: '50' }], }, ], promotionActions: [percentageItemAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 8333, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion], [order.lines[0]]); expect(order.subTotal).toBe(4167); expect(order.subTotalWithTax).toBe(5000); expect(order.lines[0].adjustments.length).toBe(1); expect(order.lines[0].adjustments[0].description).toBe('50% off each item'); expect(order.totalWithTax).toBe(5000); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 1400, taxCategory: taxCategoryStandard, quantity: 1, }, { listPrice: 650, taxCategory: taxCategoryReduced, quantity: 2, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion], [order.lines[0]]); expect(order.subTotal).toBe(1173); expect(order.subTotalWithTax).toBe(1350); expect(order.lines[0].adjustments.length).toBe(1); expect(order.lines[0].adjustments[0].description).toBe('50% off each item'); expect(order.totalWithTax).toBe(1350); assertOrderTotalsAddUp(order); }); }); }); describe('Order-level discounts', () => { describe('single line with order fixed price action', () => { const promotion = new Promotion({ id: 1, conditions: [{ code: alwaysTrueCondition.code, args: [] }], promotionConditions: [alwaysTrueCondition], actions: [{ code: fixedPriceOrderAction.code, args: [] }], promotionActions: [fixedPriceOrderAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1230, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(420); expect(order.totalWithTax).toBe(504); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 1230, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(350); expect(order.totalWithTax).toBe(420); assertOrderTotalsAddUp(order); }); }); describe('single line with order fixed discount action', () => { const promotion = new Promotion({ id: 1, conditions: [{ code: alwaysTrueCondition.code, args: [] }], promotionConditions: [alwaysTrueCondition], actions: [{ code: fixedDiscountOrderAction.code, args: [] }], promotionActions: [fixedDiscountOrderAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1230, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(730); expect(order.totalWithTax).toBe(876); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 2000, taxCategory: taxCategoryStandard, quantity: 1, }, { listPrice: 1000, taxCategory: taxCategoryReduced, quantity: 2, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.totalWithTax).toBe(3500); assertOrderTotalsAddUp(order); }); }); describe('condition based on order total', () => { const promotion = new Promotion({ id: 1, name: 'Test Promotion 1', conditions: [ { code: orderTotalCondition.code, args: [{ name: 'minimum', value: '1000' }], }, ], promotionConditions: [orderTotalCondition], actions: [{ code: fixedPriceOrderAction.code, args: [] }], promotionActions: [fixedPriceOrderAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 500, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(500); expect(order.subTotalWithTax).toBe(600); expect(order.discounts.length).toBe(0); // increase the quantity to 2, which will take the total over the minimum set by the // condition. order.lines[0].quantity = 2; await orderCalculator.applyPriceAdjustments(ctx, order, [promotion], [order.lines[0]]); expect(order.subTotalWithTax).toBe(504); // Now the fixedPriceOrderAction should be in effect expect(order.discounts.length).toBe(1); expect(order.total).toBe(420); expect(order.totalWithTax).toBe(504); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 500, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(417); expect(order.subTotalWithTax).toBe(500); expect(order.discounts.length).toBe(0); // increase the quantity to 2, which will take the total over the minimum set by the // condition. order.lines[0].quantity = 2; await orderCalculator.applyPriceAdjustments(ctx, order, [promotion], [order.lines[0]]); expect(order.subTotalWithTax).toBe(420); // Now the fixedPriceOrderAction should be in effect expect(order.discounts.length).toBe(1); expect(order.total).toBe(350); expect(order.totalWithTax).toBe(420); assertOrderTotalsAddUp(order); }); }); describe('percentage order discount', () => { const promotion = new Promotion({ id: 1, name: '50% off order', conditions: [{ code: alwaysTrueCondition.code, args: [] }], promotionConditions: [alwaysTrueCondition], actions: [ { code: percentageOrderAction.code, args: [{ name: 'discount', value: '50' }], }, ], promotionActions: [percentageOrderAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(50); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe('50% off order'); expect(order.totalWithTax).toBe(60); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(42); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe('50% off order'); expect(order.totalWithTax).toBe(50); assertOrderTotalsAddUp(order); }); it('prices include tax at 0%', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryZero, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(50); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe('50% off order'); expect(order.totalWithTax).toBe(50); assertOrderTotalsAddUp(order); }); }); it('correct proration', async () => { const promotion = new Promotion({ id: 1, name: '$5 off order', conditions: [{ code: alwaysTrueCondition.code, args: [] }], promotionConditions: [alwaysTrueCondition], actions: [ { code: fixedDiscountOrderAction.code, args: [], }, ], promotionActions: [fixedDiscountOrderAction], }); const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 500, taxCategory: taxCategoryStandard, quantity: 1, }, { listPrice: 500, taxCategory: taxCategoryZero, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotalWithTax).toBe(500); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe('$5 off order'); expect(order.lines[0].proratedLinePriceWithTax).toBe(250); expect(order.lines[1].proratedLinePriceWithTax).toBe(250); expect(order.totalWithTax).toBe(500); assertOrderTotalsAddUp(order); }); }); describe('Shipping-level discounts', () => { describe('free_shipping', () => { const couponCode = 'FREE_SHIPPING'; const promotion = new Promotion({ id: 1, name: 'Free shipping', couponCode, conditions: [], promotionConditions: [], actions: [ { code: freeShippingAction.code, args: [], }, ], promotionActions: [freeShippingAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.shippingLines = [ new ShippingLine({ shippingMethodId: mockShippingMethodId, adjustments: [], }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(100); expect(order.discounts.length).toBe(0); expect(order.total).toBe(order.subTotal + 500); assertOrderTotalsAddUp(order); order.couponCodes = [couponCode]; await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(100); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe('Free shipping'); expect(order.shipping).toBe(0); expect(order.shippingWithTax).toBe(0); expect(order.total).toBe(order.subTotal); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 100, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.shippingLines = [ new ShippingLine({ shippingMethodId: mockShippingMethodId, adjustments: [], }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(83); expect(order.discounts.length).toBe(0); expect(order.total).toBe(order.subTotal + 417); assertOrderTotalsAddUp(order); order.couponCodes = [couponCode]; await orderCalculator.applyPriceAdjustments(ctx, order, [promotion]); expect(order.subTotal).toBe(83); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe('Free shipping'); expect(order.shipping).toBe(0); expect(order.shippingWithTax).toBe(0); expect(order.total).toBe(order.subTotal); assertOrderTotalsAddUp(order); }); }); }); describe('interaction amongst promotion actions', () => { const orderQuantityCondition = new PromotionCondition({ args: { minimum: { type: 'int' } }, code: 'order_quantity_condition', description: [ { languageCode: LanguageCode.en, value: 'Passes if any order line has at least the minimum quantity', }, ], check(ctx, _order, args) { for (const line of _order.lines) { if (args.minimum <= line.quantity) { return true; } } return false; }, }); const buy3Get50pcOffOrder = new Promotion({ id: 1, name: 'Buy 3 Get 50% off order', conditions: [ { code: orderQuantityCondition.code, args: [{ name: 'minimum', value: '3' }], }, ], promotionConditions: [orderQuantityCondition], actions: [ { code: percentageOrderAction.code, args: [{ name: 'discount', value: '50' }], }, ], promotionActions: [percentageOrderAction], }); const spend1000Get10pcOffOrder = new Promotion({ id: 2, name: 'Spend $10 Get 10% off order', conditions: [ { code: orderTotalCondition.code, args: [{ name: 'minimum', value: '1000' }], }, ], promotionConditions: [orderTotalCondition], actions: [ { code: percentageOrderAction.code, args: [{ name: 'discount', value: '10' }], }, ], promotionActions: [percentageOrderAction], }); it('two order-level percentage discounts, one invalidates the other', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 500, taxCategory: taxCategoryStandard, quantity: 2, }, ], }); // initially the order is $100, so the second promotion applies await orderCalculator.applyPriceAdjustments(ctx, order, [ buy3Get50pcOffOrder, spend1000Get10pcOffOrder, ]); expect(order.subTotal).toBe(900); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe(spend1000Get10pcOffOrder.name); expect(order.totalWithTax).toBe(1080); assertOrderTotalsAddUp(order); // increase the quantity to 3, which will trigger the first promotion and thus // bring the order total below the threshold for the second promotion. order.lines[0].quantity = 3; await orderCalculator.applyPriceAdjustments( ctx, order, [buy3Get50pcOffOrder, spend1000Get10pcOffOrder], [order.lines[0]], ); expect(order.discounts.length).toBe(1); expect(order.subTotal).toBe(750); expect(order.discounts[0].description).toBe(buy3Get50pcOffOrder.name); expect(order.totalWithTax).toBe(900); assertOrderTotalsAddUp(order); }); describe('two order-level percentage discounts at the same time', () => { it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 800, taxCategory: taxCategoryStandard, quantity: 2, }, ], }); // initially the order is over $10, so the second promotion applies await orderCalculator.applyPriceAdjustments(ctx, order, [ buy3Get50pcOffOrder, spend1000Get10pcOffOrder, ]); expect(order.subTotal).toBe(1440); expect(order.discounts.length).toBe(1); expect(order.discounts[0].description).toBe(spend1000Get10pcOffOrder.name); expect(order.totalWithTax).toBe(1728); assertOrderTotalsAddUp(order); // increase the quantity to 3, which will trigger both promotions order.lines[0].quantity = 3; await orderCalculator.applyPriceAdjustments( ctx, order, [buy3Get50pcOffOrder, spend1000Get10pcOffOrder], [order.lines[0]], ); expect(order.subTotal).toBe(1080); expect(order.discounts.length).toBe(2); expect(order.totalWithTax).toBe(1296); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 800, taxCategory: taxCategoryStandard, quantity: 3, }, ], }); await orderCalculator.applyPriceAdjustments( ctx, order, [buy3Get50pcOffOrder, spend1000Get10pcOffOrder], [order.lines[0]], ); expect(order.subTotal).toBe(900); expect(order.discounts.length).toBe(2); expect(order.totalWithTax).toBe(1080); assertOrderTotalsAddUp(order); }); }); describe('item-level & order-level percentage discounts', () => { const orderPromo = new Promotion({ id: 1, name: '10% off order', couponCode: 'ORDER10', conditions: [], promotionConditions: [], actions: [ { code: percentageOrderAction.code, args: [{ name: 'discount', value: '10' }], }, ], promotionActions: [percentageOrderAction], }); const itemPromo = new Promotion({ id: 2, name: '10% off item', couponCode: 'ITEM10', conditions: [], promotionConditions: [], actions: [ { code: percentageItemAction.code, args: [{ name: 'discount', value: '10' }], }, ], promotionActions: [percentageItemAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 155880, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [orderPromo, itemPromo]); // Apply the item-level discount order.couponCodes.push('ITEM10'); await orderCalculator.applyPriceAdjustments(ctx, order, [orderPromo, itemPromo]); expect(order.subTotal).toBe(140292); expect(order.subTotalWithTax).toBe(168350); assertOrderTotalsAddUp(order); // Apply the order-level discount order.couponCodes.push('ORDER10'); await orderCalculator.applyPriceAdjustments(ctx, order, [orderPromo, itemPromo]); expect(order.subTotal).toBe(126263); expect(order.subTotalWithTax).toBe(151516); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 155880, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, [orderPromo, itemPromo]); // Apply the item-level discount order.couponCodes.push('ITEM10'); await orderCalculator.applyPriceAdjustments(ctx, order, [orderPromo, itemPromo]); expect(order.subTotal).toBe(116910); expect(order.subTotalWithTax).toBe(140292); assertOrderTotalsAddUp(order); // Apply the order-level discount order.couponCodes.push('ORDER10'); await orderCalculator.applyPriceAdjustments(ctx, order, [orderPromo, itemPromo]); expect(order.subTotal).toBe(105219); expect(order.subTotalWithTax).toBe(126263); assertOrderTotalsAddUp(order); }); }); // This is the "final boss" of the tests :D describe('item-level & order-level mixed discounts with multiple tax rates', () => { const fifteenPcOff$10ItemsAction = new PromotionItemAction({ code: 'percentage_item_action', description: [{ languageCode: LanguageCode.en, value: '' }], args: { discount: { type: 'int' } }, async execute(ctx, orderLine, args) { if (orderLine.listPrice === 1000) { const unitPrice = ctx.channel.pricesIncludeTax ? orderLine.unitPriceWithTax : orderLine.unitPrice; return -unitPrice * (15 / 100); } return 0; }, }); const $5OffOrderPromo = new Promotion({ id: 2, name: '$5 off order', couponCode: 'PROMO1', conditions: [], promotionConditions: [], actions: [ { code: fixedDiscountOrderAction.code, args: [], }, ], promotionActions: [fixedDiscountOrderAction], }); const fifteenPcOff$10Items = new Promotion({ id: 3, name: '15% off item', couponCode: 'PROMO2', conditions: [], promotionConditions: [], actions: [ { code: fifteenPcOff$10ItemsAction.code, args: [], }, ], promotionActions: [fifteenPcOff$10ItemsAction], }); it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, { listPrice: 255, taxCategory: taxCategoryReduced, quantity: 4, }, ], }); order.couponCodes.push('PROMO1', 'PROMO2'); await orderCalculator.applyPriceAdjustments(ctx, order, [ fifteenPcOff$10Items, $5OffOrderPromo, ]); expect(order.subTotal).toBe(5719); expect(order.subTotalWithTax).toBe(6448); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, { listPrice: 255, taxCategory: taxCategoryReduced, quantity: 4, }, ], }); order.couponCodes.push('PROMO1', 'PROMO2'); await orderCalculator.applyPriceAdjustments(ctx, order, [ fifteenPcOff$10Items, $5OffOrderPromo, ]); // console.table([ // { // unitPrice: order.lines[0].unitPrice, // linePrice: order.lines[0].linePrice, // linePriceWithTax: order.lines[0].linePriceWithTax, // discountedLinePrice: order.lines[0].discountedLinePrice, // discountedLinePriceWithTax: order.lines[0].discountedLinePriceWithTax, // proratedUnitPriceWithTax: order.lines[0].proratedUnitPriceWithTax, // proratedLinePriceWithTax: order.lines[0].proratedLinePriceWithTax, // }, // { // unitPrice: order.lines[1].unitPrice, // linePrice: order.lines[1].linePrice, // linePriceWithTax: order.lines[1].linePriceWithTax, // discountedLinePrice: order.lines[1].discountedLinePrice, // discountedLinePriceWithTax: order.lines[1].discountedLinePriceWithTax, // proratedUnitPriceWithTax: order.lines[1].proratedUnitPriceWithTax, // proratedLinePriceWithTax: order.lines[1].proratedLinePriceWithTax, // }, // { // unitPrice: order.lines[2].unitPrice, // linePrice: order.lines[2].linePrice, // linePriceWithTax: order.lines[2].linePriceWithTax, // discountedLinePrice: order.lines[2].discountedLinePrice, // discountedLinePriceWithTax: order.lines[2].discountedLinePriceWithTax, // proratedUnitPriceWithTax: order.lines[2].proratedUnitPriceWithTax, // proratedLinePriceWithTax: order.lines[2].proratedLinePriceWithTax, // }, // ]); // Note: This combination produces slight discrepancies when using the rounding method // of the DefaultMoneyStrategy - i.e. "round then multiply". When using a strategy // of "multiply then round", we would expect the following: // ``` // expect(order.subTotal).toBe(5082); // expect(order.subTotalWithTax).toBe(5719); // assertOrderTotalsAddUp(order); // ``` // However, there is always a tradeoff when using integer precision with compounding // fractional multiplication. expect(order.subTotal).toBe(5079); expect(order.subTotalWithTax).toBe(5722); }); }); }); }); describe('surcharges', () => { describe('positive surcharge without tax', () => { it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'payment surcharge', listPrice: 240, listPriceIncludesTax: false, taxLines: [], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(5739); expect(order.subTotalWithTax).toBe(6489); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'payment surcharge', listPrice: 240, listPriceIncludesTax: true, taxLines: [], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(5087); expect(order.subTotalWithTax).toBe(5739); assertOrderTotalsAddUp(order); }); }); describe('positive surcharge with tax', () => { it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'payment surcharge', listPrice: 240, listPriceIncludesTax: false, taxLines: [ { description: 'standard tax', taxRate: 20, }, ], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(1240); expect(order.subTotalWithTax).toBe(1488); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'payment surcharge', listPrice: 240, listPriceIncludesTax: true, taxLines: [ { description: 'standard tax', taxRate: 20, }, ], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(1033); expect(order.subTotalWithTax).toBe(1240); assertOrderTotalsAddUp(order); }); }); describe('negative surcharge with tax', () => { it('prices exclude tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'custom discount', listPrice: -240, listPriceIncludesTax: false, taxLines: [ { description: 'standard tax', taxRate: 20, }, ], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(760); expect(order.subTotalWithTax).toBe(912); assertOrderTotalsAddUp(order); }); it('prices include tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: true }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'custom discount', listPrice: -240, listPriceIncludesTax: true, taxLines: [ { description: 'standard tax', taxRate: 20, }, ], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(633); expect(order.subTotalWithTax).toBe(760); assertOrderTotalsAddUp(order); }); it('prices exclude tax but surcharge includes tax', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 1, }, ], }); order.surcharges = [ new Surcharge({ description: 'custom discount', listPrice: -240, listPriceIncludesTax: true, taxLines: [ { description: 'standard tax', taxRate: 20, }, ], sku: 'PSC', }), ]; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(800); expect(order.subTotalWithTax).toBe(960); assertOrderTotalsAddUp(order); }); }); }); }); describe('OrderCalculator with custom TaxLineCalculationStrategy', () => { let orderCalculator: OrderCalculator; const newYorkStateTaxLine: TaxLine = { description: 'New York state sales tax', taxRate: 4, }; const nycCityTaxLine: TaxLine = { description: 'NYC sales tax', taxRate: 4.5, }; /** * This strategy uses a completely custom method of calculation based on the Order * shipping address, potentially adding multiple TaxLines. This is intended to simulate * tax handling as in the US where multiple tax rates can apply based on location data. */ class CustomTaxLineCalculationStrategy implements TaxLineCalculationStrategy { calculate(args: CalculateTaxLinesArgs): Promise<TaxLine[]> { const { order } = args; const taxLines: TaxLine[] = []; if (order.shippingAddress?.province === 'New York') { taxLines.push(newYorkStateTaxLine); if (order.shippingAddress?.city === 'New York City') { taxLines.push(nycCityTaxLine); } } // Return a promise to simulate having called out to // and external tax API return Promise.resolve(taxLines); } } beforeAll(async () => { const module = await createTestModule(); orderCalculator = module.get(OrderCalculator); const mockConfigService = module.get<ConfigService, MockConfigService>(ConfigService); mockConfigService.taxOptions = { taxZoneStrategy: new DefaultTaxZoneStrategy(), taxLineCalculationStrategy: new CustomTaxLineCalculationStrategy(), }; }); it('no TaxLines applied', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, ], }); await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(5499); expect(order.subTotalWithTax).toBe(5499); expect(order.taxSummary).toEqual([]); expect(order.lines[0].taxLines).toEqual([]); expect(order.lines[1].taxLines).toEqual([]); assertOrderTotalsAddUp(order); }); it('single TaxLines applied', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, ], }); order.shippingAddress = { city: 'Rochester', province: 'New York', }; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(5499); expect(order.subTotalWithTax).toBe(5719); expect(order.taxSummary).toEqual([ { description: newYorkStateTaxLine.description, taxRate: newYorkStateTaxLine.taxRate, taxBase: 5499, taxTotal: 220, }, ]); expect(order.lines[0].taxLines).toEqual([newYorkStateTaxLine]); expect(order.lines[1].taxLines).toEqual([newYorkStateTaxLine]); assertOrderTotalsAddUp(order); }); it('multiple TaxLines applied', async () => { const ctx = createRequestContext({ pricesIncludeTax: false }); const order = createOrder({ ctx, lines: [ { listPrice: 1000, taxCategory: taxCategoryStandard, quantity: 2, }, { listPrice: 3499, taxCategory: taxCategoryReduced, quantity: 1, }, ], }); order.shippingAddress = { city: 'New York City', province: 'New York', }; await orderCalculator.applyPriceAdjustments(ctx, order, []); expect(order.subTotal).toBe(5499); expect(order.subTotalWithTax).toBe(5966); expect(order.taxSummary).toEqual([ { description: newYorkStateTaxLine.description, taxRate: newYorkStateTaxLine.taxRate, taxBase: 5499, taxTotal: 220, }, { description: nycCityTaxLine.description, taxRate: nycCityTaxLine.taxRate, taxBase: 5499, taxTotal: 247, }, ]); expect(order.lines[0].taxLines).toEqual([newYorkStateTaxLine, nycCityTaxLine]); expect(order.lines[1].taxLines).toEqual([newYorkStateTaxLine, nycCityTaxLine]); assertOrderTotalsAddUp(order); }); }); function createTestModule() { return Test.createTestingModule({ providers: [ OrderCalculator, RequestContextCacheService, { provide: TaxRateService, useClass: MockTaxRateService }, { provide: ShippingCalculator, useValue: { getEligibleShippingMethods: () => [] } }, { provide: ShippingMethodService, useValue: { findOne: (ctx: RequestContext) => ({ id: mockShippingMethodId, test: () => true, apply() { return { price: 500, priceIncludesTax: ctx.channel.pricesIncludeTax, taxRate: 20, }; }, }), }, }, { provide: ListQueryBuilder, useValue: {} }, { provide: ConfigService, useClass: MockConfigService }, { provide: EventBus, useValue: { publish: () => ({}) } }, { provide: ZoneService, useValue: { getAllWithMembers: () => [] } }, ], }).compile(); } /** * Make sure that the properties which will be displayed to the customer add up in a consistent way. */ function assertOrderTotalsAddUp(order: Order) { for (const line of order.lines) { const pricesIncludeTax = line.listPriceIncludesTax; if (pricesIncludeTax) { const lineDiscountsAmountWithTaxSum = summate(line.discounts, 'amountWithTax'); expect(line.linePriceWithTax + lineDiscountsAmountWithTaxSum).toBe(line.proratedLinePriceWithTax); } else { const lineDiscountsAmountSum = summate(line.discounts, 'amount'); expect(line.linePrice + lineDiscountsAmountSum).toBe(line.proratedLinePrice); } } const taxableLinePriceSum = summate(order.lines, 'proratedLinePrice'); const surchargeSum = summate(order.surcharges, 'price'); expect(order.subTotal).toBe(taxableLinePriceSum + surchargeSum); // Make sure the customer-facing totals also add up const displayPriceWithTaxSum = summate(order.lines, 'discountedLinePriceWithTax'); const surchargeWithTaxSum = summate(order.surcharges, 'priceWithTax'); const orderDiscountsSum = order.discounts .filter(d => d.type === AdjustmentType.DISTRIBUTED_ORDER_PROMOTION) .reduce((sum, d) => sum + d.amount, 0); const orderDiscountsWithTaxSum = order.discounts .filter(d => d.type === AdjustmentType.DISTRIBUTED_ORDER_PROMOTION) .reduce((sum, d) => sum + d.amountWithTax, 0); // The sum of the display prices + order discounts should in theory exactly // equal the subTotalWithTax. In practice, there are occasionally 1cent differences // cause by rounding errors. This should be tolerable. const differenceBetweenSumAndActual = Math.abs( displayPriceWithTaxSum + orderDiscountsWithTaxSum + surchargeWithTaxSum - order.subTotalWithTax, ); expect(differenceBetweenSumAndActual).toBeLessThanOrEqual(1); }
import { Injectable } from '@nestjs/common'; import { filterAsync } from '@vendure/common/lib/filter-async'; import { AdjustmentType } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../../api/common/request-context'; import { RequestContextCacheService } from '../../../cache/request-context-cache.service'; import { CacheKey } from '../../../common/constants'; import { InternalServerError } from '../../../common/error/errors'; import { idsAreEqual } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { OrderLine, TaxCategory, TaxRate } from '../../../entity'; import { Order } from '../../../entity/order/order.entity'; import { Promotion } from '../../../entity/promotion/promotion.entity'; import { Zone } from '../../../entity/zone/zone.entity'; import { ShippingMethodService } from '../../services/shipping-method.service'; import { TaxRateService } from '../../services/tax-rate.service'; import { ZoneService } from '../../services/zone.service'; import { ShippingCalculator } from '../shipping-calculator/shipping-calculator'; import { prorate } from './prorate'; /** * @description * This helper is used when making changes to an Order, to apply all applicable price adjustments to that Order, * including: * * - Promotions * - Taxes * - Shipping * * @docsCategory service-helpers */ @Injectable() export class OrderCalculator { constructor( private configService: ConfigService, private zoneService: ZoneService, private taxRateService: TaxRateService, private shippingMethodService: ShippingMethodService, private shippingCalculator: ShippingCalculator, private requestContextCache: RequestContextCacheService, ) {} /** * @description * Applies taxes and promotions to an Order. Mutates the order object. * Returns an array of any OrderItems which had new adjustments * applied, either tax or promotions. */ async applyPriceAdjustments( ctx: RequestContext, order: Order, promotions: Promotion[], updatedOrderLines: OrderLine[] = [], options?: { recalculateShipping?: boolean }, ): Promise<Order> { const { taxZoneStrategy } = this.configService.taxOptions; // We reset the promotions array as all promotions // must be revalidated on any changes to an Order. order.promotions = []; const zones = await this.zoneService.getAllWithMembers(ctx); const activeTaxZone = await this.requestContextCache.get(ctx, CacheKey.ActiveTaxZone, () => taxZoneStrategy.determineTaxZone(ctx, zones, ctx.channel, order), ); let taxZoneChanged = false; if (!activeTaxZone) { throw new InternalServerError('error.no-active-tax-zone'); } if (!order.taxZoneId || !idsAreEqual(order.taxZoneId, activeTaxZone.id)) { order.taxZoneId = activeTaxZone.id; taxZoneChanged = true; } for (const updatedOrderLine of updatedOrderLines) { await this.applyTaxesToOrderLine( ctx, order, updatedOrderLine, activeTaxZone, this.createTaxRateGetter(ctx, activeTaxZone), ); } this.calculateOrderTotals(order); if (order.lines.length) { if (taxZoneChanged) { // First apply taxes to the non-discounted prices await this.applyTaxes(ctx, order, activeTaxZone); } // Then test and apply promotions const totalBeforePromotions = order.subTotal; await this.applyPromotions(ctx, order, promotions); // itemsModifiedByPromotions.forEach(item => updatedOrderItems.add(item)); if (order.subTotal !== totalBeforePromotions) { // Finally, re-calculate taxes because the promotions may have // altered the unit prices, which in turn will alter the tax payable. await this.applyTaxes(ctx, order, activeTaxZone); } } if (options?.recalculateShipping !== false) { await this.applyShipping(ctx, order); await this.applyShippingPromotions(ctx, order, promotions); } this.calculateOrderTotals(order); return order; } /** * @description * Applies the correct TaxRate to each OrderLine in the order. */ private async applyTaxes(ctx: RequestContext, order: Order, activeZone: Zone) { const getTaxRate = this.createTaxRateGetter(ctx, activeZone); for (const line of order.lines) { await this.applyTaxesToOrderLine(ctx, order, line, activeZone, getTaxRate); } this.calculateOrderTotals(order); } /** * @description * Applies the correct TaxRate to an OrderLine */ private async applyTaxesToOrderLine( ctx: RequestContext, order: Order, line: OrderLine, activeZone: Zone, getTaxRate: (taxCategory: TaxCategory) => Promise<TaxRate>, ) { const applicableTaxRate = await getTaxRate(line.taxCategory); const { taxLineCalculationStrategy } = this.configService.taxOptions; line.taxLines = await taxLineCalculationStrategy.calculate({ ctx, applicableTaxRate, order, orderLine: line, }); } /** * @description * Returns a memoized function for performing an efficient * lookup of the correct TaxRate for a given TaxCategory. */ private createTaxRateGetter( ctx: RequestContext, activeZone: Zone, ): (taxCategory: TaxCategory) => Promise<TaxRate> { const taxRateCache = new Map<TaxCategory, TaxRate>(); return async (taxCategory: TaxCategory): Promise<TaxRate> => { const cached = taxRateCache.get(taxCategory); if (cached) { return cached; } const rate = await this.taxRateService.getApplicableTaxRate(ctx, activeZone, taxCategory); taxRateCache.set(taxCategory, rate); return rate; }; } /** * @description * Applies any eligible promotions to each OrderLine in the order. */ private async applyPromotions(ctx: RequestContext, order: Order, promotions: Promotion[]): Promise<void> { await this.applyOrderItemPromotions(ctx, order, promotions); await this.applyOrderPromotions(ctx, order, promotions); return; } /** * @description * Applies promotions to OrderItems. This is a quite complex function, due to the inherent complexity * of applying the promotions, and also due to added complexity in the name of performance * optimization. Therefore, it is heavily annotated so that the purpose of each step is clear. */ private async applyOrderItemPromotions( ctx: RequestContext, order: Order, promotions: Promotion[], ): Promise<void> { for (const line of order.lines) { // Must be re-calculated for each line, since the previous lines may have triggered promotions // which affected the order price. const applicablePromotions = await filterAsync(promotions, p => p.test(ctx, order).then(Boolean)); line.clearAdjustments(); for (const promotion of applicablePromotions) { let priceAdjusted = false; // We need to test the promotion *again*, even though we've tested them for the line. // This is because the previous Promotions may have adjusted the Order in such a way // as to render later promotions no longer applicable. const applicableOrState = await promotion.test(ctx, order); if (applicableOrState) { const state = typeof applicableOrState === 'object' ? applicableOrState : undefined; // for (const item of line.items) { const adjustment = await promotion.apply(ctx, { orderLine: line }, state); if (adjustment) { adjustment.amount = adjustment.amount * line.quantity; line.addAdjustment(adjustment); priceAdjusted = true; } if (priceAdjusted) { this.calculateOrderTotals(order); priceAdjusted = false; } this.addPromotion(order, promotion); } } this.calculateOrderTotals(order); } return; } private async applyOrderPromotions( ctx: RequestContext, order: Order, promotions: Promotion[], ): Promise<void> { // const updatedItems = new Set<OrderItem>(); const orderHasDistributedPromotions = !!order.discounts.find( adjustment => adjustment.type === AdjustmentType.DISTRIBUTED_ORDER_PROMOTION, ); if (orderHasDistributedPromotions) { // If the Order currently has any Order-level discounts applied, we need to // mark all OrderItems in the Order as "updated", since one or more of those // Order-level discounts may become invalid, which will require _all_ OrderItems // to be saved. order.lines.forEach(line => { line.clearAdjustments(AdjustmentType.DISTRIBUTED_ORDER_PROMOTION); }); } this.calculateOrderTotals(order); const applicableOrderPromotions = await filterAsync(promotions, p => p.test(ctx, order).then(Boolean), ); if (applicableOrderPromotions.length) { for (const promotion of applicableOrderPromotions) { // re-test the promotion on each iteration, since the order total // may be modified by a previously-applied promotion const applicableOrState = await promotion.test(ctx, order); if (applicableOrState) { const state = typeof applicableOrState === 'object' ? applicableOrState : undefined; const adjustment = await promotion.apply(ctx, { order }, state); if (adjustment && adjustment.amount !== 0) { const amount = adjustment.amount; const weights = order.lines .filter(l => l.quantity !== 0) .map(l => l.proratedLinePriceWithTax); const distribution = prorate(weights, amount); order.lines.forEach((line, i) => { const shareOfAmount = distribution[i]; const itemWeights = Array.from({ length: line.quantity, }).map(() => line.unitPrice); const itemDistribution = prorate(itemWeights, shareOfAmount); line.addAdjustment({ amount: shareOfAmount, adjustmentSource: adjustment.adjustmentSource, description: adjustment.description, type: AdjustmentType.DISTRIBUTED_ORDER_PROMOTION, data: { itemDistribution }, }); }); this.calculateOrderTotals(order); } this.addPromotion(order, promotion); } } this.calculateOrderTotals(order); } return; } private async applyShippingPromotions(ctx: RequestContext, order: Order, promotions: Promotion[]) { const applicableOrderPromotions = await filterAsync(promotions, p => p.test(ctx, order).then(Boolean), ); if (applicableOrderPromotions.length) { order.shippingLines.forEach(line => line.clearAdjustments()); for (const promotion of applicableOrderPromotions) { // re-test the promotion on each iteration, since the order total // may be modified by a previously-applied promotion const applicableOrState = await promotion.test(ctx, order); if (applicableOrState) { const state = typeof applicableOrState === 'object' ? applicableOrState : undefined; for (const shippingLine of order.shippingLines) { const adjustment = await promotion.apply(ctx, { shippingLine, order }, state); if (adjustment && adjustment.amount !== 0) { shippingLine.addAdjustment(adjustment); } } this.addPromotion(order, promotion); } } } else { // If there is no applicable promotion for shipping, // we should remove already assigned adjustment from shipping lines. for (const shippingLine of order.shippingLines) { shippingLine.clearAdjustments(); } } } private async applyShipping(ctx: RequestContext, order: Order) { // First we need to remove any ShippingLines which are no longer applicable // to the Order, i.e. there is no OrderLine which is assigned to the ShippingLine's // ShippingMethod. const orderLineShippingLineIds = order.lines.map(line => line.shippingLineId); order.shippingLines = order.shippingLines.filter(shippingLine => orderLineShippingLineIds.includes(shippingLine.id), ); for (const shippingLine of order.shippingLines) { const currentShippingMethod = shippingLine?.shippingMethodId && (await this.shippingMethodService.findOne(ctx, shippingLine.shippingMethodId)); if (!currentShippingMethod) { return; } const currentMethodStillEligible = await currentShippingMethod.test(ctx, order); if (currentMethodStillEligible) { const result = await currentShippingMethod.apply(ctx, order); if (result) { shippingLine.listPrice = result.price; shippingLine.listPriceIncludesTax = result.priceIncludesTax; shippingLine.taxLines = [ { description: 'shipping tax', taxRate: result.taxRate, }, ]; } continue; } const results = await this.shippingCalculator.getEligibleShippingMethods(ctx, order, [ currentShippingMethod.id, ]); if (results && results.length) { const cheapest = results[0]; shippingLine.listPrice = cheapest.result.price; shippingLine.listPriceIncludesTax = cheapest.result.priceIncludesTax; shippingLine.shippingMethod = cheapest.method; shippingLine.shippingMethodId = cheapest.method.id; shippingLine.taxLines = [ { description: 'shipping tax', taxRate: cheapest.result.taxRate, }, ]; } else { order.shippingLines = order.shippingLines.filter(sl => sl !== shippingLine); } } } /** * @description * Sets the totals properties on an Order by summing each OrderLine, and taking * into account any Surcharges and ShippingLines. Does not save the Order, so * the entity must be persisted to the DB after calling this method. * * Note that this method does *not* evaluate any taxes or promotions. It assumes * that has already been done and is solely responsible for summing the * totals. */ public calculateOrderTotals(order: Order) { let totalPrice = 0; let totalPriceWithTax = 0; for (const line of order.lines) { totalPrice += line.proratedLinePrice; totalPriceWithTax += line.proratedLinePriceWithTax; } for (const surcharge of order.surcharges) { totalPrice += surcharge.price; totalPriceWithTax += surcharge.priceWithTax; } order.subTotal = totalPrice; order.subTotalWithTax = totalPriceWithTax; let shippingPrice = 0; let shippingPriceWithTax = 0; for (const shippingLine of order.shippingLines) { shippingPrice += shippingLine.discountedPrice; shippingPriceWithTax += shippingLine.discountedPriceWithTax; } order.shipping = shippingPrice; order.shippingWithTax = shippingPriceWithTax; } private addPromotion(order: Order, promotion: Promotion) { if (order.promotions && !order.promotions.find(p => idsAreEqual(p.id, promotion.id))) { order.promotions.push(promotion); } } }
import { describe, expect, it } from 'vitest'; import { prorate } from './prorate'; describe('prorate()', () => { function testProrate(weights: number[], total: number, expected: number[]) { expect(prorate(weights, total)).toEqual(expected); expect(expected.reduce((a, b) => a + b, 0)).toBe(total); } it('single weight', () => { testProrate([123], 300, [300]); }); it('distributes positive integer', () => { testProrate([4000, 2000, 2000], 300, [150, 75, 75]); }); it('distributes negative integer', () => { testProrate([4000, 2000, 2000], -300, [-150, -75, -75]); }); it('handles non-neatly divisible total', () => { testProrate([4300, 1400, 2300], 299, [161, 52, 86]); }); it('distributes over equal weights', () => { testProrate([1000, 1000, 1000], 299, [100, 100, 99]); }); it('many weights', () => { testProrate([10, 20, 10, 30, 50, 20, 10, 40], 95, [5, 10, 5, 15, 25, 10, 5, 20]); }); it('many weights non-neatly divisible', () => { testProrate([10, 20, 10, 30, 50, 20, 10, 40], 93, [5, 10, 5, 15, 24, 10, 5, 19]); }); it('weights include zero', () => { testProrate([10, 0], 40, [40, 0]); }); it('all weights are zero', () => { testProrate([0, 0], 10, [5, 5]); }); it('all weights are zero with zero total', () => { testProrate([0, 0], 0, [0, 0]); }); it('amount is negative', () => { testProrate([100, 100], -20, [-10, -10]); }); });
/** * @description * "Prorate" means "to divide, distribute, or calculate proportionately." * * This function is used to distribute the `total` into parts proportional * to the `distribution` array. This is required to split up an Order-level * discount between OrderLines, and then between OrderItems in the line. * * Based on https://stackoverflow.com/a/12844927/772859 */ export function prorate(weights: number[], amount: number): number[] { const totalWeight = weights.reduce((total, val) => total + val, 0); const length = weights.length; const actual: number[] = []; const error: number[] = []; const rounded: number[] = []; let added = 0; let i = 0; for (const w of weights) { actual[i] = totalWeight === 0 ? amount / weights.length : amount * (w / totalWeight); rounded[i] = Math.floor(actual[i]); error[i] = actual[i] - rounded[i]; added += rounded[i]; i += 1; } while (added < amount) { let maxError = 0.0; let maxErrorIndex = -1; for (let e = 0; e < length; ++e) { if (error[e] > maxError) { maxError = error[e]; maxErrorIndex = e; } } rounded[maxErrorIndex] += 1; error[maxErrorIndex] -= 1; added += 1; } return rounded; }
import { Test } from '@nestjs/testing'; import { beforeEach, describe, expect, it } from 'vitest'; import { RequestContext } from '../../../api/common/request-context'; import { ConfigService } from '../../../config/config.service'; import { MockConfigService } from '../../../config/config.service.mock'; import { MergeOrdersStrategy } from '../../../config/order/merge-orders-strategy'; import { Order } from '../../../entity/order/order.entity'; import { createOrderFromLines } from '../../../testing/order-test-utils'; import { OrderMerger } from './order-merger'; describe('OrderMerger', () => { let orderMerger: OrderMerger; const ctx = RequestContext.empty(); describe('MergeOrdersStrategy', () => { beforeEach(async () => { const module = await Test.createTestingModule({ providers: [OrderMerger, { provide: ConfigService, useClass: MockConfigService }], }).compile(); const mockConfigService = module.get<ConfigService, MockConfigService>(ConfigService); mockConfigService.orderOptions = { mergeStrategy: new MergeOrdersStrategy(), }; orderMerger = module.get(OrderMerger); }); it('both orders undefined', () => { const guestOrder = new Order({ lines: [] }); const existingOrder = new Order({ lines: [] }); const result = orderMerger.merge(ctx); expect(result.order).toBeUndefined(); expect(result.linesToInsert).toBeUndefined(); expect(result.linesToModify).toBeUndefined(); expect(result.linesToDelete).toBeUndefined(); expect(result.orderToDelete).toBeUndefined(); }); it('guestOrder undefined', () => { const existingOrder = createOrderFromLines([{ lineId: 1, quantity: 2, productVariantId: 100 }]); const result = orderMerger.merge(ctx, undefined, existingOrder); expect(result.order).toBe(existingOrder); expect(result.linesToInsert).toBeUndefined(); expect(result.linesToModify).toBeUndefined(); expect(result.linesToDelete).toBeUndefined(); expect(result.orderToDelete).toBeUndefined(); }); it('existingOrder undefined', () => { const guestOrder = createOrderFromLines([{ lineId: 1, quantity: 2, productVariantId: 100 }]); const result = orderMerger.merge(ctx, guestOrder, undefined); expect(result.order).toBe(guestOrder); expect(result.linesToInsert).toBeUndefined(); expect(result.linesToModify).toBeUndefined(); expect(result.linesToDelete).toBeUndefined(); expect(result.orderToDelete).toBeUndefined(); }); it('empty guestOrder', () => { const guestOrder = createOrderFromLines([]); guestOrder.id = 42; const existingOrder = createOrderFromLines([{ lineId: 1, quantity: 2, productVariantId: 100 }]); const result = orderMerger.merge(ctx, guestOrder, existingOrder); expect(result.order).toBe(existingOrder); expect(result.linesToInsert).toBeUndefined(); expect(result.linesToModify).toBeUndefined(); expect(result.linesToDelete).toBeUndefined(); expect(result.orderToDelete).toBe(guestOrder); }); it('empty existingOrder', () => { const guestOrder = createOrderFromLines([{ lineId: 1, quantity: 2, productVariantId: 100 }]); const existingOrder = createOrderFromLines([]); existingOrder.id = 42; const result = orderMerger.merge(ctx, guestOrder, existingOrder); expect(result.order).toBe(guestOrder); expect(result.linesToInsert).toBeUndefined(); expect(result.linesToModify).toBeUndefined(); expect(result.linesToDelete).toBeUndefined(); expect(result.orderToDelete).toBe(existingOrder); }); it('new lines added by merge', () => { const guestOrder = createOrderFromLines([{ lineId: 20, quantity: 2, productVariantId: 200 }]); guestOrder.id = 42; const existingOrder = createOrderFromLines([{ lineId: 1, quantity: 2, productVariantId: 100 }]); const result = orderMerger.merge(ctx, guestOrder, existingOrder); expect(result.order).toBe(existingOrder); expect(result.linesToInsert).toEqual([{ productVariantId: 200, quantity: 2 }]); expect(result.linesToModify).toEqual([]); expect(result.linesToDelete).toEqual([]); expect(result.orderToDelete).toBe(guestOrder); }); it('guest quantity replaces existing quantity', () => { const guestOrder = createOrderFromLines([{ lineId: 20, quantity: 2, productVariantId: 100 }]); guestOrder.id = 42; const existingOrder = createOrderFromLines([{ lineId: 1, quantity: 4, productVariantId: 100 }]); const result = orderMerger.merge(ctx, guestOrder, existingOrder); expect(result.order).toBe(existingOrder); expect(result.linesToInsert).toEqual([]); expect(result.linesToModify).toEqual([{ orderLineId: 1, quantity: 2 }]); expect(result.linesToDelete).toEqual([]); expect(result.orderToDelete).toBe(guestOrder); }); it('takes customFields into account', () => { const guestOrder = createOrderFromLines([ { lineId: 20, quantity: 2, productVariantId: 200, customFields: { foo: 'bar' } }, ]); guestOrder.id = 42; const existingOrder = createOrderFromLines([{ lineId: 1, quantity: 2, productVariantId: 100 }]); const result = orderMerger.merge(ctx, guestOrder, existingOrder); expect(result.order).toBe(existingOrder); expect(result.linesToInsert).toEqual([ { productVariantId: 200, quantity: 2, customFields: { foo: 'bar' } }, ]); expect(result.orderToDelete).toBe(guestOrder); }); }); });
import { Injectable } from '@nestjs/common'; import { ID } from '@vendure/common/lib/shared-types'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { RequestContext } from '../../../api/common/request-context'; import { idsAreEqual } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { MergedOrderLine } from '../../../config/order/order-merge-strategy'; import { Order } from '../../../entity/order/order.entity'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; export type OrderWithNoLines = Order & { lines: undefined }; export type OrderWithEmptyLines = Order & { lines: ArrayLike<OrderLine> & { length: 0 } }; export type EmptyOrder = OrderWithEmptyLines | OrderWithNoLines; export type MergeResult = { order?: Order; linesToInsert?: Array<{ productVariantId: ID; quantity: number; customFields?: any }>; linesToModify?: Array<{ orderLineId: ID; quantity: number; customFields?: any }>; linesToDelete?: Array<{ orderLineId: ID }>; orderToDelete?: Order; }; @Injectable() export class OrderMerger { constructor(private configService: ConfigService) {} /** * Applies the configured OrderMergeStrategy to the supplied guestOrder and existingOrder. Returns an object * containing entities which then need to be persisted to the database by the OrderService methods. */ merge(ctx: RequestContext, guestOrder?: Order, existingOrder?: Order): MergeResult { if (guestOrder && !this.orderEmpty(guestOrder) && existingOrder && !this.orderEmpty(existingOrder)) { const { mergeStrategy } = this.configService.orderOptions; const mergedLines = mergeStrategy.merge(ctx, guestOrder, existingOrder); return { order: existingOrder, linesToInsert: this.getLinesToInsert(guestOrder, existingOrder, mergedLines), linesToModify: this.getLinesToModify(guestOrder, existingOrder, mergedLines), linesToDelete: this.getLinesToDelete(guestOrder, existingOrder, mergedLines), orderToDelete: guestOrder, }; } else if ( guestOrder && !this.orderEmpty(guestOrder) && (!existingOrder || (existingOrder && this.orderEmpty(existingOrder))) ) { return { order: guestOrder, orderToDelete: existingOrder, }; } else { return { order: existingOrder, orderToDelete: guestOrder, }; } } private getLinesToInsert( guestOrder: Order, existingOrder: Order, mergedLines: MergedOrderLine[], ): Array<{ productVariantId: ID; quantity: number; customFields?: any }> { return guestOrder.lines .map(guestLine => { const mergedLine = mergedLines.find(ml => idsAreEqual(ml.orderLineId, guestLine.id)); if (!mergedLine) { return; } return { productVariantId: guestLine.productVariant.id, quantity: mergedLine.quantity, customFields: mergedLine.customFields, }; }) .filter(notNullOrUndefined); } private getLinesToModify( guestOrder: Order, existingOrder: Order, mergedLines: MergedOrderLine[], ): Array<{ orderLineId: ID; quantity: number; customFields?: any }> { return existingOrder.lines .map(existingLine => { const mergedLine = mergedLines.find(ml => idsAreEqual(ml.orderLineId, existingLine.id)); if (!mergedLine) { return; } const lineIsModified = mergedLine.quantity !== existingLine.quantity || JSON.stringify(mergedLine.customFields) !== JSON.stringify(existingLine.customFields); if (!lineIsModified) { return; } return { orderLineId: mergedLine.orderLineId, quantity: mergedLine.quantity, customFields: mergedLine.customFields, }; }) .filter(notNullOrUndefined); } private getLinesToDelete( guestOrder: Order, existingOrder: Order, mergedLines: MergedOrderLine[], ): Array<{ orderLineId: ID }> { return existingOrder.lines .filter(existingLine => !mergedLines.find(ml => idsAreEqual(ml.orderLineId, existingLine.id))) .map(existingLine => ({ orderLineId: existingLine.id })); } private orderEmpty(order: Order | EmptyOrder): order is EmptyOrder { return !order || !order.lines || !order.lines.length; } }
import { Injectable } from '@nestjs/common'; import { AdjustmentType, CancelOrderInput, HistoryEntryType, ModifyOrderInput, ModifyOrderResult, OrderLineInput, RefundOrderInput, } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { getGraphQlInputName, summate } from '@vendure/common/lib/shared-utils'; import { RequestContext } from '../../../api/common/request-context'; import { isGraphQlErrorResult, JustErrorResults } from '../../../common/error/error-result'; import { EntityNotFoundError, InternalServerError, UserInputError } from '../../../common/error/errors'; import { CancelActiveOrderError, CouponCodeExpiredError, CouponCodeInvalidError, CouponCodeLimitError, EmptyOrderLineSelectionError, MultipleOrderError, NoChangesSpecifiedError, OrderModificationStateError, QuantityTooGreatError, RefundPaymentIdMissingError, } from '../../../common/error/generated-graphql-admin-errors'; import { IneligibleShippingMethodError, InsufficientStockError, NegativeQuantityError, OrderLimitError, } from '../../../common/error/generated-graphql-shop-errors'; import { idsAreEqual } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { CustomFieldConfig } from '../../../config/custom-field/custom-field-types'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { VendureEntity } from '../../../entity/base/base.entity'; import { Order } from '../../../entity/order/order.entity'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; import { FulfillmentLine } from '../../../entity/order-line-reference/fulfillment-line.entity'; import { OrderModificationLine } from '../../../entity/order-line-reference/order-modification-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 { ShippingLine } from '../../../entity/shipping-line/shipping-line.entity'; import { Allocation } from '../../../entity/stock-movement/allocation.entity'; import { Cancellation } from '../../../entity/stock-movement/cancellation.entity'; import { Release } from '../../../entity/stock-movement/release.entity'; import { Sale } from '../../../entity/stock-movement/sale.entity'; import { Surcharge } from '../../../entity/surcharge/surcharge.entity'; import { EventBus } from '../../../event-bus/event-bus'; import { OrderLineEvent } from '../../../event-bus/events/order-line-event'; import { CountryService } from '../../services/country.service'; import { HistoryService } from '../../services/history.service'; import { PaymentService } from '../../services/payment.service'; import { ProductVariantService } from '../../services/product-variant.service'; import { PromotionService } from '../../services/promotion.service'; import { StockMovementService } from '../../services/stock-movement.service'; import { CustomFieldRelationService } from '../custom-field-relation/custom-field-relation.service'; import { OrderCalculator } from '../order-calculator/order-calculator'; import { ShippingCalculator } from '../shipping-calculator/shipping-calculator'; import { TranslatorService } from '../translator/translator.service'; import { getOrdersFromLines, orderLinesAreAllCancelled } from '../utils/order-utils'; import { patchEntity } from '../utils/patch-entity'; /** * @description * This helper is responsible for modifying the contents of an Order. * * Note: * There is not a clear separation of concerns between the OrderService and this, since * the OrderService also contains some method which modify the Order (e.g. removeItemFromOrder). * So this helper was mainly extracted to isolate the huge `modifyOrder` method since the * OrderService was just growing too large. Future refactoring could improve the organization * of these Order-related methods into a more clearly-delineated set of classes. * * @docsCategory service-helpers */ @Injectable() export class OrderModifier { constructor( private connection: TransactionalConnection, private configService: ConfigService, private orderCalculator: OrderCalculator, private paymentService: PaymentService, private countryService: CountryService, private stockMovementService: StockMovementService, private productVariantService: ProductVariantService, private customFieldRelationService: CustomFieldRelationService, private promotionService: PromotionService, private eventBus: EventBus, private shippingCalculator: ShippingCalculator, private historyService: HistoryService, private translator: TranslatorService, ) {} /** * @description * Ensure that the ProductVariant has sufficient saleable stock to add the given * quantity to an Order. * * - `existingOrderLineQuantity` is used when adding an item to the order, since if an OrderLine * already exists then we will be adding the new quantity to the existing quantity. * - `quantityInOtherOrderLines` is used when we have more than 1 OrderLine containing the same * ProductVariant. This occurs when there are custom fields defined on the OrderLine and the lines * have differing values for one or more custom fields. In this case, we need to take _all_ of these * OrderLines into account when constraining the quantity. See https://github.com/vendure-ecommerce/vendure/issues/2702 * for more on this. */ async constrainQuantityToSaleable( ctx: RequestContext, variant: ProductVariant, quantity: number, existingOrderLineQuantity = 0, quantityInOtherOrderLines = 0, ) { let correctedQuantity = quantity + existingOrderLineQuantity; const saleableStockLevel = await this.productVariantService.getSaleableStockLevel(ctx, variant); if (saleableStockLevel < correctedQuantity + quantityInOtherOrderLines) { correctedQuantity = Math.max( saleableStockLevel - existingOrderLineQuantity - quantityInOtherOrderLines, 0, ); } return correctedQuantity; } /** * @description * Given a ProductVariant ID and optional custom fields, this method will return an existing OrderLine that * matches, or `undefined` if no match is found. */ async getExistingOrderLine( ctx: RequestContext, order: Order, productVariantId: ID, customFields?: { [key: string]: any }, ): Promise<OrderLine | undefined> { for (const line of order.lines) { const match = idsAreEqual(line.productVariant.id, productVariantId) && (await this.customFieldsAreEqual(ctx, line, customFields, line.customFields)); if (match) { return line; } } } /** * @description * Returns the OrderLine containing the given {@link ProductVariant}, taking into account any custom field values. If no existing * OrderLine is found, a new OrderLine will be created. */ async getOrCreateOrderLine( ctx: RequestContext, order: Order, productVariantId: ID, customFields?: { [key: string]: any }, ) { const existingOrderLine = await this.getExistingOrderLine(ctx, order, productVariantId, customFields); if (existingOrderLine) { return existingOrderLine; } const productVariant = await this.getProductVariantOrThrow(ctx, productVariantId); const orderLine = await this.connection.getRepository(ctx, OrderLine).save( new OrderLine({ productVariant, taxCategory: productVariant.taxCategory, featuredAsset: productVariant.featuredAsset ?? productVariant.product.featuredAsset, listPrice: productVariant.listPrice, listPriceIncludesTax: productVariant.listPriceIncludesTax, adjustments: [], taxLines: [], customFields, quantity: 0, }), ); const { orderSellerStrategy } = this.configService.orderOptions; if (typeof orderSellerStrategy.setOrderLineSellerChannel === 'function') { orderLine.sellerChannel = await orderSellerStrategy.setOrderLineSellerChannel(ctx, orderLine); await this.connection .getRepository(ctx, OrderLine) .createQueryBuilder() .relation('sellerChannel') .of(orderLine) .set(orderLine.sellerChannel); } await this.customFieldRelationService.updateRelations(ctx, OrderLine, { customFields }, orderLine); const lineWithRelations = await this.connection.getEntityOrThrow(ctx, OrderLine, orderLine.id, { relations: [ 'taxCategory', 'productVariant', 'productVariant.productVariantPrices', 'productVariant.taxCategory', ], }); lineWithRelations.productVariant = this.translator.translate( await this.productVariantService.applyChannelPriceAndTax( lineWithRelations.productVariant, ctx, order, ), ctx, ); order.lines.push(lineWithRelations); await this.connection.getRepository(ctx, Order).save(order, { reload: false }); await this.eventBus.publish(new OrderLineEvent(ctx, order, lineWithRelations, 'created')); return lineWithRelations; } /** * @description * Updates the quantity of an OrderLine, taking into account the available saleable stock level. * Returns the actual quantity that the OrderLine was updated to (which may be less than the * `quantity` argument if insufficient stock was available. */ async updateOrderLineQuantity( ctx: RequestContext, orderLine: OrderLine, quantity: number, order: Order, ): Promise<OrderLine> { const currentQuantity = orderLine.quantity; orderLine.quantity = quantity; if (currentQuantity < quantity) { if (!order.active && order.state !== 'Draft') { await this.stockMovementService.createAllocationsForOrderLines(ctx, [ { orderLineId: orderLine.id, quantity: quantity - currentQuantity, }, ]); } } else if (quantity < currentQuantity) { if (!order.active && order.state !== 'Draft') { // When an Order is not active (i.e. Customer checked out), then we don't want to just // delete the OrderItems - instead we will cancel them // const toSetAsCancelled = orderLine.items.filter(i => !i.cancelled).slice(quantity); // const fulfilledItems = toSetAsCancelled.filter(i => !!i.fulfillment); // const allocatedItems = toSetAsCancelled.filter(i => !i.fulfillment); await this.stockMovementService.createCancellationsForOrderLines(ctx, [ { orderLineId: orderLine.id, quantity }, ]); await this.stockMovementService.createReleasesForOrderLines(ctx, [ { orderLineId: orderLine.id, quantity }, ]); } } await this.connection.getRepository(ctx, OrderLine).save(orderLine); await this.eventBus.publish(new OrderLineEvent(ctx, order, orderLine, 'updated')); return orderLine; } async cancelOrderByOrderLines( ctx: RequestContext, input: CancelOrderInput, lineInputs: OrderLineInput[], ) { if (lineInputs.length === 0 || summate(lineInputs, 'quantity') === 0) { return new EmptyOrderLineSelectionError(); } const orders = await getOrdersFromLines(ctx, this.connection, lineInputs); if (1 < orders.length) { return new MultipleOrderError(); } const order = orders[0]; if (!idsAreEqual(order.id, input.orderId)) { return new MultipleOrderError(); } if (order.active) { return new CancelActiveOrderError({ orderState: order.state }); } const fullOrder = await this.connection.getEntityOrThrow(ctx, Order, order.id, { relations: ['lines'], }); const allocatedLines: OrderLineInput[] = []; const fulfilledLines: OrderLineInput[] = []; for (const lineInput of lineInputs) { const orderLine = fullOrder.lines.find(l => idsAreEqual(l.id, lineInput.orderLineId)); if (orderLine && orderLine.quantity < lineInput.quantity) { return new QuantityTooGreatError(); } const allocationsForLine = await this.connection .getRepository(ctx, Allocation) .createQueryBuilder('allocation') .leftJoinAndSelect('allocation.orderLine', 'orderLine') .where('orderLine.id = :orderLineId', { orderLineId: lineInput.orderLineId }) .getMany(); const salesForLine = await this.connection .getRepository(ctx, Sale) .createQueryBuilder('sale') .leftJoinAndSelect('sale.orderLine', 'orderLine') .where('orderLine.id = :orderLineId', { orderLineId: lineInput.orderLineId }) .getMany(); const releasesForLine = await this.connection .getRepository(ctx, Release) .createQueryBuilder('release') .leftJoinAndSelect('release.orderLine', 'orderLine') .where('orderLine.id = :orderLineId', { orderLineId: lineInput.orderLineId }) .getMany(); const totalAllocated = summate(allocationsForLine, 'quantity') + summate(salesForLine, 'quantity') - summate(releasesForLine, 'quantity'); if (0 < totalAllocated) { allocatedLines.push({ orderLineId: lineInput.orderLineId, quantity: Math.min(totalAllocated, lineInput.quantity), }); } const fulfillmentsForLine = await this.connection .getRepository(ctx, FulfillmentLine) .createQueryBuilder('fulfillmentLine') .leftJoinAndSelect('fulfillmentLine.orderLine', 'orderLine') .where('orderLine.id = :orderLineId', { orderLineId: lineInput.orderLineId }) .getMany(); const cancellationsForLine = await this.connection .getRepository(ctx, Cancellation) .createQueryBuilder('cancellation') .leftJoinAndSelect('cancellation.orderLine', 'orderLine') .where('orderLine.id = :orderLineId', { orderLineId: lineInput.orderLineId }) .getMany(); const totalFulfilled = summate(fulfillmentsForLine, 'quantity') - summate(cancellationsForLine, 'quantity'); if (0 < totalFulfilled) { fulfilledLines.push({ orderLineId: lineInput.orderLineId, quantity: Math.min(totalFulfilled, lineInput.quantity), }); } } await this.stockMovementService.createCancellationsForOrderLines(ctx, fulfilledLines); await this.stockMovementService.createReleasesForOrderLines(ctx, allocatedLines); for (const line of lineInputs) { const orderLine = fullOrder.lines.find(l => idsAreEqual(l.id, line.orderLineId)); if (orderLine) { await this.connection.getRepository(ctx, OrderLine).update(line.orderLineId, { quantity: orderLine.quantity - line.quantity, }); } } const orderWithLines = await this.connection.getEntityOrThrow(ctx, Order, order.id, { relations: ['lines', 'surcharges', 'shippingLines'], }); if (input.cancelShipping === true) { for (const shippingLine of orderWithLines.shippingLines) { shippingLine.adjustments.push({ adjustmentSource: 'CANCEL_ORDER', type: AdjustmentType.OTHER, description: 'shipping cancellation', amount: -shippingLine.discountedPriceWithTax, data: {}, }); await this.connection.getRepository(ctx, ShippingLine).save(shippingLine, { reload: false }); } } // Update totals after cancellation this.orderCalculator.calculateOrderTotals(orderWithLines); await this.connection.getRepository(ctx, Order).save(orderWithLines, { reload: false }); await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: HistoryEntryType.ORDER_CANCELLATION, data: { lines: lineInputs, reason: input.reason || undefined, shippingCancelled: !!input.cancelShipping, }, }); return orderLinesAreAllCancelled(orderWithLines); } async modifyOrder( ctx: RequestContext, input: ModifyOrderInput, order: Order, ): Promise<JustErrorResults<ModifyOrderResult> | { order: Order; modification: OrderModification }> { const { dryRun } = input; const modification = new OrderModification({ order, note: input.note || '', lines: [], surcharges: [], }); const initialTotalWithTax = order.totalWithTax; const initialShippingWithTax = order.shippingWithTax; if (order.state !== 'Modifying') { return new OrderModificationStateError(); } if (this.noChangesSpecified(input)) { return new NoChangesSpecifiedError(); } const { orderItemsLimit } = this.configService.orderOptions; let currentItemsCount = summate(order.lines, 'quantity'); const updatedOrderLineIds: ID[] = []; const refundInputArray = Array.isArray(input.refunds) ? input.refunds : input.refund ? [input.refund] : []; const refundInputs: RefundOrderInput[] = refundInputArray.map(refund => ({ lines: [], adjustment: 0, shipping: 0, paymentId: refund.paymentId, amount: refund.amount, reason: refund.reason || input.note, })); for (const row of input.addItems ?? []) { const { productVariantId, quantity } = row; if (quantity < 0) { return new NegativeQuantityError(); } const customFields = (row as any).customFields || {}; const orderLine = await this.getOrCreateOrderLine(ctx, order, productVariantId, customFields); const correctedQuantity = await this.constrainQuantityToSaleable( ctx, orderLine.productVariant, quantity, ); if (orderItemsLimit < currentItemsCount + correctedQuantity) { return new OrderLimitError({ maxItems: orderItemsLimit }); } else { currentItemsCount += correctedQuantity; } if (correctedQuantity < quantity) { return new InsufficientStockError({ quantityAvailable: correctedQuantity, order }); } updatedOrderLineIds.push(orderLine.id); const initialQuantity = orderLine.quantity; await this.updateOrderLineQuantity(ctx, orderLine, initialQuantity + correctedQuantity, order); const orderModificationLine = await this.connection .getRepository(ctx, OrderModificationLine) .save(new OrderModificationLine({ orderLine, quantity: quantity - initialQuantity })); modification.lines.push(orderModificationLine); } for (const row of input.adjustOrderLines ?? []) { const { orderLineId, quantity } = row; if (quantity < 0) { return new NegativeQuantityError(); } const orderLine = order.lines.find(line => idsAreEqual(line.id, orderLineId)); if (!orderLine) { throw new UserInputError('error.order-does-not-contain-line-with-id', { id: orderLineId }); } const initialLineQuantity = orderLine.quantity; let correctedQuantity = quantity; if (initialLineQuantity < quantity) { const additionalQuantity = await this.constrainQuantityToSaleable( ctx, orderLine.productVariant, quantity - initialLineQuantity, ); correctedQuantity = initialLineQuantity + additionalQuantity; } const resultingOrderTotalQuantity = currentItemsCount + correctedQuantity - orderLine.quantity; if (orderItemsLimit < resultingOrderTotalQuantity) { return new OrderLimitError({ maxItems: orderItemsLimit }); } else { currentItemsCount += correctedQuantity; } if (correctedQuantity < quantity) { return new InsufficientStockError({ quantityAvailable: correctedQuantity, order }); } else { const customFields = (row as any).customFields; if (customFields) { patchEntity(orderLine, { customFields }); } if (quantity < initialLineQuantity) { const cancelLinesInput = [ { orderLineId, quantity: initialLineQuantity - quantity, }, ]; await this.cancelOrderByOrderLines(ctx, { orderId: order.id }, cancelLinesInput); orderLine.quantity = quantity; } else { await this.updateOrderLineQuantity(ctx, orderLine, quantity, order); } const orderModificationLine = await this.connection .getRepository(ctx, OrderModificationLine) .save(new OrderModificationLine({ orderLine, quantity: quantity - initialLineQuantity })); modification.lines.push(orderModificationLine); if (correctedQuantity < initialLineQuantity) { const qtyDelta = initialLineQuantity - correctedQuantity; refundInputs.forEach(ri => { ri.lines.push({ orderLineId: orderLine.id, quantity: qtyDelta, }); }); } } updatedOrderLineIds.push(orderLine.id); } for (const surchargeInput of input.surcharges ?? []) { const taxLines = surchargeInput.taxRate != null ? [ { taxRate: surchargeInput.taxRate, description: surchargeInput.taxDescription || '', }, ] : []; const surcharge = await this.connection.getRepository(ctx, Surcharge).save( new Surcharge({ sku: surchargeInput.sku || '', description: surchargeInput.description, listPrice: surchargeInput.price, listPriceIncludesTax: surchargeInput.priceIncludesTax, taxLines, order, }), ); order.surcharges.push(surcharge); modification.surcharges.push(surcharge); if (surcharge.priceWithTax < 0) { refundInputs.forEach(ri => (ri.adjustment += Math.abs(surcharge.priceWithTax))); } } if (input.surcharges?.length) { await this.connection.getRepository(ctx, Order).save(order, { reload: false }); } if (input.updateShippingAddress) { order.shippingAddress = { ...order.shippingAddress, ...input.updateShippingAddress, }; if (input.updateShippingAddress.countryCode) { const country = await this.countryService.findOneByCode( ctx, input.updateShippingAddress.countryCode, ); order.shippingAddress.country = country.name; } await this.connection.getRepository(ctx, Order).save(order, { reload: false }); modification.shippingAddressChange = input.updateShippingAddress; } if (input.updateBillingAddress) { order.billingAddress = { ...order.billingAddress, ...input.updateBillingAddress, }; if (input.updateBillingAddress.countryCode) { const country = await this.countryService.findOneByCode( ctx, input.updateBillingAddress.countryCode, ); order.billingAddress.country = country.name; } await this.connection.getRepository(ctx, Order).save(order, { reload: false }); modification.billingAddressChange = input.updateBillingAddress; } if (input.couponCodes) { for (const couponCode of input.couponCodes) { const validationResult = await this.promotionService.validateCouponCode( ctx, couponCode, order.customer && order.customer.id, ); if (isGraphQlErrorResult(validationResult)) { return validationResult as | CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError; } if (!order.couponCodes.includes(couponCode)) { // This is a new coupon code that hadn't been applied before await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: HistoryEntryType.ORDER_COUPON_APPLIED, data: { couponCode, promotionId: validationResult.id }, }); } } for (const existingCouponCode of order.couponCodes) { if (!input.couponCodes.includes(existingCouponCode)) { // An existing coupon code has been removed await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: HistoryEntryType.ORDER_COUPON_REMOVED, data: { couponCode: existingCouponCode }, }); } } order.couponCodes = input.couponCodes; } const updatedOrderLines = order.lines.filter(l => updatedOrderLineIds.includes(l.id)); const promotions = await this.promotionService.getActivePromotionsInChannel(ctx); const activePromotionsPre = await this.promotionService.getActivePromotionsOnOrder(ctx, order.id); if (input.shippingMethodIds) { const result = await this.setShippingMethods(ctx, order, input.shippingMethodIds); if (isGraphQlErrorResult(result)) { return result; } } await this.orderCalculator.applyPriceAdjustments(ctx, order, promotions, updatedOrderLines, { recalculateShipping: input.options?.recalculateShipping, }); await this.connection.getRepository(ctx, OrderLine).save(order.lines, { reload: false }); const orderCustomFields = (input as any).customFields; if (orderCustomFields) { patchEntity(order, { customFields: orderCustomFields }); } await this.promotionService.runPromotionSideEffects(ctx, order, activePromotionsPre); if (dryRun) { return { order, modification }; } // Create the actual modification and commit all changes const newTotalWithTax = order.totalWithTax; const delta = newTotalWithTax - initialTotalWithTax; if (delta < 0) { if (refundInputs.length === 0) { return new RefundPaymentIdMissingError(); } // If there are multiple refunds, we select the largest one as the // "primary" refund to associate with the OrderModification. const primaryRefund = refundInputs.slice().sort((a, b) => (b.amount || 0) - (a.amount || 0))[0]; // TODO: the following code can be removed once we remove the deprecated // support for "shipping" and "adjustment" input fields for refunds const shippingDelta = order.shippingWithTax - initialShippingWithTax; if (shippingDelta < 0) { primaryRefund.shipping = shippingDelta * -1; } primaryRefund.adjustment += await this.calculateRefundAdjustment(ctx, delta, primaryRefund); // end for (const refundInput of refundInputs) { const existingPayments = await this.getOrderPayments(ctx, order.id); const payment = existingPayments.find(p => idsAreEqual(p.id, refundInput.paymentId)); if (payment) { const refund = await this.paymentService.createRefund(ctx, refundInput, order, payment); if (!isGraphQlErrorResult(refund)) { if (idsAreEqual(payment.id, primaryRefund.paymentId)) { modification.refund = refund; } } else { throw new InternalServerError(refund.message); } } } } modification.priceChange = delta; const createdModification = await this.connection .getRepository(ctx, OrderModification) .save(modification); await this.connection.getRepository(ctx, Order).save(order); await this.connection.getRepository(ctx, ShippingLine).save(order.shippingLines, { reload: false }); return { order, modification: createdModification }; } async setShippingMethods(ctx: RequestContext, order: Order, shippingMethodIds: ID[]) { for (const [i, shippingMethodId] of shippingMethodIds.entries()) { const shippingMethod = await this.shippingCalculator.getMethodIfEligible( ctx, order, shippingMethodId, ); if (!shippingMethod) { return new IneligibleShippingMethodError(); } let shippingLine: ShippingLine | undefined = order.shippingLines[i]; if (shippingLine) { shippingLine.shippingMethod = shippingMethod; shippingLine.shippingMethodId = shippingMethod.id; } else { shippingLine = await this.connection.getRepository(ctx, ShippingLine).save( new ShippingLine({ shippingMethod, order, adjustments: [], listPrice: 0, listPriceIncludesTax: ctx.channel.pricesIncludeTax, taxLines: [], }), ); if (order.shippingLines) { order.shippingLines.push(shippingLine); } else { order.shippingLines = [shippingLine]; } } await this.connection.getRepository(ctx, ShippingLine).save(shippingLine); } // remove any now-unused ShippingLines if (shippingMethodIds.length < order.shippingLines.length) { const shippingLinesToDelete = order.shippingLines.splice(shippingMethodIds.length - 1); await this.connection.getRepository(ctx, ShippingLine).remove(shippingLinesToDelete); } // assign the ShippingLines to the OrderLines await this.connection .getRepository(ctx, OrderLine) .createQueryBuilder('line') .update({ shippingLine: undefined }) .whereInIds(order.lines.map(l => l.id)) .execute(); const { shippingLineAssignmentStrategy } = this.configService.shippingOptions; for (const shippingLine of order.shippingLines) { const orderLinesForShippingLine = await shippingLineAssignmentStrategy.assignShippingLineToOrderLines(ctx, shippingLine, order); await this.connection .getRepository(ctx, OrderLine) .createQueryBuilder('line') .update({ shippingLineId: shippingLine.id }) .whereInIds(orderLinesForShippingLine.map(l => l.id)) .execute(); orderLinesForShippingLine.forEach(line => { line.shippingLine = shippingLine; }); } return order; } private noChangesSpecified(input: ModifyOrderInput): boolean { const noChanges = !input.adjustOrderLines?.length && !input.addItems?.length && !input.surcharges?.length && !input.updateShippingAddress && !input.updateBillingAddress && !input.couponCodes && !(input as any).customFields && (!input.shippingMethodIds || input.shippingMethodIds.length === 0); return noChanges; } /** * @description * Because a Refund's amount is calculated based on the orderItems changed, plus shipping change, * we need to make sure the amount gets adjusted to match any changes caused by other factors, * i.e. promotions that were previously active but are no longer. * * TODO: Deprecated - can be removed once we remove support for the "shipping" & "adjustment" input * fields for refunds. */ private async calculateRefundAdjustment( ctx: RequestContext, delta: number, refundInput: RefundOrderInput, ): Promise<number> { const existingAdjustment = refundInput.adjustment; let itemAmount = 0; // TODO: figure out what this should be for (const lineInput of refundInput.lines) { const orderLine = await this.connection.getEntityOrThrow(ctx, OrderLine, lineInput.orderLineId); itemAmount += orderLine.proratedUnitPriceWithTax * lineInput.quantity; } const calculatedDelta = itemAmount + refundInput.shipping + existingAdjustment; const absDelta = Math.abs(delta); return absDelta !== calculatedDelta ? absDelta - calculatedDelta : 0; } private getOrderPayments(ctx: RequestContext, orderId: ID): Promise<Payment[]> { return this.connection.getRepository(ctx, Payment).find({ relations: ['refunds'], where: { order: { id: orderId } as any, }, }); } private async customFieldsAreEqual( ctx: RequestContext, orderLine: OrderLine, inputCustomFields: { [key: string]: any } | null | undefined, existingCustomFields?: { [key: string]: any }, ): Promise<boolean> { const customFieldDefs = this.configService.customFields.OrderLine; if (inputCustomFields == null && typeof existingCustomFields === 'object') { // A null value for an OrderLine customFields input is the equivalent // of every property of an existing customFields object being null // or equal to the defaultValue for (const def of customFieldDefs) { const key = def.name; const existingValue = this.coerceValue(def, existingCustomFields); if (existingValue != null && (!def.list || existingValue?.length !== 0)) { if (def.defaultValue != null) { if (existingValue !== def.defaultValue) { return false; } } else { return false; } } } return true; } const customFieldRelations = customFieldDefs.filter(d => d.type === 'relation'); let lineWithCustomFieldRelations: OrderLine | undefined; if (customFieldRelations.length) { // for relation types, we need to actually query the DB and check if there is an // existing entity assigned. lineWithCustomFieldRelations = await this.connection .getRepository(ctx, OrderLine) .findOne({ where: { id: orderLine.id }, relations: customFieldRelations.map(r => `customFields.${r.name}`), }) .then(result => result ?? undefined); } for (const def of customFieldDefs) { const key = def.name; const existingValue = this.coerceValue(def, existingCustomFields); if (def.type !== 'relation' && existingValue !== undefined) { const valuesMatch = JSON.stringify(inputCustomFields?.[key]) === JSON.stringify(existingValue); const undefinedMatchesNull = existingValue === null && inputCustomFields?.[key] === undefined; const defaultValueMatch = inputCustomFields?.[key] === undefined && def.defaultValue === existingValue; if (!valuesMatch && !undefinedMatchesNull && !defaultValueMatch) { return false; } } else if (def.type === 'relation') { const inputId = getGraphQlInputName(def); const inputValue = inputCustomFields?.[inputId]; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const existingRelation = (lineWithCustomFieldRelations!.customFields as any)[key]; if (inputValue) { const customFieldNotEqual = def.list ? JSON.stringify((inputValue as ID[]).sort()) !== JSON.stringify( existingRelation?.map((relation: VendureEntity) => relation.id).sort(), ) : inputValue !== existingRelation?.id; if (customFieldNotEqual) { return false; } } } } return true; } /** * This function is required because with the MySQL driver, boolean customFields with a default * of `false` were being represented as `0`, thus causing the equality check to fail. * So if it's a boolean, we'll explicitly coerce the value to a boolean. */ private coerceValue(def: CustomFieldConfig, existingCustomFields: { [p: string]: any } | undefined) { const key = def.name; return def.type === 'boolean' && typeof existingCustomFields?.[key] === 'number' ? !!existingCustomFields?.[key] : existingCustomFields?.[key]; } private async getProductVariantOrThrow( ctx: RequestContext, productVariantId: ID, ): Promise<ProductVariant> { const productVariant = await this.productVariantService.findOne(ctx, productVariantId); if (!productVariant) { throw new EntityNotFoundError('ProductVariant', productVariantId); } return productVariant; } }
import { Injectable } from '@nestjs/common'; import { OrderType } from '@vendure/common/lib/generated-types'; import { pick } from '@vendure/common/lib/pick'; import { RequestContext } from '../../../api/common/request-context'; import { ConfigService } from '../../../config/config.service'; import { TransactionalConnection } from '../../../connection/transactional-connection'; 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 { ChannelService } from '../../services/channel.service'; import { OrderService } from '../../services/order.service'; @Injectable() export class OrderSplitter { constructor( private connection: TransactionalConnection, private configService: ConfigService, private channelService: ChannelService, private orderService: OrderService, ) {} async createSellerOrders(ctx: RequestContext, order: Order): Promise<Order[]> { const { orderSellerStrategy } = this.configService.orderOptions; const partialOrders = await orderSellerStrategy.splitOrder?.(ctx, order); if (!partialOrders || partialOrders.length === 0) { // No split is needed return []; } const defaultChannel = await this.channelService.getDefaultChannel(ctx); order.type = OrderType.Aggregate; const sellerOrders: Order[] = []; for (const partialOrder of partialOrders) { const lines: OrderLine[] = []; for (const line of partialOrder.lines) { lines.push(await this.duplicateOrderLine(ctx, line)); } const shippingLines: ShippingLine[] = []; for (const shippingLine of partialOrder.shippingLines) { const newShippingLine = await this.duplicateShippingLine(ctx, shippingLine); lines.map((line) => { if(shippingLine.id === line.shippingLineId) { line.shippingLineId = newShippingLine.id; } }) shippingLines.push(newShippingLine); } const sellerOrder = await this.connection.getRepository(ctx, Order).save( new Order({ type: OrderType.Seller, aggregateOrderId: order.id, code: await this.configService.orderOptions.orderCodeStrategy.generate(ctx), active: false, orderPlacedAt: new Date(), customer: order.customer, channels: [new Channel({ id: partialOrder.channelId }), defaultChannel], state: partialOrder.state, lines, surcharges: [], shippingLines, couponCodes: order.couponCodes, modifications: [], shippingAddress: order.shippingAddress, billingAddress: order.billingAddress, subTotal: 0, subTotalWithTax: 0, currencyCode: order.currencyCode, }), ); await this.connection .getRepository(ctx, Order) .createQueryBuilder() .relation('sellerOrders') .of(order) .add(sellerOrder); await this.orderService.applyPriceAdjustments(ctx, sellerOrder); sellerOrders.push(sellerOrder); } await orderSellerStrategy.afterSellerOrdersCreated?.(ctx, order, sellerOrders); return order.sellerOrders; } private async duplicateOrderLine(ctx: RequestContext, line: OrderLine): Promise<OrderLine> { const newLine = await this.connection.getRepository(ctx, OrderLine).save( new OrderLine({ ...pick(line, [ 'quantity', 'productVariant', 'taxCategory', 'featuredAsset', 'shippingLine', 'shippingLineId', 'customFields', 'sellerChannel', 'sellerChannelId', 'initialListPrice', 'listPrice', 'listPriceIncludesTax', 'adjustments', 'taxLines', 'orderPlacedQuantity', ]), }), ); return newLine; } private async duplicateShippingLine( ctx: RequestContext, shippingLine: ShippingLine, ): Promise<ShippingLine> { return await this.connection.getRepository(ctx, ShippingLine).save( new ShippingLine({ ...pick(shippingLine, [ 'shippingMethodId', 'order', 'listPrice', 'listPriceIncludesTax', 'adjustments', 'taxLines', ]), }), ); } }
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { IllegalOperationError } from '../../../common/error/errors'; import { FSM } from '../../../common/finite-state-machine/finite-state-machine'; import { mergeTransitionDefinitions } from '../../../common/finite-state-machine/merge-transition-definitions'; import { StateMachineConfig, Transitions } from '../../../common/finite-state-machine/types'; import { validateTransitionDefinition } from '../../../common/finite-state-machine/validate-transition-definition'; import { awaitPromiseOrObservable } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { Logger } from '../../../config/logger/vendure-logger'; import { Order } from '../../../entity/order/order.entity'; import { OrderState, OrderTransitionData } from './order-state'; @Injectable() export class OrderStateMachine { readonly config: StateMachineConfig<OrderState, OrderTransitionData>; private readonly initialState: OrderState = 'Created'; constructor(private configService: ConfigService) { this.config = this.initConfig(); } getInitialState(): OrderState { return this.initialState; } canTransition(currentState: OrderState, newState: OrderState): boolean { return new FSM(this.config, currentState).canTransitionTo(newState); } getNextStates(order: Order): readonly OrderState[] { const fsm = new FSM(this.config, order.state); return fsm.getNextStates(); } async transition(ctx: RequestContext, order: Order, state: OrderState) { const fsm = new FSM(this.config, order.state); const result = await fsm.transitionTo(state, { ctx, order }); order.state = fsm.currentState; return result; } private initConfig(): StateMachineConfig<OrderState, OrderTransitionData> { const orderProcesses = this.configService.orderOptions.process ?? []; const allTransitions = orderProcesses.reduce( (transitions, process) => mergeTransitionDefinitions(transitions, process.transitions as Transitions<any>), {} as Transitions<OrderState>, ); const validationResult = validateTransitionDefinition(allTransitions, this.initialState); if (!validationResult.valid && validationResult.error) { Logger.error(`The order process has an invalid configuration:`); throw new Error(validationResult.error); } if (validationResult.valid && validationResult.error) { Logger.warn(`Order process: ${validationResult.error}`); } return { transitions: allTransitions, onTransitionStart: async (fromState, toState, data) => { for (const process of orderProcesses) { if (typeof process.onTransitionStart === 'function') { const result = await awaitPromiseOrObservable( process.onTransitionStart(fromState, toState, data), ); if (result === false || typeof result === 'string') { return result; } } } }, onTransitionEnd: async (fromState, toState, data) => { for (const process of orderProcesses) { if (typeof process.onTransitionEnd === 'function') { await awaitPromiseOrObservable(process.onTransitionEnd(fromState, toState, data)); } } }, onError: async (fromState, toState, message) => { for (const process of orderProcesses) { if (typeof process.onTransitionError === 'function') { await awaitPromiseOrObservable( process.onTransitionError(fromState, toState, message), ); } } throw new IllegalOperationError(message || 'message.cannot-transition-order-from-to', { fromState, toState, }); }, }; } }
import { RequestContext } from '../../../api/common/request-context'; import { Order } from '../../../entity/order/order.entity'; /** * @description * An interface to extend standard {@link OrderState}. * * @docsCategory orders * @deprecated use OrderStates */ export interface CustomOrderStates {} /** * @description * An interface to extend the {@link OrderState} type. * * @docsCategory orders * @docsPage OrderProcess * @since 2.0.0 */ export interface OrderStates {} /** * @description * These are the default states of the Order process. They can be augmented and * modified by using the {@link OrderOptions} `process` property, and by default * the {@link defaultOrderProcess} will add the states * * - `ArrangingPayment` * - `PaymentAuthorized` * - `PaymentSettled` * - `PartiallyShipped` * - `Shipped` * - `PartiallyDelivered` * - `Delivered` * - `Modifying` * - `ArrangingAdditionalPayment` * * @docsCategory orders * @docsPage OrderProcess */ export type OrderState = | 'Created' | 'Draft' | 'AddingItems' | 'Cancelled' | keyof CustomOrderStates | keyof OrderStates; /** * @description * This is the object passed to the {@link OrderProcess} state transition hooks. * * @docsCategory orders * @docsPage OrderProcess */ export interface OrderTransitionData { ctx: RequestContext; order: Order; }
import { Injectable } from '@nestjs/common'; import { ConfigService } from '../../../config/config.service'; /** * @description * Used in the {@link NativeAuthenticationStrategy} when hashing and checking user passwords. */ @Injectable() export class PasswordCipher { constructor(private configService: ConfigService) {} hash(plaintext: string): Promise<string> { return this.configService.authOptions.passwordHashingStrategy.hash(plaintext); } check(plaintext: string, hash: string): Promise<boolean> { return this.configService.authOptions.passwordHashingStrategy.check(plaintext, hash); } }
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { IllegalOperationError } from '../../../common/error/errors'; import { FSM } from '../../../common/finite-state-machine/finite-state-machine'; import { mergeTransitionDefinitions } from '../../../common/finite-state-machine/merge-transition-definitions'; import { StateMachineConfig, Transitions } from '../../../common/finite-state-machine/types'; import { validateTransitionDefinition } from '../../../common/finite-state-machine/validate-transition-definition'; import { awaitPromiseOrObservable } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { Logger } from '../../../config/logger/vendure-logger'; import { Order } from '../../../entity/order/order.entity'; import { Payment } from '../../../entity/payment/payment.entity'; import { PaymentState, PaymentTransitionData } from './payment-state'; @Injectable() export class PaymentStateMachine { private readonly config: StateMachineConfig<PaymentState, PaymentTransitionData>; private readonly initialState: PaymentState = 'Created'; constructor(private configService: ConfigService) { this.config = this.initConfig(); } getInitialState(): PaymentState { return this.initialState; } canTransition(currentState: PaymentState, newState: PaymentState): boolean { return new FSM(this.config, currentState).canTransitionTo(newState); } getNextStates(payment: Payment): readonly PaymentState[] { const fsm = new FSM(this.config, payment.state); return fsm.getNextStates(); } async transition(ctx: RequestContext, order: Order, payment: Payment, state: PaymentState) { const fsm = new FSM(this.config, payment.state); const result = await fsm.transitionTo(state, { ctx, order, payment }); payment.state = state; return result; } private initConfig(): StateMachineConfig<PaymentState, PaymentTransitionData> { const { paymentMethodHandlers } = this.configService.paymentOptions; const customProcesses = this.configService.paymentOptions.customPaymentProcess ?? []; const processes = [...customProcesses, ...(this.configService.paymentOptions.process ?? [])]; const allTransitions = processes.reduce( (transitions, process) => mergeTransitionDefinitions(transitions, process.transitions as Transitions<any>), {} as Transitions<PaymentState>, ); const validationResult = validateTransitionDefinition(allTransitions, this.initialState); if (!validationResult.valid && validationResult.error) { Logger.error(`The payment process has an invalid configuration:`); throw new Error(validationResult.error); } if (validationResult.valid && validationResult.error) { Logger.warn(`Payment process: ${validationResult.error}`); } return { transitions: allTransitions, onTransitionStart: async (fromState, toState, data) => { for (const process of processes) { if (typeof process.onTransitionStart === 'function') { const result = await awaitPromiseOrObservable( process.onTransitionStart(fromState, toState, data), ); if (result === false || typeof result === 'string') { return result; } } } for (const handler of paymentMethodHandlers) { if (data.payment.method === handler.code) { const result = await awaitPromiseOrObservable( handler.onStateTransitionStart(fromState, toState, data), ); if (result !== true) { return result; } } } }, onTransitionEnd: async (fromState, toState, data) => { for (const process of processes) { if (typeof process.onTransitionEnd === 'function') { await awaitPromiseOrObservable(process.onTransitionEnd(fromState, toState, data)); } } }, onError: async (fromState, toState, message) => { for (const process of processes) { if (typeof process.onTransitionError === 'function') { await awaitPromiseOrObservable( process.onTransitionError(fromState, toState, message), ); } } throw new IllegalOperationError(message || 'error.cannot-transition-payment-from-to', { fromState, toState, }); }, }; } }
import { RequestContext } from '../../../api/common/request-context'; import { Order } from '../../../entity/order/order.entity'; import { Payment } from '../../../entity/payment/payment.entity'; /** * @description * An interface to extend standard {@link PaymentState}. * * @deprecated use PaymentStates */ export interface CustomPaymentStates {} /** * @description * An interface to extend standard {@link PaymentState}. * * @docsCategory payment */ export interface PaymentStates {} /** * @description * These are the default states of the payment process. * * @docsCategory payment */ export type PaymentState = | 'Created' | 'Error' | 'Cancelled' | keyof CustomPaymentStates | keyof PaymentStates; /** * @description * The data which is passed to the `onStateTransitionStart` function configured when constructing * a new `PaymentMethodHandler` * * @docsCategory payment */ export interface PaymentTransitionData { ctx: RequestContext; payment: Payment; order: Order; }
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { RequestContextCacheService } from '../../../cache/request-context-cache.service'; import { CacheKey } from '../../../common/constants'; import { InternalServerError } from '../../../common/error/errors'; import { ConfigService } from '../../../config/config.service'; import { Order } from '../../../entity/order/order.entity'; import { ProductVariant } from '../../../entity/product-variant/product-variant.entity'; import { TaxRateService } from '../../services/tax-rate.service'; import { ZoneService } from '../../services/zone.service'; /** * @description * This helper is used to apply the correct price to a ProductVariant based on the current context * including active Channel, any current Order, etc. If you use the {@link TransactionalConnection} to * directly query ProductVariants, you will find that the `price` and `priceWithTax` properties will * always be `0` until you use the `applyChannelPriceAndTax()` method: * * @example * ```ts * export class MyCustomService { * constructor(private connection: TransactionalConnection, * private productPriceApplicator: ProductPriceApplicator) {} * * getVariant(ctx: RequestContext, id: ID) { * const productVariant = await this.connection * .getRepository(ctx, ProductVariant) * .findOne(id, { relations: ['taxCategory'] }); * * await this.productPriceApplicator * .applyChannelPriceAndTax(productVariant, ctx); * * return productVariant; * } * } * ``` * * @docsCategory service-helpers */ @Injectable() export class ProductPriceApplicator { constructor( private configService: ConfigService, private taxRateService: TaxRateService, private zoneService: ZoneService, private requestCache: RequestContextCacheService, ) {} /** * @description * Populates the `price` field with the price for the specified channel. Make sure that * the ProductVariant being passed in has its `taxCategory` relation joined. * * If the `throwIfNoPriceFound` option is set to `true`, then an error will be thrown if no * price is found for the given Channel. */ async applyChannelPriceAndTax( variant: ProductVariant, ctx: RequestContext, order?: Order, throwIfNoPriceFound = false, ): Promise<ProductVariant> { const { productVariantPriceSelectionStrategy, productVariantPriceCalculationStrategy } = this.configService.catalogOptions; const channelPrice = await productVariantPriceSelectionStrategy.selectPrice( ctx, variant.productVariantPrices, ); if (!channelPrice && throwIfNoPriceFound) { throw new InternalServerError('error.no-price-found-for-channel', { variantId: variant.id, channel: ctx.channel.code, }); } const { taxZoneStrategy } = this.configService.taxOptions; const zones = await this.requestCache.get(ctx, CacheKey.AllZones, () => this.zoneService.getAllWithMembers(ctx), ); const activeTaxZone = await this.requestCache.get(ctx, CacheKey.ActiveTaxZone_PPA, () => taxZoneStrategy.determineTaxZone(ctx, zones, ctx.channel, order), ); if (!activeTaxZone) { throw new InternalServerError('error.no-active-tax-zone'); } const applicableTaxRate = await this.requestCache.get( ctx, `applicableTaxRate-${activeTaxZone.id}-${variant.taxCategory.id}`, () => this.taxRateService.getApplicableTaxRate(ctx, activeTaxZone, variant.taxCategory), ); const { price, priceIncludesTax } = await productVariantPriceCalculationStrategy.calculate({ inputPrice: channelPrice?.price ?? 0, taxCategory: variant.taxCategory, productVariant: variant, activeTaxZone, ctx, }); variant.listPrice = price; variant.listPriceIncludesTax = priceIncludesTax; variant.taxRateApplied = applicableTaxRate; variant.currencyCode = channelPrice?.currencyCode ?? ctx.currencyCode; return variant; } }
import { Injectable } from '@nestjs/common'; import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../../api/common/request-context'; import { IllegalOperationError } from '../../../common/error/errors'; import { FSM } from '../../../common/finite-state-machine/finite-state-machine'; import { StateMachineConfig } from '../../../common/finite-state-machine/types'; import { ConfigService } from '../../../config/config.service'; import { Order } from '../../../entity/order/order.entity'; import { Refund } from '../../../entity/refund/refund.entity'; import { HistoryService } from '../../services/history.service'; import { RefundState, refundStateTransitions, RefundTransitionData } from './refund-state'; @Injectable() export class RefundStateMachine { private readonly config: StateMachineConfig<RefundState, RefundTransitionData> = { transitions: refundStateTransitions, onTransitionStart: async (fromState, toState, data) => { return true; }, onTransitionEnd: async (fromState, toState, data) => { await this.historyService.createHistoryEntryForOrder({ ctx: data.ctx, orderId: data.order.id, type: HistoryEntryType.ORDER_REFUND_TRANSITION, data: { refundId: data.refund.id, from: fromState, to: toState, reason: data.refund.reason, }, }); }, onError: (fromState, toState, message) => { throw new IllegalOperationError(message || 'error.cannot-transition-refund-from-to', { fromState, toState, }); }, }; constructor(private configService: ConfigService, private historyService: HistoryService) {} getNextStates(refund: Refund): readonly RefundState[] { const fsm = new FSM(this.config, refund.state); return fsm.getNextStates(); } async transition(ctx: RequestContext, order: Order, refund: Refund, state: RefundState) { const fsm = new FSM(this.config, refund.state); const result = await fsm.transitionTo(state, { ctx, order, refund }); refund.state = state; return result; } }
import { RequestContext } from '../../../api/common/request-context'; import { Transitions } from '../../../common/finite-state-machine/types'; import { Order } from '../../../entity/order/order.entity'; import { Payment } from '../../../entity/payment/payment.entity'; import { Refund } from '../../../entity/refund/refund.entity'; /** * @description * These are the default states of the refund process. * * @docsCategory payment */ export type RefundState = 'Pending' | 'Settled' | 'Failed'; export const refundStateTransitions: Transitions<RefundState> = { Pending: { to: ['Settled', 'Failed'], }, Settled: { to: [], }, Failed: { to: [], }, }; /** * @description * The data which is passed to the state transition handler of the RefundStateMachine. * * @docsCategory payment */ export interface RefundTransitionData { ctx: RequestContext; order: Order; refund: Refund; }
import { Injectable } from '@nestjs/common'; import { CurrencyCode, LanguageCode, Permission } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { Request } from 'express'; import { GraphQLResolveInfo } from 'graphql'; import ms from 'ms'; import { ApiType, getApiType } from '../../../api/common/get-api-type'; import { RequestContext } from '../../../api/common/request-context'; import { UserInputError } from '../../../common/error/errors'; import { idsAreEqual } from '../../../common/utils'; import { ConfigService } from '../../../config/config.service'; import { CachedSession, CachedSessionUser } from '../../../config/session-cache/session-cache-strategy'; import { Channel } from '../../../entity/channel/channel.entity'; import { User } from '../../../entity/user/user.entity'; import { ChannelService } from '../../services/channel.service'; import { getUserChannelsPermissions } from '../utils/get-user-channels-permissions'; /** * @description * Creates new {@link RequestContext} instances. * * @docsCategory request */ @Injectable() export class RequestContextService { /** @internal */ constructor(private channelService: ChannelService, private configService: ConfigService) {} /** * @description * Creates a RequestContext based on the config provided. This can be useful when interacting * with services outside the request-response cycle, for example in stand-alone scripts or in * worker jobs. * * @since 1.5.0 */ async create(config: { req?: Request; apiType: ApiType; channelOrToken?: Channel | string; languageCode?: LanguageCode; currencyCode?: CurrencyCode; user?: User; activeOrderId?: ID; }): Promise<RequestContext> { const { req, apiType, channelOrToken, languageCode, currencyCode, user, activeOrderId } = config; let channel: Channel; if (channelOrToken instanceof Channel) { channel = channelOrToken; } else if (typeof channelOrToken === 'string') { channel = await this.channelService.getChannelFromToken(channelOrToken); } else { channel = await this.channelService.getDefaultChannel(); } let session: CachedSession | undefined; if (user) { const channelPermissions = user.roles ? getUserChannelsPermissions(user) : []; session = { user: { id: user.id, identifier: user.identifier, verified: user.verified, channelPermissions, }, id: '__dummy_session_id__', token: '__dummy_session_token__', expires: new Date(Date.now() + ms('1y')), cacheExpiry: ms('1y'), activeOrderId, }; } return new RequestContext({ req, apiType, channel, languageCode, currencyCode, session, isAuthorized: true, authorizedAsOwnerOnly: false, }); } /** * @description * Creates a new RequestContext based on an Express request object. This is used internally * in the API layer by the AuthGuard, and creates the RequestContext which is then passed * to all resolvers & controllers. */ async fromRequest( req: Request, info?: GraphQLResolveInfo, requiredPermissions?: Permission[], session?: CachedSession, ): Promise<RequestContext> { const channelToken = this.getChannelToken(req); const channel = await this.channelService.getChannelFromToken(channelToken); const apiType = getApiType(info); const hasOwnerPermission = !!requiredPermissions && requiredPermissions.includes(Permission.Owner); const languageCode = this.getLanguageCode(req, channel); const currencyCode = this.getCurrencyCode(req, channel); const user = session && session.user; const isAuthorized = this.userHasRequiredPermissionsOnChannel(requiredPermissions, channel, user); const authorizedAsOwnerOnly = !isAuthorized && hasOwnerPermission; const translationFn = (req as any).t; return new RequestContext({ req, apiType, channel, languageCode, currencyCode, session, isAuthorized, authorizedAsOwnerOnly, translationFn, }); } private getChannelToken(req: Request<any, any, any, { [key: string]: any }>): string { const tokenKey = this.configService.apiOptions.channelTokenKey; let channelToken = ''; if (req && req.query && req.query[tokenKey]) { channelToken = req.query[tokenKey]; } else if (req && req.headers && req.headers[tokenKey]) { channelToken = req.headers[tokenKey] as string; } return channelToken; } private getLanguageCode(req: Request, channel: Channel): LanguageCode | undefined { return ( (req.query && (req.query.languageCode as LanguageCode)) ?? channel.defaultLanguageCode ?? this.configService.defaultLanguageCode ); } private getCurrencyCode(req: Request, channel: Channel): CurrencyCode | undefined { const queryCurrencyCode = req.query && (req.query.currencyCode as CurrencyCode); if (queryCurrencyCode && !channel.availableCurrencyCodes.includes(queryCurrencyCode)) { throw new UserInputError('error.currency-not-available-in-channel', { currencyCode: queryCurrencyCode, }); } return queryCurrencyCode ?? channel.defaultCurrencyCode; } /** * TODO: Deprecate and remove, since this function is now handled internally in the RequestContext. * @private */ private userHasRequiredPermissionsOnChannel( permissions: Permission[] = [], channel?: Channel, user?: CachedSessionUser, ): boolean { if (!user || !channel) { return false; } const permissionsOnChannel = user.channelPermissions.find(c => idsAreEqual(c.id, channel.id)); if (permissionsOnChannel) { return this.arraysIntersect(permissionsOnChannel.permissions, permissions); } return false; } /** * Returns true if any element of arr1 appears in arr2. */ private arraysIntersect<T>(arr1: T[], arr2: T[]): boolean { return arr1.reduce((intersects, role) => { return intersects || arr2.includes(role); }, false as boolean); } }
import { Injectable } from '@nestjs/common'; import { ID } from '@vendure/common/lib/shared-types'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { RequestContext } from '../../../api/common/request-context'; import { ShippingCalculationResult } from '../../../config/shipping-method/shipping-calculator'; import { Order } from '../../../entity/order/order.entity'; import { ShippingMethod } from '../../../entity/shipping-method/shipping-method.entity'; import { ShippingMethodService } from '../../services/shipping-method.service'; type EligibleShippingMethod = { method: ShippingMethod; result: ShippingCalculationResult; }; @Injectable() export class ShippingCalculator { constructor(private shippingMethodService: ShippingMethodService) {} /** * Returns an array of each eligible ShippingMethod for the given Order and sorts them by * price, with the cheapest first. * * The `skipIds` argument is used to skip ShippingMethods with those IDs from being checked and calculated. */ async getEligibleShippingMethods( ctx: RequestContext, order: Order, skipIds: ID[] = [], ): Promise<EligibleShippingMethod[]> { const shippingMethods = (await this.shippingMethodService.getActiveShippingMethods(ctx)).filter( method => !skipIds.includes(method.id), ); const checkEligibilityPromises = shippingMethods.map(method => this.checkEligibilityByShippingMethod(ctx, order, method), ); const eligibleMethods = await Promise.all(checkEligibilityPromises); return eligibleMethods.filter(notNullOrUndefined).sort((a, b) => a.result.price - b.result.price); } async getMethodIfEligible( ctx: RequestContext, order: Order, shippingMethodId: ID, ): Promise<ShippingMethod | undefined> { const method = await this.shippingMethodService.findOne(ctx, shippingMethodId); if (method) { const eligible = await method.test(ctx, order); if (eligible) { return method; } } } private async checkEligibilityByShippingMethod( ctx: RequestContext, order: Order, method: ShippingMethod, ): Promise<EligibleShippingMethod | undefined> { const eligible = await method.test(ctx, order); if (eligible) { const result = await method.apply(ctx, order); if (result) { return { method, result }; } } } }
import { Injectable } from '@nestjs/common'; import { LanguageCode } from '@vendure/common/lib/generated-types'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { ID, Type } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../../api/common/request-context'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Collection, Product } from '../../../entity'; import { VendureEntity } from '../../../entity/base/base.entity'; import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity'; /** * @docsCategory service-helpers * @docsPage SlugValidator */ export type InputWithSlug = { id?: ID | null; translations?: Array<{ id?: ID | null; languageCode: LanguageCode; slug?: string | null; }> | null; }; /** * @docsCategory service-helpers * @docsPage SlugValidator */ export type TranslationEntity = VendureEntity & { id: ID; languageCode: LanguageCode; slug: string; base: any; }; /** * @description * Used to validate slugs to ensure they are URL-safe and unique. Designed to be used with translatable * entities such as {@link Product} and {@link Collection}. * * @docsCategory service-helpers * @docsWeight 0 */ @Injectable() export class SlugValidator { constructor(private connection: TransactionalConnection) {} /** * Normalizes the slug to be URL-safe, and ensures it is unique for the given languageCode. * Mutates the input. */ async validateSlugs<T extends InputWithSlug, E extends TranslationEntity>( ctx: RequestContext, input: T, translationEntity: Type<E>, ): Promise<T> { if (input.translations) { for (const t of input.translations) { if (t.slug) { t.slug = normalizeString(t.slug, '-'); let match: E | null; let suffix = 1; const seen: ID[] = []; const alreadySuffixed = /-\d+$/; do { const qb = this.connection .getRepository(ctx, translationEntity) .createQueryBuilder('translation') .innerJoinAndSelect('translation.base', 'base') .innerJoinAndSelect('base.channels', 'channel') .where('channel.id = :channelId', { channelId: ctx.channelId }) .andWhere('translation.slug = :slug', { slug: t.slug }) .andWhere('translation.languageCode = :languageCode', { languageCode: t.languageCode, }); if (input.id) { qb.andWhere('translation.base != :id', { id: input.id }); } if (seen.length) { qb.andWhere('translation.id NOT IN (:...seen)', { seen }); } match = await qb.getOne(); if (match) { if (!match.base.deletedAt) { suffix++; if (alreadySuffixed.test(t.slug)) { t.slug = t.slug.replace(alreadySuffixed, `-${suffix}`); } else { t.slug = `${t.slug}-${suffix}`; } } else { seen.push(match.id); } } } while (match); } } } return input; } }
import { Injectable } from '@nestjs/common'; import { omit } from '@vendure/common/lib/omit'; import { ID, Type } from '@vendure/common/lib/shared-types'; import { FindOneOptions } from 'typeorm'; import { FindManyOptions } from 'typeorm/find-options/FindManyOptions'; import { RequestContext } from '../../../api/common/request-context'; import { Translatable, TranslatedInput, Translation } from '../../../common/types/locale-types'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { VendureEntity } from '../../../entity/base/base.entity'; import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity'; import { patchEntity } from '../utils/patch-entity'; import { TranslationDiffer } from './translation-differ'; export interface CreateTranslatableOptions<T extends Translatable> { ctx: RequestContext; entityType: Type<T>; translationType: Type<Translation<T>>; input: TranslatedInput<T>; beforeSave?: (newEntity: T) => any | Promise<any>; typeOrmSubscriberData?: any; } export interface UpdateTranslatableOptions<T extends Translatable> extends CreateTranslatableOptions<T> { input: TranslatedInput<T> & { id: ID }; } /** * @description * A helper which contains methods for creating and updating entities which implement the {@link Translatable} interface. * * @example * ```ts * export class MyService { * constructor(private translatableSaver: TranslatableSaver) {} * * async create(ctx: RequestContext, input: CreateFacetInput): Promise<Translated<Facet>> { * const facet = await this.translatableSaver.create({ * ctx, * input, * entityType: Facet, * translationType: FacetTranslation, * beforeSave: async f => { * f.code = await this.ensureUniqueCode(ctx, f.code); * }, * }); * return facet; * } * * // ... * } * ``` * * @docsCategory service-helpers */ @Injectable() export class TranslatableSaver { constructor(private connection: TransactionalConnection) {} /** * @description * Create a translatable entity, including creating any translation entities according * to the `translations` array. */ async create<T extends Translatable & VendureEntity>(options: CreateTranslatableOptions<T>): Promise<T> { const { ctx, entityType, translationType, input, beforeSave, typeOrmSubscriberData } = options; const entity = new entityType(input); const translations: Array<Translation<T>> = []; if (input.translations) { for (const translationInput of input.translations) { const translation = new translationType(translationInput); translations.push(translation); await this.connection.getRepository(ctx, translationType).save(translation as any); } } entity.translations = translations; if (typeof beforeSave === 'function') { await beforeSave(entity); } return await this.connection .getRepository(ctx, entityType) .save(entity as any, { data: typeOrmSubscriberData }); } /** * @description * Update a translatable entity. Performs a diff of the `translations` array in order to * perform the correct operation on the translations. */ async update<T extends Translatable & VendureEntity>(options: UpdateTranslatableOptions<T>): Promise<T> { const { ctx, entityType, translationType, input, beforeSave, typeOrmSubscriberData } = options; const existingTranslations = await this.connection.getRepository(ctx, translationType).find({ relationLoadStrategy: 'query', loadEagerRelations: false, where: { base: { id: input.id } }, relations: ['base'], } as FindManyOptions<Translation<T>>); const differ = new TranslationDiffer(translationType, this.connection); const diff = differ.diff(existingTranslations, input.translations); const entity = await differ.applyDiff( ctx, new entityType({ ...input, translations: existingTranslations }), diff, ); entity.updatedAt = new Date(); const updatedEntity = patchEntity(entity as any, omit(input, ['translations'])); if (typeof beforeSave === 'function') { await beforeSave(entity); } return this.connection .getRepository(ctx, entityType) .save(updatedEntity, { data: typeOrmSubscriberData }); } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { beforeEach, describe, expect, it } from 'vitest'; import { TranslationInput } from '../../../common/types/locale-types'; import { ProductTranslation } from '../../../entity/product/product-translation.entity'; import { Product } from '../../../entity/product/product.entity'; import { TranslationDiffer } from './translation-differ'; describe('TranslationUpdater', () => { describe('diff()', () => { const existing: ProductTranslation[] = [ new ProductTranslation({ id: '10', languageCode: LanguageCode.en, name: '', slug: '', description: '', }), new ProductTranslation({ id: '11', languageCode: LanguageCode.de, name: '', slug: '', description: '', }), ]; let connection: any; beforeEach(() => { connection = {}; }); it('correctly marks translations for update', async () => { const updated: Array<TranslationInput<Product>> = [ { languageCode: LanguageCode.en, name: '', slug: '', description: '', }, { languageCode: LanguageCode.de, name: '', slug: '', description: '', }, ]; const diff = new TranslationDiffer(ProductTranslation as any, connection).diff(existing, updated); expect(diff.toUpdate).toEqual(existing); }); it('correctly marks translations for addition', async () => { const updated: Array<TranslationInput<Product>> = [ { languageCode: LanguageCode.af, name: '', slug: '', description: '', }, { languageCode: LanguageCode.zh, name: '', slug: '', description: '', }, ]; const diff = new TranslationDiffer(ProductTranslation as any, connection).diff(existing, updated); expect(diff.toAdd).toEqual(updated); }); it('correctly marks languages for update, addition and deletion', async () => { const updated: Array<TranslationInput<Product>> = [ { languageCode: LanguageCode.en, name: '', slug: '', description: '', }, { languageCode: LanguageCode.zh, name: '', slug: '', description: '', }, ]; const diff = new TranslationDiffer(ProductTranslation as any, connection).diff(existing, updated); expect(diff.toUpdate).toEqual([existing[0]]); expect(diff.toAdd).toEqual([updated[1]]); }); }); });
import { DeepPartial } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../../api/common/request-context'; import { InternalServerError } from '../../../common/error/errors'; import { Translatable, Translation, TranslationInput } from '../../../common/types/locale-types'; import { foundIn, not } from '../../../common/utils'; import { TransactionalConnection } from '../../../connection/transactional-connection'; export type TranslationContructor<T> = new ( input?: DeepPartial<TranslationInput<T>> | DeepPartial<Translation<T>>, ) => Translation<T>; export interface TranslationDiff<T> { toUpdate: Array<Translation<T>>; toAdd: Array<Translation<T>>; } /** * This class is to be used when performing an update on a Translatable entity. */ export class TranslationDiffer<Entity extends Translatable> { constructor( private translationCtor: TranslationContructor<Entity>, private connection: TransactionalConnection, ) {} /** * Compares the existing translations with the updated translations and produces a diff of * added, removed and updated translations. */ diff( existing: Array<Translation<Entity>>, updated?: Array<TranslationInput<Entity>> | null, ): TranslationDiff<Entity> { if (updated) { const translationEntities = this.translationInputsToEntities(updated, existing); const toAdd = translationEntities.filter(not(foundIn(existing, 'languageCode'))); const toUpdate = translationEntities.filter(foundIn(existing, 'languageCode')); return { toUpdate, toAdd }; } else { return { toUpdate: [], toAdd: [], }; } } async applyDiff( ctx: RequestContext, entity: Entity, { toUpdate, toAdd }: TranslationDiff<Entity>, ): Promise<Entity> { if (toUpdate.length) { for (const translation of toUpdate) { // any cast below is required due to TS issue: https://github.com/Microsoft/TypeScript/issues/21592 const updated = await this.connection .getRepository(ctx, this.translationCtor) .save(translation as any); const index = entity.translations.findIndex(t => t.languageCode === updated.languageCode); entity.translations.splice(index, 1, updated); } } if (toAdd.length) { for (const translation of toAdd) { translation.base = entity; let newTranslation: any; try { newTranslation = await this.connection .getRepository(ctx, this.translationCtor) .save(translation as any); } catch (err: any) { throw new InternalServerError(err.message); } entity.translations.push(newTranslation); } } return entity; } private translationInputsToEntities( inputs: Array<TranslationInput<Entity>>, existing: Array<Translation<Entity>>, ): Array<Translation<Entity>> { return inputs.map(input => { const counterpart = existing.find(e => e.languageCode === input.languageCode); // any cast below is required due to TS issue: https://github.com/Microsoft/TypeScript/issues/21592 const entity = new this.translationCtor(input as any); if (counterpart) { entity.id = counterpart.id; entity.base = counterpart.base; } return entity; }); } }
import { Injectable } from '@nestjs/common'; import { RequestContext } from '../../../api/common/request-context'; import { Translatable } from '../../../common/types/locale-types'; import { ConfigService } from '../../../config'; import { VendureEntity } from '../../../entity'; import { DeepTranslatableRelations, translateDeep } from '../utils/translate-entity'; /** * @description * The TranslatorService is used to translate entities into the current language. * * @example * ```ts * import { Injectable } from '\@nestjs/common'; * import { ID, Product, RequestContext, TransactionalConnection, TranslatorService } from '\@vendure/core'; * * \@Injectable() * export class ProductService { * * constructor(private connection: TransactionalConnection, * private translator: TranslatorService){} * * async findOne(ctx: RequestContext, productId: ID): Promise<Product | undefined> { * const product = await this.connection.findOneInChannel(ctx, Product, productId, ctx.channelId, { * relations: { * facetValues: { * facet: true, * } * } * }); * if (!product) { * return; * } * return this.translator.translate(product, ctx, ['facetValues', ['facetValues', 'facet']]); * } * } * ``` * * @docsCategory service-helpers */ @Injectable() export class TranslatorService { constructor(private configService: ConfigService) {} translate<T extends Translatable & VendureEntity>( translatable: T, ctx: RequestContext, translatableRelations: DeepTranslatableRelations<T> = [], ) { return translateDeep( translatable, [ctx.languageCode, ctx.channel.defaultLanguageCode, this.configService.defaultLanguageCode], translatableRelations, ); } }
import { OrderAddress } from '@vendure/common/lib/generated-types'; import { Address } from '../../../entity/address/address.entity'; /** * Given an Address object, this function converts it into a single line * consisting of streetLine1, (postalCode), (countryCode). */ export function addressToLine(address: Address | OrderAddress): string { const propsToInclude: Array<keyof (Address | OrderAddress)> = ['streetLine1', 'postalCode', 'country']; let result = address.streetLine1 || ''; if (address.postalCode) { result += ', ' + address.postalCode; } if (address.country) { if (typeof address.country === 'string') { result += ', ' + address.country; } else { result += ', ' + address.country.name; } } return result; }
import { Permission } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { Role } from '../../../entity/role/role.entity'; import { User } from '../../../entity/user/user.entity'; export interface UserChannelPermissions { id: ID; token: string; code: string; permissions: Permission[]; } /** * Returns an array of Channels and permissions on those Channels for the given User. */ export function getUserChannelsPermissions(user: User): UserChannelPermissions[] { return getChannelPermissions(user.roles); } /** * @description * Returns an array of Channels and permissions on those Channels for the given Roles. */ export function getChannelPermissions(roles: Role[]): UserChannelPermissions[] { const channelsMap: { [code: string]: UserChannelPermissions } = {}; for (const role of roles) { for (const channel of role.channels) { if (!channelsMap[channel.code]) { channelsMap[channel.code] = { id: channel.id, token: channel.token, code: channel.code, permissions: [], }; } channelsMap[channel.code].permissions = unique([ ...channelsMap[channel.code].permissions, ...role.permissions, ]); } } return Object.values(channelsMap).sort((a, b) => (a.id < b.id ? -1 : 1)); }
import { Orderable } from '../../../common/types/common-types'; import { idsAreEqual } from '../../../common/utils'; import { VendureEntity } from '../../../entity/base/base.entity'; /** * Moves the target Orderable entity to the given index amongst its siblings. * Returns the siblings (including the target) which should then be * persisted to the database. */ export function moveToIndex<T extends Orderable & VendureEntity>( index: number, target: T, siblings: T[], ): T[] { const normalizedIndex = Math.max(Math.min(index, siblings.length), 0); let currentIndex = siblings.findIndex(sibling => idsAreEqual(sibling.id, target.id)); const orderedSiblings = [...siblings].sort((a, b) => (a.position > b.position ? 1 : -1)); const siblingsWithTarget = currentIndex < 0 ? [...orderedSiblings, target] : [...orderedSiblings]; currentIndex = siblingsWithTarget.findIndex(sibling => idsAreEqual(sibling.id, target.id)); if (currentIndex !== normalizedIndex) { siblingsWithTarget.splice(normalizedIndex, 0, siblingsWithTarget.splice(currentIndex, 1)[0]); siblingsWithTarget.forEach((collection, i) => { collection.position = i; if (target.id === collection.id) { target.position = i; } }); } return siblingsWithTarget; }
import { describe, expect, it } from 'vitest'; import { Order } from '../../../entity/order/order.entity'; import { Payment } from '../../../entity/payment/payment.entity'; import { totalCoveredByPayments } from './order-utils'; describe('totalCoveredByPayments()', () => { it('single payment, any state, no refunds', () => { const order = new Order({ payments: [ new Payment({ state: 'Settled', amount: 500, }), ], }); expect(totalCoveredByPayments(order)).toBe(500); }); it('multiple payments, any state, no refunds', () => { const order = new Order({ payments: [ new Payment({ state: 'Settled', amount: 500, }), new Payment({ state: 'Settled', amount: 300, }), ], }); expect(totalCoveredByPayments(order)).toBe(800); }); it('multiple payments, any state, error and declined', () => { const order = new Order({ payments: [ new Payment({ state: 'Error', amount: 500, }), new Payment({ state: 'Declined', amount: 300, }), ], }); expect(totalCoveredByPayments(order)).toBe(0); }); it('multiple payments, single state', () => { const order = new Order({ payments: [ new Payment({ state: 'Settled', amount: 500, }), new Payment({ state: 'Authorized', amount: 300, }), ], }); expect(totalCoveredByPayments(order, 'Settled')).toBe(500); }); it('multiple payments, multiple states', () => { const order = new Order({ payments: [ new Payment({ state: 'Settled', amount: 500, }), new Payment({ state: 'Authorized', amount: 300, }), ], }); expect(totalCoveredByPayments(order, ['Settled', 'Authorized'])).toBe(800); }); });
import { OrderLineInput } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { summate } from '@vendure/common/lib/shared-utils'; import { unique } from '@vendure/common/lib/unique'; import { In } from 'typeorm'; import { RequestContext } from '../../../api/common/request-context'; import { EntityNotFoundError } from '../../../common/error/errors'; import { idsAreEqual } from '../../../common/utils'; import { TransactionalConnection } from '../../../connection/transactional-connection'; import { Order } from '../../../entity/order/order.entity'; import { OrderLine } from '../../../entity/order-line/order-line.entity'; import { FulfillmentLine } from '../../../entity/order-line-reference/fulfillment-line.entity'; import { FulfillmentState } from '../fulfillment-state-machine/fulfillment-state'; import { PaymentState } from '../payment-state-machine/payment-state'; /** * Returns true if the Order total is covered by Payments in the specified state. */ export function orderTotalIsCovered(order: Order, state: PaymentState | PaymentState[]): boolean { const paymentsTotal = totalCoveredByPayments(order, state); return paymentsTotal >= order.totalWithTax; } /** * Returns the total amount covered by all Payments (minus any refunds) */ export function totalCoveredByPayments(order: Order, state?: PaymentState | PaymentState[]): number { const payments = state ? Array.isArray(state) ? order.payments.filter(p => state.includes(p.state)) : order.payments.filter(p => p.state === state) : order.payments.filter( p => p.state !== 'Error' && p.state !== 'Declined' && p.state !== 'Cancelled', ); let total = 0; for (const payment of payments) { const refundTotal = summate(payment.refunds, 'total'); total += payment.amount - Math.abs(refundTotal); } return total; } /** * Returns true if all (non-cancelled) OrderItems are delivered. */ export function orderItemsAreDelivered(order: Order) { return ( getOrderLinesFulfillmentStates(order).every(state => state === 'Delivered') && !isOrderPartiallyFulfilled(order) ); } /** * Returns true if at least one, but not all (non-cancelled) OrderItems are delivered. */ export function orderItemsArePartiallyDelivered(order: Order) { const states = getOrderLinesFulfillmentStates(order); return ( states.some(state => state === 'Delivered') && (!states.every(state => state === 'Delivered') || isOrderPartiallyFulfilled(order)) ); } function getOrderLinesFulfillmentStates(order: Order): Array<FulfillmentState | undefined> { const fulfillmentLines = getOrderFulfillmentLines(order); const states = unique( order.lines .filter(line => line.quantity !== 0) .map(line => { const matchingFulfillmentLines = fulfillmentLines.filter(fl => idsAreEqual(fl.orderLineId, line.id), ); const totalFulfilled = summate(matchingFulfillmentLines, 'quantity'); if (0 < totalFulfilled) { return matchingFulfillmentLines.map(l => l.fulfillment.state); } else { return undefined; } }) .flat(), ); return states; } /** * Returns true if at least one, but not all (non-cancelled) OrderItems are shipped. */ export function orderItemsArePartiallyShipped(order: Order) { const states = getOrderLinesFulfillmentStates(order); return ( states.some(state => state === 'Shipped') && (!states.every(state => state === 'Shipped') || isOrderPartiallyFulfilled(order)) ); } /** * Returns true if all (non-cancelled) OrderItems are shipped. */ export function orderItemsAreShipped(order: Order) { return ( getOrderLinesFulfillmentStates(order).every(state => state === 'Shipped') && !isOrderPartiallyFulfilled(order) ); } /** * Returns true if all OrderItems in the order are cancelled */ export function orderLinesAreAllCancelled(order: Order) { return order.lines.every(line => line.quantity === 0); } function getOrderFulfillmentLines(order: Order): FulfillmentLine[] { return order.fulfillments .filter(f => f.state !== 'Cancelled') .reduce( (fulfillmentLines, fulfillment) => [...fulfillmentLines, ...fulfillment.lines], [] as FulfillmentLine[], ); } /** * Returns true if Fulfillments exist for only some but not all of the * order items. */ function isOrderPartiallyFulfilled(order: Order) { const fulfillmentLines = getOrderFulfillmentLines(order); const lines = fulfillmentLines.reduce((acc, item) => { acc[item.orderLineId] = (acc[item.orderLineId] || 0) + item.quantity; return acc; }, {} as { [orderLineId: string]: number }); return order.lines.some(line => line.quantity > lines[line.id]); } export async function getOrdersFromLines( ctx: RequestContext, connection: TransactionalConnection, orderLinesInput: OrderLineInput[], ): Promise<Order[]> { const orders = new Map<ID, Order>(); const lines = await connection.getRepository(ctx, OrderLine).find({ where: { id: In(orderLinesInput.map(l => l.orderLineId)) }, relations: ['order', 'order.channels'], order: { id: 'ASC' }, }); for (const line of lines) { const inputLine = orderLinesInput.find(l => idsAreEqual(l.orderLineId, line.id)); if (!inputLine) { continue; } const order = line.order; if (!order.channels.some(channel => channel.id === ctx.channelId)) { throw new EntityNotFoundError('Order', order.id); } if (!orders.has(order.id)) { orders.set(order.id, order); } } return Array.from(orders.values()); }
import { describe, expect, it } from 'vitest'; import { patchEntity } from './patch-entity'; describe('patchEntity()', () => { it('updates non-undefined values', () => { const entity: any = { foo: 'foo', bar: 'bar', baz: 'baz', }; const result = patchEntity(entity, { bar: 'bar2', baz: undefined }); expect(result).toEqual({ foo: 'foo', bar: 'bar2', baz: 'baz', }); }); it('updates null values', () => { const entity: any = { foo: 'foo', bar: 'bar', baz: 'baz', }; const result = patchEntity(entity, { bar: null }); expect(result).toEqual({ foo: 'foo', bar: null, baz: 'baz', }); }); it('does not update id field', () => { const entity: any = { id: 123, bar: 'bar', }; const result = patchEntity(entity, { id: 456 }); expect(result).toEqual({ id: 123, bar: 'bar', }); }); it('updates individual customFields', () => { const entity: any = { customFields: { cf1: 'cf1', cf2: 'cf2', }, }; const result = patchEntity(entity, { customFields: { cf2: 'foo' } }); expect(result).toEqual({ customFields: { cf1: 'cf1', cf2: 'foo', }, }); }); it('handles missing input customFields', () => { const entity: any = { f1: 'f1', customFields: { cf1: 'cf1', cf2: 'cf2', }, }; const result = patchEntity(entity, { f1: 'foo' }); expect(result).toEqual({ f1: 'foo', customFields: { cf1: 'cf1', cf2: 'cf2', }, }); }); });
import { VendureEntity } from '../../../entity/base/base.entity'; export type InputPatch<T> = { [K in keyof T]?: T[K] | null }; /** * Updates only the specified properties from an Input object as long as the value is not * undefined. Null values can be passed, however, which will set the corresponding entity * field to "null". So care must be taken that this is only done on nullable fields. */ export function patchEntity<T extends VendureEntity, I extends InputPatch<T>>(entity: T, input: I): T { for (const key of Object.keys(entity)) { const value = input[key as keyof T]; if (key === 'customFields' && value) { patchEntity((entity as any)[key], value as any); } else if (value !== undefined && key !== 'id') { entity[key as keyof T] = value as any; } } return entity; }
import { describe, expect, it } from 'vitest'; import { samplesEach } from './samples-each'; describe('samplesEach()', () => { it('single group match', () => { const result = samplesEach([1], [[1]]); expect(result).toBe(true); }); it('single group no match', () => { const result = samplesEach([1], [[3, 4, 5]]); expect(result).toBe(false); }); it('does not sample all groups', () => { const result = samplesEach( [1, 3], [ [0, 1, 3], [2, 5, 4], ], ); expect(result).toBe(false); }); it('two groups in order', () => { const result = samplesEach( [1, 4], [ [0, 1, 3], [2, 5, 4], ], ); expect(result).toBe(true); }); it('two groups not in order', () => { const result = samplesEach( [1, 4], [ [2, 5, 4], [0, 1, 3], ], ); expect(result).toBe(true); }); it('three groups in order', () => { const result = samplesEach( [1, 4, 'a'], [ [0, 1, 3], [2, 5, 4], ['b', 'a'], ], ); expect(result).toBe(true); }); it('three groups not in order', () => { const result = samplesEach( [1, 4, 'a'], [ [2, 5, 4], ['b', 'a'], [0, 1, 3], ], ); expect(result).toBe(true); }); it('input is unchanged', () => { const input = [1, 4, 'a']; const result = samplesEach(input, [ [2, 5, 4], ['b', 'a'], [0, 1, 3], ]); expect(result).toBe(true); expect(input).toEqual([1, 4, 'a']); }); it('empty input arrays', () => { const result = samplesEach([], []); expect(result).toBe(true); }); it('length mismatch', () => { const result = samplesEach( [1, 4, 5], [ [2, 5, 4], [0, 1, 3], ], ); expect(result).toBe(false); }); });
/** * Returns true if and only if exactly one item from each * of the "groups" arrays appears in the "sample" array. */ export function samplesEach<T>(sample: T[], groups: T[][]): boolean { if (sample.length !== groups.length) { return false; } return groups.every(group => { for (const item of sample) { if (group.includes(item)) { return true; } } return false; }); }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { beforeEach, describe, expect, it } from 'vitest'; import { Translatable, Translation } from '../../../common/types/locale-types'; import { VendureEntity } from '../../../entity/base/base.entity'; import { CollectionTranslation } from '../../../entity/collection/collection-translation.entity'; import { Collection } from '../../../entity/collection/collection.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 { ProductVariantTranslation } from '../../../entity/product-variant/product-variant-translation.entity'; import { ProductVariant } from '../../../entity/product-variant/product-variant.entity'; import { translateDeep, translateEntity, translateTree } from './translate-entity'; const LANGUAGE_CODE = LanguageCode.en; const PRODUCT_NAME_EN = 'English Name'; const VARIANT_NAME_EN = 'English Variant'; const OPTION_NAME_EN = 'English Option'; const PRODUCT_NAME_DE = 'German Name'; const VARIANT_NAME_DE = 'German Variant'; const OPTION_NAME_DE = 'German Option'; describe('translateEntity()', () => { let product: Product; let productTranslationEN: ProductTranslation; let productTranslationDE: ProductTranslation; beforeEach(() => { productTranslationEN = new ProductTranslation({ id: '2', languageCode: LanguageCode.en, name: PRODUCT_NAME_EN, slug: '', description: '', }); productTranslationEN.base = { id: 1 } as any; productTranslationEN.customFields = {}; productTranslationDE = new ProductTranslation({ id: '3', languageCode: LanguageCode.de, name: PRODUCT_NAME_DE, slug: '', description: '', }); productTranslationDE.base = { id: 1 } as any; productTranslationDE.customFields = {}; product = new Product(); product.id = '1'; product.translations = [productTranslationEN, productTranslationDE]; product.customFields = {}; }); it('should unwrap the matching translation', () => { const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result).toHaveProperty('name', PRODUCT_NAME_EN); }); it('should not overwrite translatable id with translation id', () => { const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result).toHaveProperty('id', '1'); }); it('should note transfer the base from the selected translation', () => { const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result).not.toHaveProperty('base'); }); it('should transfer the languageCode from the selected translation', () => { const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result).toHaveProperty('languageCode', 'en'); }); describe('customFields handling', () => { it('should leave customFields with no localeStrings intact', () => { const customFields = { aBooleanField: true, }; product.customFields = customFields; const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result.customFields).toEqual(customFields); }); it('should translate customFields with localeStrings', () => { const translatedCustomFields = { aLocaleString1: 'translated1', aLocaleString2: 'translated2', }; product.translations[0].customFields = translatedCustomFields; const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result.customFields).toEqual(translatedCustomFields); }); it('should translate customFields with localeStrings and other types', () => { const productCustomFields = { aBooleanField: true, aStringField: 'foo', }; const translatedCustomFields = { aLocaleString1: 'translated1', aLocaleString2: 'translated2', }; product.customFields = productCustomFields; product.translations[0].customFields = translatedCustomFields; const result = translateEntity(product, [LanguageCode.en, LanguageCode.en]); expect(result.customFields).toEqual({ ...productCustomFields, ...translatedCustomFields }); }); }); it('throw if there are no translations available', () => { product.translations = []; expect(() => translateEntity(product, [LanguageCode.en, LanguageCode.en])).toThrow( 'error.entity-has-no-translation-in-language', ); }); it('falls back to default language', () => { expect(translateEntity(product, [LanguageCode.zu, LanguageCode.en]).name).toEqual(PRODUCT_NAME_EN); }); it('falls back to default language', () => { expect(translateEntity(product, [LanguageCode.zu, LanguageCode.de]).name).toEqual(PRODUCT_NAME_DE); }); }); describe('translateDeep()', () => { interface TestProduct extends VendureEntity { singleTestVariant: TestVariant; singleRealVariant: ProductVariant; } class TestProductEntity extends VendureEntity implements Translatable { constructor() { super(); } id: string; singleTestVariant: TestVariantEntity; singleRealVariant: ProductVariant; translations: Array<Translation<TestProduct>>; } interface TestVariant extends VendureEntity { singleOption: ProductOption; } class TestVariantEntity extends VendureEntity implements Translatable { constructor() { super(); } id: string; singleOption: ProductOption; translations: Array<Translation<TestVariant>>; } let testProduct: TestProductEntity; let testVariant: TestVariantEntity; let product: Product; let productTranslation: ProductTranslation; let productVariant: ProductVariant; let productVariantTranslation: ProductVariantTranslation; let productOption: ProductOption; let productOptionTranslation: ProductOptionTranslation; beforeEach(() => { productTranslation = new ProductTranslation(); productTranslation.id = '2'; productTranslation.languageCode = LANGUAGE_CODE; productTranslation.name = PRODUCT_NAME_EN; productOptionTranslation = new ProductOptionTranslation(); productOptionTranslation.id = '31'; productOptionTranslation.languageCode = LANGUAGE_CODE; productOptionTranslation.name = OPTION_NAME_EN; productOption = new ProductOption(); productOption.id = '3'; productOption.translations = [productOptionTranslation]; productVariantTranslation = new ProductVariantTranslation(); productVariantTranslation.id = '41'; productVariantTranslation.languageCode = LANGUAGE_CODE; productVariantTranslation.name = VARIANT_NAME_EN; productVariant = new ProductVariant(); productVariant.id = '3'; productVariant.translations = [productVariantTranslation]; productVariant.options = [productOption]; product = new Product(); product.id = '1'; product.translations = [productTranslation]; product.variants = [productVariant]; testVariant = new TestVariantEntity(); testVariant.singleOption = productOption; testProduct = new TestProductEntity(); testProduct.singleTestVariant = testVariant; testProduct.singleRealVariant = productVariant; }); it('should translate the root entity', () => { const result = translateDeep(product, [LanguageCode.en, LanguageCode.en]); expect(result).toHaveProperty('name', PRODUCT_NAME_EN); }); it('should not throw if root entity has no translations', () => { expect(() => translateDeep(testProduct, [LanguageCode.en, LanguageCode.en])).not.toThrow(); }); it('should not throw if first-level nested entity is not defined', () => { testProduct.singleRealVariant = undefined as any; expect(() => translateDeep(testProduct, [LanguageCode.en, LanguageCode.en], ['singleRealVariant']), ).not.toThrow(); }); it('should not throw if second-level nested entity is not defined', () => { testProduct.singleRealVariant.options = undefined as any; expect(() => translateDeep( testProduct, [LanguageCode.en, LanguageCode.en], [['singleRealVariant', 'options']], ), ).not.toThrow(); }); it('should translate a first-level nested non-array entity', () => { const result = translateDeep(testProduct, [LanguageCode.en, LanguageCode.en], ['singleRealVariant']); expect(result.singleRealVariant).toHaveProperty('name', VARIANT_NAME_EN); }); it('should translate a first-level nested entity array', () => { const result = translateDeep(product, [LanguageCode.en, LanguageCode.en], ['variants']); expect(result).toHaveProperty('name', PRODUCT_NAME_EN); expect(result.variants[0]).toHaveProperty('name', VARIANT_NAME_EN); }); it('should translate a second-level nested non-array entity', () => { const result = translateDeep( testProduct, [LanguageCode.en, LanguageCode.en], [['singleTestVariant', 'singleOption']], ); expect(result.singleTestVariant.singleOption).toHaveProperty('name', OPTION_NAME_EN); }); it('should translate a second-level nested entity array (first-level is not array)', () => { const result = translateDeep( testProduct, [LanguageCode.en, LanguageCode.en], [['singleRealVariant', 'options']], ); expect(result.singleRealVariant.options[0]).toHaveProperty('name', OPTION_NAME_EN); }); it('should translate a second-level nested entity array', () => { const result = translateDeep( product, [LanguageCode.en, LanguageCode.en], ['variants', ['variants', 'options']], ); expect(result).toHaveProperty('name', PRODUCT_NAME_EN); expect(result.variants[0]).toHaveProperty('name', VARIANT_NAME_EN); expect(result.variants[0].options[0]).toHaveProperty('name', OPTION_NAME_EN); }); }); describe('translateTree()', () => { let cat1: Collection; let cat11: Collection; let cat12: Collection; let cat111: Collection; beforeEach(() => { cat1 = new Collection({ translations: [ new CollectionTranslation({ languageCode: LanguageCode.en, name: 'cat1 en', }), ], }); cat11 = new Collection({ translations: [ new CollectionTranslation({ languageCode: LanguageCode.en, name: 'cat11 en', }), ], }); cat12 = new Collection({ translations: [ new CollectionTranslation({ languageCode: LanguageCode.en, name: 'cat12 en', }), ], }); cat111 = new Collection({ translations: [ new CollectionTranslation({ languageCode: LanguageCode.en, name: 'cat111 en', }), ], }); cat1.children = [cat11, cat12]; cat11.children = [cat111]; }); it('translates all entities in the tree', () => { const result = translateTree(cat1, [LanguageCode.en, LanguageCode.en], []); expect(result.languageCode).toBe(LanguageCode.en); expect(result.name).toBe('cat1 en'); expect(result.children[0].name).toBe('cat11 en'); expect(result.children[1].name).toBe('cat12 en'); expect(result.children[0].children[0].name).toBe('cat111 en'); }); });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { DEFAULT_LANGUAGE_CODE } from '../../../common/constants'; import { InternalServerError } from '../../../common/error/errors'; import { UnwrappedArray } from '../../../common/types/common-types'; import { Translatable, Translated, Translation } from '../../../common/types/locale-types'; import { VendureEntity } from '../../../entity/base/base.entity'; // prettier-ignore export type TranslatableRelationsKeys<T> = { [K in keyof T]: T[K] extends string ? never : T[K] extends number ? never : T[K] extends boolean ? never : T[K] extends undefined ? never : T[K] extends string[] ? never : T[K] extends number[] ? never : T[K] extends boolean[] ? never : K extends 'translations' ? never : K extends 'customFields' ? never : K }[keyof T]; // prettier-ignore export type NestedTranslatableRelations<T> = { [K in TranslatableRelationsKeys<T>]: T[K] extends any[] ? [K, TranslatableRelationsKeys<UnwrappedArray<T[K]>>] : [K, TranslatableRelationsKeys<T[K]>] }; // prettier-ignore export type NestedTranslatableRelationKeys<T> = NestedTranslatableRelations<T>[keyof NestedTranslatableRelations<T>]; // prettier-ignore export type DeepTranslatableRelations<T> = Array<TranslatableRelationsKeys<T> | NestedTranslatableRelationKeys<T>>; /** * Converts a Translatable entity into the public-facing entity by unwrapping * the translated strings from the matching Translation entity. */ export function translateEntity<T extends Translatable & VendureEntity>( translatable: T, languageCode: LanguageCode | [LanguageCode, ...LanguageCode[]], ): Translated<T> { let translation: Translation<VendureEntity> | undefined; if (translatable.translations) { if (Array.isArray(languageCode)) { for (const lc of languageCode) { translation = translatable.translations.find(t => t.languageCode === lc); if (translation) break; } } else { translation = translatable.translations.find(t => t.languageCode === languageCode); } if (!translation && languageCode !== DEFAULT_LANGUAGE_CODE) { translation = translatable.translations.find(t => t.languageCode === DEFAULT_LANGUAGE_CODE); } if (!translation) { // If we cannot find any suitable translation, just return the first one to at least // prevent graphql errors when returning the entity. translation = translatable.translations[0]; } } if (!translation) { throw new InternalServerError('error.entity-has-no-translation-in-language', { entityName: translatable.constructor.name, languageCode: Array.isArray(languageCode) ? languageCode.join() : languageCode, }); } const translated = Object.create( Object.getPrototypeOf(translatable), Object.getOwnPropertyDescriptors(translatable), ); for (const [key, value] of Object.entries(translation)) { if (key === 'customFields') { if (!translated.customFields) { translated.customFields = {}; } Object.assign(translated.customFields, value); } else if (key !== 'base' && key !== 'id' && key !== 'createdAt' && key !== 'updatedAt') { translated[key] = value ?? ''; } } return translated; } /** * Translates an entity and its deeply-nested translatable properties. Supports up to 2 levels of nesting. */ export function translateDeep<T extends Translatable & VendureEntity>( translatable: T, languageCode: LanguageCode | [LanguageCode, ...LanguageCode[]], translatableRelations: DeepTranslatableRelations<T> = [], ): Translated<T> { let translatedEntity: Translated<T>; try { translatedEntity = translateEntity(translatable, languageCode); } catch (e: any) { translatedEntity = translatable as any; } for (const path of translatableRelations) { let object: any; let property: string; let value: any; if (Array.isArray(path) && path.length === 2) { const [path0, path1] = path as any; const valueLevel0 = (translatable as any)[path0]; if (Array.isArray(valueLevel0)) { valueLevel0.forEach((nested1, index) => { object = (translatedEntity as any)[path0][index]; property = path1; object[property] = translateLeaf(object, property, languageCode); }); property = ''; object = null; } else { object = (translatedEntity as any)[path0]; property = path1; value = translateLeaf(object, property, languageCode); } } else { object = translatedEntity; property = path as any; value = translateLeaf(object, property, languageCode); } if (object && property) { object[property] = value; } } return translatedEntity; } function translateLeaf( object: { [key: string]: any } | undefined, property: string, languageCode: LanguageCode | [LanguageCode, ...LanguageCode[]], ): any { if (object && object[property]) { if (Array.isArray(object[property])) { return object[property].map((nested2: any) => translateEntity(nested2, languageCode)); } else if (object[property]) { return translateEntity(object[property], languageCode); } } } export type TreeNode = { children: TreeNode[] } & Translatable & VendureEntity; /** * Translates a tree structure of Translatable entities */ export function translateTree<T extends TreeNode>( node: T, languageCode: LanguageCode | [LanguageCode, ...LanguageCode[]], translatableRelations: DeepTranslatableRelations<T> = [], ): Translated<T> { const output = translateDeep(node, languageCode, translatableRelations); if (Array.isArray(output.children)) { output.children = output.children.map(child => translateTree(child, languageCode, translatableRelations as any), ); } return output; }
import { EntityMetadata, FindOneOptions, SelectQueryBuilder } from 'typeorm'; import { EntityTarget } from 'typeorm/common/EntityTarget'; import { FindOptionsRelationByString, FindOptionsRelations } from 'typeorm/find-options/FindOptionsRelations'; import { findOptionsObjectToArray } from '../../../connection/find-options-object-to-array'; import { VendureEntity } from '../../../entity'; /** * @description * Check if the current entity has one or more self-referencing relations * to determine if it is a tree type or has tree relations. * @param metadata * @private */ function isTreeEntityMetadata(metadata: EntityMetadata): boolean { if (metadata.treeType !== undefined) { return true; } for (const relation of metadata.relations) { if (relation.isTreeParent || relation.isTreeChildren) { return true; } if (relation.inverseEntityMetadata === metadata) { return true; } } return false; } /** * Dynamically joins tree relations and their eager counterparts in a TypeORM SelectQueryBuilder, addressing * challenges of managing deeply nested relations and optimizing query efficiency. It leverages TypeORM tree * decorators (@TreeParent, @TreeChildren) to automate joins of self-related entities, including those marked for eager loading. * The process avoids duplicate joins and manual join specifications by using relation metadata. * * @param {SelectQueryBuilder<T>} qb - The query builder instance for joining relations. * @param {EntityTarget<T>} entity - The target entity class or schema name, used to access entity metadata. * @param {string[]} [requestedRelations=[]] - An array of relation paths (e.g., 'parent.children') to join dynamically. * @param {number} [maxEagerDepth=1] - Limits the depth of eager relation joins to avoid excessively deep joins. * @returns {Map<string, string>} - A Map of joined relation paths to their aliases, aiding in tracking and preventing duplicates. * @template T - The entity type, extending VendureEntity for compatibility with Vendure's data layer. * * Usage Notes: * - Only entities utilizing TypeORM tree decorators and having nested relations are supported. * - The `maxEagerDepth` parameter controls the recursion depth for eager relations, preventing performance issues. * * For more context on the issue this function addresses, refer to TypeORM issue #9936: * https://github.com/typeorm/typeorm/issues/9936 * * Example: * ```typescript * const qb = repository.createQueryBuilder("entity"); * joinTreeRelationsDynamically(qb, EntityClass, ["parent.children"], 2); * ``` */ export function joinTreeRelationsDynamically<T extends VendureEntity>( qb: SelectQueryBuilder<T>, entity: EntityTarget<T>, requestedRelations: FindOneOptions['relations'] = {}, maxEagerDepth: number = 1, ): Map<string, string> { const joinedRelations = new Map<string, string>(); const relationsArray = findOptionsObjectToArray(requestedRelations); if (!relationsArray.length) { return joinedRelations; } const sourceMetadata = qb.connection.getMetadata(entity); const sourceMetadataIsTree = isTreeEntityMetadata(sourceMetadata); const processRelation = ( currentMetadata: EntityMetadata, parentMetadataIsTree: boolean, currentPath: string, currentAlias: string, parentPath?: string[], eagerDepth: number = 0, ) => { if (currentPath === '') { return; } parentPath = parentPath?.filter(p => p !== ''); const currentMetadataIsTree = isTreeEntityMetadata(currentMetadata) || sourceMetadataIsTree || parentMetadataIsTree; if (!currentMetadataIsTree) { return; } const parts = currentPath.split('.'); let part = parts.shift(); if (!part || !currentMetadata) return; if (part === 'customFields' && parts.length > 0) { const relation = parts.shift(); if (!relation) return; part += `.${relation}`; } const relationMetadata = currentMetadata.findRelationWithPropertyPath(part); if (!relationMetadata) { return; } let joinConnector = '_'; if (relationMetadata.isEager) { joinConnector = '__'; } const nextAlias = `${currentAlias}${joinConnector}${part.replace(/\./g, '_')}`; const nextPath = parts.join('.'); const fullPath = [...(parentPath || []), part].join('.'); if (!qb.expressionMap.joinAttributes.some(ja => ja.alias.name === nextAlias)) { qb.leftJoinAndSelect(`${currentAlias}.${part}`, nextAlias); joinedRelations.set(fullPath, nextAlias); } const inverseEntityMetadataIsTree = isTreeEntityMetadata(relationMetadata.inverseEntityMetadata); if (!currentMetadataIsTree && !inverseEntityMetadataIsTree) { return; } const newEagerDepth = relationMetadata.isEager ? eagerDepth + 1 : eagerDepth; if (newEagerDepth <= maxEagerDepth) { relationMetadata.inverseEntityMetadata.relations.forEach(subRelation => { if (subRelation.isEager) { processRelation( relationMetadata.inverseEntityMetadata, currentMetadataIsTree, subRelation.propertyPath, nextAlias, [fullPath], newEagerDepth, ); } }); } if (nextPath) { processRelation( relationMetadata.inverseEntityMetadata, currentMetadataIsTree, nextPath, nextAlias, [fullPath], ); } }; relationsArray.forEach(relationPath => { if (!joinedRelations.has(relationPath)) { processRelation(sourceMetadata, sourceMetadataIsTree, relationPath, qb.alias); } }); return joinedRelations; }
import { Injectable } from '@nestjs/common'; import ms from 'ms'; import { generatePublicId } from '../../../common/generate-public-id'; import { ConfigService } from '../../../config/config.service'; /** * This class is responsible for generating and verifying the tokens issued when new accounts are registered * or when a password reset is requested. */ @Injectable() export class VerificationTokenGenerator { constructor(private configService: ConfigService) {} /** * Generates a verification token which encodes the time of generation and concatenates it with a * random id. */ generateVerificationToken() { const now = new Date(); const base64Now = Buffer.from(now.toJSON()).toString('base64'); const id = generatePublicId(); return `${base64Now}_${id}`; } /** * Checks the age of the verification token to see if it falls within the token duration * as specified in the VendureConfig. */ verifyVerificationToken(token: string): boolean { const duration = ms(this.configService.authOptions.verificationTokenDuration as string); const [generatedOn] = token.split('_'); const dateString = Buffer.from(generatedOn, 'base64').toString(); const date = new Date(dateString); const elapsed = +new Date() - +date; return elapsed < duration; } }
import { Injectable } from '@nestjs/common'; import { CreateAdministratorInput, DeletionResult, UpdateAdministratorInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { In, IsNull } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { EntityNotFoundError, InternalServerError, UserInputError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual, normalizeEmailAddress } from '../../common/utils'; import { ConfigService } from '../../config'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Administrator } from '../../entity/administrator/administrator.entity'; import { NativeAuthenticationMethod } from '../../entity/authentication-method/native-authentication-method.entity'; import { Role } from '../../entity/role/role.entity'; import { User } from '../../entity/user/user.entity'; import { EventBus } from '../../event-bus'; import { AdministratorEvent } from '../../event-bus/events/administrator-event'; import { RoleChangeEvent } from '../../event-bus/events/role-change-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { PasswordCipher } from '../helpers/password-cipher/password-cipher'; import { RequestContextService } from '../helpers/request-context/request-context.service'; import { getChannelPermissions } from '../helpers/utils/get-user-channels-permissions'; import { patchEntity } from '../helpers/utils/patch-entity'; import { RoleService } from './role.service'; import { UserService } from './user.service'; /** * @description * Contains methods relating to {@link Administrator} entities. * * @docsCategory services */ @Injectable() export class AdministratorService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private listQueryBuilder: ListQueryBuilder, private passwordCipher: PasswordCipher, private userService: UserService, private roleService: RoleService, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private requestContextService: RequestContextService, ) {} /** @internal */ async initAdministrators() { await this.ensureSuperAdminExists(); } /** * @description * Get a paginated list of Administrators. */ findAll( ctx: RequestContext, options?: ListQueryOptions<Administrator>, relations?: RelationPaths<Administrator>, ): Promise<PaginatedList<Administrator>> { return this.listQueryBuilder .build(Administrator, options, { relations: relations ?? ['user', 'user.roles'], where: { deletedAt: IsNull() }, ctx, }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } /** * @description * Get an Administrator by id. */ findOne( ctx: RequestContext, administratorId: ID, relations?: RelationPaths<Administrator>, ): Promise<Administrator | undefined> { return this.connection .getRepository(ctx, Administrator) .findOne({ relations: relations ?? ['user', 'user.roles'], where: { id: administratorId, deletedAt: IsNull(), }, }) .then(result => result ?? undefined); } /** * @description * Get an Administrator based on the User id. */ findOneByUserId( ctx: RequestContext, userId: ID, relations?: RelationPaths<Administrator>, ): Promise<Administrator | undefined> { return this.connection .getRepository(ctx, Administrator) .findOne({ relations, where: { user: { id: userId }, deletedAt: IsNull(), }, }) .then(result => result ?? undefined); } /** * @description * Create a new Administrator. */ async create(ctx: RequestContext, input: CreateAdministratorInput): Promise<Administrator> { await this.checkActiveUserCanGrantRoles(ctx, input.roleIds); const administrator = new Administrator(input); administrator.emailAddress = normalizeEmailAddress(input.emailAddress); administrator.user = await this.userService.createAdminUser(ctx, input.emailAddress, input.password); let createdAdministrator = await this.connection .getRepository(ctx, Administrator) .save(administrator); for (const roleId of input.roleIds) { createdAdministrator = await this.assignRole(ctx, createdAdministrator.id, roleId); } await this.customFieldRelationService.updateRelations( ctx, Administrator, input, createdAdministrator, ); await this.eventBus.publish(new AdministratorEvent(ctx, createdAdministrator, 'created', input)); return createdAdministrator; } /** * @description * Update an existing Administrator. */ async update(ctx: RequestContext, input: UpdateAdministratorInput): Promise<Administrator> { const administrator = await this.findOne(ctx, input.id); if (!administrator) { throw new EntityNotFoundError('Administrator', input.id); } if (input.roleIds) { await this.checkActiveUserCanGrantRoles(ctx, input.roleIds); } let updatedAdministrator = patchEntity(administrator, input); await this.connection.getRepository(ctx, Administrator).save(administrator, { reload: false }); if (input.emailAddress) { updatedAdministrator.user.identifier = input.emailAddress; await this.connection.getRepository(ctx, User).save(updatedAdministrator.user); } if (input.password) { const user = await this.userService.getUserById(ctx, administrator.user.id); if (user) { const nativeAuthMethod = user.getNativeAuthenticationMethod(); nativeAuthMethod.passwordHash = await this.passwordCipher.hash(input.password); await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod); } } if (input.roleIds) { const isSoleSuperAdmin = await this.isSoleSuperadmin(ctx, input.id); if (isSoleSuperAdmin) { const superAdminRole = await this.roleService.getSuperAdminRole(ctx); if (!input.roleIds.find(id => idsAreEqual(id, superAdminRole.id))) { throw new InternalServerError('error.superadmin-must-have-superadmin-role'); } } const removeIds = administrator.user.roles .map(role => role.id) .filter(roleId => (input.roleIds as ID[]).indexOf(roleId) === -1); const addIds = (input.roleIds as ID[]).filter( roleId => !administrator.user.roles.some(role => role.id === roleId), ); administrator.user.roles = []; await this.connection.getRepository(ctx, User).save(administrator.user, { reload: false }); for (const roleId of input.roleIds) { updatedAdministrator = await this.assignRole(ctx, administrator.id, roleId); } await this.eventBus.publish(new RoleChangeEvent(ctx, administrator, addIds, 'assigned')); await this.eventBus.publish(new RoleChangeEvent(ctx, administrator, removeIds, 'removed')); } await this.customFieldRelationService.updateRelations( ctx, Administrator, input, updatedAdministrator, ); await this.eventBus.publish(new AdministratorEvent(ctx, administrator, 'updated', input)); return updatedAdministrator; } /** * @description * Checks that the active user is allowed to grant the specified Roles when creating or * updating an Administrator. */ private async checkActiveUserCanGrantRoles(ctx: RequestContext, roleIds: ID[]) { const roles = await this.connection.getRepository(ctx, Role).find({ where: { id: In(roleIds) }, relations: { channels: true }, }); const permissionsRequired = getChannelPermissions(roles); for (const channelPermissions of permissionsRequired) { const activeUserHasRequiredPermissions = await this.roleService.userHasAllPermissionsOnChannel( ctx, channelPermissions.id, channelPermissions.permissions, ); if (!activeUserHasRequiredPermissions) { throw new UserInputError('error.active-user-does-not-have-sufficient-permissions'); } } } /** * @description * Assigns a Role to the Administrator's User entity. */ async assignRole(ctx: RequestContext, administratorId: ID, roleId: ID): Promise<Administrator> { const administrator = await this.findOne(ctx, administratorId); if (!administrator) { throw new EntityNotFoundError('Administrator', administratorId); } const role = await this.roleService.findOne(ctx, roleId); if (!role) { throw new EntityNotFoundError('Role', roleId); } administrator.user.roles.push(role); await this.connection.getRepository(ctx, User).save(administrator.user, { reload: false }); return administrator; } /** * @description * Soft deletes an Administrator (sets the `deletedAt` field). */ async softDelete(ctx: RequestContext, id: ID) { const administrator = await this.connection.getEntityOrThrow(ctx, Administrator, id, { relations: ['user'], }); const isSoleSuperadmin = await this.isSoleSuperadmin(ctx, id); if (isSoleSuperadmin) { throw new InternalServerError('error.cannot-delete-sole-superadmin'); } await this.connection.getRepository(ctx, Administrator).update({ id }, { deletedAt: new Date() }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await this.userService.softDelete(ctx, administrator.user.id); await this.eventBus.publish(new AdministratorEvent(ctx, administrator, 'deleted', id)); return { result: DeletionResult.DELETED, }; } /** * @description * Resolves to `true` if the administrator ID belongs to the only Administrator * with SuperAdmin permissions. */ private async isSoleSuperadmin(ctx: RequestContext, id: ID) { const superAdminRole = await this.roleService.getSuperAdminRole(ctx); const allAdmins = await this.connection.getRepository(ctx, Administrator).find({ relations: ['user', 'user.roles'], }); const superAdmins = allAdmins.filter( admin => !!admin.user.roles.find(r => r.id === superAdminRole.id), ); if (1 < superAdmins.length) { return false; } else { return idsAreEqual(superAdmins[0].id, id); } } /** * @description * There must always exist a SuperAdmin, otherwise full administration via API will * no longer be possible. * * @internal */ private async ensureSuperAdminExists() { const { superadminCredentials } = this.configService.authOptions; const superAdminUser = await this.connection.rawConnection.getRepository(User).findOne({ where: { identifier: superadminCredentials.identifier, }, }); if (!superAdminUser) { const ctx = await this.requestContextService.create({ apiType: 'admin' }); const superAdminRole = await this.roleService.getSuperAdminRole(); const administrator = new Administrator({ emailAddress: superadminCredentials.identifier, firstName: 'Super', lastName: 'Admin', }); administrator.user = await this.userService.createAdminUser( ctx, superadminCredentials.identifier, superadminCredentials.password, ); const { id } = await this.connection.getRepository(ctx, Administrator).save(administrator); const createdAdministrator = await assertFound(this.findOne(ctx, id)); createdAdministrator.user.roles.push(superAdminRole); await this.connection.getRepository(ctx, User).save(createdAdministrator.user, { reload: false }); } else { const superAdministrator = await this.connection.rawConnection .getRepository(Administrator) .findOne({ where: { user: { id: superAdminUser.id, }, }, }); if (!superAdministrator) { const administrator = new Administrator({ emailAddress: superadminCredentials.identifier, firstName: 'Super', lastName: 'Admin', }); const createdAdministrator = await this.connection.rawConnection .getRepository(Administrator) .save(administrator); createdAdministrator.user = superAdminUser; await this.connection.rawConnection.getRepository(Administrator).save(createdAdministrator); } else if (superAdministrator.deletedAt != null) { superAdministrator.deletedAt = null; await this.connection.rawConnection.getRepository(Administrator).save(superAdministrator); } if (superAdminUser.deletedAt != null) { superAdminUser.deletedAt = null; await this.connection.rawConnection.getRepository(User).save(superAdminUser); } } } }
import { Injectable } from '@nestjs/common'; import { AssetListOptions, AssetType, AssignAssetsToChannelInput, CreateAssetInput, CreateAssetResult, DeletionResponse, DeletionResult, LogicalOperator, Permission, UpdateAssetInput, } from '@vendure/common/lib/generated-types'; import { omit } from '@vendure/common/lib/omit'; import { ID, PaginatedList, Type } from '@vendure/common/lib/shared-types'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { unique } from '@vendure/common/lib/unique'; import { ReadStream as FSReadStream } from 'fs'; import { ReadStream } from 'fs-extra'; import { IncomingMessage } from 'http'; import mime from 'mime-types'; import path from 'path'; import { Readable, Stream } from 'stream'; import { IsNull } from 'typeorm'; import { FindOneOptions } from 'typeorm/find-options/FindOneOptions'; import { camelCase } from 'typeorm/util/StringUtils'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { isGraphQlErrorResult } from '../../common/error/error-result'; import { ForbiddenError, InternalServerError } from '../../common/error/errors'; import { MimeTypeError } from '../../common/error/generated-graphql-admin-errors'; import { ChannelAware } from '../../common/types/common-types'; import { getAssetType, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { Logger } from '../../config/logger/vendure-logger'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Asset } from '../../entity/asset/asset.entity'; import { OrderableAsset } from '../../entity/asset/orderable-asset.entity'; import { VendureEntity } from '../../entity/base/base.entity'; import { Collection } from '../../entity/collection/collection.entity'; import { Product } from '../../entity/product/product.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { EventBus } from '../../event-bus/event-bus'; import { AssetChannelEvent } from '../../event-bus/events/asset-channel-event'; import { AssetEvent } from '../../event-bus/events/asset-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { patchEntity } from '../helpers/utils/patch-entity'; import { ChannelService } from './channel.service'; import { RoleService } from './role.service'; import { TagService } from './tag.service'; // eslint-disable-next-line @typescript-eslint/no-var-requires const sizeOf = require('image-size'); /** * @description * Certain entities (Product, ProductVariant, Collection) use this interface * to model a featured asset and then a list of assets with a defined order. * * @docsCategory services * @docsPage AssetService */ export interface EntityWithAssets extends VendureEntity { featuredAsset: Asset | null; assets: OrderableAsset[]; } /** * @description * Used when updating entities which implement {@link EntityWithAssets}. * * @docsCategory services * @docsPage AssetService */ export interface EntityAssetInput { assetIds?: ID[] | null; featuredAssetId?: ID | null; } /** * @description * Contains methods relating to {@link Asset} entities. * * @docsCategory services * @docsWeight 0 */ @Injectable() export class AssetService { private permittedMimeTypes: Array<{ type: string; subtype: string }> = []; constructor( private connection: TransactionalConnection, private configService: ConfigService, private listQueryBuilder: ListQueryBuilder, private eventBus: EventBus, private tagService: TagService, private channelService: ChannelService, private roleService: RoleService, private customFieldRelationService: CustomFieldRelationService, ) { this.permittedMimeTypes = this.configService.assetOptions.permittedFileTypes .map(val => (/\.[\w]+/.test(val) ? mime.lookup(val) || undefined : val)) .filter(notNullOrUndefined) .map(val => { const [type, subtype] = val.split('/'); return { type, subtype }; }); } findOne(ctx: RequestContext, id: ID, relations?: RelationPaths<Asset>): Promise<Asset | undefined> { return this.connection .findOneInChannel(ctx, Asset, id, ctx.channelId, { relations: relations ?? [], }) .then(result => result ?? undefined); } findAll( ctx: RequestContext, options?: AssetListOptions, relations?: RelationPaths<Asset>, ): Promise<PaginatedList<Asset>> { const qb = this.listQueryBuilder.build(Asset, options, { ctx, relations: [...(relations ?? []), 'tags'], channelId: ctx.channelId, }); const tags = options?.tags; if (tags && tags.length) { const operator = options?.tagsOperator ?? LogicalOperator.AND; const subquery = qb.connection .createQueryBuilder() .select('asset.id') .from(Asset, 'asset') .leftJoin('asset.tags', 'tags') .where('tags.value IN (:...tags)'); if (operator === LogicalOperator.AND) { subquery.groupBy('asset.id').having('COUNT(asset.id) = :tagCount'); } qb.andWhere(`asset.id IN (${subquery.getQuery()})`).setParameters({ tags, tagCount: tags.length, }); } return qb.getManyAndCount().then(([items, totalItems]) => ({ items, totalItems, })); } async getFeaturedAsset<T extends Omit<EntityWithAssets, 'assets'>>( ctx: RequestContext, entity: T, ): Promise<Asset | undefined> { const entityType: Type<T> = Object.getPrototypeOf(entity).constructor; let entityWithFeaturedAsset: T | undefined; if (this.channelService.isChannelAware(entity)) { entityWithFeaturedAsset = await this.connection.findOneInChannel( ctx, entityType as Type<T & ChannelAware>, entity.id, ctx.channelId, { relations: ['featuredAsset'], }, ); } else { entityWithFeaturedAsset = await this.connection .getRepository(ctx, entityType) .findOne({ where: { id: entity.id }, relations: { featuredAsset: true, }, // TODO: satisfies } as FindOneOptions<T>) .then(result => result ?? undefined); } return (entityWithFeaturedAsset && entityWithFeaturedAsset.featuredAsset) || undefined; } /** * @description * Returns the Assets of an entity which has a well-ordered list of Assets, such as Product, * ProductVariant or Collection. */ async getEntityAssets<T extends EntityWithAssets>( ctx: RequestContext, entity: T, ): Promise<Asset[] | undefined> { let orderableAssets = entity.assets; if (!orderableAssets) { const entityType: Type<EntityWithAssets> = Object.getPrototypeOf(entity).constructor; const entityWithAssets = await this.connection .getRepository(ctx, entityType) .createQueryBuilder('entity') .leftJoinAndSelect('entity.assets', 'orderable_asset') .leftJoinAndSelect('orderable_asset.asset', 'asset') .leftJoinAndSelect('asset.channels', 'asset_channel') .where('entity.id = :id', { id: entity.id }) .andWhere('asset_channel.id = :channelId', { channelId: ctx.channelId }) .getOne(); orderableAssets = entityWithAssets?.assets ?? []; } else if (0 < orderableAssets.length) { // the Assets are already loaded, but we need to limit them by Channel if (orderableAssets[0].asset?.channels) { orderableAssets = orderableAssets.filter( a => !!a.asset.channels.map(c => c.id).find(id => idsAreEqual(id, ctx.channelId)), ); } else { const assetsInChannel = await this.connection .getRepository(ctx, Asset) .createQueryBuilder('asset') .leftJoinAndSelect('asset.channels', 'asset_channel') .where('asset.id IN (:...ids)', { ids: orderableAssets.map(a => a.assetId) }) .andWhere('asset_channel.id = :channelId', { channelId: ctx.channelId }) .getMany(); orderableAssets = orderableAssets.filter( oa => !!assetsInChannel.find(a => idsAreEqual(a.id, oa.assetId)), ); } } else { orderableAssets = []; } return orderableAssets.sort((a, b) => a.position - b.position).map(a => a.asset); } async updateFeaturedAsset<T extends EntityWithAssets>( ctx: RequestContext, entity: T, input: EntityAssetInput, ): Promise<T> { const { assetIds, featuredAssetId } = input; if (featuredAssetId === null || (assetIds && assetIds.length === 0)) { entity.featuredAsset = null; return entity; } if (featuredAssetId === undefined) { return entity; } const featuredAsset = await this.findOne(ctx, featuredAssetId); if (featuredAsset) { entity.featuredAsset = featuredAsset; } return entity; } /** * @description * Updates the assets / featuredAsset of an entity, ensuring that only valid assetIds are used. */ async updateEntityAssets<T extends EntityWithAssets>( ctx: RequestContext, entity: T, input: EntityAssetInput, ): Promise<T> { if (!entity.id) { throw new InternalServerError('error.entity-must-have-an-id'); } const { assetIds } = input; if (assetIds && assetIds.length) { const assets = await this.connection.findByIdsInChannel(ctx, Asset, assetIds, ctx.channelId, {}); const sortedAssets = assetIds .map(id => assets.find(a => idsAreEqual(a.id, id))) .filter(notNullOrUndefined); await this.removeExistingOrderableAssets(ctx, entity); entity.assets = await this.createOrderableAssets(ctx, entity, sortedAssets); } else if (assetIds && assetIds.length === 0) { await this.removeExistingOrderableAssets(ctx, entity); } return entity; } /** * @description * Create an Asset based on a file uploaded via the GraphQL API. The file should be uploaded * using the [GraphQL multipart request specification](https://github.com/jaydenseric/graphql-multipart-request-spec), * e.g. using the [apollo-upload-client](https://github.com/jaydenseric/apollo-upload-client) npm package. * * See the [Uploading Files docs](/guides/developer-guide/uploading-files) for an example of usage. */ async create(ctx: RequestContext, input: CreateAssetInput): Promise<CreateAssetResult> { return new Promise(async (resolve, reject) => { const { createReadStream, filename, mimetype } = await input.file; const stream = createReadStream(); stream.on('error', (err: any) => { reject(err); }); let result: Asset | MimeTypeError; try { result = await this.createAssetInternal(ctx, stream, filename, mimetype, input.customFields); } catch (e: any) { reject(e); return; } if (isGraphQlErrorResult(result)) { resolve(result); return; } await this.customFieldRelationService.updateRelations(ctx, Asset, input, result); if (input.tags) { const tags = await this.tagService.valuesToTags(ctx, input.tags); result.tags = tags; await this.connection.getRepository(ctx, Asset).save(result); } await this.eventBus.publish(new AssetEvent(ctx, result, 'created', input)); resolve(result); }); } /** * @description * Updates the name, focalPoint, tags & custom fields of an Asset. */ async update(ctx: RequestContext, input: UpdateAssetInput): Promise<Asset> { const asset = await this.connection.getEntityOrThrow(ctx, Asset, input.id); if (input.focalPoint) { const to3dp = (x: number) => +x.toFixed(3); input.focalPoint.x = to3dp(input.focalPoint.x); input.focalPoint.y = to3dp(input.focalPoint.y); } patchEntity(asset, omit(input, ['tags'])); await this.customFieldRelationService.updateRelations(ctx, Asset, input, asset); if (input.tags) { asset.tags = await this.tagService.valuesToTags(ctx, input.tags); } const updatedAsset = await this.connection.getRepository(ctx, Asset).save(asset); await this.eventBus.publish(new AssetEvent(ctx, updatedAsset, 'updated', input)); return updatedAsset; } /** * @description * Deletes an Asset after performing checks to ensure that the Asset is not currently in use * by a Product, ProductVariant or Collection. */ async delete( ctx: RequestContext, ids: ID[], force: boolean = false, deleteFromAllChannels: boolean = false, ): Promise<DeletionResponse> { const assets = await this.connection.findByIdsInChannel(ctx, Asset, ids, ctx.channelId, { relations: ['channels'], }); let channelsOfAssets: ID[] = []; assets.forEach(a => a.channels.forEach(c => channelsOfAssets.push(c.id))); channelsOfAssets = unique(channelsOfAssets); const usageCount = { products: 0, variants: 0, collections: 0, }; for (const asset of assets) { const usages = await this.findAssetUsages(ctx, asset); usageCount.products += usages.products.length; usageCount.variants += usages.variants.length; usageCount.collections += usages.collections.length; } const hasUsages = !!(usageCount.products || usageCount.variants || usageCount.collections); if (hasUsages && !force) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.asset-to-be-deleted-is-featured', { assetCount: assets.length, products: usageCount.products, variants: usageCount.variants, collections: usageCount.collections, }), }; } const hasDeleteAllPermission = await this.hasDeletePermissionForChannels(ctx, channelsOfAssets); if (deleteFromAllChannels && !hasDeleteAllPermission) { throw new ForbiddenError(); } if (!deleteFromAllChannels) { await Promise.all( assets.map(async asset => { await this.channelService.removeFromChannels(ctx, Asset, asset.id, [ctx.channelId]); await this.eventBus.publish(new AssetChannelEvent(ctx, asset, ctx.channelId, 'removed')); }), ); const isOnlyChannel = channelsOfAssets.length === 1; if (isOnlyChannel) { // only channel, so also delete asset await this.deleteUnconditional(ctx, assets); } return { result: DeletionResult.DELETED, }; } // This leaves us with deleteFromAllChannels with force or deleteFromAllChannels with no current usages await Promise.all( assets.map(async asset => { await this.channelService.removeFromChannels(ctx, Asset, asset.id, channelsOfAssets); await this.eventBus.publish(new AssetChannelEvent(ctx, asset, ctx.channelId, 'removed')); }), ); return this.deleteUnconditional(ctx, assets); } async assignToChannel(ctx: RequestContext, input: AssignAssetsToChannelInput): Promise<Asset[]> { const hasPermission = await this.roleService.userHasPermissionOnChannel( ctx, input.channelId, Permission.UpdateCatalog, ); if (!hasPermission) { throw new ForbiddenError(); } const assets = await this.connection.findByIdsInChannel( ctx, Asset, input.assetIds, ctx.channelId, {}, ); await Promise.all( assets.map(async asset => { await this.channelService.assignToChannels(ctx, Asset, asset.id, [input.channelId]); return await this.eventBus.publish( new AssetChannelEvent(ctx, asset, input.channelId, 'assigned'), ); }), ); return this.connection.findByIdsInChannel( ctx, Asset, assets.map(a => a.id), ctx.channelId, {}, ); } /** * @description * Create an Asset from a file stream, for example to create an Asset during data import. */ async createFromFileStream(stream: ReadStream, ctx?: RequestContext): Promise<CreateAssetResult>; async createFromFileStream( stream: Readable, filePath: string, ctx?: RequestContext, ): Promise<CreateAssetResult>; async createFromFileStream( stream: ReadStream | Readable, maybeFilePathOrCtx?: string | RequestContext, maybeCtx?: RequestContext, ): Promise<CreateAssetResult> { const { assetImportStrategy } = this.configService.importExportOptions; const filePathFromArgs = maybeFilePathOrCtx instanceof RequestContext ? undefined : maybeFilePathOrCtx; const filePath = stream instanceof ReadStream || stream instanceof FSReadStream ? stream.path : filePathFromArgs; if (typeof filePath === 'string') { const filename = path.basename(filePath).split('?')[0]; const mimetype = this.getMimeType(stream, filename); const ctx = maybeFilePathOrCtx instanceof RequestContext ? maybeFilePathOrCtx : maybeCtx instanceof RequestContext ? maybeCtx : RequestContext.empty(); return this.createAssetInternal(ctx, stream, filename, mimetype); } else { throw new InternalServerError('error.path-should-be-a-string-got-buffer'); } } private getMimeType(stream: Readable, filename: string): string { if (stream instanceof IncomingMessage) { const contentType = stream.headers['content-type']; if (contentType) { return contentType; } } return mime.lookup(filename) || 'application/octet-stream'; } /** * @description * Unconditionally delete given assets. * Does not remove assets from channels */ private async deleteUnconditional(ctx: RequestContext, assets: Asset[]): Promise<DeletionResponse> { for (const asset of assets) { // Create a new asset so that the id is still available // after deletion (the .remove() method sets it to undefined) const deletedAsset = new Asset(asset); await this.connection.getRepository(ctx, Asset).remove(asset); try { await this.configService.assetOptions.assetStorageStrategy.deleteFile(asset.source); await this.configService.assetOptions.assetStorageStrategy.deleteFile(asset.preview); } catch (e: any) { Logger.error('error.could-not-delete-asset-file', undefined, e.stack); } await this.eventBus.publish(new AssetEvent(ctx, deletedAsset, 'deleted', deletedAsset.id)); } return { result: DeletionResult.DELETED, }; } /** * Check if current user has permissions to delete assets from all channels */ private async hasDeletePermissionForChannels(ctx: RequestContext, channelIds: ID[]): Promise<boolean> { const permissions = await Promise.all( channelIds.map(async channelId => { return this.roleService.userHasPermissionOnChannel(ctx, channelId, Permission.DeleteCatalog); }), ); return !permissions.includes(false); } private async createAssetInternal( ctx: RequestContext, stream: Stream, filename: string, mimetype: string, customFields?: { [key: string]: any }, ): Promise<Asset | MimeTypeError> { const { assetOptions } = this.configService; if (!this.validateMimeType(mimetype)) { return new MimeTypeError({ fileName: filename, mimeType: mimetype }); } const { assetPreviewStrategy, assetStorageStrategy } = assetOptions; const sourceFileName = await this.getSourceFileName(ctx, filename); const previewFileName = await this.getPreviewFileName(ctx, sourceFileName); const sourceFileIdentifier = await assetStorageStrategy.writeFileFromStream(sourceFileName, stream); const sourceFile = await assetStorageStrategy.readFileToBuffer(sourceFileIdentifier); let preview: Buffer; try { preview = await assetPreviewStrategy.generatePreviewImage(ctx, mimetype, sourceFile); } catch (e: any) { const message: string = typeof e.message === 'string' ? e.message : e.message.toString(); Logger.error(`Could not create Asset preview image: ${message}`, undefined, e.stack); throw e; } const previewFileIdentifier = await assetStorageStrategy.writeFileFromBuffer( previewFileName, preview, ); const type = getAssetType(mimetype); const { width, height } = this.getDimensions(type === AssetType.IMAGE ? sourceFile : preview); const asset = new Asset({ type, width, height, name: path.basename(sourceFileName), fileSize: sourceFile.byteLength, mimeType: mimetype, source: sourceFileIdentifier, preview: previewFileIdentifier, focalPoint: null, customFields, }); await this.channelService.assignToCurrentChannel(asset, ctx); return this.connection.getRepository(ctx, Asset).save(asset); } private async getSourceFileName(ctx: RequestContext, fileName: string): Promise<string> { const { assetOptions } = this.configService; return this.generateUniqueName(fileName, (name, conflict) => assetOptions.assetNamingStrategy.generateSourceFileName(ctx, name, conflict), ); } private async getPreviewFileName(ctx: RequestContext, fileName: string): Promise<string> { const { assetOptions } = this.configService; return this.generateUniqueName(fileName, (name, conflict) => assetOptions.assetNamingStrategy.generatePreviewFileName(ctx, name, conflict), ); } private async generateUniqueName( inputFileName: string, generateNameFn: (fileName: string, conflictName?: string) => string, ): Promise<string> { const { assetOptions } = this.configService; let outputFileName: string | undefined; do { outputFileName = generateNameFn(inputFileName, outputFileName); } while (await assetOptions.assetStorageStrategy.fileExists(outputFileName)); return outputFileName; } private getDimensions(imageFile: Buffer): { width: number; height: number } { try { const { width, height } = sizeOf(imageFile); return { width, height }; } catch (e: any) { Logger.error('Could not determine Asset dimensions: ' + JSON.stringify(e)); return { width: 0, height: 0 }; } } private createOrderableAssets( ctx: RequestContext, entity: EntityWithAssets, assets: Asset[], ): Promise<OrderableAsset[]> { const orderableAssets = assets.map((asset, i) => this.getOrderableAsset(ctx, entity, asset, i)); return this.connection.getRepository(ctx, orderableAssets[0].constructor).save(orderableAssets); } private getOrderableAsset( ctx: RequestContext, entity: EntityWithAssets, asset: Asset, index: number, ): OrderableAsset { const entityIdProperty = this.getHostEntityIdProperty(entity); const orderableAssetType = this.getOrderableAssetType(ctx, entity); return new orderableAssetType({ assetId: asset.id, position: index, [entityIdProperty]: entity.id, }); } private async removeExistingOrderableAssets(ctx: RequestContext, entity: EntityWithAssets) { const propertyName = this.getHostEntityIdProperty(entity); const orderableAssetType = this.getOrderableAssetType(ctx, entity); await this.connection.getRepository(ctx, orderableAssetType).delete({ [propertyName]: entity.id, }); } private getOrderableAssetType(ctx: RequestContext, entity: EntityWithAssets): Type<OrderableAsset> { const assetRelation = this.connection .getRepository(ctx, entity.constructor) .metadata.relations.find(r => r.propertyName === 'assets'); if (!assetRelation || typeof assetRelation.type === 'string') { throw new InternalServerError('error.could-not-find-matching-orderable-asset'); } return assetRelation.type as Type<OrderableAsset>; } private getHostEntityIdProperty(entity: EntityWithAssets): string { const entityName = entity.constructor.name; switch (entityName) { case 'Product': return 'productId'; case 'ProductVariant': return 'productVariantId'; case 'Collection': return 'collectionId'; default: return `${camelCase(entityName)}Id`; } } private validateMimeType(mimeType: string): boolean { const [type, subtype] = mimeType.split('/'); const typeMatches = this.permittedMimeTypes.filter(t => t.type === type); for (const match of typeMatches) { if (match.subtype === subtype || match.subtype === '*') { return true; } } return false; } /** * Find the entities which reference the given Asset as a featuredAsset. */ private async findAssetUsages( ctx: RequestContext, asset: Asset, ): Promise<{ products: Product[]; variants: ProductVariant[]; collections: Collection[] }> { const products = await this.connection.getRepository(ctx, Product).find({ where: { featuredAsset: { id: asset.id }, deletedAt: IsNull(), }, }); const variants = await this.connection.getRepository(ctx, ProductVariant).find({ where: { featuredAsset: { id: asset.id }, deletedAt: IsNull(), }, }); const collections = await this.connection.getRepository(ctx, Collection).find({ where: { featuredAsset: { id: asset.id }, }, }); return { products, variants, collections }; } }
import { Injectable } from '@nestjs/common'; import { ID } from '@vendure/common/lib/shared-types'; import { ApiType } from '../../api/common/get-api-type'; import { RequestContext } from '../../api/common/request-context'; import { InternalServerError } from '../../common/error/errors'; import { InvalidCredentialsError } from '../../common/error/generated-graphql-admin-errors'; import { InvalidCredentialsError as ShopInvalidCredentialsError, NotVerifiedError, } from '../../common/error/generated-graphql-shop-errors'; import { AuthenticationStrategy } from '../../config/auth/authentication-strategy'; import { NativeAuthenticationData, NativeAuthenticationStrategy, NATIVE_AUTH_STRATEGY_NAME, } from '../../config/auth/native-authentication-strategy'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { ExternalAuthenticationMethod } from '../../entity/authentication-method/external-authentication-method.entity'; import { AuthenticatedSession } from '../../entity/session/authenticated-session.entity'; import { User } from '../../entity/user/user.entity'; import { EventBus } from '../../event-bus/event-bus'; import { AttemptedLoginEvent } from '../../event-bus/events/attempted-login-event'; import { LoginEvent } from '../../event-bus/events/login-event'; import { LogoutEvent } from '../../event-bus/events/logout-event'; import { SessionService } from './session.service'; /** * @description * Contains methods relating to {@link Session}, {@link AuthenticatedSession} & {@link AnonymousSession} entities. * * @docsCategory services */ @Injectable() export class AuthService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private sessionService: SessionService, private eventBus: EventBus, ) {} /** * @description * Authenticates a user's credentials and if okay, creates a new {@link AuthenticatedSession}. */ async authenticate( ctx: RequestContext, apiType: ApiType, authenticationMethod: string, authenticationData: any, ): Promise<AuthenticatedSession | InvalidCredentialsError | NotVerifiedError> { await this.eventBus.publish( new AttemptedLoginEvent( ctx, authenticationMethod, authenticationMethod === NATIVE_AUTH_STRATEGY_NAME ? (authenticationData as NativeAuthenticationData).username : undefined, ), ); const authenticationStrategy = this.getAuthenticationStrategy(apiType, authenticationMethod); const authenticateResult = await authenticationStrategy.authenticate(ctx, authenticationData); if (typeof authenticateResult === 'string') { return new InvalidCredentialsError({ authenticationError: authenticateResult }); } if (!authenticateResult) { return new InvalidCredentialsError({ authenticationError: '' }); } return this.createAuthenticatedSessionForUser(ctx, authenticateResult, authenticationStrategy.name); } async createAuthenticatedSessionForUser( ctx: RequestContext, user: User, authenticationStrategyName: string, ): Promise<AuthenticatedSession | NotVerifiedError> { if (!user.roles || !user.roles[0]?.channels) { const userWithRoles = await this.connection .getRepository(ctx, User) .createQueryBuilder('user') .leftJoinAndSelect('user.roles', 'role') .leftJoinAndSelect('role.channels', 'channel') .where('user.id = :userId', { userId: user.id }) .getOne(); user.roles = userWithRoles?.roles || []; } const extAuths = (user.authenticationMethods ?? []).filter( am => am instanceof ExternalAuthenticationMethod, ); if (!extAuths.length && this.configService.authOptions.requireVerification && !user.verified) { return new NotVerifiedError(); } if (ctx.session && ctx.session.activeOrderId) { await this.sessionService.deleteSessionsByActiveOrderId(ctx, ctx.session.activeOrderId); } user.lastLogin = new Date(); await this.connection.getRepository(ctx, User).save(user, { reload: false }); const session = await this.sessionService.createNewAuthenticatedSession( ctx, user, authenticationStrategyName, ); await this.eventBus.publish(new LoginEvent(ctx, user)); return session; } /** * @description * Verify the provided password against the one we have for the given user. Requires * the {@link NativeAuthenticationStrategy} to be configured. */ async verifyUserPassword( ctx: RequestContext, userId: ID, password: string, ): Promise<boolean | InvalidCredentialsError | ShopInvalidCredentialsError> { const nativeAuthenticationStrategy = this.getAuthenticationStrategy( 'shop', NATIVE_AUTH_STRATEGY_NAME, ); const passwordMatches = await nativeAuthenticationStrategy.verifyUserPassword(ctx, userId, password); if (!passwordMatches) { return new InvalidCredentialsError({ authenticationError: '' }); } return true; } /** * @description * Deletes all sessions for the user associated with the given session token. */ async destroyAuthenticatedSession(ctx: RequestContext, sessionToken: string): Promise<void> { const session = await this.connection.getRepository(ctx, AuthenticatedSession).findOne({ where: { token: sessionToken }, relations: ['user', 'user.authenticationMethods'], }); if (session) { const authenticationStrategy = this.getAuthenticationStrategy( ctx.apiType, session.authenticationStrategy, ); if (typeof authenticationStrategy.onLogOut === 'function') { await authenticationStrategy.onLogOut(ctx, session.user); } await this.eventBus.publish(new LogoutEvent(ctx)); return this.sessionService.deleteSessionsByUser(ctx, session.user); } } private getAuthenticationStrategy( apiType: ApiType, method: typeof NATIVE_AUTH_STRATEGY_NAME, ): NativeAuthenticationStrategy; private getAuthenticationStrategy(apiType: ApiType, method: string): AuthenticationStrategy; private getAuthenticationStrategy(apiType: ApiType, method: string): AuthenticationStrategy { const { authOptions } = this.configService; const strategies = apiType === 'admin' ? authOptions.adminAuthenticationStrategy : authOptions.shopAuthenticationStrategy; const match = strategies.find(s => s.name === method); if (!match) { throw new InternalServerError('error.unrecognized-authentication-strategy', { name: method }); } return match; } }
import { Injectable } from '@nestjs/common'; import { CreateChannelInput, CreateChannelResult, CurrencyCode, DeletionResponse, DeletionResult, UpdateChannelInput, UpdateChannelResult, } from '@vendure/common/lib/generated-types'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { ID, PaginatedList, Type } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { FindOptionsWhere } from 'typeorm'; import { RelationPaths } from '../../api'; import { RequestContext } from '../../api/common/request-context'; import { ErrorResultUnion, isGraphQlErrorResult } from '../../common/error/error-result'; import { ChannelNotFoundError, EntityNotFoundError, InternalServerError, UserInputError, } from '../../common/error/errors'; import { LanguageNotAvailableError } from '../../common/error/generated-graphql-admin-errors'; import { createSelfRefreshingCache, SelfRefreshingCache } from '../../common/self-refreshing-cache'; import { ChannelAware, ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { VendureEntity } from '../../entity/base/base.entity'; import { Channel } from '../../entity/channel/channel.entity'; import { Order } from '../../entity/order/order.entity'; import { ProductVariantPrice } from '../../entity/product-variant/product-variant-price.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { Seller } from '../../entity/seller/seller.entity'; import { Session } from '../../entity/session/session.entity'; import { Zone } from '../../entity/zone/zone.entity'; import { EventBus } from '../../event-bus'; import { ChangeChannelEvent } from '../../event-bus/events/change-channel-event'; import { ChannelEvent } from '../../event-bus/events/channel-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { patchEntity } from '../helpers/utils/patch-entity'; import { GlobalSettingsService } from './global-settings.service'; /** * @description * Contains methods relating to {@link Channel} entities. * * @docsCategory services */ @Injectable() export class ChannelService { private allChannels: SelfRefreshingCache<Channel[], [RequestContext]>; constructor( private connection: TransactionalConnection, private configService: ConfigService, private globalSettingsService: GlobalSettingsService, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private listQueryBuilder: ListQueryBuilder, ) {} /** * When the app is bootstrapped, ensure a default Channel exists and populate the * channel lookup array. * * @internal */ async initChannels() { await this.ensureDefaultChannelExists(); await this.ensureCacheExists(); } /** * Creates a channels cache, that can be used to reduce number of channel queries to database * * @internal */ async createCache(): Promise<SelfRefreshingCache<Channel[], [RequestContext]>> { return createSelfRefreshingCache({ name: 'ChannelService.allChannels', ttl: this.configService.entityOptions.channelCacheTtl, refresh: { fn: async ctx => { const result = await this.listQueryBuilder .build( Channel, {}, { ctx, relations: ['defaultShippingZone', 'defaultTaxZone'], ignoreQueryLimits: true, }, ) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); return result.items; }, defaultArgs: [RequestContext.empty()], }, }); } /** * @description * Assigns a ChannelAware entity to the default Channel as well as any channel * specified in the RequestContext. */ async assignToCurrentChannel<T extends ChannelAware & VendureEntity>( entity: T, ctx: RequestContext, ): Promise<T> { const defaultChannel = await this.getDefaultChannel(ctx); const channelIds = unique([ctx.channelId, defaultChannel.id]); entity.channels = channelIds.map(id => ({ id })) as any; await this.eventBus.publish(new ChangeChannelEvent(ctx, entity, [ctx.channelId], 'assigned')); return entity; } /** * This method is used to bypass a bug with Typeorm when working with ManyToMany relationships. * For some reason, a regular query does not return all the channels that an entity has. * This is a most optimized way to get all the channels that an entity has. * * @param ctx - The RequestContext object. * @param entityType - The type of the entity. * @param entityId - The ID of the entity. * @returns A promise that resolves to an array of objects, each containing a channel ID. * @private */ private async getAssignedEntityChannels<T extends ChannelAware & VendureEntity>( ctx: RequestContext, entityType: Type<T>, entityId: T['id'], ): Promise<Array<{ channelId: ID }>> { const repository = this.connection.getRepository(ctx, entityType); const metadata = repository.metadata; const channelsRelation = metadata.findRelationWithPropertyPath('channels'); if (!channelsRelation) { throw new InternalServerError(`Could not find the channels relation for entity ${metadata.name}`); } const junctionTableName = channelsRelation.junctionEntityMetadata?.tableName; const junctionColumnName = channelsRelation.junctionEntityMetadata?.columns[0].databaseName; const inverseJunctionColumnName = channelsRelation.junctionEntityMetadata?.inverseColumns[0].databaseName; if (!junctionTableName || !junctionColumnName || !inverseJunctionColumnName) { throw new InternalServerError( `Could not find necessary join table information for the channels relation of entity ${metadata.name}`, ); } return await this.connection .getRepository(ctx, entityType) .manager.createQueryBuilder() .select(`channel.${inverseJunctionColumnName}`, 'channelId') .from(junctionTableName, 'channel') .where(`channel.${junctionColumnName} = :entityId`, { entityId }) .execute(); } /** * @description * Assigns the entity to the given Channels and saves. */ async assignToChannels<T extends ChannelAware & VendureEntity>( ctx: RequestContext, entityType: Type<T>, entityId: ID, channelIds: ID[], ): Promise<T> { const relations = []; // This is a work-around for https://github.com/vendure-ecommerce/vendure/issues/1391 // A better API would be to allow the consumer of this method to supply an entity instance // so that this join could be done prior to invoking this method. // TODO: overload the assignToChannels method to allow it to take an entity instance if (entityType === (Order as any)) { relations.push('lines', 'shippingLines'); } const entity = await this.connection.getEntityOrThrow(ctx, entityType, entityId, { loadEagerRelations: false, relationLoadStrategy: 'query', where: { id: entityId, } as FindOptionsWhere<T>, relations, }); const assignedChannels = await this.getAssignedEntityChannels(ctx, entityType, entityId); const newChannelIds = channelIds.filter( id => !assignedChannels.some(ec => idsAreEqual(ec.channelId, id)), ); await this.connection .getRepository(ctx, entityType) .createQueryBuilder() .relation('channels') .of(entity.id) .add(newChannelIds); await this.eventBus.publish(new ChangeChannelEvent(ctx, entity, channelIds, 'assigned', entityType)); return entity; } /** * @description * Removes the entity from the given Channels and saves. */ async removeFromChannels<T extends ChannelAware & VendureEntity>( ctx: RequestContext, entityType: Type<T>, entityId: ID, channelIds: ID[], ): Promise<T | undefined> { const entity = await this.connection.getRepository(ctx, entityType).findOne({ loadEagerRelations: false, relationLoadStrategy: 'query', where: { id: entityId, } as FindOptionsWhere<T>, }); if (!entity) { return; } const assignedChannels = await this.getAssignedEntityChannels(ctx, entityType, entityId); const existingChannelIds = channelIds.filter(id => assignedChannels.some(ec => idsAreEqual(ec.channelId, id)), ); if (!existingChannelIds.length) { return; } await this.connection .getRepository(ctx, entityType) .createQueryBuilder() .relation('channels') .of(entity.id) .remove(existingChannelIds); await this.eventBus.publish(new ChangeChannelEvent(ctx, entity, channelIds, 'removed', entityType)); return entity; } /** * @description * Given a channel token, returns the corresponding Channel if it exists, else will throw * a {@link ChannelNotFoundError}. */ async getChannelFromToken(token: string): Promise<Channel>; async getChannelFromToken(ctx: RequestContext, token: string): Promise<Channel>; async getChannelFromToken(ctxOrToken: RequestContext | string, token?: string): Promise<Channel> { const [ctx, channelToken] = // eslint-disable-next-line @typescript-eslint/no-non-null-assertion ctxOrToken instanceof RequestContext ? [ctxOrToken, token!] : [undefined, ctxOrToken]; const allChannels = await this.allChannels.value(ctx); if (allChannels.length === 1 || channelToken === '') { // there is only the default channel, so return it return this.getDefaultChannel(ctx); } const channel = allChannels.find(c => c.token === channelToken); if (!channel) { throw new ChannelNotFoundError(channelToken); } return channel; } /** * @description * Returns the default Channel. */ async getDefaultChannel(ctx?: RequestContext): Promise<Channel> { const allChannels = await this.allChannels.value(ctx); const defaultChannel = allChannels.find(channel => channel.code === DEFAULT_CHANNEL_CODE); if (!defaultChannel) { throw new InternalServerError('error.default-channel-not-found'); } return defaultChannel; } findAll( ctx: RequestContext, options?: ListQueryOptions<Channel>, relations?: RelationPaths<Channel>, ): Promise<PaginatedList<Channel>> { return this.listQueryBuilder .build(Channel, options, { relations: relations ?? ['defaultShippingZone', 'defaultTaxZone'], ctx, }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } findOne(ctx: RequestContext, id: ID): Promise<Channel | undefined> { return this.connection .getRepository(ctx, Channel) .findOne({ where: { id }, relations: ['defaultShippingZone', 'defaultTaxZone'] }) .then(result => result ?? undefined); } async create( ctx: RequestContext, input: CreateChannelInput, ): Promise<ErrorResultUnion<CreateChannelResult, Channel>> { const defaultCurrencyCode = input.defaultCurrencyCode || input.currencyCode; if (!defaultCurrencyCode) { throw new UserInputError('Either a defaultCurrencyCode or currencyCode must be provided'); } const channel = new Channel({ ...input, defaultCurrencyCode, availableCurrencyCodes: input.availableCurrencyCodes ?? (defaultCurrencyCode ? [defaultCurrencyCode] : []), availableLanguageCodes: input.availableLanguageCodes ?? [input.defaultLanguageCode], }); const defaultLanguageValidationResult = await this.validateDefaultLanguageCode(ctx, input); if (isGraphQlErrorResult(defaultLanguageValidationResult)) { return defaultLanguageValidationResult; } if (input.defaultTaxZoneId) { channel.defaultTaxZone = await this.connection.getEntityOrThrow( ctx, Zone, input.defaultTaxZoneId, ); } if (input.defaultShippingZoneId) { channel.defaultShippingZone = await this.connection.getEntityOrThrow( ctx, Zone, input.defaultShippingZoneId, ); } const newChannel = await this.connection.getRepository(ctx, Channel).save(channel); if (input.sellerId) { const seller = await this.connection.getEntityOrThrow(ctx, Seller, input.sellerId); newChannel.seller = seller; await this.connection.getRepository(ctx, Channel).save(newChannel); } await this.customFieldRelationService.updateRelations(ctx, Channel, input, newChannel); await this.allChannels.refresh(ctx); await this.eventBus.publish(new ChannelEvent(ctx, newChannel, 'created', input)); return newChannel; } async update( ctx: RequestContext, input: UpdateChannelInput, ): Promise<ErrorResultUnion<UpdateChannelResult, Channel>> { const channel = await this.findOne(ctx, input.id); if (!channel) { throw new EntityNotFoundError('Channel', input.id); } const originalDefaultCurrencyCode = channel.defaultCurrencyCode; const defaultLanguageValidationResult = await this.validateDefaultLanguageCode(ctx, input); if (isGraphQlErrorResult(defaultLanguageValidationResult)) { return defaultLanguageValidationResult; } const updatedChannel = patchEntity(channel, input); if (input.defaultTaxZoneId) { updatedChannel.defaultTaxZone = await this.connection.getEntityOrThrow( ctx, Zone, input.defaultTaxZoneId, ); } if (input.defaultShippingZoneId) { updatedChannel.defaultShippingZone = await this.connection.getEntityOrThrow( ctx, Zone, input.defaultShippingZoneId, ); } if (input.sellerId) { const seller = await this.connection.getEntityOrThrow(ctx, Seller, input.sellerId); updatedChannel.seller = seller; } if (input.currencyCode) { updatedChannel.defaultCurrencyCode = input.currencyCode; } if (input.currencyCode || input.defaultCurrencyCode) { const newCurrencyCode = input.defaultCurrencyCode || input.currencyCode; updatedChannel.availableCurrencyCodes = unique([ ...updatedChannel.availableCurrencyCodes, updatedChannel.defaultCurrencyCode, ]); if (originalDefaultCurrencyCode !== newCurrencyCode) { // When updating the default currency code for a Channel, we also need to update // and ProductVariantPrices in that channel which use the old currency code. const [selectQbQuery, selectQbParams] = this.connection .getRepository(ctx, ProductVariant) .createQueryBuilder('variant') .select('variant.id', 'id') .innerJoin(ProductVariantPrice, 'pvp', 'pvp.variantId = variant.id') .andWhere('pvp.channelId = :channelId') .andWhere('pvp.currencyCode = :newCurrencyCode') .groupBy('variant.id') .getQueryAndParameters(); const qb = this.connection .getRepository(ctx, ProductVariantPrice) .createQueryBuilder('pvp') .update() .where('channelId = :channelId') .andWhere('currencyCode = :oldCurrencyCode') .set({ currencyCode: newCurrencyCode }) .setParameters({ channelId: channel.id, oldCurrencyCode: originalDefaultCurrencyCode, newCurrencyCode, }); if (this.connection.rawConnection.options.type === 'mysql') { // MySQL does not support sub-queries joining the table that is being updated, // it will cause a "You can't specify target table 'product_variant_price' for update in FROM clause" error. // This is a work-around from https://stackoverflow.com/a/9843719/772859 qb.andWhere( `variantId NOT IN (SELECT id FROM (${selectQbQuery}) as temp)`, selectQbParams, ); } else { qb.andWhere(`variantId NOT IN (${selectQbQuery})`, selectQbParams); } await qb.execute(); } } if ( input.availableCurrencyCodes && !updatedChannel.availableCurrencyCodes.includes(updatedChannel.defaultCurrencyCode) ) { throw new UserInputError(`error.available-currency-codes-must-include-default`, { defaultCurrencyCode: updatedChannel.defaultCurrencyCode, }); } await this.connection.getRepository(ctx, Channel).save(updatedChannel, { reload: false }); await this.customFieldRelationService.updateRelations(ctx, Channel, input, updatedChannel); await this.allChannels.refresh(ctx); await this.eventBus.publish(new ChannelEvent(ctx, channel, 'updated', input)); return assertFound(this.findOne(ctx, channel.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const channel = await this.connection.getEntityOrThrow(ctx, Channel, id); const deletedChannel = new Channel(channel); await this.connection.getRepository(ctx, Session).delete({ activeChannelId: id }); await this.connection.getRepository(ctx, Channel).delete(id); await this.connection.getRepository(ctx, ProductVariantPrice).delete({ channelId: id, }); await this.eventBus.publish(new ChannelEvent(ctx, deletedChannel, 'deleted', id)); return { result: DeletionResult.DELETED, }; } /** * @description * Type guard method which returns true if the given entity is an * instance of a class which implements the {@link ChannelAware} interface. */ public isChannelAware(entity: VendureEntity): entity is VendureEntity & ChannelAware { const entityType = Object.getPrototypeOf(entity).constructor; return !!this.connection.rawConnection .getMetadata(entityType) .relations.find(r => r.type === Channel && r.propertyName === 'channels'); } /** * Ensures channel cache exists. If not, this method creates one. */ private async ensureCacheExists() { if (this.allChannels) { return; } this.allChannels = await this.createCache(); } /** * There must always be a default Channel. If none yet exists, this method creates one. * Also ensures the default Channel token matches the defaultChannelToken config setting. */ private async ensureDefaultChannelExists() { const { defaultChannelToken } = this.configService; let defaultChannel = await this.connection.rawConnection.getRepository(Channel).findOne({ where: { code: DEFAULT_CHANNEL_CODE, }, relations: ['seller'], }); if (!defaultChannel) { defaultChannel = new Channel({ code: DEFAULT_CHANNEL_CODE, defaultLanguageCode: this.configService.defaultLanguageCode, availableLanguageCodes: [this.configService.defaultLanguageCode], pricesIncludeTax: false, defaultCurrencyCode: CurrencyCode.USD, availableCurrencyCodes: [CurrencyCode.USD], token: defaultChannelToken, }); } else if (defaultChannelToken && defaultChannel.token !== defaultChannelToken) { defaultChannel.token = defaultChannelToken; await this.connection.rawConnection .getRepository(Channel) .save(defaultChannel, { reload: false }); } if (!defaultChannel.seller) { const seller = await this.connection.rawConnection.getRepository(Seller).find(); if (seller.length === 0) { throw new InternalServerError('No Sellers were found. Could not initialize default Channel.'); } defaultChannel.seller = seller[0]; await this.connection.rawConnection .getRepository(Channel) .save(defaultChannel, { reload: false }); } } private async validateDefaultLanguageCode( ctx: RequestContext, input: CreateChannelInput | UpdateChannelInput, ): Promise<LanguageNotAvailableError | undefined> { if (input.defaultLanguageCode) { const availableLanguageCodes = await this.globalSettingsService .getSettings(ctx) .then(s => s.availableLanguages); if (!availableLanguageCodes.includes(input.defaultLanguageCode)) { return new LanguageNotAvailableError({ languageCode: input.defaultLanguageCode }); } } } }
import { Injectable, OnModuleInit } from '@nestjs/common'; import { AssignCollectionsToChannelInput, ConfigurableOperation, ConfigurableOperationDefinition, CreateCollectionInput, DeletionResponse, DeletionResult, JobState, MoveCollectionInput, Permission, PreviewCollectionVariantsInput, RemoveCollectionsFromChannelInput, UpdateCollectionInput, } from '@vendure/common/lib/generated-types'; import { pick } from '@vendure/common/lib/pick'; import { ROOT_COLLECTION_NAME } from '@vendure/common/lib/shared-constants'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { merge } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { In, IsNull } from 'typeorm'; import { RequestContext, SerializedRequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ForbiddenError, IllegalOperationError, UserInputError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { Logger } from '../../config/logger/vendure-logger'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { CollectionTranslation } from '../../entity/collection/collection-translation.entity'; import { Collection } from '../../entity/collection/collection.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { EventBus } from '../../event-bus/event-bus'; import { CollectionEvent } from '../../event-bus/events/collection-event'; import { CollectionModificationEvent } from '../../event-bus/events/collection-modification-event'; import { ProductEvent } from '../../event-bus/events/product-event'; import { ProductVariantEvent } from '../../event-bus/events/product-variant-event'; import { JobQueue } from '../../job-queue/job-queue'; import { JobQueueService } from '../../job-queue/job-queue.service'; import { ConfigArgService } from '../helpers/config-arg/config-arg.service'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { SlugValidator } from '../helpers/slug-validator/slug-validator'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { moveToIndex } from '../helpers/utils/move-to-index'; import { AssetService } from './asset.service'; import { ChannelService } from './channel.service'; import { RoleService } from './role.service'; export type ApplyCollectionFiltersJobData = { ctx: SerializedRequestContext; collectionIds: ID[]; applyToChangedVariantsOnly?: boolean; }; /** * @description * Contains methods relating to {@link Collection} entities. * * @docsCategory services */ @Injectable() export class CollectionService implements OnModuleInit { private rootCollection: Translated<Collection> | undefined; private applyFiltersQueue: JobQueue<ApplyCollectionFiltersJobData>; constructor( private connection: TransactionalConnection, private channelService: ChannelService, private assetService: AssetService, private listQueryBuilder: ListQueryBuilder, private translatableSaver: TranslatableSaver, private eventBus: EventBus, private jobQueueService: JobQueueService, private configService: ConfigService, private slugValidator: SlugValidator, private configArgService: ConfigArgService, private customFieldRelationService: CustomFieldRelationService, private translator: TranslatorService, private roleService: RoleService, ) {} /** * @internal */ async onModuleInit() { const productEvents$ = this.eventBus.ofType(ProductEvent); const variantEvents$ = this.eventBus.ofType(ProductVariantEvent); merge(productEvents$, variantEvents$) .pipe(debounceTime(50)) // eslint-disable-next-line @typescript-eslint/no-misused-promises .subscribe(async event => { const collections = await this.connection.rawConnection .getRepository(Collection) .createQueryBuilder('collection') .select('collection.id', 'id') .getRawMany(); await this.applyFiltersQueue.add({ ctx: event.ctx.serialize(), collectionIds: collections.map(c => c.id), }, { ctx: event.ctx }); }); this.applyFiltersQueue = await this.jobQueueService.createQueue({ name: 'apply-collection-filters', process: async job => { const ctx = RequestContext.deserialize(job.data.ctx); Logger.verbose(`Processing ${job.data.collectionIds.length} Collections`); let completed = 0; for (const collectionId of job.data.collectionIds) { if (job.state === JobState.CANCELLED) { throw new Error(`Job was cancelled`); } let collection: Collection | undefined; try { collection = await this.connection.getEntityOrThrow(ctx, Collection, collectionId, { retries: 5, retryDelay: 50, }); } catch (err: any) { Logger.warn(`Could not find Collection with id ${collectionId}, skipping`); } completed++; if (collection) { let affectedVariantIds: ID[] = []; try { affectedVariantIds = await this.applyCollectionFiltersInternal( collection, job.data.applyToChangedVariantsOnly, ); } catch (e: any) { const translatedCollection = this.translator.translate(collection, ctx); Logger.error( 'An error occurred when processing the filters for ' + `the collection "${translatedCollection.name}" (id: ${collection.id})`, ); Logger.error(e.message); continue; } job.setProgress(Math.ceil((completed / job.data.collectionIds.length) * 100)); if (affectedVariantIds.length) { await this.eventBus.publish( new CollectionModificationEvent(ctx, collection, affectedVariantIds), ); } } } }, }); } async findAll( ctx: RequestContext, options?: ListQueryOptions<Collection> & { topLevelOnly?: boolean }, relations?: RelationPaths<Collection>, ): Promise<PaginatedList<Translated<Collection>>> { const qb = this.listQueryBuilder.build(Collection, options, { relations: relations ?? ['featuredAsset', 'parent', 'channels'], channelId: ctx.channelId, where: { isRoot: false }, orderBy: { position: 'ASC' }, ctx, }); if (options?.topLevelOnly === true) { qb.innerJoin('collection.parent', 'parent_filter', 'parent_filter.isRoot = :isRoot', { isRoot: true, }); } return qb.getManyAndCount().then(async ([collections, totalItems]) => { const items = collections.map(collection => this.translator.translate(collection, ctx, ['parent']), ); return { items, totalItems, }; }); } async findOne( ctx: RequestContext, collectionId: ID, relations?: RelationPaths<Collection>, ): Promise<Translated<Collection> | undefined> { const collection = await this.connection.findOneInChannel( ctx, Collection, collectionId, ctx.channelId, { relations: relations ?? ['featuredAsset', 'assets', 'channels', 'parent'], loadEagerRelations: true, }, ); if (!collection) { return; } return this.translator.translate(collection, ctx, ['parent']); } async findByIds( ctx: RequestContext, ids: ID[], relations?: RelationPaths<Collection>, ): Promise<Array<Translated<Collection>>> { const collections = this.connection.findByIdsInChannel(ctx, Collection, ids, ctx.channelId, { relations: relations ?? ['featuredAsset', 'assets', 'channels', 'parent'], loadEagerRelations: true, }); return collections.then(values => values.map(collection => this.translator.translate(collection, ctx, ['parent'])), ); } async findOneBySlug( ctx: RequestContext, slug: string, relations?: RelationPaths<Collection>, ): Promise<Translated<Collection> | undefined> { const translations = await this.connection.getRepository(ctx, CollectionTranslation).find({ relations: ['base'], where: { slug, base: { channels: { id: ctx.channelId, }, }, }, }); if (!translations?.length) { return; } const bestMatch = translations.find(t => t.languageCode === ctx.languageCode) ?? translations.find(t => t.languageCode === ctx.channel.defaultLanguageCode) ?? translations[0]; return this.findOne(ctx, bestMatch.base.id, relations); } /** * @description * Returns all configured CollectionFilters, as specified by the {@link CatalogOptions}. */ getAvailableFilters(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.configService.catalogOptions.collectionFilters.map(f => f.toGraphQlType(ctx)); } async getParent(ctx: RequestContext, collectionId: ID): Promise<Collection | undefined> { const parent = await this.connection .getRepository(ctx, Collection) .createQueryBuilder('collection') .leftJoinAndSelect('collection.translations', 'translation') .where( qb => `collection.id = ${qb .subQuery() .select(`${qb.escape('child')}.${qb.escape('parentId')}`) .from(Collection, 'child') .where('child.id = :id', { id: collectionId }) .getQuery()}`, ) .getOne(); return (parent && this.translator.translate(parent, ctx)) ?? undefined; } /** * @description * Returns all child Collections of the Collection with the given id. */ async getChildren(ctx: RequestContext, collectionId: ID): Promise<Collection[]> { return this.getDescendants(ctx, collectionId, 1); } /** * @description * Returns an array of name/id pairs representing all ancestor Collections up * to the Root Collection. */ async getBreadcrumbs( ctx: RequestContext, collection: Collection, ): Promise<Array<{ name: string; id: ID }>> { const rootCollection = await this.getRootCollection(ctx); if (idsAreEqual(collection.id, rootCollection.id)) { return [pick(rootCollection, ['id', 'name', 'slug'])]; } const pickProps = pick(['id', 'name', 'slug']); const ancestors = await this.getAncestors(collection.id, ctx); if (collection.name == null || collection.slug == null) { collection = this.translator.translate( await this.connection.getEntityOrThrow(ctx, Collection, collection.id), ctx, ); } return [pickProps(rootCollection), ...ancestors.map(pickProps).reverse(), pickProps(collection)]; } /** * @description * Returns all Collections which are associated with the given Product ID. */ async getCollectionsByProductId( ctx: RequestContext, productId: ID, publicOnly: boolean, ): Promise<Array<Translated<Collection>>> { const qb = this.connection .getRepository(ctx, Collection) .createQueryBuilder('collection') .leftJoinAndSelect('collection.translations', 'translation') .leftJoin('collection.productVariants', 'variant') .where('variant.product = :productId', { productId }) .groupBy('collection.id, translation.id') .orderBy('collection.id', 'ASC'); if (publicOnly) { qb.andWhere('collection.isPrivate = :isPrivate', { isPrivate: false }); } const result = await qb.getMany(); return result.map(collection => this.translator.translate(collection, ctx)); } /** * @description * Returns the descendants of a Collection as a flat array. The depth of the traversal can be limited * with the maxDepth argument. So to get only the immediate children, set maxDepth = 1. */ async getDescendants( ctx: RequestContext, rootId: ID, maxDepth: number = Number.MAX_SAFE_INTEGER, ): Promise<Array<Translated<Collection>>> { const getChildren = async (id: ID, _descendants: Collection[] = [], depth = 1) => { const children = await this.connection .getRepository(ctx, Collection) .find({ where: { parent: { id } }, order: { position: 'ASC' } }); for (const child of children) { _descendants.push(child); if (depth < maxDepth) { await getChildren(child.id, _descendants, depth++); } } return _descendants; }; const descendants = await getChildren(rootId); return descendants.map(c => this.translator.translate(c, ctx)); } /** * @description * Gets the ancestors of a given collection. Note that since ProductCategories are implemented as an adjacency list, this method * will produce more queries the deeper the collection is in the tree. */ getAncestors(collectionId: ID): Promise<Collection[]>; getAncestors(collectionId: ID, ctx: RequestContext): Promise<Array<Translated<Collection>>>; async getAncestors( collectionId: ID, ctx?: RequestContext, ): Promise<Array<Translated<Collection> | Collection>> { const getParent = async (id: ID, _ancestors: Collection[] = []): Promise<Collection[]> => { const parent = await this.connection .getRepository(ctx, Collection) .createQueryBuilder() .relation(Collection, 'parent') .of(id) .loadOne(); if (parent) { if (!parent.isRoot) { _ancestors.push(parent); return getParent(parent.id, _ancestors); } } return _ancestors; }; const ancestors = await getParent(collectionId); return this.connection .getRepository(ctx, Collection) .find({ where: { id: In(ancestors.map(c => c.id)) } }) .then(categories => { const resultCategories: Array<Collection | Translated<Collection>> = []; ancestors.forEach(a => { const category = categories.find(c => c.id === a.id); if (category) { resultCategories.push(ctx ? this.translator.translate(category, ctx) : category); } }); return resultCategories; }); } async previewCollectionVariants( ctx: RequestContext, input: PreviewCollectionVariantsInput, options?: ListQueryOptions<ProductVariant>, relations?: RelationPaths<Collection>, ): Promise<PaginatedList<ProductVariant>> { const applicableFilters = this.getCollectionFiltersFromInput(input); if (input.parentId && input.inheritFilters) { const parentFilters = (await this.findOne(ctx, input.parentId, []))?.filters ?? []; const ancestorFilters = await this.getAncestors(input.parentId).then(ancestors => ancestors.reduce( (_filters, c) => [..._filters, ...(c.filters || [])], [] as ConfigurableOperation[], ), ); applicableFilters.push(...parentFilters, ...ancestorFilters); } let qb = this.listQueryBuilder.build(ProductVariant, options, { relations: relations ?? ['taxCategory'], channelId: ctx.channelId, where: { deletedAt: IsNull() }, ctx, entityAlias: 'productVariant', }); const { collectionFilters } = this.configService.catalogOptions; for (const filterType of collectionFilters) { const filtersOfType = applicableFilters.filter(f => f.code === filterType.code); if (filtersOfType.length) { for (const filter of filtersOfType) { qb = filterType.apply(qb, filter.args); } } } return qb.getManyAndCount().then(([items, totalItems]) => ({ items, totalItems, })); } async create(ctx: RequestContext, input: CreateCollectionInput): Promise<Translated<Collection>> { await this.slugValidator.validateSlugs(ctx, input, CollectionTranslation); const collection = await this.translatableSaver.create({ ctx, input, entityType: Collection, translationType: CollectionTranslation, beforeSave: async coll => { await this.channelService.assignToCurrentChannel(coll, ctx); const parent = await this.getParentCollection(ctx, input.parentId); if (parent) { coll.parent = parent; } coll.position = await this.getNextPositionInParent(ctx, input.parentId || undefined); coll.filters = this.getCollectionFiltersFromInput(input); await this.assetService.updateFeaturedAsset(ctx, coll, input); }, }); await this.assetService.updateEntityAssets(ctx, collection, input); const collectionWithRelations = await this.customFieldRelationService.updateRelations( ctx, Collection, input, collection, ); await this.applyFiltersQueue.add({ ctx: ctx.serialize(), collectionIds: [collection.id], }, { ctx }); await this.eventBus.publish(new CollectionEvent(ctx, collectionWithRelations, 'created', input)); return assertFound(this.findOne(ctx, collection.id)); } async update(ctx: RequestContext, input: UpdateCollectionInput): Promise<Translated<Collection>> { await this.slugValidator.validateSlugs(ctx, input, CollectionTranslation); const collection = await this.translatableSaver.update({ ctx, input, entityType: Collection, translationType: CollectionTranslation, beforeSave: async coll => { if (input.filters) { coll.filters = this.getCollectionFiltersFromInput(input); } await this.assetService.updateFeaturedAsset(ctx, coll, input); await this.assetService.updateEntityAssets(ctx, coll, input); }, }); await this.customFieldRelationService.updateRelations(ctx, Collection, input, collection); if (input.filters) { await this.applyFiltersQueue.add({ ctx: ctx.serialize(), collectionIds: [collection.id], applyToChangedVariantsOnly: false, }, { ctx }); } else { const affectedVariantIds = await this.getCollectionProductVariantIds(collection); await this.eventBus.publish(new CollectionModificationEvent(ctx, collection, affectedVariantIds)); } await this.eventBus.publish(new CollectionEvent(ctx, collection, 'updated', input)); return assertFound(this.findOne(ctx, collection.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const collection = await this.connection.getEntityOrThrow(ctx, Collection, id, { channelId: ctx.channelId, }); const deletedCollection = new Collection(collection); const descendants = await this.getDescendants(ctx, collection.id); for (const coll of [...descendants.reverse(), collection]) { const affectedVariantIds = await this.getCollectionProductVariantIds(coll); const deletedColl = new Collection(coll); // To avoid performance issues on huge collections, we first delete the links // between the product variants and the collection by chunks const chunkedDeleteIds = this.chunkArray(affectedVariantIds, 500); for (const chunkedDeleteId of chunkedDeleteIds) { await this.connection.rawConnection .createQueryBuilder() .relation(Collection, 'productVariants') .of(collection) .remove(chunkedDeleteId); } await this.connection.getRepository(ctx, Collection).remove(coll); await this.eventBus.publish( new CollectionModificationEvent(ctx, deletedColl, affectedVariantIds), ); } await this.eventBus.publish(new CollectionEvent(ctx, deletedCollection, 'deleted', id)); return { result: DeletionResult.DELETED, }; } /** * @description * Moves a Collection by specifying the parent Collection ID, and an index representing the order amongst * its siblings. */ async move(ctx: RequestContext, input: MoveCollectionInput): Promise<Translated<Collection>> { const target = await this.connection.getEntityOrThrow(ctx, Collection, input.collectionId, { channelId: ctx.channelId, relations: ['parent'], }); const descendants = await this.getDescendants(ctx, input.collectionId); if ( idsAreEqual(input.parentId, target.id) || descendants.some(cat => idsAreEqual(input.parentId, cat.id)) ) { throw new IllegalOperationError('error.cannot-move-collection-into-self'); } let siblings = await this.connection .getRepository(ctx, Collection) .createQueryBuilder('collection') .leftJoin('collection.parent', 'parent') .where('parent.id = :id', { id: input.parentId }) .getMany(); if (!idsAreEqual(target.parent.id, input.parentId)) { target.parent = new Collection({ id: input.parentId }); } siblings = moveToIndex(input.index, target, siblings); await this.connection.getRepository(ctx, Collection).save(siblings); await this.applyFiltersQueue.add({ ctx: ctx.serialize(), collectionIds: [target.id], }, { ctx }); return assertFound(this.findOne(ctx, input.collectionId)); } private getCollectionFiltersFromInput( input: CreateCollectionInput | UpdateCollectionInput | PreviewCollectionVariantsInput, ): ConfigurableOperation[] { const filters: ConfigurableOperation[] = []; if (input.filters) { for (const filter of input.filters) { filters.push(this.configArgService.parseInput('CollectionFilter', filter)); } } return filters; } private chunkArray = <T>(array: T[], chunkSize: number): T[][] => { const results = []; for (let i = 0; i < array.length; i += chunkSize) { results.push(array.slice(i, i + chunkSize)); } return results; }; /** * Applies the CollectionFilters * * If applyToChangedVariantsOnly (default: true) is true, then apply collection job will process only changed variants * If applyToChangedVariantsOnly (default: true) is false, then apply collection job will process all variants * This param is used when we update collection and collection filters are changed to update all * variants (because other attributes of collection can be changed https://github.com/vendure-ecommerce/vendure/issues/1015) */ private async applyCollectionFiltersInternal( collection: Collection, applyToChangedVariantsOnly = true, ): Promise<ID[]> { const ancestorFilters = await this.getAncestorFilters(collection); const preIds = await this.getCollectionProductVariantIds(collection); const filteredVariantIds = await this.getFilteredProductVariantIds([ ...ancestorFilters, ...(collection.filters || []), ]); const postIds = filteredVariantIds.map(v => v.id); const preIdsSet = new Set(preIds); const postIdsSet = new Set(postIds); const toDeleteIds = preIds.filter(id => !postIdsSet.has(id)); const toAddIds = postIds.filter(id => !preIdsSet.has(id)); try { // First we remove variants that are no longer in the collection const chunkedDeleteIds = this.chunkArray(toDeleteIds, 500); for (const chunkedDeleteId of chunkedDeleteIds) { await this.connection.rawConnection .createQueryBuilder() .relation(Collection, 'productVariants') .of(collection) .remove(chunkedDeleteId); } // Then we add variants have been added const chunkedAddIds = this.chunkArray(toAddIds, 500); for (const chunkedAddId of chunkedAddIds) { await this.connection.rawConnection .createQueryBuilder() .relation(Collection, 'productVariants') .of(collection) .add(chunkedAddId); } } catch (e: any) { Logger.error(e); } if (applyToChangedVariantsOnly) { return [...preIds.filter(id => !postIdsSet.has(id)), ...postIds.filter(id => !preIdsSet.has(id))]; } else { return [...preIds.filter(id => !postIdsSet.has(id)), ...postIds]; } } /** * Gets all filters of ancestor Collections while respecting the `inheritFilters` setting of each. * As soon as `inheritFilters === false` is encountered, the collected filters are returned. */ private async getAncestorFilters(collection: Collection): Promise<ConfigurableOperation[]> { const ancestorFilters: ConfigurableOperation[] = []; if (collection.inheritFilters) { const ancestors = await this.getAncestors(collection.id); for (const ancestor of ancestors) { ancestorFilters.push(...ancestor.filters); if (ancestor.inheritFilters === false) { return ancestorFilters; } } } return ancestorFilters; } /** * Applies the CollectionFilters and returns an array of ProductVariant entities which match. */ private async getFilteredProductVariantIds(filters: ConfigurableOperation[]): Promise<Array<{ id: ID }>> { if (filters.length === 0) { return []; } const { collectionFilters } = this.configService.catalogOptions; let qb = this.connection.rawConnection .getRepository(ProductVariant) .createQueryBuilder('productVariant'); for (const filterType of collectionFilters) { const filtersOfType = filters.filter(f => f.code === filterType.code); if (filtersOfType.length) { for (const filter of filtersOfType) { qb = filterType.apply(qb, filter.args); } } } // This is the most performant (time & memory) way to get // just the variant IDs, which is all we need. return qb.select('productVariant.id', 'id').getRawMany(); } /** * Returns the IDs of the Collection's ProductVariants. */ async getCollectionProductVariantIds(collection: Collection, ctx?: RequestContext): Promise<ID[]> { if (collection.productVariants) { return collection.productVariants.map(v => v.id); } else { const productVariants = await this.connection .getRepository(ctx, ProductVariant) .createQueryBuilder('variant') .select('variant.id', 'id') .innerJoin('variant.collections', 'collection', 'collection.id = :id', { id: collection.id }) .getRawMany(); return productVariants.map(v => v.id); } } /** * Returns the next position value in the given parent collection. */ private async getNextPositionInParent(ctx: RequestContext, maybeParentId?: ID): Promise<number> { const parentId = maybeParentId || (await this.getRootCollection(ctx)).id; const result = await this.connection .getRepository(ctx, Collection) .createQueryBuilder('collection') .leftJoin('collection.parent', 'parent') .select('MAX(collection.position)', 'index') .where('parent.id = :id', { id: parentId }) .getRawOne(); const index = result.index; return (typeof index === 'number' ? index : 0) + 1; } private async getParentCollection( ctx: RequestContext, parentId?: ID | null, ): Promise<Collection | undefined> { if (parentId) { return this.connection .getRepository(ctx, Collection) .createQueryBuilder('collection') .leftJoin('collection.channels', 'channel') .where('collection.id = :id', { id: parentId }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .getOne() .then(result => result ?? undefined); } else { return this.getRootCollection(ctx); } } private async getRootCollection(ctx: RequestContext): Promise<Collection> { const cachedRoot = this.rootCollection; if (cachedRoot) { return cachedRoot; } const existingRoot = await this.connection .getRepository(ctx, Collection) .createQueryBuilder('collection') .leftJoin('collection.channels', 'channel') .leftJoinAndSelect('collection.translations', 'translation') .where('collection.isRoot = :isRoot', { isRoot: true }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .getOne(); if (existingRoot) { this.rootCollection = this.translator.translate(existingRoot, ctx); return this.rootCollection; } // We purposefully do not use the ctx in saving the new root Collection // so that even if the outer transaction fails, the root collection will still // get persisted. const rootTranslation = await this.connection.rawConnection.getRepository(CollectionTranslation).save( new CollectionTranslation({ languageCode: this.configService.defaultLanguageCode, name: ROOT_COLLECTION_NAME, description: 'The root of the Collection tree.', slug: ROOT_COLLECTION_NAME, }), ); const newRoot = await this.connection.rawConnection.getRepository(Collection).save( new Collection({ isRoot: true, position: 0, translations: [rootTranslation], channels: [ctx.channel], filters: [], }), ); this.rootCollection = this.translator.translate(newRoot, ctx); return this.rootCollection; } /** * @description * Assigns Collections to the specified Channel */ async assignCollectionsToChannel( ctx: RequestContext, input: AssignCollectionsToChannelInput, ): Promise<Array<Translated<Collection>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.UpdateCollection, Permission.UpdateCatalog, ]); if (!hasPermission) { throw new ForbiddenError(); } const collectionsToAssign = await this.connection .getRepository(ctx, Collection) .find({ where: { id: In(input.collectionIds) }, relations: { assets: true } }); await Promise.all( collectionsToAssign.map(collection => this.channelService.assignToChannels(ctx, Collection, collection.id, [input.channelId]), ), ); const assetIds: ID[] = unique( ([] as ID[]).concat(...collectionsToAssign.map(c => c.assets.map(a => a.assetId))), ); await this.assetService.assignToChannel(ctx, { channelId: input.channelId, assetIds }); await this.applyFiltersQueue.add({ ctx: ctx.serialize(), collectionIds: collectionsToAssign.map(collection => collection.id), }, { ctx }); return this.connection .findByIdsInChannel( ctx, Collection, collectionsToAssign.map(c => c.id), ctx.channelId, {}, ) .then(collections => collections.map(collection => this.translator.translate(collection, ctx))); } /** * @description * Remove Collections from the specified Channel */ async removeCollectionsFromChannel( ctx: RequestContext, input: RemoveCollectionsFromChannelInput, ): Promise<Array<Translated<Collection>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.DeleteCollection, Permission.DeleteCatalog, ]); if (!hasPermission) { throw new ForbiddenError(); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); if (idsAreEqual(input.channelId, defaultChannel.id)) { throw new UserInputError('error.items-cannot-be-removed-from-default-channel'); } const collectionsToRemove = await this.connection .getRepository(ctx, Collection) .find({ where: { id: In(input.collectionIds) } }); await Promise.all( collectionsToRemove.map(async collection => { const affectedVariantIds = await this.getCollectionProductVariantIds(collection); await this.channelService.removeFromChannels(ctx, Collection, collection.id, [ input.channelId, ]); await this.eventBus.publish( new CollectionModificationEvent(ctx, collection, affectedVariantIds), ); }), ); return this.connection .findByIdsInChannel( ctx, Collection, collectionsToRemove.map(c => c.id), ctx.channelId, {}, ) .then(collections => collections.map(collection => this.translator.translate(collection, ctx))); } }
import { Injectable } from '@nestjs/common'; import { CreateCountryInput, DeletionResponse, DeletionResult, UpdateCountryInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList, Type } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { UserInputError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Address } from '../../entity'; import { Country } from '../../entity/region/country.entity'; import { RegionTranslation } from '../../entity/region/region-translation.entity'; import { Region } from '../../entity/region/region.entity'; import { EventBus } from '../../event-bus'; import { CountryEvent } from '../../event-bus/events/country-event'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; /** * @description * Contains methods relating to {@link Country} entities. * * @docsCategory services */ @Injectable() export class CountryService { constructor( private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder, private translatableSaver: TranslatableSaver, private eventBus: EventBus, private translator: TranslatorService, ) {} findAll( ctx: RequestContext, options?: ListQueryOptions<Country>, relations: RelationPaths<Country> = [], ): Promise<PaginatedList<Translated<Country>>> { return this.listQueryBuilder .build(Country, options, { ctx, relations }) .getManyAndCount() .then(([countries, totalItems]) => { const items = countries.map(country => this.translator.translate(country, ctx)); return { items, totalItems, }; }); } findOne( ctx: RequestContext, countryId: ID, relations: RelationPaths<Country> = [], ): Promise<Translated<Country> | undefined> { return this.connection .getRepository(ctx, Country) .findOne({ where: { id: countryId }, relations }) .then(country => (country && this.translator.translate(country, ctx)) ?? undefined); } /** * @description * Returns an array of enabled Countries, intended for use in a public-facing (ie. Shop) API. */ findAllAvailable(ctx: RequestContext): Promise<Array<Translated<Country>>> { return this.connection .getRepository(ctx, Country) .find({ where: { enabled: true } }) .then(items => items.map(country => this.translator.translate(country, ctx))); } /** * @description * Returns a Country based on its ISO country code. */ async findOneByCode(ctx: RequestContext, countryCode: string): Promise<Translated<Country>> { const country = await this.connection.getRepository(ctx, Country).findOne({ where: { code: countryCode, }, }); if (!country) { throw new UserInputError('error.country-code-not-valid', { countryCode }); } return this.translator.translate(country, ctx); } async create(ctx: RequestContext, input: CreateCountryInput): Promise<Translated<Country>> { const country = await this.translatableSaver.create({ ctx, input, entityType: Country, translationType: RegionTranslation, }); await this.eventBus.publish(new CountryEvent(ctx, country, 'created', input)); return assertFound(this.findOne(ctx, country.id)); } async update(ctx: RequestContext, input: UpdateCountryInput): Promise<Translated<Country>> { const country = await this.translatableSaver.update({ ctx, input, entityType: Country, translationType: RegionTranslation, }); await this.eventBus.publish(new CountryEvent(ctx, country, 'updated', input)); return assertFound(this.findOne(ctx, country.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const country = await this.connection.getEntityOrThrow(ctx, Country, id); const addressesUsingCountry = await this.connection .getRepository(ctx, Address) .createQueryBuilder('address') .where('address.country = :id', { id }) .getCount(); if (0 < addressesUsingCountry) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.country-used-in-addresses', { count: addressesUsingCountry }), }; } else { const deletedCountry = new Country(country); await this.connection.getRepository(ctx, Country).remove(country); await this.eventBus.publish(new CountryEvent(ctx, deletedCountry, 'deleted', id)); return { result: DeletionResult.DELETED, message: '', }; } } }
import { Injectable } from '@nestjs/common'; import { CreateCustomerGroupInput, CustomerGroupListOptions, CustomerListOptions, DeletionResponse, DeletionResult, HistoryEntryType, MutationAddCustomersToGroupArgs, MutationRemoveCustomersFromGroupArgs, UpdateCustomerGroupInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { UserInputError } from '../../common/error/errors'; import { assertFound, idsAreEqual } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Customer } from '../../entity/customer/customer.entity'; import { CustomerGroup } from '../../entity/customer-group/customer-group.entity'; import { EventBus } from '../../event-bus/event-bus'; import { CustomerGroupChangeEvent } from '../../event-bus/events/customer-group-change-event'; import { CustomerGroupEvent } from '../../event-bus/events/customer-group-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { patchEntity } from '../helpers/utils/patch-entity'; import { HistoryService } from './history.service'; /** * @description * Contains methods relating to {@link CustomerGroup} entities. * * @docsCategory services */ @Injectable() export class CustomerGroupService { constructor( private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder, private historyService: HistoryService, private eventBus: EventBus, private customFieldRelationService: CustomFieldRelationService, ) {} findAll( ctx: RequestContext, options?: CustomerGroupListOptions, relations: RelationPaths<CustomerGroup> = [], ): Promise<PaginatedList<CustomerGroup>> { return this.listQueryBuilder .build(CustomerGroup, options, { ctx, relations }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems })); } findOne( ctx: RequestContext, customerGroupId: ID, relations: RelationPaths<CustomerGroup> = [], ): Promise<CustomerGroup | undefined> { return this.connection .getRepository(ctx, CustomerGroup) .findOne({ where: { id: customerGroupId }, relations }) .then(result => result ?? undefined); } /** * @description * Returns a {@link PaginatedList} of all the Customers in the group. */ getGroupCustomers( ctx: RequestContext, customerGroupId: ID, options?: CustomerListOptions, ): Promise<PaginatedList<Customer>> { return this.listQueryBuilder .build(Customer, options, { ctx }) .leftJoin('customer.groups', 'group') .leftJoin('customer.channels', 'channel') .andWhere('group.id = :groupId', { groupId: customerGroupId }) .andWhere('customer.deletedAt IS NULL', { groupId: customerGroupId }) .andWhere('channel.id =:channelId', { channelId: ctx.channelId }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems })); } async create(ctx: RequestContext, input: CreateCustomerGroupInput): Promise<CustomerGroup> { const customerGroup = new CustomerGroup(input); const newCustomerGroup = await this.connection.getRepository(ctx, CustomerGroup).save(customerGroup); if (input.customerIds) { const customers = await this.getCustomersFromIds(ctx, input.customerIds); for (const customer of customers) { customer.groups = [...(customer.groups || []), newCustomerGroup]; await this.historyService.createHistoryEntryForCustomer({ ctx, customerId: customer.id, type: HistoryEntryType.CUSTOMER_ADDED_TO_GROUP, data: { groupName: customerGroup.name, }, }); } await this.connection.getRepository(ctx, Customer).save(customers); } const savedCustomerGroup = await assertFound(this.findOne(ctx, newCustomerGroup.id)); await this.customFieldRelationService.updateRelations(ctx, CustomerGroup, input, savedCustomerGroup); await this.eventBus.publish(new CustomerGroupEvent(ctx, savedCustomerGroup, 'created', input)); return assertFound(this.findOne(ctx, savedCustomerGroup.id)); } async update(ctx: RequestContext, input: UpdateCustomerGroupInput): Promise<CustomerGroup> { const customerGroup = await this.connection.getEntityOrThrow(ctx, CustomerGroup, input.id); const updatedCustomerGroup = patchEntity(customerGroup, input); await this.connection.getRepository(ctx, CustomerGroup).save(updatedCustomerGroup, { reload: false }); await this.customFieldRelationService.updateRelations( ctx, CustomerGroup, input, updatedCustomerGroup, ); await this.eventBus.publish(new CustomerGroupEvent(ctx, customerGroup, 'updated', input)); return assertFound(this.findOne(ctx, customerGroup.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const group = await this.connection.getEntityOrThrow(ctx, CustomerGroup, id); try { const deletedGroup = new CustomerGroup(group); await this.connection.getRepository(ctx, CustomerGroup).remove(group); await this.eventBus.publish(new CustomerGroupEvent(ctx, deletedGroup, 'deleted', id)); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.message, }; } } async addCustomersToGroup( ctx: RequestContext, input: MutationAddCustomersToGroupArgs, ): Promise<CustomerGroup> { const customers = await this.getCustomersFromIds(ctx, input.customerIds); const group = await this.connection.getEntityOrThrow(ctx, CustomerGroup, input.customerGroupId); for (const customer of customers) { if (!customer.groups.map(g => g.id).includes(input.customerGroupId)) { customer.groups.push(group); await this.historyService.createHistoryEntryForCustomer({ ctx, customerId: customer.id, type: HistoryEntryType.CUSTOMER_ADDED_TO_GROUP, data: { groupName: group.name, }, }); } } await this.connection.getRepository(ctx, Customer).save(customers, { reload: false }); await this.eventBus.publish(new CustomerGroupChangeEvent(ctx, customers, group, 'assigned')); return assertFound(this.findOne(ctx, group.id)); } async removeCustomersFromGroup( ctx: RequestContext, input: MutationRemoveCustomersFromGroupArgs, ): Promise<CustomerGroup> { const customers = await this.getCustomersFromIds(ctx, input.customerIds); const group = await this.connection.getEntityOrThrow(ctx, CustomerGroup, input.customerGroupId); for (const customer of customers) { if (!customer.groups.map(g => g.id).includes(input.customerGroupId)) { throw new UserInputError('error.customer-does-not-belong-to-customer-group'); } customer.groups = customer.groups.filter(g => !idsAreEqual(g.id, group.id)); await this.historyService.createHistoryEntryForCustomer({ ctx, customerId: customer.id, type: HistoryEntryType.CUSTOMER_REMOVED_FROM_GROUP, data: { groupName: group.name, }, }); } await this.connection.getRepository(ctx, Customer).save(customers, { reload: false }); await this.eventBus.publish(new CustomerGroupChangeEvent(ctx, customers, group, 'removed')); return assertFound(this.findOne(ctx, group.id)); } private getCustomersFromIds(ctx: RequestContext, ids: ID[]): Promise<Customer[]> | Customer[] { if (ids.length === 0) { return new Array<Customer>(); } // TypeORM throws error when list is empty return this.connection .getRepository(ctx, Customer) .createQueryBuilder('customer') .leftJoin('customer.channels', 'channel') .leftJoinAndSelect('customer.groups', 'group') .where('customer.id IN (:...customerIds)', { customerIds: ids }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .andWhere('customer.deletedAt is null') .getMany(); } }
import { Injectable } from '@nestjs/common'; import { RegisterCustomerAccountResult, RegisterCustomerInput, UpdateCustomerInput as UpdateCustomerShopInput, VerifyCustomerAccountResult, } from '@vendure/common/lib/generated-shop-types'; import { AddNoteToCustomerInput, CreateAddressInput, CreateCustomerInput, CreateCustomerResult, CustomerFilterParameter, CustomerListOptions, DeletionResponse, DeletionResult, HistoryEntryType, OrderAddress, UpdateAddressInput, UpdateCustomerInput, UpdateCustomerNoteInput, UpdateCustomerResult, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { IsNull } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ErrorResultUnion, isGraphQlErrorResult } from '../../common/error/error-result'; import { EntityNotFoundError, InternalServerError } from '../../common/error/errors'; import { EmailAddressConflictError as EmailAddressConflictAdminError } from '../../common/error/generated-graphql-admin-errors'; import { EmailAddressConflictError, IdentifierChangeTokenExpiredError, IdentifierChangeTokenInvalidError, MissingPasswordError, PasswordResetTokenExpiredError, PasswordResetTokenInvalidError, PasswordValidationError, } from '../../common/error/generated-graphql-shop-errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual, normalizeEmailAddress } from '../../common/utils'; import { NATIVE_AUTH_STRATEGY_NAME } from '../../config/auth/native-authentication-strategy'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Address } from '../../entity/address/address.entity'; import { NativeAuthenticationMethod } from '../../entity/authentication-method/native-authentication-method.entity'; import { Channel } from '../../entity/channel/channel.entity'; import { Customer } from '../../entity/customer/customer.entity'; import { CustomerGroup } from '../../entity/customer-group/customer-group.entity'; import { HistoryEntry } from '../../entity/history-entry/history-entry.entity'; import { Order } from '../../entity/order/order.entity'; import { User } from '../../entity/user/user.entity'; import { EventBus } from '../../event-bus/event-bus'; import { AccountRegistrationEvent } from '../../event-bus/events/account-registration-event'; import { AccountVerifiedEvent } from '../../event-bus/events/account-verified-event'; import { CustomerAddressEvent } from '../../event-bus/events/customer-address-event'; import { CustomerEvent } from '../../event-bus/events/customer-event'; import { IdentifierChangeEvent } from '../../event-bus/events/identifier-change-event'; import { IdentifierChangeRequestEvent } from '../../event-bus/events/identifier-change-request-event'; import { PasswordResetEvent } from '../../event-bus/events/password-reset-event'; import { PasswordResetVerifiedEvent } from '../../event-bus/events/password-reset-verified-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatorService } from '../helpers/translator/translator.service'; import { addressToLine } from '../helpers/utils/address-to-line'; import { patchEntity } from '../helpers/utils/patch-entity'; import { ChannelService } from './channel.service'; import { CountryService } from './country.service'; import { HistoryService } from './history.service'; import { UserService } from './user.service'; /** * @description * Contains methods relating to {@link Customer} entities. * * @docsCategory services */ @Injectable() export class CustomerService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private userService: UserService, private countryService: CountryService, private listQueryBuilder: ListQueryBuilder, private eventBus: EventBus, private historyService: HistoryService, private channelService: ChannelService, private customFieldRelationService: CustomFieldRelationService, private translator: TranslatorService, ) {} findAll( ctx: RequestContext, options: ListQueryOptions<Customer> | undefined, relations: RelationPaths<Customer> = [], ): Promise<PaginatedList<Customer>> { const customPropertyMap: { [name: string]: string } = {}; const hasPostalCodeFilter = this.listQueryBuilder.filterObjectHasProperty<CustomerFilterParameter>( options?.filter, 'postalCode', ); if (hasPostalCodeFilter) { relations.push('addresses'); customPropertyMap.postalCode = 'addresses.postalCode'; } return this.listQueryBuilder .build(Customer, options, { relations, channelId: ctx.channelId, where: { deletedAt: IsNull() }, ctx, customPropertyMap, }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems })); } findOne( ctx: RequestContext, id: ID, relations: RelationPaths<Customer> = [], ): Promise<Customer | undefined> { return this.connection .findOneInChannel(ctx, Customer, id, ctx.channelId, { relations, where: { deletedAt: IsNull() }, }) .then(result => result ?? undefined); } /** * @description * Returns the Customer entity associated with the given userId, if one exists. * Setting `filterOnChannel` to `true` will limit the results to Customers which are assigned * to the current active Channel only. */ findOneByUserId(ctx: RequestContext, userId: ID, filterOnChannel = true): Promise<Customer | undefined> { let query = this.connection .getRepository(ctx, Customer) .createQueryBuilder('customer') .leftJoin('customer.channels', 'channel') .leftJoinAndSelect('customer.user', 'user') .where('user.id = :userId', { userId }) .andWhere('customer.deletedAt is null'); if (filterOnChannel) { query = query.andWhere('channel.id = :channelId', { channelId: ctx.channelId }); } return query.getOne().then(result => result ?? undefined); } /** * @description * Returns all {@link Address} entities associated with the specified Customer. */ findAddressesByCustomerId(ctx: RequestContext, customerId: ID): Promise<Address[]> { return this.connection .getRepository(ctx, Address) .createQueryBuilder('address') .leftJoinAndSelect('address.country', 'country') .leftJoinAndSelect('country.translations', 'countryTranslation') .where('address.customer = :id', { id: customerId }) .getMany() .then(addresses => { addresses.forEach(address => { address.country = this.translator.translate(address.country, ctx); }); return addresses; }); } /** * @description * Returns a list of all {@link CustomerGroup} entities. */ async getCustomerGroups(ctx: RequestContext, customerId: ID): Promise<CustomerGroup[]> { const customerWithGroups = await this.connection.findOneInChannel( ctx, Customer, customerId, ctx?.channelId, { relations: ['groups'], where: { deletedAt: IsNull(), }, }, ); if (customerWithGroups) { return customerWithGroups.groups; } else { return []; } } /** * @description * Creates a new Customer, including creation of a new User with the special `customer` Role. * * If the `password` argument is specified, the Customer will be immediately verified. If not, * then an {@link AccountRegistrationEvent} is published, so that the customer can have their * email address verified and set their password in a later step using the `verifyCustomerEmailAddress()` * method. * * This method is intended to be used in admin-created Customer flows. */ async create( ctx: RequestContext, input: CreateCustomerInput, password?: string, ): Promise<ErrorResultUnion<CreateCustomerResult, Customer>> { input.emailAddress = normalizeEmailAddress(input.emailAddress); const customer = new Customer(input); const existingCustomerInChannel = await this.connection .getRepository(ctx, Customer) .createQueryBuilder('customer') .leftJoin('customer.channels', 'channel') .where('channel.id = :channelId', { channelId: ctx.channelId }) .andWhere('customer.emailAddress = :emailAddress', { emailAddress: input.emailAddress }) .andWhere('customer.deletedAt is null') .getOne(); if (existingCustomerInChannel) { return new EmailAddressConflictAdminError(); } const existingCustomer = await this.connection.getRepository(ctx, Customer).findOne({ relations: ['channels'], where: { emailAddress: input.emailAddress, deletedAt: IsNull(), }, }); const existingUser = await this.userService.getUserByEmailAddress( ctx, input.emailAddress, 'customer', ); if (existingCustomer && existingUser) { // Customer already exists, bring to this Channel const updatedCustomer = patchEntity(existingCustomer, input); updatedCustomer.channels.push(ctx.channel); return this.connection.getRepository(ctx, Customer).save(updatedCustomer); } else if (existingCustomer || existingUser) { // Not sure when this situation would occur return new EmailAddressConflictAdminError(); } const customerUser = await this.userService.createCustomerUser(ctx, input.emailAddress, password); if (isGraphQlErrorResult(customerUser)) { throw customerUser; } customer.user = customerUser; if (password && password !== '') { const verificationToken = customer.user.getNativeAuthenticationMethod().verificationToken; if (verificationToken) { const result = await this.userService.verifyUserByToken(ctx, verificationToken); if (isGraphQlErrorResult(result)) { // In theory this should never be reached, so we will just // throw the result throw result; } else { customer.user = result; } } } await this.eventBus.publish(new AccountRegistrationEvent(ctx, customer.user)); await this.channelService.assignToCurrentChannel(customer, ctx); const createdCustomer = await this.connection.getRepository(ctx, Customer).save(customer); await this.customFieldRelationService.updateRelations(ctx, Customer, input, createdCustomer); await this.historyService.createHistoryEntryForCustomer({ ctx, customerId: createdCustomer.id, type: HistoryEntryType.CUSTOMER_REGISTERED, data: { strategy: NATIVE_AUTH_STRATEGY_NAME, }, }); if (customer.user?.verified) { await this.historyService.createHistoryEntryForCustomer({ ctx, customerId: createdCustomer.id, type: HistoryEntryType.CUSTOMER_VERIFIED, data: { strategy: NATIVE_AUTH_STRATEGY_NAME, }, }); } await this.eventBus.publish(new CustomerEvent(ctx, createdCustomer, 'created', input)); return createdCustomer; } async update(ctx: RequestContext, input: UpdateCustomerShopInput & { id: ID }): Promise<Customer>; async update( ctx: RequestContext, input: UpdateCustomerInput, ): Promise<ErrorResultUnion<UpdateCustomerResult, Customer>>; async update( ctx: RequestContext, input: UpdateCustomerInput | (UpdateCustomerShopInput & { id: ID }), ): Promise<ErrorResultUnion<UpdateCustomerResult, Customer>> { const hasEmailAddress = (i: any): i is UpdateCustomerInput & { emailAddress: string } => Object.hasOwnProperty.call(i, 'emailAddress'); const customer = await this.connection.getEntityOrThrow(ctx, Customer, input.id, { channelId: ctx.channelId, }); if (hasEmailAddress(input)) { input.emailAddress = normalizeEmailAddress(input.emailAddress); if (input.emailAddress !== customer.emailAddress) { const existingCustomerInChannel = await this.connection .getRepository(ctx, Customer) .createQueryBuilder('customer') .leftJoin('customer.channels', 'channel') .where('channel.id = :channelId', { channelId: ctx.channelId }) .andWhere('customer.emailAddress = :emailAddress', { emailAddress: input.emailAddress, }) .andWhere('customer.id != :customerId', { customerId: input.id }) .andWhere('customer.deletedAt is null') .getOne(); if (existingCustomerInChannel) { return new EmailAddressConflictAdminError(); } if (customer.user) { const existingUserWithEmailAddress = await this.userService.getUserByEmailAddress( ctx, input.emailAddress, 'customer', ); if ( existingUserWithEmailAddress && !idsAreEqual(customer.user.id, existingUserWithEmailAddress.id) ) { return new EmailAddressConflictAdminError(); } await this.userService.changeUserAndNativeIdentifier( ctx, customer.user.id, input.emailAddress, ); } } } const updatedCustomer = patchEntity(customer, input); await this.connection.getRepository(ctx, Customer).save(updatedCustomer, { reload: false }); await this.customFieldRelationService.updateRelations(ctx, Customer, input, updatedCustomer); await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_DETAIL_UPDATED, data: { input, }, }); await this.eventBus.publish(new CustomerEvent(ctx, customer, 'updated', input)); return assertFound(this.findOne(ctx, customer.id)); } /** * @description * Registers a new Customer account with the {@link NativeAuthenticationStrategy} and starts * the email verification flow (unless {@link AuthOptions} `requireVerification` is set to `false`) * by publishing an {@link AccountRegistrationEvent}. * * This method is intended to be used in storefront Customer-creation flows. */ async registerCustomerAccount( ctx: RequestContext, input: RegisterCustomerInput, ): Promise<RegisterCustomerAccountResult | EmailAddressConflictError | PasswordValidationError> { if (!this.configService.authOptions.requireVerification) { if (!input.password) { return new MissingPasswordError(); } } let user = await this.userService.getUserByEmailAddress(ctx, input.emailAddress); const hasNativeAuthMethod = !!user?.authenticationMethods.find( m => m instanceof NativeAuthenticationMethod, ); if (user && user.verified) { if (hasNativeAuthMethod) { // If the user has already been verified and has already // registered with the native authentication strategy, do nothing. return { success: true }; } } const customFields = (input as any).customFields; const customer = await this.createOrUpdate(ctx, { emailAddress: input.emailAddress, title: input.title || '', firstName: input.firstName || '', lastName: input.lastName || '', phoneNumber: input.phoneNumber || '', ...(customFields ? { customFields } : {}), }); if (isGraphQlErrorResult(customer)) { return customer; } await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_REGISTERED, data: { strategy: NATIVE_AUTH_STRATEGY_NAME, }, }); if (!user) { const customerUser = await this.userService.createCustomerUser( ctx, input.emailAddress, input.password || undefined, ); if (isGraphQlErrorResult(customerUser)) { return customerUser; } else { user = customerUser; } } if (!hasNativeAuthMethod) { const addAuthenticationResult = await this.userService.addNativeAuthenticationMethod( ctx, user, input.emailAddress, input.password || undefined, ); if (isGraphQlErrorResult(addAuthenticationResult)) { return addAuthenticationResult; } else { user = addAuthenticationResult; } } if (!user.verified) { user = await this.userService.setVerificationToken(ctx, user); } customer.user = user; await this.connection.getRepository(ctx, User).save(user, { reload: false }); await this.connection.getRepository(ctx, Customer).save(customer, { reload: false }); if (!user.verified) { await this.eventBus.publish(new AccountRegistrationEvent(ctx, user)); } else { await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_VERIFIED, data: { strategy: NATIVE_AUTH_STRATEGY_NAME, }, }); } return { success: true }; } /** * @description * Refreshes a stale email address verification token by generating a new one and * publishing a {@link AccountRegistrationEvent}. */ async refreshVerificationToken(ctx: RequestContext, emailAddress: string): Promise<void> { const user = await this.userService.getUserByEmailAddress(ctx, emailAddress); if (user && !user.verified) { await this.userService.setVerificationToken(ctx, user); await this.eventBus.publish(new AccountRegistrationEvent(ctx, user)); } } /** * @description * Given a valid verification token which has been published in an {@link AccountRegistrationEvent}, this * method is used to set the Customer as `verified` as part of the account registration flow. */ async verifyCustomerEmailAddress( ctx: RequestContext, verificationToken: string, password?: string, ): Promise<ErrorResultUnion<VerifyCustomerAccountResult, Customer>> { const result = await this.userService.verifyUserByToken(ctx, verificationToken, password); if (isGraphQlErrorResult(result)) { return result; } const customer = await this.findOneByUserId(ctx, result.id, false); if (!customer) { throw new InternalServerError('error.cannot-locate-customer-for-user'); } if (ctx.channelId) { await this.channelService.assignToChannels(ctx, Customer, customer.id, [ctx.channelId]); } await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_VERIFIED, data: { strategy: NATIVE_AUTH_STRATEGY_NAME, }, }); const user = assertFound(this.findOneByUserId(ctx, result.id)); await this.eventBus.publish(new AccountVerifiedEvent(ctx, customer)); return user; } /** * @description * Publishes a new {@link PasswordResetEvent} for the given email address. This event creates * a token which can be used in the `resetPassword()` method. */ async requestPasswordReset(ctx: RequestContext, emailAddress: string): Promise<void> { const user = await this.userService.setPasswordResetToken(ctx, emailAddress); if (user) { await this.eventBus.publish(new PasswordResetEvent(ctx, user)); const customer = await this.findOneByUserId(ctx, user.id); if (!customer) { throw new InternalServerError('error.cannot-locate-customer-for-user'); } await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_PASSWORD_RESET_REQUESTED, data: {}, }); } } /** * @description * Given a valid password reset token created by a call to the `requestPasswordReset()` method, * this method will change the Customer's password to that given as the `password` argument. */ async resetPassword( ctx: RequestContext, passwordResetToken: string, password: string, ): Promise< User | PasswordResetTokenExpiredError | PasswordResetTokenInvalidError | PasswordValidationError > { const result = await this.userService.resetPasswordByToken(ctx, passwordResetToken, password); if (isGraphQlErrorResult(result)) { return result; } const customer = await this.findOneByUserId(ctx, result.id); if (!customer) { throw new InternalServerError('error.cannot-locate-customer-for-user'); } await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_PASSWORD_RESET_VERIFIED, data: {}, }); await this.eventBus.publish(new PasswordResetVerifiedEvent(ctx, result)); return result; } /** * @description * Publishes a {@link IdentifierChangeRequestEvent} for the given User. This event contains a token * which is then used in the `updateEmailAddress()` method to change the email address of the User & * Customer. */ async requestUpdateEmailAddress( ctx: RequestContext, userId: ID, newEmailAddress: string, ): Promise<boolean | EmailAddressConflictError> { const normalizedEmailAddress = normalizeEmailAddress(newEmailAddress); const userWithConflictingIdentifier = await this.userService.getUserByEmailAddress( ctx, newEmailAddress, ); if (userWithConflictingIdentifier) { return new EmailAddressConflictError(); } const user = await this.userService.getUserById(ctx, userId); if (!user) { return false; } const customer = await this.findOneByUserId(ctx, user.id); if (!customer) { return false; } const oldEmailAddress = customer.emailAddress; await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_EMAIL_UPDATE_REQUESTED, data: { oldEmailAddress, newEmailAddress: normalizedEmailAddress, }, }); if (this.configService.authOptions.requireVerification) { user.getNativeAuthenticationMethod().pendingIdentifier = normalizedEmailAddress; await this.userService.setIdentifierChangeToken(ctx, user); await this.eventBus.publish(new IdentifierChangeRequestEvent(ctx, user)); return true; } else { const oldIdentifier = user.identifier; user.identifier = normalizedEmailAddress; customer.emailAddress = normalizedEmailAddress; await this.connection.getRepository(ctx, User).save(user, { reload: false }); await this.connection.getRepository(ctx, Customer).save(customer, { reload: false }); await this.eventBus.publish(new IdentifierChangeEvent(ctx, user, oldIdentifier)); await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_EMAIL_UPDATE_VERIFIED, data: { oldEmailAddress, newEmailAddress: normalizedEmailAddress, }, }); return true; } } /** * @description * Given a valid email update token published in a {@link IdentifierChangeRequestEvent}, this method * will update the Customer & User email address. */ async updateEmailAddress( ctx: RequestContext, token: string, ): Promise<boolean | IdentifierChangeTokenInvalidError | IdentifierChangeTokenExpiredError> { const result = await this.userService.changeIdentifierByToken(ctx, token); if (isGraphQlErrorResult(result)) { return result; } const { user, oldIdentifier } = result; if (!user) { return false; } const customer = await this.findOneByUserId(ctx, user.id); if (!customer) { return false; } await this.eventBus.publish(new IdentifierChangeEvent(ctx, user, oldIdentifier)); customer.emailAddress = user.identifier; await this.connection.getRepository(ctx, Customer).save(customer, { reload: false }); await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_EMAIL_UPDATE_VERIFIED, data: { oldEmailAddress: oldIdentifier, newEmailAddress: customer.emailAddress, }, }); return true; } /** * @description * For guest checkouts, we assume that a matching email address is the same customer. */ async createOrUpdate( ctx: RequestContext, input: Partial<CreateCustomerInput> & { emailAddress: string }, errorOnExistingUser: boolean = false, ): Promise<Customer | EmailAddressConflictError> { input.emailAddress = normalizeEmailAddress(input.emailAddress); let customer: Customer; const existing = await this.connection.getRepository(ctx, Customer).findOne({ relations: ['channels'], where: { emailAddress: input.emailAddress, deletedAt: IsNull(), }, }); if (existing) { if (existing.user && errorOnExistingUser) { // It is not permitted to modify an existing *registered* Customer return new EmailAddressConflictError(); } customer = patchEntity(existing, input); customer.channels.push(await this.connection.getEntityOrThrow(ctx, Channel, ctx.channelId)); } else { customer = await this.connection.getRepository(ctx, Customer).save(new Customer(input)); await this.channelService.assignToCurrentChannel(customer, ctx); await this.eventBus.publish(new CustomerEvent(ctx, customer, 'created', input)); } return this.connection.getRepository(ctx, Customer).save(customer); } /** * @description * Creates a new {@link Address} for the given Customer. */ async createAddress(ctx: RequestContext, customerId: ID, input: CreateAddressInput): Promise<Address> { const customer = await this.connection.getEntityOrThrow(ctx, Customer, customerId, { where: { deletedAt: IsNull() }, relations: ['addresses'], channelId: ctx.channelId, }); const country = await this.countryService.findOneByCode(ctx, input.countryCode); const address = new Address({ ...input, country, }); const createdAddress = await this.connection.getRepository(ctx, Address).save(address); await this.customFieldRelationService.updateRelations(ctx, Address, input, createdAddress); customer.addresses.push(createdAddress); await this.connection.getRepository(ctx, Customer).save(customer, { reload: false }); await this.enforceSingleDefaultAddress(ctx, createdAddress.id, input); await this.historyService.createHistoryEntryForCustomer({ customerId: customer.id, ctx, type: HistoryEntryType.CUSTOMER_ADDRESS_CREATED, data: { address: addressToLine(createdAddress) }, }); createdAddress.customer = customer; await this.eventBus.publish(new CustomerAddressEvent(ctx, createdAddress, 'created', input)); return createdAddress; } async updateAddress(ctx: RequestContext, input: UpdateAddressInput): Promise<Address> { const address = await this.connection.getEntityOrThrow(ctx, Address, input.id, { relations: ['customer', 'country'], }); const customer = await this.connection.findOneInChannel<Customer>( ctx, Customer, address.customer.id, ctx.channelId, ); if (!customer) { throw new EntityNotFoundError('Address', input.id); } if (input.countryCode && input.countryCode !== address.country.code) { address.country = await this.countryService.findOneByCode(ctx, input.countryCode); } else { address.country = this.translator.translate(address.country, ctx); } let updatedAddress = patchEntity(address, input); updatedAddress = await this.connection.getRepository(ctx, Address).save(updatedAddress); await this.customFieldRelationService.updateRelations(ctx, Address, input, updatedAddress); await this.enforceSingleDefaultAddress(ctx, input.id, input); await this.historyService.createHistoryEntryForCustomer({ customerId: address.customer.id, ctx, type: HistoryEntryType.CUSTOMER_ADDRESS_UPDATED, data: { address: addressToLine(updatedAddress), input, }, }); updatedAddress.customer = customer; await this.eventBus.publish(new CustomerAddressEvent(ctx, updatedAddress, 'updated', input)); return updatedAddress; } async deleteAddress(ctx: RequestContext, id: ID): Promise<boolean> { const address = await this.connection.getEntityOrThrow(ctx, Address, id, { relations: ['customer', 'country'], }); const customer = await this.connection.findOneInChannel( ctx, Customer, address.customer.id, ctx.channelId, ); if (!customer) { throw new EntityNotFoundError('Address', id); } address.country = this.translator.translate(address.country, ctx); await this.reassignDefaultsForDeletedAddress(ctx, address); await this.historyService.createHistoryEntryForCustomer({ customerId: address.customer.id, ctx, type: HistoryEntryType.CUSTOMER_ADDRESS_DELETED, data: { address: addressToLine(address), }, }); const deletedAddress = new Address(address); await this.connection.getRepository(ctx, Address).remove(address); address.customer = customer; await this.eventBus.publish(new CustomerAddressEvent(ctx, deletedAddress, 'deleted', id)); return true; } async softDelete(ctx: RequestContext, customerId: ID): Promise<DeletionResponse> { const customer = await this.connection.getEntityOrThrow(ctx, Customer, customerId, { channelId: ctx.channelId, }); await this.connection .getRepository(ctx, Customer) .update({ id: customerId }, { deletedAt: new Date() }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (customer.user) { await this.userService.softDelete(ctx, customer.user.id); } await this.eventBus.publish(new CustomerEvent(ctx, customer, 'deleted', customerId)); return { result: DeletionResult.DELETED, }; } /** * @description * If the Customer associated with the given Order does not yet have any Addresses, * this method will create new Address(es) based on the Order's shipping & billing * addresses. */ async createAddressesForNewCustomer(ctx: RequestContext, order: Order) { if (!order.customer) { return; } const addresses = await this.findAddressesByCustomerId(ctx, order.customer.id); // If the Customer has no addresses yet, use the shipping/billing address data // to populate the initial default Address. if (addresses.length === 0 && order.shippingAddress?.country) { const shippingAddress = order.shippingAddress; const billingAddress = order.billingAddress; const hasSeparateBillingAddress = billingAddress?.streetLine1 && !this.addressesAreEqual(shippingAddress, billingAddress); if (shippingAddress.streetLine1) { await this.createAddress(ctx, order.customer.id, { ...shippingAddress, company: shippingAddress.company || '', streetLine1: shippingAddress.streetLine1 || '', streetLine2: shippingAddress.streetLine2 || '', countryCode: shippingAddress.countryCode || '', defaultBillingAddress: !hasSeparateBillingAddress, defaultShippingAddress: true, }); } if (hasSeparateBillingAddress) { await this.createAddress(ctx, order.customer.id, { ...billingAddress, company: billingAddress.company || '', streetLine1: billingAddress.streetLine1 || '', streetLine2: billingAddress.streetLine2 || '', countryCode: billingAddress.countryCode || '', defaultBillingAddress: true, defaultShippingAddress: false, }); } } } private addressesAreEqual(address1: OrderAddress, address2: OrderAddress): boolean { return ( address1.streetLine1 === address2.streetLine1 && address1.streetLine2 === address2.streetLine2 && address1.postalCode === address2.postalCode ); } async addNoteToCustomer(ctx: RequestContext, input: AddNoteToCustomerInput): Promise<Customer> { const customer = await this.connection.getEntityOrThrow(ctx, Customer, input.id, { channelId: ctx.channelId, }); await this.historyService.createHistoryEntryForCustomer( { ctx, customerId: customer.id, type: HistoryEntryType.CUSTOMER_NOTE, data: { note: input.note, }, }, input.isPublic, ); return customer; } async updateCustomerNote(ctx: RequestContext, input: UpdateCustomerNoteInput): Promise<HistoryEntry> { return this.historyService.updateCustomerHistoryEntry(ctx, { type: HistoryEntryType.CUSTOMER_NOTE, data: input.note ? { note: input.note } : undefined, ctx, entryId: input.noteId, }); } async deleteCustomerNote(ctx: RequestContext, id: ID): Promise<DeletionResponse> { try { await this.historyService.deleteCustomerHistoryEntry(ctx, id); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.message, }; } } private async enforceSingleDefaultAddress( ctx: RequestContext, addressId: ID, input: CreateAddressInput | UpdateAddressInput, ) { const result = await this.connection .getRepository(ctx, Address) .findOne({ where: { id: addressId }, relations: ['customer', 'customer.addresses'] }); if (result) { const customerAddressIds = result.customer.addresses .map(a => a.id) .filter(id => !idsAreEqual(id, addressId)) as string[]; if (customerAddressIds.length) { if (input.defaultBillingAddress === true) { await this.connection.getRepository(ctx, Address).update(customerAddressIds, { defaultBillingAddress: false, }); } if (input.defaultShippingAddress === true) { await this.connection.getRepository(ctx, Address).update(customerAddressIds, { defaultShippingAddress: false, }); } } } } /** * If a Customer Address is to be deleted, check if it is assigned as a default for shipping or * billing. If so, attempt to transfer default status to one of the other addresses if there are * any. */ private async reassignDefaultsForDeletedAddress(ctx: RequestContext, addressToDelete: Address) { if (!addressToDelete.defaultBillingAddress && !addressToDelete.defaultShippingAddress) { return; } const result = await this.connection .getRepository(ctx, Address) .findOne({ where: { id: addressToDelete.id }, relations: ['customer', 'customer.addresses'] }); if (result) { const customerAddresses = result.customer.addresses; if (1 < customerAddresses.length) { const otherAddresses = customerAddresses .filter(address => !idsAreEqual(address.id, addressToDelete.id)) .sort((a, b) => (a.id < b.id ? -1 : 1)); if (addressToDelete.defaultShippingAddress) { otherAddresses[0].defaultShippingAddress = true; } if (addressToDelete.defaultBillingAddress) { otherAddresses[0].defaultBillingAddress = true; } await this.connection.getRepository(ctx, Address).save(otherAddresses[0], { reload: false }); } } } }
import { Injectable } from '@nestjs/common'; import { CreateFacetValueInput, CreateFacetValueWithFacetInput, DeletionResponse, DeletionResult, LanguageCode, UpdateFacetValueInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Product, ProductVariant } from '../../entity'; import { Facet } from '../../entity/facet/facet.entity'; import { FacetValueTranslation } from '../../entity/facet-value/facet-value-translation.entity'; import { FacetValue } from '../../entity/facet-value/facet-value.entity'; import { EventBus } from '../../event-bus'; import { FacetValueEvent } from '../../event-bus/events/facet-value-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { translateDeep } from '../helpers/utils/translate-entity'; import { ChannelService } from './channel.service'; /** * @description * Contains methods relating to {@link FacetValue} entities. * * @docsCategory services */ @Injectable() export class FacetValueService { constructor( private connection: TransactionalConnection, private translatableSaver: TranslatableSaver, private configService: ConfigService, private customFieldRelationService: CustomFieldRelationService, private channelService: ChannelService, private eventBus: EventBus, private translator: TranslatorService, private listQueryBuilder: ListQueryBuilder, ) {} /** * @deprecated Use {@link FacetValueService.findAll findAll(ctx, lang)} instead */ findAll(lang: LanguageCode): Promise<Array<Translated<FacetValue>>>; findAll(ctx: RequestContext, lang: LanguageCode): Promise<Array<Translated<FacetValue>>>; findAll( ctxOrLang: RequestContext | LanguageCode, lang?: LanguageCode, ): Promise<Array<Translated<FacetValue>>> { const [repository, languageCode] = ctxOrLang instanceof RequestContext ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion [this.connection.getRepository(ctxOrLang, FacetValue), lang!] : [this.connection.rawConnection.getRepository(FacetValue), ctxOrLang]; // TODO: Implement usage of channelLanguageCode return repository .find({ relations: ['facet'], }) .then(facetValues => facetValues.map(facetValue => translateDeep(facetValue, languageCode, ['facet'])), ); } /** * @description * Returns a PaginatedList of FacetValues. * * TODO: in v2 this should replace the `findAll()` method. * A separate method was created just to avoid a breaking change in v1.9. */ findAllList( ctx: RequestContext, options?: ListQueryOptions<FacetValue>, relations?: RelationPaths<FacetValue>, ): Promise<PaginatedList<Translated<FacetValue>>> { return this.listQueryBuilder .build(FacetValue, options, { ctx, relations: relations ?? ['facet'], channelId: ctx.channelId, }) .getManyAndCount() .then(([items, totalItems]) => { return { items: items.map(item => this.translator.translate(item, ctx, ['facet'])), totalItems, }; }); } findOne(ctx: RequestContext, id: ID): Promise<Translated<FacetValue> | undefined> { return this.connection .getRepository(ctx, FacetValue) .findOne({ where: { id }, relations: ['facet'], }) .then( facetValue => (facetValue && this.translator.translate(facetValue, ctx, ['facet'])) ?? undefined, ); } findByIds(ctx: RequestContext, ids: ID[]): Promise<Array<Translated<FacetValue>>> { const facetValues = this.connection.findByIdsInChannel(ctx, FacetValue, ids, ctx.channelId, { relations: ['facet'], }); return facetValues.then(values => values.map(facetValue => this.translator.translate(facetValue, ctx, ['facet'])), ); } /** * @description * Returns all FacetValues belonging to the Facet with the given id. */ findByFacetId(ctx: RequestContext, id: ID): Promise<Array<Translated<FacetValue>>> { return this.connection .getRepository(ctx, FacetValue) .find({ where: { facet: { id }, }, }) .then(values => values.map(facetValue => this.translator.translate(facetValue, ctx))); } /** * @description * Returns all FacetValues belonging to the Facet with the given id. */ findByFacetIdList( ctx: RequestContext, id: ID, options?: ListQueryOptions<FacetValue>, relations?: RelationPaths<FacetValue>, ): Promise<PaginatedList<Translated<FacetValue>>> { return this.listQueryBuilder .build(FacetValue, options, { ctx, relations: relations ?? ['facet'], channelId: ctx.channelId, entityAlias: 'facetValue', }) .andWhere('facetValue.facetId = :id', { id }) .getManyAndCount() .then(([items, totalItems]) => { return { items: items.map(item => this.translator.translate(item, ctx, ['facet'])), totalItems, }; }); } async create( ctx: RequestContext, facet: Facet, input: CreateFacetValueInput | CreateFacetValueWithFacetInput, ): Promise<Translated<FacetValue>> { const facetValue = await this.translatableSaver.create({ ctx, input, entityType: FacetValue, translationType: FacetValueTranslation, beforeSave: async fv => { fv.facet = facet; await this.channelService.assignToCurrentChannel(fv, ctx); }, }); const facetValueWithRelations = await this.customFieldRelationService.updateRelations( ctx, FacetValue, input as CreateFacetValueInput, facetValue, ); await this.eventBus.publish(new FacetValueEvent(ctx, facetValueWithRelations, 'created', input)); return assertFound(this.findOne(ctx, facetValue.id)); } async update(ctx: RequestContext, input: UpdateFacetValueInput): Promise<Translated<FacetValue>> { const facetValue = await this.translatableSaver.update({ ctx, input, entityType: FacetValue, translationType: FacetValueTranslation, }); await this.customFieldRelationService.updateRelations(ctx, FacetValue, input, facetValue); await this.eventBus.publish(new FacetValueEvent(ctx, facetValue, 'updated', input)); return assertFound(this.findOne(ctx, facetValue.id)); } async delete(ctx: RequestContext, id: ID, force: boolean = false): Promise<DeletionResponse> { const { productCount, variantCount } = await this.checkFacetValueUsage(ctx, [id]); const isInUse = !!(productCount || variantCount); const both = !!(productCount && variantCount) ? 'both' : 'single'; let message = ''; let result: DeletionResult; const facetValue = await this.connection.getEntityOrThrow(ctx, FacetValue, id); const i18nVars = { products: productCount, variants: variantCount, both, facetValueCode: facetValue.code, }; // Create a new facetValue so that the id is still available // after deletion (the .remove() method sets it to undefined) const deletedFacetValue = new FacetValue(facetValue); if (!isInUse) { await this.connection.getRepository(ctx, FacetValue).remove(facetValue); await this.eventBus.publish(new FacetValueEvent(ctx, deletedFacetValue, 'deleted', id)); result = DeletionResult.DELETED; } else if (force) { await this.connection.getRepository(ctx, FacetValue).remove(facetValue); await this.eventBus.publish(new FacetValueEvent(ctx, deletedFacetValue, 'deleted', id)); message = ctx.translate('message.facet-value-force-deleted', i18nVars); result = DeletionResult.DELETED; } else { message = ctx.translate('message.facet-value-used', i18nVars); result = DeletionResult.NOT_DELETED; } return { result, message, }; } /** * @description * Checks for usage of the given FacetValues in any Products or Variants, and returns the counts. */ async checkFacetValueUsage( ctx: RequestContext, facetValueIds: ID[], channelId?: ID, ): Promise<{ productCount: number; variantCount: number }> { const consumingProductsQb = this.connection .getRepository(ctx, Product) .createQueryBuilder('product') .leftJoinAndSelect('product.facetValues', 'facetValues') .where('facetValues.id IN (:...facetValueIds)', { facetValueIds }) .andWhere('product.deletedAt IS NULL'); const consumingVariantsQb = this.connection .getRepository(ctx, ProductVariant) .createQueryBuilder('variant') .leftJoinAndSelect('variant.facetValues', 'facetValues') .where('facetValues.id IN (:...facetValueIds)', { facetValueIds }) .andWhere('variant.deletedAt IS NULL'); if (channelId) { consumingProductsQb .leftJoin('product.channels', 'product_channel') .leftJoin('facetValues.channels', 'channel') .andWhere('product_channel.id = :channelId') .andWhere('channel.id = :channelId') .setParameter('channelId', channelId); consumingVariantsQb .leftJoin('variant.channels', 'variant_channel') .leftJoin('facetValues.channels', 'channel') .andWhere('variant_channel.id = :channelId') .andWhere('channel.id = :channelId') .setParameter('channelId', channelId); } return { productCount: await consumingProductsQb.getCount(), variantCount: await consumingVariantsQb.getCount(), }; } }
import { Injectable } from '@nestjs/common'; import { AssignFacetsToChannelInput, CreateFacetInput, DeletionResponse, DeletionResult, LanguageCode, Permission, RemoveFacetFromChannelResult, RemoveFacetsFromChannelInput, UpdateFacetInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { In } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ErrorResultUnion, FacetInUseError, ForbiddenError, UserInputError } from '../../common'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { FacetTranslation } from '../../entity/facet/facet-translation.entity'; import { Facet } from '../../entity/facet/facet.entity'; import { FacetValue } from '../../entity/facet-value/facet-value.entity'; import { EventBus } from '../../event-bus'; import { FacetEvent } from '../../event-bus/events/facet-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { translateDeep } from '../helpers/utils/translate-entity'; import { ChannelService } from './channel.service'; import { FacetValueService } from './facet-value.service'; import { RoleService } from './role.service'; /** * @description * Contains methods relating to {@link Facet} entities. * * @docsCategory services */ @Injectable() export class FacetService { constructor( private connection: TransactionalConnection, private facetValueService: FacetValueService, private translatableSaver: TranslatableSaver, private listQueryBuilder: ListQueryBuilder, private configService: ConfigService, private channelService: ChannelService, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private translator: TranslatorService, private roleService: RoleService, ) {} findAll( ctx: RequestContext, options?: ListQueryOptions<Facet>, relations?: RelationPaths<Facet>, ): Promise<PaginatedList<Translated<Facet>>> { return this.listQueryBuilder .build(Facet, options, { relations: relations ?? ['values', 'values.facet', 'channels'], ctx, channelId: ctx.channelId, }) .getManyAndCount() .then(([facets, totalItems]) => { const items = facets.map(facet => this.translator.translate(facet, ctx, ['values', ['values', 'facet']]), ); return { items, totalItems, }; }); } findOne( ctx: RequestContext, facetId: ID, relations?: RelationPaths<Facet>, ): Promise<Translated<Facet> | undefined> { return this.connection .findOneInChannel(ctx, Facet, facetId, ctx.channelId, { relations: relations ?? ['values', 'values.facet', 'channels'], }) .then( facet => (facet && this.translator.translate(facet, ctx, ['values', ['values', 'facet']])) ?? undefined, ); } /** * @deprecated Use {@link FacetService.findByCode findByCode(ctx, facetCode, lang)} instead */ findByCode(facetCode: string, lang: LanguageCode): Promise<Translated<Facet> | undefined>; findByCode( ctx: RequestContext, facetCode: string, lang: LanguageCode, ): Promise<Translated<Facet> | undefined>; findByCode( ctxOrFacetCode: RequestContext | string, facetCodeOrLang: string | LanguageCode, lang?: LanguageCode, ): Promise<Translated<Facet> | undefined> { const relations = ['values', 'values.facet']; const [repository, facetCode, languageCode] = ctxOrFacetCode instanceof RequestContext ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion [this.connection.getRepository(ctxOrFacetCode, Facet), facetCodeOrLang, lang!] : [ this.connection.rawConnection.getRepository(Facet), ctxOrFacetCode, facetCodeOrLang as LanguageCode, ]; // TODO: Implement usage of channelLanguageCode return repository .findOne({ where: { code: facetCode, }, relations, }) .then( facet => (facet && translateDeep(facet, languageCode, ['values', ['values', 'facet']])) ?? undefined, ); } /** * @description * Returns the Facet which contains the given FacetValue id. */ async findByFacetValueId(ctx: RequestContext, id: ID): Promise<Translated<Facet> | undefined> { const facet = await this.connection .getRepository(ctx, Facet) .createQueryBuilder('facet') .leftJoinAndSelect('facet.translations', 'translations') .leftJoin('facet.values', 'facetValue') .where('facetValue.id = :id', { id }) .getOne(); if (facet) { return this.translator.translate(facet, ctx); } } async create(ctx: RequestContext, input: CreateFacetInput): Promise<Translated<Facet>> { const facet = await this.translatableSaver.create({ ctx, input, entityType: Facet, translationType: FacetTranslation, beforeSave: async f => { f.code = await this.ensureUniqueCode(ctx, f.code); await this.channelService.assignToCurrentChannel(f, ctx); }, }); const facetWithRelations = await this.customFieldRelationService.updateRelations( ctx, Facet, input, facet, ); await this.eventBus.publish(new FacetEvent(ctx, facetWithRelations, 'created', input)); return assertFound(this.findOne(ctx, facet.id)); } async update(ctx: RequestContext, input: UpdateFacetInput): Promise<Translated<Facet>> { const facet = await this.translatableSaver.update({ ctx, input, entityType: Facet, translationType: FacetTranslation, beforeSave: async f => { if (f.code) { f.code = await this.ensureUniqueCode(ctx, f.code, f.id); } }, }); await this.customFieldRelationService.updateRelations(ctx, Facet, input, facet); await this.eventBus.publish(new FacetEvent(ctx, facet, 'updated', input)); return assertFound(this.findOne(ctx, facet.id)); } async delete(ctx: RequestContext, id: ID, force: boolean = false): Promise<DeletionResponse> { const facet = await this.connection.getEntityOrThrow(ctx, Facet, id, { relations: ['values'], channelId: ctx.channelId, }); let productCount = 0; let variantCount = 0; if (facet.values.length) { const counts = await this.facetValueService.checkFacetValueUsage( ctx, facet.values.map(fv => fv.id), ); productCount = counts.productCount; variantCount = counts.variantCount; } const isInUse = !!(productCount || variantCount); const both = !!(productCount && variantCount) ? 'both' : 'single'; const i18nVars = { products: productCount, variants: variantCount, both, facetCode: facet.code }; let message = ''; let result: DeletionResult; const deletedFacet = new Facet(facet); if (!isInUse) { await this.connection.getRepository(ctx, Facet).remove(facet); await this.eventBus.publish(new FacetEvent(ctx, deletedFacet, 'deleted', id)); result = DeletionResult.DELETED; } else if (force) { await this.connection.getRepository(ctx, Facet).remove(facet); await this.eventBus.publish(new FacetEvent(ctx, deletedFacet, 'deleted', id)); message = ctx.translate('message.facet-force-deleted', i18nVars); result = DeletionResult.DELETED; } else { message = ctx.translate('message.facet-used', i18nVars); result = DeletionResult.NOT_DELETED; } return { result, message, }; } /** * Checks to ensure the Facet code is unique. If there is a conflict, then the code is suffixed * with an incrementing integer. */ private async ensureUniqueCode(ctx: RequestContext, code: string, id?: ID) { let candidate = code; let suffix = 1; let conflict = false; const alreadySuffixed = /-\d+$/; do { const match = await this.connection .getRepository(ctx, Facet) .findOne({ where: { code: candidate } }); conflict = !!match && ((id != null && !idsAreEqual(match.id, id)) || id == null); if (conflict) { suffix++; if (alreadySuffixed.test(candidate)) { candidate = candidate.replace(alreadySuffixed, `-${suffix}`); } else { candidate = `${candidate}-${suffix}`; } } } while (conflict); return candidate; } /** * @description * Assigns Facets to the specified Channel */ async assignFacetsToChannel( ctx: RequestContext, input: AssignFacetsToChannelInput, ): Promise<Array<Translated<Facet>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.UpdateFacet, Permission.UpdateCatalog, ]); if (!hasPermission) { throw new ForbiddenError(); } const facetsToAssign = await this.connection .getRepository(ctx, Facet) .find({ where: { id: In(input.facetIds) }, relations: ['values'] }); const valuesToAssign = facetsToAssign.reduce( (values, facet) => [...values, ...facet.values], [] as FacetValue[], ); await Promise.all<any>([ ...facetsToAssign.map(async facet => { return this.channelService.assignToChannels(ctx, Facet, facet.id, [input.channelId]); }), ...valuesToAssign.map(async value => this.channelService.assignToChannels(ctx, FacetValue, value.id, [input.channelId]), ), ]); return this.connection .findByIdsInChannel( ctx, Facet, facetsToAssign.map(f => f.id), ctx.channelId, {}, ) .then(facets => facets.map(facet => translateDeep(facet, ctx.languageCode))); } /** * @description * Remove Facets from the specified Channel */ async removeFacetsFromChannel( ctx: RequestContext, input: RemoveFacetsFromChannelInput, ): Promise<Array<ErrorResultUnion<RemoveFacetFromChannelResult, Facet>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.DeleteFacet, Permission.DeleteCatalog, ]); if (!hasPermission) { throw new ForbiddenError(); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); if (idsAreEqual(input.channelId, defaultChannel.id)) { throw new UserInputError('error.items-cannot-be-removed-from-default-channel'); } const facetsToRemove = await this.connection .getRepository(ctx, Facet) .find({ where: { id: In(input.facetIds) }, relations: ['values'] }); const results: Array<ErrorResultUnion<RemoveFacetFromChannelResult, Facet>> = []; for (const facet of facetsToRemove) { let productCount = 0; let variantCount = 0; if (facet.values.length) { const counts = await this.facetValueService.checkFacetValueUsage( ctx, facet.values.map(fv => fv.id), input.channelId, ); productCount = counts.productCount; variantCount = counts.variantCount; const isInUse = !!(productCount || variantCount); const both = !!(productCount && variantCount) ? 'both' : 'single'; const i18nVars = { products: productCount, variants: variantCount, both }; let result: Translated<Facet> | undefined; if (!isInUse || input.force) { await this.channelService.removeFromChannels(ctx, Facet, facet.id, [input.channelId]); await Promise.all( facet.values.map(fv => this.channelService.removeFromChannels(ctx, FacetValue, fv.id, [input.channelId]), ), ); result = await this.findOne(ctx, facet.id); if (result) { results.push(result); } } else { results.push(new FacetInUseError({ facetCode: facet.code, productCount, variantCount })); } } } return results; } }
import { Injectable } from '@nestjs/common'; import { ConfigurableOperationInput, OrderLineInput } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { isObject } from '@vendure/common/lib/shared-utils'; import { unique } from '@vendure/common/lib/unique'; import { In, Not } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { CreateFulfillmentError, FulfillmentStateTransitionError, InvalidFulfillmentHandlerError, } from '../../common/error/generated-graphql-admin-errors'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Fulfillment } from '../../entity/fulfillment/fulfillment.entity'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { FulfillmentLine } from '../../entity/order-line-reference/fulfillment-line.entity'; import { EventBus } from '../../event-bus/event-bus'; import { FulfillmentEvent } from '../../event-bus/events/fulfillment-event'; import { FulfillmentStateTransitionEvent } from '../../event-bus/events/fulfillment-state-transition-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { FulfillmentState } from '../helpers/fulfillment-state-machine/fulfillment-state'; import { FulfillmentStateMachine } from '../helpers/fulfillment-state-machine/fulfillment-state-machine'; /** * @description * Contains methods relating to {@link Fulfillment} entities. * * @docsCategory services */ @Injectable() export class FulfillmentService { constructor( private connection: TransactionalConnection, private fulfillmentStateMachine: FulfillmentStateMachine, private eventBus: EventBus, private configService: ConfigService, private customFieldRelationService: CustomFieldRelationService, ) {} /** * @description * Creates a new Fulfillment for the given Orders and OrderItems, using the specified * {@link FulfillmentHandler}. */ async create( ctx: RequestContext, orders: Order[], lines: OrderLineInput[], handler: ConfigurableOperationInput, ): Promise<Fulfillment | InvalidFulfillmentHandlerError | CreateFulfillmentError> { const fulfillmentHandler = this.configService.shippingOptions.fulfillmentHandlers.find( h => h.code === handler.code, ); if (!fulfillmentHandler) { return new InvalidFulfillmentHandlerError(); } let fulfillmentPartial; try { fulfillmentPartial = await fulfillmentHandler.createFulfillment( ctx, orders, lines, handler.arguments, ); } catch (e: unknown) { let message = 'No error message'; if (isObject(e)) { message = (e as any).message || e.toString(); } return new CreateFulfillmentError({ fulfillmentHandlerError: message }); } const orderLines = await this.connection .getRepository(ctx, OrderLine) .find({ where: { id: In(lines.map(l => l.orderLineId)) } }); const newFulfillment = await this.connection.getRepository(ctx, Fulfillment).save( new Fulfillment({ method: '', trackingCode: '', ...fulfillmentPartial, lines: [], state: this.fulfillmentStateMachine.getInitialState(), handlerCode: fulfillmentHandler.code, }), ); const fulfillmentLines: FulfillmentLine[] = []; for (const { orderLineId, quantity } of lines) { const fulfillmentLine = await this.connection.getRepository(ctx, FulfillmentLine).save( new FulfillmentLine({ orderLineId, quantity, }), ); fulfillmentLines.push(fulfillmentLine); } await this.connection .getRepository(ctx, Fulfillment) .createQueryBuilder() .relation('lines') .of(newFulfillment) .add(fulfillmentLines); const fulfillmentWithRelations = await this.customFieldRelationService.updateRelations( ctx, Fulfillment, fulfillmentPartial, newFulfillment, ); await this.eventBus.publish( new FulfillmentEvent(ctx, fulfillmentWithRelations, { orders, lines, handler, }), ); return newFulfillment; } async getFulfillmentLines(ctx: RequestContext, id: ID): Promise<FulfillmentLine[]> { return this.connection .getEntityOrThrow(ctx, Fulfillment, id, { relations: ['lines'], }) .then(fulfillment => fulfillment.lines); } async getFulfillmentsLinesForOrderLine( ctx: RequestContext, orderLineId: ID, relations: RelationPaths<FulfillmentLine> = [], ): Promise<FulfillmentLine[]> { const defaultRelations = ['fulfillment']; return this.connection.getRepository(ctx, FulfillmentLine).find({ relations: Array.from(new Set([...defaultRelations, ...relations])), where: { fulfillment: { state: Not('Cancelled'), }, orderLineId, }, }); } /** * @description * Transitions the specified Fulfillment to a new state and upon successful transition * publishes a {@link FulfillmentStateTransitionEvent}. */ async transitionToState( ctx: RequestContext, fulfillmentId: ID, state: FulfillmentState, ): Promise< | { fulfillment: Fulfillment; orders: Order[]; fromState: FulfillmentState; toState: FulfillmentState; } | FulfillmentStateTransitionError > { const fulfillment = await this.connection.getEntityOrThrow(ctx, Fulfillment, fulfillmentId, { relations: ['lines'], }); const orderLinesIds = unique(fulfillment.lines.map(lines => lines.orderLineId)); const orders = await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .leftJoinAndSelect('order.lines', 'line') .where('line.id IN (:...lineIds)', { lineIds: orderLinesIds }) .getMany(); const fromState = fulfillment.state; let finalize: () => Promise<any>; try { const result = await this.fulfillmentStateMachine.transition(ctx, fulfillment, orders, state); finalize = result.finalize; } catch (e: any) { const transitionError = ctx.translate(e.message, { fromState, toState: state }); return new FulfillmentStateTransitionError({ transitionError, fromState, toState: state }); } await this.connection.getRepository(ctx, Fulfillment).save(fulfillment, { reload: false }); await this.eventBus.publish(new FulfillmentStateTransitionEvent(fromState, state, ctx, fulfillment)); await finalize(); return { fulfillment, orders, fromState, toState: state }; } /** * @description * Returns an array of the next valid states for the Fulfillment. */ getNextStates(fulfillment: Fulfillment): readonly FulfillmentState[] { return this.fulfillmentStateMachine.getNextStates(fulfillment); } }
import { Injectable } from '@nestjs/common'; import { UpdateGlobalSettingsInput } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { RequestContextCacheService } from '../../cache/request-context-cache.service'; import { CacheKey } from '../../common/constants'; import { InternalServerError } from '../../common/error/errors'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { GlobalSettings } from '../../entity/global-settings/global-settings.entity'; import { EventBus } from '../../event-bus'; import { GlobalSettingsEvent } from '../../event-bus/events/global-settings-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { patchEntity } from '../helpers/utils/patch-entity'; /** * @description * Contains methods relating to the {@link GlobalSettings} entity. * * @docsCategory services */ @Injectable() export class GlobalSettingsService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private requestCache: RequestContextCacheService, ) {} /** * Ensure there is a single global settings row in the database. * @internal */ async initGlobalSettings() { try { const result = await this.connection.rawConnection.getRepository(GlobalSettings).find(); if (result.length === 0) { throw new Error('No global settings'); } if (1 < result.length) { // Strange edge case, see https://github.com/vendure-ecommerce/vendure/issues/987 const toDelete = result.slice(1); await this.connection.rawConnection.getRepository(GlobalSettings).remove(toDelete); } } catch (err: any) { const settings = new GlobalSettings({ availableLanguages: [this.configService.defaultLanguageCode], }); await this.connection.rawConnection .getRepository(GlobalSettings) .save(settings, { reload: false }); } } /** * @description * Returns the GlobalSettings entity. */ async getSettings(ctx: RequestContext): Promise<GlobalSettings> { const settings = await this.requestCache.get(ctx, CacheKey.GlobalSettings, () => this.connection .getRepository(ctx, GlobalSettings) .createQueryBuilder('global_settings') .orderBy(this.connection.rawConnection.driver.escape('createdAt'), 'ASC') .getOne(), ); if (!settings) { throw new InternalServerError('error.global-settings-not-found'); } return settings; } async updateSettings(ctx: RequestContext, input: UpdateGlobalSettingsInput): Promise<GlobalSettings> { const settings = await this.getSettings(ctx); await this.eventBus.publish(new GlobalSettingsEvent(ctx, settings, input)); patchEntity(settings, input); await this.customFieldRelationService.updateRelations(ctx, GlobalSettings, input, settings); return this.connection.getRepository(ctx, GlobalSettings).save(settings); } }
import { Injectable } from '@nestjs/common'; import { UpdateCustomerInput as UpdateCustomerShopInput } from '@vendure/common/lib/generated-shop-types'; import { HistoryEntryListOptions, HistoryEntryType, OrderLineInput, UpdateAddressInput, UpdateCustomerInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList, Type } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Administrator } from '../../entity/administrator/administrator.entity'; import { CustomerHistoryEntry } from '../../entity/history-entry/customer-history-entry.entity'; import { HistoryEntry } from '../../entity/history-entry/history-entry.entity'; import { OrderHistoryEntry } from '../../entity/history-entry/order-history-entry.entity'; import { EventBus } from '../../event-bus'; import { HistoryEntryEvent } from '../../event-bus/events/history-entry-event'; import { FulfillmentState } from '../helpers/fulfillment-state-machine/fulfillment-state'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { OrderState } from '../helpers/order-state-machine/order-state'; import { PaymentState } from '../helpers/payment-state-machine/payment-state'; import { RefundState } from '../helpers/refund-state-machine/refund-state'; import { AdministratorService } from './administrator.service'; export interface CustomerHistoryEntryData { [HistoryEntryType.CUSTOMER_REGISTERED]: { strategy: string; }; [HistoryEntryType.CUSTOMER_VERIFIED]: { strategy: string; }; [HistoryEntryType.CUSTOMER_DETAIL_UPDATED]: { input: UpdateCustomerInput | UpdateCustomerShopInput; }; [HistoryEntryType.CUSTOMER_ADDRESS_CREATED]: { address: string; }; [HistoryEntryType.CUSTOMER_ADDED_TO_GROUP]: { groupName: string; }; [HistoryEntryType.CUSTOMER_REMOVED_FROM_GROUP]: { groupName: string; }; [HistoryEntryType.CUSTOMER_ADDRESS_UPDATED]: { address: string; input: UpdateAddressInput; }; [HistoryEntryType.CUSTOMER_ADDRESS_DELETED]: { address: string; }; [HistoryEntryType.CUSTOMER_PASSWORD_UPDATED]: Record<string, never>; [HistoryEntryType.CUSTOMER_PASSWORD_RESET_REQUESTED]: Record<string, never>; [HistoryEntryType.CUSTOMER_PASSWORD_RESET_VERIFIED]: Record<string, never>; [HistoryEntryType.CUSTOMER_EMAIL_UPDATE_REQUESTED]: { oldEmailAddress: string; newEmailAddress: string; }; [HistoryEntryType.CUSTOMER_EMAIL_UPDATE_VERIFIED]: { oldEmailAddress: string; newEmailAddress: string; }; [HistoryEntryType.CUSTOMER_NOTE]: { note: string; }; } export interface OrderHistoryEntryData { [HistoryEntryType.ORDER_STATE_TRANSITION]: { from: OrderState; to: OrderState; }; [HistoryEntryType.ORDER_PAYMENT_TRANSITION]: { paymentId: ID; from: PaymentState; to: PaymentState; }; [HistoryEntryType.ORDER_FULFILLMENT_TRANSITION]: { fulfillmentId: ID; from: FulfillmentState; to: FulfillmentState; }; [HistoryEntryType.ORDER_FULFILLMENT]: { fulfillmentId: ID; }; [HistoryEntryType.ORDER_CANCELLATION]: { lines: OrderLineInput[]; shippingCancelled: boolean; reason?: string; }; [HistoryEntryType.ORDER_REFUND_TRANSITION]: { refundId: ID; from: RefundState; to: RefundState; reason?: string; }; [HistoryEntryType.ORDER_NOTE]: { note: string; }; [HistoryEntryType.ORDER_COUPON_APPLIED]: { couponCode: string; promotionId: ID; }; [HistoryEntryType.ORDER_COUPON_REMOVED]: { couponCode: string; }; [HistoryEntryType.ORDER_MODIFIED]: { modificationId: ID; }; [HistoryEntryType.ORDER_CUSTOMER_UPDATED]: { previousCustomerId?: ID; previousCustomerName?: ID; newCustomerId: ID; newCustomerName: ID; note?: string; }; } export interface CreateCustomerHistoryEntryArgs<T extends keyof CustomerHistoryEntryData> { customerId: ID; ctx: RequestContext; type: T; data: CustomerHistoryEntryData[T]; } export interface CreateOrderHistoryEntryArgs<T extends keyof OrderHistoryEntryData> { orderId: ID; ctx: RequestContext; type: T; data: OrderHistoryEntryData[T]; } export interface UpdateOrderHistoryEntryArgs<T extends keyof OrderHistoryEntryData> { entryId: ID; ctx: RequestContext; type: T; isPublic?: boolean; data?: OrderHistoryEntryData[T]; } export interface UpdateCustomerHistoryEntryArgs<T extends keyof CustomerHistoryEntryData> { entryId: ID; ctx: RequestContext; type: T; data?: CustomerHistoryEntryData[T]; } /** * @description * Contains methods relating to {@link HistoryEntry} entities. Histories are timelines of actions * related to a particular Customer or Order, recording significant events such as creation, state changes, * notes, etc. * * ## Custom History Entry Types * * Since Vendure v1.9.0, it is possible to define custom HistoryEntry types. * * Let's take an example where we have some Customers who are businesses. We want to verify their * tax ID in order to allow them wholesale rates. As part of this verification, we'd like to add * an entry into the Customer's history with data about the tax ID verification. * * First of all we'd extend the GraphQL `HistoryEntryType` enum for our new type as part of a plugin * * @example * ```ts * import { PluginCommonModule, VendurePlugin } from '\@vendure/core'; * import { VerificationService } from './verification.service'; * * \@VendurePlugin({ * imports: [PluginCommonModule], * adminApiExtensions: { * schema: gql` * extend enum HistoryEntryType { * CUSTOMER_TAX_ID_VERIFICATION * } * `, * }, * providers: [VerificationService], * }) * export class TaxIDVerificationPlugin {} * ``` * * Next we need to create a TypeScript type definition file where we extend the `CustomerHistoryEntryData` interface. This is done * via TypeScript's [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces) * and [ambient modules](https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules) features. * * @example * ```ts * // types.ts * import { CustomerHistoryEntryData } from '\@vendure/core'; * * export const CUSTOMER_TAX_ID_VERIFICATION = 'CUSTOMER_TAX_ID_VERIFICATION'; * * declare module '@vendure/core' { * interface CustomerHistoryEntryData { * [CUSTOMER_TAX_ID_VERIFICATION]: { * taxId: string; * valid: boolean; * name?: string; * address?: string; * }; * } * } * ``` * * Note: it works exactly the same way if we wanted to add a custom type for Order history, except in that case we'd extend the * `OrderHistoryEntryData` interface instead. * * Now that we have our types set up, we can use the HistoryService to add a new HistoryEntry in a type-safe manner: * * @example * ```ts * // verification.service.ts * import { Injectable } from '\@nestjs/common'; * import { RequestContext } from '\@vendure/core'; * import { CUSTOMER_TAX_ID_VERIFICATION } from './types'; * * \@Injectable() * export class VerificationService { * constructor(private historyService: HistoryService) {} * * async verifyTaxId(ctx: RequestContext, customerId: ID, taxId: string) { * const result = await someTaxIdCheckingService(taxId); * * await this.historyService.createHistoryEntryForCustomer({ * customerId, * ctx, * type: CUSTOMER_TAX_ID_VERIFICATION, * data: { * taxId, * valid: result.isValid, * name: result.companyName, * address: result.registeredAddress, * }, * }); * } * } * ``` * :::info * It is also possible to define a UI component to display custom history entry types. See the * [Custom History Timeline Components guide](/guides/extending-the-admin-ui/custom-timeline-components/). * ::: * * @docsCategory services */ @Injectable() export class HistoryService { constructor( private connection: TransactionalConnection, private administratorService: AdministratorService, private listQueryBuilder: ListQueryBuilder, private eventBus: EventBus, ) {} async getHistoryForOrder( ctx: RequestContext, orderId: ID, publicOnly: boolean, options?: HistoryEntryListOptions, ): Promise<PaginatedList<OrderHistoryEntry>> { return this.listQueryBuilder .build(HistoryEntry as any as Type<OrderHistoryEntry>, options, { where: { order: { id: orderId } as any, ...(publicOnly ? { isPublic: true } : {}), }, relations: ['administrator'], ctx, }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } async createHistoryEntryForOrder<T extends keyof OrderHistoryEntryData>( args: CreateOrderHistoryEntryArgs<T>, isPublic = true, ): Promise<OrderHistoryEntry> { const { ctx, data, orderId, type } = args; const administrator = await this.getAdministratorFromContext(ctx); const entry = new OrderHistoryEntry({ type, isPublic, data: data as any, order: { id: orderId }, administrator, }); const history = await this.connection.getRepository(ctx, OrderHistoryEntry).save(entry); await this.eventBus.publish(new HistoryEntryEvent(ctx, history, 'created', 'order', { type, data })); return history; } async getHistoryForCustomer( ctx: RequestContext, customerId: ID, publicOnly: boolean, options?: HistoryEntryListOptions, ): Promise<PaginatedList<CustomerHistoryEntry>> { return this.listQueryBuilder .build(HistoryEntry as any as Type<CustomerHistoryEntry>, options, { where: { customer: { id: customerId } as any, ...(publicOnly ? { isPublic: true } : {}), }, relations: ['administrator'], ctx, }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } async createHistoryEntryForCustomer<T extends keyof CustomerHistoryEntryData>( args: CreateCustomerHistoryEntryArgs<T>, isPublic = false, ): Promise<CustomerHistoryEntry> { const { ctx, data, customerId, type } = args; const administrator = await this.getAdministratorFromContext(ctx); const entry = new CustomerHistoryEntry({ createdAt: new Date(), type, isPublic, data: data as any, customer: { id: customerId }, administrator, }); const history = await this.connection.getRepository(ctx, CustomerHistoryEntry).save(entry); await this.eventBus.publish( new HistoryEntryEvent(ctx, history, 'created', 'customer', { type, data }), ); return history; } async updateOrderHistoryEntry<T extends keyof OrderHistoryEntryData>( ctx: RequestContext, args: UpdateOrderHistoryEntryArgs<T>, ) { const entry = await this.connection.getEntityOrThrow(ctx, OrderHistoryEntry, args.entryId, { where: { type: args.type }, }); if (args.data) { entry.data = args.data; } if (typeof args.isPublic === 'boolean') { entry.isPublic = args.isPublic; } const administrator = await this.getAdministratorFromContext(ctx); if (administrator) { entry.administrator = administrator; } const newEntry = await this.connection.getRepository(ctx, OrderHistoryEntry).save(entry); await this.eventBus.publish(new HistoryEntryEvent(ctx, entry, 'updated', 'order', args)); return newEntry; } async deleteOrderHistoryEntry(ctx: RequestContext, id: ID): Promise<void> { const entry = await this.connection.getEntityOrThrow(ctx, OrderHistoryEntry, id); const deletedEntry = new OrderHistoryEntry(entry); await this.connection.getRepository(ctx, OrderHistoryEntry).remove(entry); await this.eventBus.publish(new HistoryEntryEvent(ctx, deletedEntry, 'deleted', 'order', id)); } async updateCustomerHistoryEntry<T extends keyof CustomerHistoryEntryData>( ctx: RequestContext, args: UpdateCustomerHistoryEntryArgs<T>, ) { const entry = await this.connection.getEntityOrThrow(ctx, CustomerHistoryEntry, args.entryId, { where: { type: args.type }, }); if (args.data) { entry.data = args.data; } const administrator = await this.getAdministratorFromContext(ctx); if (administrator) { entry.administrator = administrator; } const newEntry = await this.connection.getRepository(ctx, CustomerHistoryEntry).save(entry); await this.eventBus.publish(new HistoryEntryEvent(ctx, entry, 'updated', 'customer', args)); return newEntry; } async deleteCustomerHistoryEntry(ctx: RequestContext, id: ID): Promise<void> { const entry = await this.connection.getEntityOrThrow(ctx, CustomerHistoryEntry, id); const deletedEntry = new CustomerHistoryEntry(entry); await this.connection.getRepository(ctx, CustomerHistoryEntry).remove(entry); await this.eventBus.publish(new HistoryEntryEvent(ctx, deletedEntry, 'deleted', 'customer', id)); } private async getAdministratorFromContext(ctx: RequestContext): Promise<Administrator | undefined> { const administrator = ctx.activeUserId ? await this.administratorService.findOneByUserId(ctx, ctx.activeUserId) : null; return administrator ?? undefined; } }
import { Injectable } from '@nestjs/common'; import { CreateAddressInput, ShippingMethodQuote, TestEligibleShippingMethodsInput, TestShippingMethodInput, TestShippingMethodQuote, TestShippingMethodResult, } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { grossPriceOf, netPriceOf } from '../../common/tax-utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { ShippingLine } from '../../entity/shipping-line/shipping-line.entity'; import { ShippingMethod } from '../../entity/shipping-method/shipping-method.entity'; import { ConfigArgService } from '../helpers/config-arg/config-arg.service'; import { OrderCalculator } from '../helpers/order-calculator/order-calculator'; import { ProductPriceApplicator } from '../helpers/product-price-applicator/product-price-applicator'; import { ShippingCalculator } from '../helpers/shipping-calculator/shipping-calculator'; import { TranslatorService } from '../helpers/translator/translator.service'; /** * @description * This service is responsible for creating temporary mock Orders against which tests can be run, such as * testing a ShippingMethod or Promotion. * * @docsCategory services */ @Injectable() export class OrderTestingService { constructor( private connection: TransactionalConnection, private orderCalculator: OrderCalculator, private shippingCalculator: ShippingCalculator, private configArgService: ConfigArgService, private configService: ConfigService, private productPriceApplicator: ProductPriceApplicator, private translator: TranslatorService, ) {} /** * @description * Runs a given ShippingMethod configuration against a mock Order to test for eligibility and resulting * price. */ async testShippingMethod( ctx: RequestContext, input: TestShippingMethodInput, ): Promise<TestShippingMethodResult> { const shippingMethod = new ShippingMethod({ checker: this.configArgService.parseInput('ShippingEligibilityChecker', input.checker), calculator: this.configArgService.parseInput('ShippingCalculator', input.calculator), }); const mockOrder = await this.buildMockOrder(ctx, input.shippingAddress, input.lines); const eligible = await shippingMethod.test(ctx, mockOrder); const result = eligible ? await shippingMethod.apply(ctx, mockOrder) : undefined; let quote: TestShippingMethodQuote | undefined; if (result) { const { price, priceIncludesTax, taxRate, metadata } = result; quote = { price: priceIncludesTax ? netPriceOf(price, taxRate) : price, priceWithTax: priceIncludesTax ? price : grossPriceOf(price, taxRate), metadata, }; } return { eligible, quote, }; } /** * @description * Tests all available ShippingMethods against a mock Order and return those which are eligible. This * is intended to simulate a call to the `eligibleShippingMethods` query of the Shop API. */ async testEligibleShippingMethods( ctx: RequestContext, input: TestEligibleShippingMethodsInput, ): Promise<ShippingMethodQuote[]> { const mockOrder = await this.buildMockOrder(ctx, input.shippingAddress, input.lines); const eligibleMethods = await this.shippingCalculator.getEligibleShippingMethods(ctx, mockOrder); return eligibleMethods .map(result => { this.translator.translate(result.method, ctx); return result; }) .map(result => { const { price, taxRate, priceIncludesTax, metadata } = result.result; return { id: result.method.id, price: priceIncludesTax ? netPriceOf(price, taxRate) : price, priceWithTax: priceIncludesTax ? price : grossPriceOf(price, taxRate), name: result.method.name, code: result.method.code, description: result.method.description, metadata: result.result.metadata, }; }); } private async buildMockOrder( ctx: RequestContext, shippingAddress: CreateAddressInput, lines: Array<{ productVariantId: ID; quantity: number }>, ): Promise<Order> { const { orderItemPriceCalculationStrategy } = this.configService.orderOptions; const mockOrder = new Order({ lines: [], surcharges: [], modifications: [], }); mockOrder.shippingAddress = shippingAddress; for (const line of lines) { const productVariant = await this.connection.getEntityOrThrow( ctx, ProductVariant, line.productVariantId, { relations: ['taxCategory'] }, ); await this.productPriceApplicator.applyChannelPriceAndTax(productVariant, ctx, mockOrder); const orderLine = new OrderLine({ productVariant, adjustments: [], taxLines: [], quantity: line.quantity, taxCategory: productVariant.taxCategory, }); mockOrder.lines.push(orderLine); const { price, priceIncludesTax } = await orderItemPriceCalculationStrategy.calculateUnitPrice( ctx, productVariant, orderLine.customFields || {}, mockOrder, orderLine.quantity, ); const taxRate = productVariant.taxRateApplied; orderLine.listPrice = price; orderLine.listPriceIncludesTax = priceIncludesTax; } mockOrder.shippingLines = [ new ShippingLine({ listPrice: 0, listPriceIncludesTax: ctx.channel.pricesIncludeTax, taxLines: [], adjustments: [], }), ]; await this.orderCalculator.applyPriceAdjustments(ctx, mockOrder, []); return mockOrder; } }
import { Injectable } from '@nestjs/common'; import { AddPaymentToOrderResult, ApplyCouponCodeResult, PaymentInput, PaymentMethodQuote, RemoveOrderItemsResult, SetOrderShippingMethodResult, UpdateOrderItemsResult, } from '@vendure/common/lib/generated-shop-types'; import { AddFulfillmentToOrderResult, AddManualPaymentToOrderResult, AddNoteToOrderInput, AdjustmentType, CancelOrderInput, CancelOrderResult, CancelPaymentResult, CreateAddressInput, DeletionResponse, DeletionResult, FulfillOrderInput, HistoryEntryType, ManualPaymentInput, ModifyOrderInput, ModifyOrderResult, OrderLineInput, OrderListOptions, OrderProcessState, OrderType, RefundOrderInput, RefundOrderResult, SetOrderCustomerInput, SettlePaymentResult, SettleRefundInput, ShippingMethodQuote, TransitionPaymentToStateResult, UpdateOrderNoteInput, } from '@vendure/common/lib/generated-types'; import { omit } from '@vendure/common/lib/omit'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { summate } from '@vendure/common/lib/shared-utils'; import { In, IsNull } from 'typeorm'; import { FindOptionsUtils } from 'typeorm/find-options/FindOptionsUtils'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { RequestContextCacheService } from '../../cache/request-context-cache.service'; import { CacheKey } from '../../common/constants'; import { ErrorResultUnion, isGraphQlErrorResult } from '../../common/error/error-result'; import { EntityNotFoundError, InternalServerError, UserInputError } from '../../common/error/errors'; import { CancelPaymentError, EmptyOrderLineSelectionError, FulfillmentStateTransitionError, InsufficientStockOnHandError, ItemsAlreadyFulfilledError, ManualPaymentStateError, MultipleOrderError, NothingToRefundError, PaymentOrderMismatchError, RefundOrderStateError, SettlePaymentError, } from '../../common/error/generated-graphql-admin-errors'; import { InsufficientStockError, NegativeQuantityError, OrderLimitError, OrderModificationError, OrderPaymentStateError, OrderStateTransitionError, PaymentDeclinedError, PaymentFailedError, } from '../../common/error/generated-graphql-shop-errors'; import { grossPriceOf, netPriceOf } from '../../common/tax-utils'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Channel } from '../../entity/channel/channel.entity'; import { Customer } from '../../entity/customer/customer.entity'; import { Fulfillment } from '../../entity/fulfillment/fulfillment.entity'; import { HistoryEntry } from '../../entity/history-entry/history-entry.entity'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { FulfillmentLine } from '../../entity/order-line-reference/fulfillment-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 { Promotion } from '../../entity/promotion/promotion.entity'; import { Refund } from '../../entity/refund/refund.entity'; import { Session } from '../../entity/session/session.entity'; import { ShippingLine } from '../../entity/shipping-line/shipping-line.entity'; import { Surcharge } from '../../entity/surcharge/surcharge.entity'; import { User } from '../../entity/user/user.entity'; import { EventBus } from '../../event-bus/event-bus'; import { CouponCodeEvent } from '../../event-bus/events/coupon-code-event'; import { OrderEvent } from '../../event-bus/events/order-event'; import { OrderLineEvent } from '../../event-bus/events/order-line-event'; import { OrderStateTransitionEvent } from '../../event-bus/events/order-state-transition-event'; import { RefundStateTransitionEvent } from '../../event-bus/events/refund-state-transition-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { FulfillmentState } from '../helpers/fulfillment-state-machine/fulfillment-state'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { OrderCalculator } from '../helpers/order-calculator/order-calculator'; import { OrderMerger } from '../helpers/order-merger/order-merger'; import { OrderModifier } from '../helpers/order-modifier/order-modifier'; import { OrderState } from '../helpers/order-state-machine/order-state'; import { OrderStateMachine } from '../helpers/order-state-machine/order-state-machine'; import { PaymentState } from '../helpers/payment-state-machine/payment-state'; import { RefundStateMachine } from '../helpers/refund-state-machine/refund-state-machine'; import { ShippingCalculator } from '../helpers/shipping-calculator/shipping-calculator'; import { TranslatorService } from '../helpers/translator/translator.service'; import { getOrdersFromLines, totalCoveredByPayments } from '../helpers/utils/order-utils'; import { patchEntity } from '../helpers/utils/patch-entity'; import { ChannelService } from './channel.service'; import { CountryService } from './country.service'; import { CustomerService } from './customer.service'; import { FulfillmentService } from './fulfillment.service'; import { HistoryService } from './history.service'; import { PaymentMethodService } from './payment-method.service'; import { PaymentService } from './payment.service'; import { ProductVariantService } from './product-variant.service'; import { PromotionService } from './promotion.service'; import { StockLevelService } from './stock-level.service'; /** * @description * Contains methods relating to {@link Order} entities. * * @docsCategory services */ @Injectable() export class OrderService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private productVariantService: ProductVariantService, private customerService: CustomerService, private countryService: CountryService, private orderCalculator: OrderCalculator, private shippingCalculator: ShippingCalculator, private orderStateMachine: OrderStateMachine, private orderMerger: OrderMerger, private paymentService: PaymentService, private paymentMethodService: PaymentMethodService, private fulfillmentService: FulfillmentService, private listQueryBuilder: ListQueryBuilder, private refundStateMachine: RefundStateMachine, private historyService: HistoryService, private promotionService: PromotionService, private eventBus: EventBus, private channelService: ChannelService, private orderModifier: OrderModifier, private customFieldRelationService: CustomFieldRelationService, private requestCache: RequestContextCacheService, private translator: TranslatorService, private stockLevelService: StockLevelService, ) {} /** * @description * Returns an array of all the configured states and transitions of the order process. This is * based on the default order process plus all configured {@link OrderProcess} objects * defined in the {@link OrderOptions} `process` array. */ getOrderProcessStates(): OrderProcessState[] { return Object.entries(this.orderStateMachine.config.transitions).map(([name, { to }]) => ({ name, to, })) as OrderProcessState[]; } findAll( ctx: RequestContext, options?: OrderListOptions, relations?: RelationPaths<Order>, ): Promise<PaginatedList<Order>> { return this.listQueryBuilder .build(Order, options, { ctx, relations: relations ?? [ 'lines', 'customer', 'lines.productVariant', 'channels', 'shippingLines', 'payments', ], channelId: ctx.channelId, customPropertyMap: { customerLastName: 'customer.lastName', transactionId: 'payments.transactionId', }, }) .getManyAndCount() .then(([items, totalItems]) => { return { items, totalItems, }; }); } async findOne( ctx: RequestContext, orderId: ID, relations?: RelationPaths<Order>, ): Promise<Order | undefined> { const qb = this.connection.getRepository(ctx, Order).createQueryBuilder('order'); const effectiveRelations = relations ?? [ 'channels', 'customer', 'customer.user', 'lines', 'lines.productVariant', 'lines.productVariant.taxCategory', 'lines.productVariant.productVariantPrices', 'lines.productVariant.translations', 'lines.featuredAsset', 'lines.taxCategory', 'shippingLines', 'surcharges', ]; if ( relations && effectiveRelations.includes('lines.productVariant') && !effectiveRelations.includes('lines.productVariant.taxCategory') ) { effectiveRelations.push('lines.productVariant.taxCategory'); } qb.setFindOptions({ relations: effectiveRelations }) .leftJoin('order.channels', 'channel') .where('order.id = :orderId', { orderId }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }); if (effectiveRelations.includes('lines')) { qb.addOrderBy(`order__order_lines.${qb.escape('createdAt')}`, 'ASC').addOrderBy( `order__order_lines.${qb.escape('productVariantId')}`, 'ASC', ); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion FindOptionsUtils.joinEagerRelations(qb, qb.alias, qb.expressionMap.mainAlias!.metadata); const order = await qb.getOne(); if (order) { if (effectiveRelations.includes('lines.productVariant')) { for (const line of order.lines) { line.productVariant = this.translator.translate( await this.productVariantService.applyChannelPriceAndTax( line.productVariant, ctx, order, ), ctx, ); } } return order; } } async findOneByCode( ctx: RequestContext, orderCode: string, relations?: RelationPaths<Order>, ): Promise<Order | undefined> { const order = await this.connection.getRepository(ctx, Order).findOne({ relations: ['customer'], where: { code: orderCode, }, }); return order ? this.findOne(ctx, order.id, relations) : undefined; } async findOneByOrderLineId( ctx: RequestContext, orderLineId: ID, relations?: RelationPaths<Order>, ): Promise<Order | undefined> { const order = await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .innerJoin('order.lines', 'line', 'line.id = :orderLineId', { orderLineId }) .getOne(); return order ? this.findOne(ctx, order.id, relations) : undefined; } async findByCustomerId( ctx: RequestContext, customerId: ID, options?: ListQueryOptions<Order>, relations?: RelationPaths<Order>, ): Promise<PaginatedList<Order>> { const effectiveRelations = (relations ?? ['lines', 'customer', 'channels', 'shippingLines']).filter( r => // Don't join productVariant because it messes with the // price calculation in certain edge-case field resolver scenarios !r.includes('productVariant'), ); return this.listQueryBuilder .build(Order, options, { relations: relations ?? ['lines', 'customer', 'channels', 'shippingLines'], channelId: ctx.channelId, ctx, }) .andWhere('order.state != :draftState', { draftState: 'Draft' }) .andWhere('order.customer.id = :customerId', { customerId }) .getManyAndCount() .then(([items, totalItems]) => { return { items, totalItems, }; }); } /** * @description * Returns all {@link Payment} entities associated with the Order. */ getOrderPayments(ctx: RequestContext, orderId: ID): Promise<Payment[]> { return this.connection.getRepository(ctx, Payment).find({ relations: ['refunds'], where: { order: { id: orderId } as any, }, }); } /** * @description * Returns an array of any {@link OrderModification} entities associated with the Order. */ getOrderModifications(ctx: RequestContext, orderId: ID): Promise<OrderModification[]> { return this.connection.getRepository(ctx, OrderModification).find({ where: { order: { id: orderId }, }, relations: ['lines', 'payment', 'refund', 'surcharges'], }); } /** * @description * Returns any {@link Refund}s associated with a {@link Payment}. */ getPaymentRefunds(ctx: RequestContext, paymentId: ID): Promise<Refund[]> { return this.connection.getRepository(ctx, Refund).find({ where: { paymentId, }, }); } getSellerOrders(ctx: RequestContext, order: Order): Promise<Order[]> { return this.connection.getRepository(ctx, Order).find({ where: { aggregateOrderId: order.id, }, relations: ['channels'], }); } async getAggregateOrder(ctx: RequestContext, order: Order): Promise<Order | undefined> { return order.aggregateOrderId == null ? undefined : this.connection .getRepository(ctx, Order) .findOne({ where: { id: order.aggregateOrderId }, relations: ['channels', 'lines'] }) .then(result => result ?? undefined); } getOrderChannels(ctx: RequestContext, order: Order): Promise<Channel[]> { return this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .relation('channels') .of(order) .loadMany(); } /** * @description * Returns any Order associated with the specified User's Customer account * that is still in the `active` state. */ async getActiveOrderForUser(ctx: RequestContext, userId: ID): Promise<Order | undefined> { const customer = await this.customerService.findOneByUserId(ctx, userId); if (customer) { const activeOrder = await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .innerJoinAndSelect('order.channels', 'channel', 'channel.id = :channelId', { channelId: ctx.channelId, }) .leftJoinAndSelect('order.customer', 'customer') .leftJoinAndSelect('order.shippingLines', 'shippingLines') .where('order.active = :active', { active: true }) .andWhere('order.customer.id = :customerId', { customerId: customer.id }) .orderBy('order.createdAt', 'DESC') .getOne(); if (activeOrder) { return this.findOne(ctx, activeOrder.id); } } } /** * @description * Creates a new, empty Order. If a `userId` is passed, the Order will get associated with that * User's Customer account. */ async create(ctx: RequestContext, userId?: ID): Promise<Order> { const newOrder = await this.createEmptyOrderEntity(ctx); if (userId) { const customer = await this.customerService.findOneByUserId(ctx, userId); if (customer) { newOrder.customer = customer; } } await this.channelService.assignToCurrentChannel(newOrder, ctx); const order = await this.connection.getRepository(ctx, Order).save(newOrder); await this.eventBus.publish(new OrderEvent(ctx, order, 'created')); const transitionResult = await this.transitionToState(ctx, order.id, 'AddingItems'); if (isGraphQlErrorResult(transitionResult)) { // this should never occur, so we will throw rather than return throw transitionResult; } return transitionResult; } async createDraft(ctx: RequestContext) { const newOrder = await this.createEmptyOrderEntity(ctx); newOrder.active = false; await this.channelService.assignToCurrentChannel(newOrder, ctx); const order = await this.connection.getRepository(ctx, Order).save(newOrder); await this.eventBus.publish(new OrderEvent(ctx, order, 'created')); const transitionResult = await this.transitionToState(ctx, order.id, 'Draft'); if (isGraphQlErrorResult(transitionResult)) { // this should never occur, so we will throw rather than return throw transitionResult; } return transitionResult; } private async createEmptyOrderEntity(ctx: RequestContext) { return new Order({ type: OrderType.Regular, code: await this.configService.orderOptions.orderCodeStrategy.generate(ctx), state: this.orderStateMachine.getInitialState(), lines: [], surcharges: [], couponCodes: [], modifications: [], shippingAddress: {}, billingAddress: {}, subTotal: 0, subTotalWithTax: 0, currencyCode: ctx.currencyCode, }); } /** * @description * Updates the custom fields of an Order. */ async updateCustomFields(ctx: RequestContext, orderId: ID, customFields: any) { let order = await this.getOrderOrThrow(ctx, orderId); order = patchEntity(order, { customFields }); await this.customFieldRelationService.updateRelations(ctx, Order, { customFields }, order); const updatedOrder = await this.connection.getRepository(ctx, Order).save(order); await this.eventBus.publish(new OrderEvent(ctx, updatedOrder, 'updated')); return updatedOrder; } /** * @description * Updates the Customer which is assigned to a given Order. The target Customer must be assigned to the same * Channels as the Order, otherwise an error will be thrown. * * @since 2.2.0 */ async updateOrderCustomer(ctx: RequestContext, { customerId, orderId, note }: SetOrderCustomerInput) { const order = await this.getOrderOrThrow(ctx, orderId); const currentCustomer = order.customer; if (currentCustomer?.id === customerId) { // No change in customer, so just return the order as-is return order; } const targetCustomer = await this.customerService.findOne(ctx, customerId, ['channels']); if (!targetCustomer) { throw new EntityNotFoundError('Customer', customerId); } // ensure the customer is assigned to the same channels as the order const channelIds = order.channels.map(c => c.id); const customerChannelIds = targetCustomer.channels.map(c => c.id); const missingChannelIds = channelIds.filter(id => !customerChannelIds.includes(id)); if (missingChannelIds.length) { throw new UserInputError(`error.target-customer-not-assigned-to-order-channels`, { channelIds: missingChannelIds.join(', '), }); } const updatedOrder = await this.addCustomerToOrder(ctx, order.id, targetCustomer); await this.eventBus.publish(new OrderEvent(ctx, updatedOrder, 'updated')); await this.historyService.createHistoryEntryForOrder({ ctx, orderId, type: HistoryEntryType.ORDER_CUSTOMER_UPDATED, data: { previousCustomerId: currentCustomer?.id, previousCustomerName: currentCustomer && `${currentCustomer.firstName} ${currentCustomer.lastName}`, newCustomerId: targetCustomer.id, newCustomerName: `${targetCustomer.firstName} ${targetCustomer.lastName}`, note, }, }); return updatedOrder; } /** * @description * Adds an item to the Order, either creating a new OrderLine or * incrementing an existing one. */ async addItemToOrder( ctx: RequestContext, orderId: ID, productVariantId: ID, quantity: number, customFields?: { [key: string]: any }, ): Promise<ErrorResultUnion<UpdateOrderItemsResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); const existingOrderLine = await this.orderModifier.getExistingOrderLine( ctx, order, productVariantId, customFields, ); const validationError = this.assertQuantityIsPositive(quantity) || this.assertAddingItemsState(order) || this.assertNotOverOrderItemsLimit(order, quantity) || this.assertNotOverOrderLineItemsLimit(existingOrderLine, quantity); if (validationError) { return validationError; } const variant = await this.connection.getEntityOrThrow(ctx, ProductVariant, productVariantId, { relations: ['product'], where: { enabled: true, deletedAt: IsNull(), }, }); if (variant.product.enabled === false) { throw new EntityNotFoundError('ProductVariant', productVariantId); } const existingQuantityInOtherLines = summate( order.lines.filter( l => idsAreEqual(l.productVariantId, productVariantId) && !idsAreEqual(l.id, existingOrderLine?.id), ), 'quantity', ); const correctedQuantity = await this.orderModifier.constrainQuantityToSaleable( ctx, variant, quantity, existingOrderLine?.quantity, existingQuantityInOtherLines, ); if (correctedQuantity === 0) { return new InsufficientStockError({ order, quantityAvailable: correctedQuantity }); } const orderLine = await this.orderModifier.getOrCreateOrderLine( ctx, order, productVariantId, customFields, ); if (correctedQuantity < quantity) { const newQuantity = (existingOrderLine ? existingOrderLine?.quantity : 0) + correctedQuantity; await this.orderModifier.updateOrderLineQuantity(ctx, orderLine, newQuantity, order); } else { await this.orderModifier.updateOrderLineQuantity(ctx, orderLine, correctedQuantity, order); } const quantityWasAdjustedDown = correctedQuantity < quantity; const updatedOrder = await this.applyPriceAdjustments(ctx, order, [orderLine]); if (quantityWasAdjustedDown) { return new InsufficientStockError({ quantityAvailable: correctedQuantity, order: updatedOrder }); } else { return updatedOrder; } } /** * @description * Adjusts the quantity and/or custom field values of an existing OrderLine. */ async adjustOrderLine( ctx: RequestContext, orderId: ID, orderLineId: ID, quantity: number, customFields?: { [key: string]: any }, ): Promise<ErrorResultUnion<UpdateOrderItemsResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); const orderLine = this.getOrderLineOrThrow(order, orderLineId); const validationError = this.assertAddingItemsState(order) || this.assertQuantityIsPositive(quantity) || this.assertNotOverOrderItemsLimit(order, quantity - orderLine.quantity) || this.assertNotOverOrderLineItemsLimit(orderLine, quantity - orderLine.quantity); if (validationError) { return validationError; } if (customFields != null) { orderLine.customFields = customFields; await this.customFieldRelationService.updateRelations( ctx, OrderLine, { customFields }, orderLine, ); } const existingQuantityInOtherLines = summate( order.lines.filter( l => idsAreEqual(l.productVariantId, orderLine.productVariantId) && !idsAreEqual(l.id, orderLineId), ), 'quantity', ); const correctedQuantity = await this.orderModifier.constrainQuantityToSaleable( ctx, orderLine.productVariant, quantity, 0, existingQuantityInOtherLines, ); let updatedOrderLines = [orderLine]; if (correctedQuantity === 0) { order.lines = order.lines.filter(l => !idsAreEqual(l.id, orderLine.id)); const deletedOrderLine = new OrderLine(orderLine); await this.connection.getRepository(ctx, OrderLine).remove(orderLine); await this.eventBus.publish(new OrderLineEvent(ctx, order, deletedOrderLine, 'deleted')); updatedOrderLines = []; } else { await this.orderModifier.updateOrderLineQuantity(ctx, orderLine, correctedQuantity, order); } const quantityWasAdjustedDown = correctedQuantity < quantity; const updatedOrder = await this.applyPriceAdjustments(ctx, order, updatedOrderLines); if (quantityWasAdjustedDown) { return new InsufficientStockError({ quantityAvailable: correctedQuantity, order: updatedOrder }); } else { return updatedOrder; } } /** * @description * Removes the specified OrderLine from the Order. */ async removeItemFromOrder( ctx: RequestContext, orderId: ID, orderLineId: ID, ): Promise<ErrorResultUnion<RemoveOrderItemsResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); const validationError = this.assertAddingItemsState(order); if (validationError) { return validationError; } const orderLine = this.getOrderLineOrThrow(order, orderLineId); order.lines = order.lines.filter(line => !idsAreEqual(line.id, orderLineId)); // Persist the orderLine removal before applying price adjustments // so that any hydration of the Order entity during the course of the // `applyPriceAdjustments()` (e.g. in a ShippingEligibilityChecker etc) // will not re-add the OrderLine. await this.connection.getRepository(ctx, Order).save(order, { reload: false }); const updatedOrder = await this.applyPriceAdjustments(ctx, order); const deletedOrderLine = new OrderLine(orderLine); await this.connection.getRepository(ctx, OrderLine).remove(orderLine); await this.eventBus.publish(new OrderLineEvent(ctx, order, deletedOrderLine, 'deleted')); return updatedOrder; } /** * @description * Removes all OrderLines from the Order. */ async removeAllItemsFromOrder( ctx: RequestContext, orderId: ID, ): Promise<ErrorResultUnion<RemoveOrderItemsResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); const validationError = this.assertAddingItemsState(order); if (validationError) { return validationError; } await this.connection.getRepository(ctx, OrderLine).remove(order.lines); order.lines = []; const updatedOrder = await this.applyPriceAdjustments(ctx, order); return updatedOrder; } /** * @description * Adds a {@link Surcharge} to the Order. */ async addSurchargeToOrder( ctx: RequestContext, orderId: ID, surchargeInput: Partial<Omit<Surcharge, 'id' | 'createdAt' | 'updatedAt' | 'order'>>, ): Promise<Order> { const order = await this.getOrderOrThrow(ctx, orderId); const surcharge = await this.connection.getRepository(ctx, Surcharge).save( new Surcharge({ taxLines: [], sku: '', listPriceIncludesTax: ctx.channel.pricesIncludeTax, order, ...surchargeInput, }), ); order.surcharges.push(surcharge); const updatedOrder = await this.applyPriceAdjustments(ctx, order); return updatedOrder; } /** * @description * Removes a {@link Surcharge} from the Order. */ async removeSurchargeFromOrder(ctx: RequestContext, orderId: ID, surchargeId: ID): Promise<Order> { const order = await this.getOrderOrThrow(ctx, orderId); const surcharge = await this.connection.getEntityOrThrow(ctx, Surcharge, surchargeId); if (order.surcharges.find(s => idsAreEqual(s.id, surcharge.id))) { order.surcharges = order.surcharges.filter(s => !idsAreEqual(s.id, surchargeId)); const updatedOrder = await this.applyPriceAdjustments(ctx, order); await this.connection.getRepository(ctx, Surcharge).remove(surcharge); return updatedOrder; } else { return order; } } /** * @description * Applies a coupon code to the Order, which should be a valid coupon code as specified in the configuration * of an active {@link Promotion}. */ async applyCouponCode( ctx: RequestContext, orderId: ID, couponCode: string, ): Promise<ErrorResultUnion<ApplyCouponCodeResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); if (order.couponCodes.includes(couponCode)) { return order; } const validationResult = await this.promotionService.validateCouponCode( ctx, couponCode, order.customer && order.customer.id, ); if (isGraphQlErrorResult(validationResult)) { return validationResult; } order.couponCodes.push(couponCode); await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: HistoryEntryType.ORDER_COUPON_APPLIED, data: { couponCode, promotionId: validationResult.id }, }); await this.eventBus.publish(new CouponCodeEvent(ctx, couponCode, orderId, 'assigned')); return this.applyPriceAdjustments(ctx, order); } /** * @description * Removes a coupon code from the Order. */ async removeCouponCode(ctx: RequestContext, orderId: ID, couponCode: string) { const order = await this.getOrderOrThrow(ctx, orderId); if (order.couponCodes.includes(couponCode)) { // When removing a couponCode which has triggered an Order-level discount // we need to make sure we persist the changes to the adjustments array of // any affected OrderLines. const affectedOrderLines = order.lines.filter( line => line.adjustments.filter(a => a.type === AdjustmentType.DISTRIBUTED_ORDER_PROMOTION) .length, ); order.couponCodes = order.couponCodes.filter(cc => cc !== couponCode); await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: HistoryEntryType.ORDER_COUPON_REMOVED, data: { couponCode }, }); await this.eventBus.publish(new CouponCodeEvent(ctx, couponCode, orderId, 'removed')); const result = await this.applyPriceAdjustments(ctx, order); await this.connection.getRepository(ctx, OrderLine).save(affectedOrderLines); return result; } else { return order; } } /** * @description * Returns all {@link Promotion}s associated with an Order. */ async getOrderPromotions(ctx: RequestContext, orderId: ID): Promise<Promotion[]> { const order = await this.connection.getEntityOrThrow(ctx, Order, orderId, { channelId: ctx.channelId, relations: ['promotions'], }); return order.promotions.map(p => this.translator.translate(p, ctx)) || []; } /** * @description * Returns the next possible states that the Order may transition to. */ getNextOrderStates(order: Order): readonly OrderState[] { return this.orderStateMachine.getNextStates(order); } /** * @description * Sets the shipping address for the Order. */ async setShippingAddress(ctx: RequestContext, orderId: ID, input: CreateAddressInput): Promise<Order> { const order = await this.getOrderOrThrow(ctx, orderId); const country = await this.countryService.findOneByCode(ctx, input.countryCode); const shippingAddress = { ...input, countryCode: input.countryCode, country: country.name }; await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .update(Order) .set({ shippingAddress }) .where('id = :id', { id: order.id }) .execute(); order.shippingAddress = shippingAddress; // Since a changed ShippingAddress could alter the activeTaxZone, // we will remove any cached activeTaxZone, so it can be re-calculated // as needed. this.requestCache.set(ctx, CacheKey.ActiveTaxZone, undefined); this.requestCache.set(ctx, CacheKey.ActiveTaxZone_PPA, undefined); return this.applyPriceAdjustments(ctx, order, order.lines); } /** * @description * Sets the billing address for the Order. */ async setBillingAddress(ctx: RequestContext, orderId: ID, input: CreateAddressInput): Promise<Order> { const order = await this.getOrderOrThrow(ctx, orderId); const country = await this.countryService.findOneByCode(ctx, input.countryCode); const billingAddress = { ...input, countryCode: input.countryCode, country: country.name }; await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .update(Order) .set({ billingAddress }) .where('id = :id', { id: order.id }) .execute(); order.billingAddress = billingAddress; // Since a changed BillingAddress could alter the activeTaxZone, // we will remove any cached activeTaxZone, so it can be re-calculated // as needed. this.requestCache.set(ctx, CacheKey.ActiveTaxZone, undefined); this.requestCache.set(ctx, CacheKey.ActiveTaxZone_PPA, undefined); return this.applyPriceAdjustments(ctx, order, order.lines); } /** * @description * Returns an array of quotes stating which {@link ShippingMethod}s may be applied to this Order. * This is determined by the configured {@link ShippingEligibilityChecker} of each ShippingMethod. * * The quote also includes a price for each method, as determined by the configured * {@link ShippingCalculator} of each eligible ShippingMethod. */ async getEligibleShippingMethods(ctx: RequestContext, orderId: ID): Promise<ShippingMethodQuote[]> { const order = await this.getOrderOrThrow(ctx, orderId); const eligibleMethods = await this.shippingCalculator.getEligibleShippingMethods(ctx, order); return eligibleMethods.map(eligible => { const { price, taxRate, priceIncludesTax, metadata } = eligible.result; return { id: eligible.method.id, price: priceIncludesTax ? netPriceOf(price, taxRate) : price, priceWithTax: priceIncludesTax ? price : grossPriceOf(price, taxRate), description: eligible.method.description, name: eligible.method.name, code: eligible.method.code, metadata, customFields: eligible.method.customFields, }; }); } /** * @description * Returns an array of quotes stating which {@link PaymentMethod}s may be used on this Order. */ async getEligiblePaymentMethods(ctx: RequestContext, orderId: ID): Promise<PaymentMethodQuote[]> { const order = await this.getOrderOrThrow(ctx, orderId); return this.paymentMethodService.getEligiblePaymentMethods(ctx, order); } /** * @description * Sets the ShippingMethod to be used on this Order. */ async setShippingMethod( ctx: RequestContext, orderId: ID, shippingMethodIds: ID[], ): Promise<ErrorResultUnion<SetOrderShippingMethodResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); const validationError = this.assertAddingItemsState(order); if (validationError) { return validationError; } const result = await this.orderModifier.setShippingMethods(ctx, order, shippingMethodIds); if (isGraphQlErrorResult(result)) { return result; } const updatedOrder = await this.getOrderOrThrow(ctx, orderId); await this.applyPriceAdjustments(ctx, updatedOrder); return this.connection.getRepository(ctx, Order).save(updatedOrder); } /** * @description * Transitions the Order to the given state. */ async transitionToState( ctx: RequestContext, orderId: ID, state: OrderState, ): Promise<Order | OrderStateTransitionError> { const order = await this.getOrderOrThrow(ctx, orderId); order.payments = await this.getOrderPayments(ctx, orderId); const fromState = order.state; let finalize: () => Promise<any>; try { const result = await this.orderStateMachine.transition(ctx, order, state); finalize = result.finalize; } catch (e: any) { const transitionError = ctx.translate(e.message, { fromState, toState: state }); return new OrderStateTransitionError({ transitionError, fromState, toState: state }); } await this.connection.getRepository(ctx, Order).save(order, { reload: false }); await this.eventBus.publish(new OrderStateTransitionEvent(fromState, state, ctx, order)); await finalize(); await this.connection.getRepository(ctx, Order).save(order, { reload: false }); return order; } /** * @description * Transitions a Fulfillment to the given state and then transitions the Order state based on * whether all Fulfillments of the Order are shipped or delivered. */ async transitionFulfillmentToState( ctx: RequestContext, fulfillmentId: ID, state: FulfillmentState, ): Promise<Fulfillment | FulfillmentStateTransitionError> { const result = await this.fulfillmentService.transitionToState(ctx, fulfillmentId, state); if (isGraphQlErrorResult(result)) { return result; } return result.fulfillment; } /** * @description * Allows the Order to be modified, which allows several aspects of the Order to be changed: * * * Changes to OrderLine quantities * * New OrderLines being added * * Arbitrary {@link Surcharge}s being added * * Shipping or billing address changes * * Setting the `dryRun` input property to `true` will apply all changes, including updating the price of the * Order, except history entry and additional payment actions. * * __Using dryRun option, you must wrap function call in transaction manually.__ * */ async modifyOrder( ctx: RequestContext, input: ModifyOrderInput, ): Promise<ErrorResultUnion<ModifyOrderResult, Order>> { const order = await this.getOrderOrThrow(ctx, input.orderId); const result = await this.orderModifier.modifyOrder(ctx, input, order); if (isGraphQlErrorResult(result)) { return result; } if (input.dryRun) { return result.order; } await this.historyService.createHistoryEntryForOrder({ ctx, orderId: input.orderId, type: HistoryEntryType.ORDER_MODIFIED, data: { modificationId: result.modification.id, }, }); return this.getOrderOrThrow(ctx, input.orderId); } /** * @description * Transitions the given {@link Payment} to a new state. If the order totalWithTax price is then * covered by Payments, the Order state will be automatically transitioned to `PaymentSettled` * or `PaymentAuthorized`. */ async transitionPaymentToState( ctx: RequestContext, paymentId: ID, state: PaymentState, ): Promise<ErrorResultUnion<TransitionPaymentToStateResult, Payment>> { const result = await this.paymentService.transitionToState(ctx, paymentId, state); if (isGraphQlErrorResult(result)) { return result; } return result; } /** * @description * Adds a new Payment to the Order. If the Order totalWithTax is covered by Payments, then the Order * state will get automatically transitioned to the `PaymentSettled` or `PaymentAuthorized` state. */ async addPaymentToOrder( ctx: RequestContext, orderId: ID, input: PaymentInput, ): Promise<ErrorResultUnion<AddPaymentToOrderResult, Order>> { const order = await this.getOrderOrThrow(ctx, orderId); if (!this.canAddPaymentToOrder(order)) { return new OrderPaymentStateError(); } order.payments = await this.getOrderPayments(ctx, order.id); const amountToPay = order.totalWithTax - totalCoveredByPayments(order); const payment = await this.paymentService.createPayment( ctx, order, amountToPay, input.method, input.metadata, ); if (isGraphQlErrorResult(payment)) { return payment; } await this.connection .getRepository(ctx, Order) .createQueryBuilder() .relation('payments') .of(order) .add(payment); if (payment.state === 'Error') { return new PaymentFailedError({ paymentErrorMessage: payment.errorMessage || '' }); } if (payment.state === 'Declined') { return new PaymentDeclinedError({ paymentErrorMessage: payment.errorMessage || '' }); } return assertFound(this.findOne(ctx, order.id)); } /** * @description * We can add a Payment to the order if: * 1. the Order is in the `ArrangingPayment` state or * 2. the Order's current state can transition to `PaymentAuthorized` and `PaymentSettled` */ private canAddPaymentToOrder(order: Order): boolean { if (order.state === 'ArrangingPayment') { return true; } const canTransitionToPaymentAuthorized = this.orderStateMachine.canTransition( order.state, 'PaymentAuthorized', ); const canTransitionToPaymentSettled = this.orderStateMachine.canTransition( order.state, 'PaymentSettled', ); return canTransitionToPaymentAuthorized && canTransitionToPaymentSettled; } /** * @description * This method is used after modifying an existing completed order using the `modifyOrder()` method. If the modifications * cause the order total to increase (such as when adding a new OrderLine), then there will be an outstanding charge to * pay. * * This method allows you to add a new Payment and assumes the actual processing has been done manually, e.g. in the * dashboard of your payment provider. */ async addManualPaymentToOrder( ctx: RequestContext, input: ManualPaymentInput, ): Promise<ErrorResultUnion<AddManualPaymentToOrderResult, Order>> { const order = await this.getOrderOrThrow(ctx, input.orderId); if (order.state !== 'ArrangingAdditionalPayment' && order.state !== 'ArrangingPayment') { return new ManualPaymentStateError(); } const existingPayments = await this.getOrderPayments(ctx, order.id); order.payments = existingPayments; const amount = order.totalWithTax - totalCoveredByPayments(order); const modifications = await this.getOrderModifications(ctx, order.id); const unsettledModifications = modifications.filter(m => !m.isSettled); if (0 < unsettledModifications.length) { const outstandingModificationsTotal = summate(unsettledModifications, 'priceChange'); if (outstandingModificationsTotal !== amount) { throw new InternalServerError( `The outstanding order amount (${amount}) should equal the unsettled OrderModifications total (${outstandingModificationsTotal})`, ); } } const payment = await this.paymentService.createManualPayment(ctx, order, amount, input); await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .relation('payments') .of(order) .add(payment); for (const modification of unsettledModifications) { modification.payment = payment; await this.connection.getRepository(ctx, OrderModification).save(modification); } return assertFound(this.findOne(ctx, order.id)); } /** * @description * Settles a payment by invoking the {@link PaymentMethodHandler}'s `settlePayment()` method. Automatically * transitions the Order state if all Payments are settled. */ async settlePayment( ctx: RequestContext, paymentId: ID, ): Promise<ErrorResultUnion<SettlePaymentResult, Payment>> { const payment = await this.paymentService.settlePayment(ctx, paymentId); if (!isGraphQlErrorResult(payment)) { if (payment.state !== 'Settled') { return new SettlePaymentError({ paymentErrorMessage: payment.errorMessage || '' }); } } return payment; } /** * @description * Cancels a payment by invoking the {@link PaymentMethodHandler}'s `cancelPayment()` method (if defined), and transitions the Payment to * the `Cancelled` state. */ async cancelPayment( ctx: RequestContext, paymentId: ID, ): Promise<ErrorResultUnion<CancelPaymentResult, Payment>> { const payment = await this.paymentService.cancelPayment(ctx, paymentId); if (!isGraphQlErrorResult(payment)) { if (payment.state !== 'Cancelled') { return new CancelPaymentError({ paymentErrorMessage: payment.errorMessage || '' }); } } return payment; } /** * @description * Creates a new Fulfillment associated with the given Order and OrderItems. */ async createFulfillment( ctx: RequestContext, input: FulfillOrderInput, ): Promise<ErrorResultUnion<AddFulfillmentToOrderResult, Fulfillment>> { if (!input.lines || input.lines.length === 0 || summate(input.lines, 'quantity') === 0) { return new EmptyOrderLineSelectionError(); } const orders = await getOrdersFromLines(ctx, this.connection, input.lines); if (await this.requestedFulfillmentQuantityExceedsLineQuantity(ctx, input)) { return new ItemsAlreadyFulfilledError(); } const stockCheckResult = await this.ensureSufficientStockForFulfillment(ctx, input); if (isGraphQlErrorResult(stockCheckResult)) { return stockCheckResult; } const fulfillment = await this.fulfillmentService.create(ctx, orders, input.lines, input.handler); if (isGraphQlErrorResult(fulfillment)) { return fulfillment; } await this.connection .getRepository(ctx, Order) .createQueryBuilder() .relation('fulfillments') .of(orders) .add(fulfillment); for (const order of orders) { await this.historyService.createHistoryEntryForOrder({ ctx, orderId: order.id, type: HistoryEntryType.ORDER_FULFILLMENT, data: { fulfillmentId: fulfillment.id, }, }); } const result = await this.fulfillmentService.transitionToState(ctx, fulfillment.id, 'Pending'); if (isGraphQlErrorResult(result)) { return result; } return result.fulfillment; } private async requestedFulfillmentQuantityExceedsLineQuantity( ctx: RequestContext, input: FulfillOrderInput, ) { const existingFulfillmentLines = await this.connection .getRepository(ctx, FulfillmentLine) .createQueryBuilder('fulfillmentLine') .leftJoinAndSelect('fulfillmentLine.orderLine', 'orderLine') .leftJoinAndSelect('fulfillmentLine.fulfillment', 'fulfillment') .where('fulfillmentLine.orderLineId IN (:...orderLineIds)', { orderLineIds: input.lines.map(l => l.orderLineId), }) .andWhere('fulfillment.state != :state', { state: 'Cancelled' }) .getMany(); for (const inputLine of input.lines) { const existingFulfillmentLine = existingFulfillmentLines.find(l => idsAreEqual(l.orderLineId, inputLine.orderLineId), ); if (existingFulfillmentLine) { const unfulfilledQuantity = existingFulfillmentLine.orderLine.quantity - existingFulfillmentLine.quantity; if (unfulfilledQuantity < inputLine.quantity) { return true; } } else { const orderLine = await this.connection.getEntityOrThrow( ctx, OrderLine, inputLine.orderLineId, ); if (orderLine.quantity < inputLine.quantity) { return true; } } } return false; } private async ensureSufficientStockForFulfillment( ctx: RequestContext, input: FulfillOrderInput, ): Promise<InsufficientStockOnHandError | undefined> { const lines = await this.connection.getRepository(ctx, OrderLine).find({ where: { id: In(input.lines.map(l => l.orderLineId)), }, relations: ['productVariant'], }); for (const line of lines) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const lineInput = input.lines.find(l => idsAreEqual(l.orderLineId, line.id))!; const fulfillableStockLevel = await this.productVariantService.getFulfillableStockLevel( ctx, line.productVariant, ); if (fulfillableStockLevel < lineInput.quantity) { const { stockOnHand } = await this.stockLevelService.getAvailableStock( ctx, line.productVariant.id, ); const productVariant = this.translator.translate(line.productVariant, ctx); return new InsufficientStockOnHandError({ productVariantId: productVariant.id as string, productVariantName: productVariant.name, stockOnHand, }); } } } /** * @description * Returns an array of all Fulfillments associated with the Order. */ async getOrderFulfillments(ctx: RequestContext, order: Order): Promise<Fulfillment[]> { const { fulfillments } = await this.connection.getEntityOrThrow(ctx, Order, order.id, { relations: ['fulfillments'], }); return fulfillments; } /** * @description * Returns an array of all Surcharges associated with the Order. */ async getOrderSurcharges(ctx: RequestContext, orderId: ID): Promise<Surcharge[]> { const order = await this.connection.getEntityOrThrow(ctx, Order, orderId, { channelId: ctx.channelId, relations: ['surcharges'], }); return order.surcharges || []; } /** * @description * Cancels an Order by transitioning it to the `Cancelled` state. If stock is being tracked for the ProductVariants * in the Order, then new {@link StockMovement}s will be created to correct the stock levels. */ async cancelOrder( ctx: RequestContext, input: CancelOrderInput, ): Promise<ErrorResultUnion<CancelOrderResult, Order>> { let allOrderItemsCancelled = false; const cancelResult = input.lines != null ? await this.orderModifier.cancelOrderByOrderLines(ctx, input, input.lines) : await this.cancelOrderById(ctx, input); if (isGraphQlErrorResult(cancelResult)) { return cancelResult; } else { allOrderItemsCancelled = cancelResult; } if (allOrderItemsCancelled) { const transitionResult = await this.transitionToState(ctx, input.orderId, 'Cancelled'); if (isGraphQlErrorResult(transitionResult)) { return transitionResult; } } return assertFound(this.findOne(ctx, input.orderId)); } private async cancelOrderById(ctx: RequestContext, input: CancelOrderInput) { const order = await this.getOrderOrThrow(ctx, input.orderId); if (order.active) { return true; } else { const lines: OrderLineInput[] = order.lines.map(l => ({ orderLineId: l.id, quantity: l.quantity, })); return this.orderModifier.cancelOrderByOrderLines(ctx, input, lines); } } /** * @description * Creates a {@link Refund} against the order and in doing so invokes the `createRefund()` method of the * {@link PaymentMethodHandler}. */ async refundOrder( ctx: RequestContext, input: RefundOrderInput, ): Promise<ErrorResultUnion<RefundOrderResult, Refund>> { if ( (!input.lines || input.lines.length === 0 || summate(input.lines, 'quantity') === 0) && input.shipping === 0 && !input.amount ) { return new NothingToRefundError(); } const orders = await getOrdersFromLines(ctx, this.connection, input.lines ?? []); if (1 < orders.length) { return new MultipleOrderError(); } const payment = await this.connection.getEntityOrThrow(ctx, Payment, input.paymentId, { relations: ['order'], }); if (orders && orders.length && !idsAreEqual(payment.order.id, orders[0].id)) { return new PaymentOrderMismatchError(); } const order = payment.order; if ( order.state === 'AddingItems' || order.state === 'ArrangingPayment' || order.state === 'PaymentAuthorized' ) { return new RefundOrderStateError({ orderState: order.state }); } return await this.paymentService.createRefund(ctx, input, order, payment); } /** * @description * Settles a Refund by transitioning it to the `Settled` state. */ async settleRefund(ctx: RequestContext, input: SettleRefundInput): Promise<Refund> { const refund = await this.connection.getEntityOrThrow(ctx, Refund, input.id, { relations: ['payment', 'payment.order'], }); refund.transactionId = input.transactionId; const fromState = refund.state; const toState = 'Settled'; const { finalize } = await this.refundStateMachine.transition( ctx, refund.payment.order, refund, toState, ); await this.connection.getRepository(ctx, Refund).save(refund); await finalize(); await this.eventBus.publish( new RefundStateTransitionEvent(fromState, toState, ctx, refund, refund.payment.order), ); return refund; } /** * @description * Associates a Customer with the Order. */ async addCustomerToOrder( ctx: RequestContext, orderIdOrOrder: ID | Order, customer: Customer, ): Promise<Order> { const order = orderIdOrOrder instanceof Order ? orderIdOrOrder : await this.getOrderOrThrow(ctx, orderIdOrOrder); order.customer = customer; await this.connection.getRepository(ctx, Order).save(order, { reload: false }); let updatedOrder = order; // Check that any applied couponCodes are still valid now that // we know the Customer. if (order.active && order.couponCodes) { for (const couponCode of order.couponCodes.slice()) { const validationResult = await this.promotionService.validateCouponCode( ctx, couponCode, customer.id, ); if (isGraphQlErrorResult(validationResult)) { updatedOrder = await this.removeCouponCode(ctx, order.id, couponCode); } } } return updatedOrder; } /** * @description * Creates a new "ORDER_NOTE" type {@link OrderHistoryEntry} in the Order's history timeline. */ async addNoteToOrder(ctx: RequestContext, input: AddNoteToOrderInput): Promise<Order> { const order = await this.getOrderOrThrow(ctx, input.id); await this.historyService.createHistoryEntryForOrder( { ctx, orderId: order.id, type: HistoryEntryType.ORDER_NOTE, data: { note: input.note, }, }, input.isPublic, ); return order; } async updateOrderNote(ctx: RequestContext, input: UpdateOrderNoteInput): Promise<HistoryEntry> { return this.historyService.updateOrderHistoryEntry(ctx, { type: HistoryEntryType.ORDER_NOTE, data: input.note ? { note: input.note } : undefined, isPublic: input.isPublic ?? undefined, ctx, entryId: input.noteId, }); } async deleteOrderNote(ctx: RequestContext, id: ID): Promise<DeletionResponse> { try { await this.historyService.deleteOrderHistoryEntry(ctx, id); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.message, }; } } /** * @description * Deletes an Order, ensuring that any Sessions that reference this Order are dereferenced before deletion. * * @since 1.5.0 */ async deleteOrder(ctx: RequestContext, orderOrId: ID | Order) { const orderToDelete = orderOrId instanceof Order ? orderOrId : await this.connection .getRepository(ctx, Order) .findOneOrFail({ where: { id: orderOrId }, relations: ['lines', 'shippingLines'] }); // If there is a Session referencing the Order to be deleted, we must first remove that // reference in order to avoid a foreign key error. See https://github.com/vendure-ecommerce/vendure/issues/1454 const sessions = await this.connection .getRepository(ctx, Session) .find({ where: { activeOrderId: orderToDelete.id } }); if (sessions.length) { await this.connection .getRepository(ctx, Session) .update(sessions.map(s => s.id) as string[], { activeOrder: null }); } const deletedOrder = new Order(orderToDelete); await this.connection.getRepository(ctx, Order).delete(orderToDelete.id); await this.eventBus.publish(new OrderEvent(ctx, deletedOrder, 'deleted')); } /** * @description * When a guest user with an anonymous Order signs in and has an existing Order associated with that Customer, * we need to reconcile the contents of the two orders. * * The logic used to do the merging is specified in the {@link OrderOptions} `mergeStrategy` config setting. */ async mergeOrders( ctx: RequestContext, user: User, guestOrder?: Order, existingOrder?: Order, ): Promise<Order | undefined> { if (guestOrder && guestOrder.customer) { // In this case the "guest order" is actually an order of an existing Customer, // so we do not want to merge at all. See https://github.com/vendure-ecommerce/vendure/issues/263 return existingOrder; } const mergeResult = this.orderMerger.merge(ctx, guestOrder, existingOrder); const { orderToDelete, linesToInsert, linesToDelete, linesToModify } = mergeResult; let { order } = mergeResult; if (orderToDelete) { await this.deleteOrder(ctx, orderToDelete); } if (order && linesToInsert) { const orderId = order.id; for (const line of linesToInsert) { const result = await this.addItemToOrder( ctx, orderId, line.productVariantId, line.quantity, line.customFields, ); if (!isGraphQlErrorResult(result)) { order = result; } } } if (order && linesToModify) { const orderId = order.id; for (const line of linesToModify) { const result = await this.adjustOrderLine( ctx, orderId, line.orderLineId, line.quantity, line.customFields, ); if (!isGraphQlErrorResult(result)) { order = result; } } } if (order && linesToDelete) { const orderId = order.id; for (const line of linesToDelete) { const result = await this.removeItemFromOrder(ctx, orderId, line.orderLineId); if (!isGraphQlErrorResult(result)) { order = result; } } } const customer = await this.customerService.findOneByUserId(ctx, user.id); if (order && customer) { order.customer = customer; await this.connection.getRepository(ctx, Order).save(order, { reload: false }); } return order; } private async getOrderOrThrow(ctx: RequestContext, orderId: ID): Promise<Order> { const order = await this.findOne(ctx, orderId); if (!order) { throw new EntityNotFoundError('Order', orderId); } return order; } private getOrderLineOrThrow(order: Order, orderLineId: ID): OrderLine { const orderLine = order.lines.find(line => idsAreEqual(line.id, orderLineId)); if (!orderLine) { throw new UserInputError('error.order-does-not-contain-line-with-id', { id: orderLineId }); } return orderLine; } /** * Returns error if quantity is negative. */ private assertQuantityIsPositive(quantity: number) { if (quantity < 0) { return new NegativeQuantityError(); } } /** * Returns error if the Order is not in the "AddingItems" or "Draft" state. */ private assertAddingItemsState(order: Order) { if (order.state !== 'AddingItems' && order.state !== 'Draft') { return new OrderModificationError(); } } /** * Throws if adding the given quantity would take the total order items over the * maximum limit specified in the config. */ private assertNotOverOrderItemsLimit(order: Order, quantityToAdd: number) { const currentItemsCount = summate(order.lines, 'quantity'); const { orderItemsLimit } = this.configService.orderOptions; if (orderItemsLimit < currentItemsCount + quantityToAdd) { return new OrderLimitError({ maxItems: orderItemsLimit }); } } /** * Throws if adding the given quantity would exceed the maximum allowed * quantity for one order line. */ private assertNotOverOrderLineItemsLimit(orderLine: OrderLine | undefined, quantityToAdd: number) { const currentQuantity = orderLine?.quantity || 0; const { orderLineItemsLimit } = this.configService.orderOptions; if (orderLineItemsLimit < currentQuantity + quantityToAdd) { return new OrderLimitError({ maxItems: orderLineItemsLimit }); } } /** * @description * Applies promotions, taxes and shipping to the Order. If the `updatedOrderLines` argument is passed in, * then all of those OrderLines will have their prices re-calculated using the configured {@link OrderItemPriceCalculationStrategy}. */ async applyPriceAdjustments( ctx: RequestContext, order: Order, updatedOrderLines?: OrderLine[], ): Promise<Order> { const promotions = await this.promotionService.getActivePromotionsInChannel(ctx); const activePromotionsPre = await this.promotionService.getActivePromotionsOnOrder(ctx, order.id); // When changing the Order's currencyCode (on account of passing // a different currencyCode into the RequestContext), we need to make sure // to update all existing OrderLines to use prices in this new currency. if (ctx.currencyCode !== order.currencyCode) { updatedOrderLines = order.lines; order.currencyCode = ctx.currencyCode; } if (updatedOrderLines?.length) { const { orderItemPriceCalculationStrategy, changedPriceHandlingStrategy } = this.configService.orderOptions; for (const updatedOrderLine of updatedOrderLines) { const variant = await this.productVariantService.applyChannelPriceAndTax( updatedOrderLine.productVariant, ctx, order, ); let priceResult = await orderItemPriceCalculationStrategy.calculateUnitPrice( ctx, variant, updatedOrderLine.customFields || {}, order, updatedOrderLine.quantity, ); const initialListPrice = updatedOrderLine.initialListPrice ?? priceResult.price; if (initialListPrice !== priceResult.price) { priceResult = await changedPriceHandlingStrategy.handlePriceChange( ctx, priceResult, updatedOrderLine, order, ); } if (updatedOrderLine.initialListPrice == null) { updatedOrderLine.initialListPrice = initialListPrice; } updatedOrderLine.listPrice = priceResult.price; updatedOrderLine.listPriceIncludesTax = priceResult.priceIncludesTax; } } const updatedOrder = await this.orderCalculator.applyPriceAdjustments( ctx, order, promotions, updatedOrderLines ?? [], ); await this.connection .getRepository(ctx, Order) // Explicitly omit the shippingAddress and billingAddress properties to avoid // a race condition where changing one or the other in parallel can // overwrite the other's changes. .save(omit(updatedOrder, ['shippingAddress', 'billingAddress']), { reload: false }); await this.connection.getRepository(ctx, OrderLine).save(updatedOrder.lines, { reload: false }); await this.connection.getRepository(ctx, ShippingLine).save(order.shippingLines, { reload: false }); await this.promotionService.runPromotionSideEffects(ctx, order, activePromotionsPre); return assertFound(this.findOne(ctx, order.id)); } }
import { Injectable } from '@nestjs/common'; import { PaymentMethodQuote } from '@vendure/common/lib/generated-shop-types'; import { AssignPaymentMethodsToChannelInput, ConfigurableOperationDefinition, CreatePaymentMethodInput, DeletionResponse, DeletionResult, Permission, RemovePaymentMethodsFromChannelInput, UpdatePaymentMethodInput, } from '@vendure/common/lib/generated-types'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ForbiddenError, UserInputError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { PaymentMethodEligibilityChecker } from '../../config/payment/payment-method-eligibility-checker'; import { PaymentMethodHandler } from '../../config/payment/payment-method-handler'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Order } from '../../entity/order/order.entity'; import { PaymentMethodTranslation } from '../../entity/payment-method/payment-method-translation.entity'; import { PaymentMethod } from '../../entity/payment-method/payment-method.entity'; import { EventBus } from '../../event-bus/event-bus'; import { PaymentMethodEvent } from '../../event-bus/events/payment-method-event'; import { ConfigArgService } from '../helpers/config-arg/config-arg.service'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { ChannelService } from './channel.service'; import { RoleService } from './role.service'; /** * @description * Contains methods relating to {@link PaymentMethod} entities. * * @docsCategory services */ @Injectable() export class PaymentMethodService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private roleService: RoleService, private listQueryBuilder: ListQueryBuilder, private eventBus: EventBus, private configArgService: ConfigArgService, private channelService: ChannelService, private customFieldRelationService: CustomFieldRelationService, private translatableSaver: TranslatableSaver, private translator: TranslatorService, ) {} findAll( ctx: RequestContext, options?: ListQueryOptions<PaymentMethod>, relations: RelationPaths<PaymentMethod> = [], ): Promise<PaginatedList<PaymentMethod>> { return this.listQueryBuilder .build(PaymentMethod, options, { ctx, relations, channelId: ctx.channelId }) .getManyAndCount() .then(([methods, totalItems]) => { const items = methods.map(m => this.translator.translate(m, ctx)); return { items, totalItems, }; }); } findOne( ctx: RequestContext, paymentMethodId: ID, relations: RelationPaths<PaymentMethod> = [], ): Promise<PaymentMethod | undefined> { return this.connection .findOneInChannel(ctx, PaymentMethod, paymentMethodId, ctx.channelId, { relations, }) .then(paymentMethod => { if (paymentMethod) { return this.translator.translate(paymentMethod, ctx); } }); } async create(ctx: RequestContext, input: CreatePaymentMethodInput): Promise<PaymentMethod> { const savedPaymentMethod = await this.translatableSaver.create({ ctx, input, entityType: PaymentMethod, translationType: PaymentMethodTranslation, beforeSave: async pm => { pm.handler = this.configArgService.parseInput('PaymentMethodHandler', input.handler); if (input.checker) { pm.checker = this.configArgService.parseInput( 'PaymentMethodEligibilityChecker', input.checker, ); } await this.channelService.assignToCurrentChannel(pm, ctx); }, }); await this.customFieldRelationService.updateRelations(ctx, PaymentMethod, input, savedPaymentMethod); await this.eventBus.publish(new PaymentMethodEvent(ctx, savedPaymentMethod, 'created', input)); return assertFound(this.findOne(ctx, savedPaymentMethod.id)); } async update(ctx: RequestContext, input: UpdatePaymentMethodInput): Promise<PaymentMethod> { const updatedPaymentMethod = await this.translatableSaver.update({ ctx, input, entityType: PaymentMethod, translationType: PaymentMethodTranslation, beforeSave: async pm => { if (input.checker) { pm.checker = this.configArgService.parseInput( 'PaymentMethodEligibilityChecker', input.checker, ); } if (input.checker === null) { pm.checker = null; } if (input.handler) { pm.handler = this.configArgService.parseInput('PaymentMethodHandler', input.handler); } }, }); await this.customFieldRelationService.updateRelations( ctx, PaymentMethod, input, updatedPaymentMethod, ); await this.eventBus.publish(new PaymentMethodEvent(ctx, updatedPaymentMethod, 'updated', input)); await this.connection.getRepository(ctx, PaymentMethod).save(updatedPaymentMethod, { reload: false }); return assertFound(this.findOne(ctx, updatedPaymentMethod.id)); } async delete( ctx: RequestContext, paymentMethodId: ID, force: boolean = false, ): Promise<DeletionResponse> { const paymentMethod = await this.connection.getEntityOrThrow(ctx, PaymentMethod, paymentMethodId, { relations: ['channels'], channelId: ctx.channelId, }); if (ctx.channel.code === DEFAULT_CHANNEL_CODE) { const nonDefaultChannels = paymentMethod.channels.filter( channel => channel.code !== DEFAULT_CHANNEL_CODE, ); if (0 < nonDefaultChannels.length && !force) { const message = ctx.translate('message.payment-method-used-in-channels', { channelCodes: nonDefaultChannels.map(c => c.code).join(', '), }); const result = DeletionResult.NOT_DELETED; return { result, message }; } try { const deletedPaymentMethod = new PaymentMethod(paymentMethod); await this.connection.getRepository(ctx, PaymentMethod).remove(paymentMethod); await this.eventBus.publish( new PaymentMethodEvent(ctx, deletedPaymentMethod, 'deleted', paymentMethodId), ); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.message || String(e), }; } } else { // If not deleting from the default channel, we will not actually delete, // but will remove from the current channel paymentMethod.channels = paymentMethod.channels.filter(c => !idsAreEqual(c.id, ctx.channelId)); await this.connection.getRepository(ctx, PaymentMethod).save(paymentMethod); await this.eventBus.publish( new PaymentMethodEvent(ctx, paymentMethod, 'deleted', paymentMethodId), ); return { result: DeletionResult.DELETED, }; } } async assignPaymentMethodsToChannel( ctx: RequestContext, input: AssignPaymentMethodsToChannelInput, ): Promise<Array<Translated<PaymentMethod>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.UpdatePaymentMethod, Permission.UpdateSettings, ]); if (!hasPermission) { throw new ForbiddenError(); } for (const paymentMethodId of input.paymentMethodIds) { const paymentMethod = await this.connection.findOneInChannel( ctx, PaymentMethod, paymentMethodId, ctx.channelId, ); await this.channelService.assignToChannels(ctx, PaymentMethod, paymentMethodId, [ input.channelId, ]); } return this.connection .findByIdsInChannel(ctx, PaymentMethod, input.paymentMethodIds, ctx.channelId, {}) .then(methods => methods.map(method => this.translator.translate(method, ctx))); } async removePaymentMethodsFromChannel( ctx: RequestContext, input: RemovePaymentMethodsFromChannelInput, ): Promise<Array<Translated<PaymentMethod>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.DeletePaymentMethod, Permission.DeleteSettings, ]); if (!hasPermission) { throw new ForbiddenError(); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); if (idsAreEqual(input.channelId, defaultChannel.id)) { throw new UserInputError('error.items-cannot-be-removed-from-default-channel'); } for (const paymentMethodId of input.paymentMethodIds) { const paymentMethod = await this.connection.getEntityOrThrow(ctx, PaymentMethod, paymentMethodId); await this.channelService.removeFromChannels(ctx, PaymentMethod, paymentMethodId, [ input.channelId, ]); } return this.connection .findByIdsInChannel(ctx, PaymentMethod, input.paymentMethodIds, ctx.channelId, {}) .then(methods => methods.map(method => this.translator.translate(method, ctx))); } getPaymentMethodEligibilityCheckers(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.configArgService .getDefinitions('PaymentMethodEligibilityChecker') .map(x => x.toGraphQlType(ctx)); } getPaymentMethodHandlers(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.configArgService.getDefinitions('PaymentMethodHandler').map(x => x.toGraphQlType(ctx)); } async getEligiblePaymentMethods(ctx: RequestContext, order: Order): Promise<PaymentMethodQuote[]> { const paymentMethods = await this.connection .getRepository(ctx, PaymentMethod) .find({ where: { enabled: true }, relations: ['channels'] }); const results: PaymentMethodQuote[] = []; const paymentMethodsInChannel = paymentMethods .filter(p => p.channels.find(pc => idsAreEqual(pc.id, ctx.channelId))) .map(p => this.translator.translate(p, ctx)); for (const method of paymentMethodsInChannel) { let isEligible = true; let eligibilityMessage: string | undefined; if (method.checker) { const checker = this.configArgService.getByCode( 'PaymentMethodEligibilityChecker', method.checker.code, ); const eligible = await checker.check(ctx, order, method.checker.args, method); if (eligible === false || typeof eligible === 'string') { isEligible = false; eligibilityMessage = typeof eligible === 'string' ? eligible : undefined; } } results.push({ id: method.id, code: method.code, name: method.name, description: method.description, isEligible, eligibilityMessage, customFields: method.customFields, }); } return results; } async getMethodAndOperations( ctx: RequestContext, method: string, ): Promise<{ paymentMethod: PaymentMethod; handler: PaymentMethodHandler; checker: PaymentMethodEligibilityChecker | null; }> { const paymentMethod = await this.connection .getRepository(ctx, PaymentMethod) .createQueryBuilder('method') .leftJoin('method.channels', 'channel') .where('method.code = :code', { code: method }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .getOne(); if (!paymentMethod) { throw new UserInputError('error.payment-method-not-found', { method }); } const handler = this.configArgService.getByCode('PaymentMethodHandler', paymentMethod.handler.code); const checker = paymentMethod.checker && this.configArgService.getByCode('PaymentMethodEligibilityChecker', paymentMethod.checker.code); return { paymentMethod, handler, checker }; } }
import { Injectable } from '@nestjs/common'; import { ManualPaymentInput, RefundOrderInput } from '@vendure/common/lib/generated-types'; import { DeepPartial, ID } from '@vendure/common/lib/shared-types'; import { summate } from '@vendure/common/lib/shared-utils'; import { In } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { InternalServerError } from '../../common/error/errors'; import { PaymentStateTransitionError, RefundAmountError, RefundStateTransitionError, } from '../../common/error/generated-graphql-admin-errors'; import { IneligiblePaymentMethodError } from '../../common/error/generated-graphql-shop-errors'; import { PaymentMetadata } from '../../common/types/common-types'; import { idsAreEqual } from '../../common/utils'; import { Logger } from '../../config/logger/vendure-logger'; import { PaymentMethodHandler } from '../../config/payment/payment-method-handler'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Fulfillment } from '../../entity/fulfillment/fulfillment.entity'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { FulfillmentLine } from '../../entity/order-line-reference/fulfillment-line.entity'; import { RefundLine } from '../../entity/order-line-reference/refund-line.entity'; import { Payment } from '../../entity/payment/payment.entity'; import { PaymentMethod } from '../../entity/payment-method/payment-method.entity'; import { Refund } from '../../entity/refund/refund.entity'; import { EventBus } from '../../event-bus/event-bus'; import { PaymentStateTransitionEvent } from '../../event-bus/events/payment-state-transition-event'; import { RefundStateTransitionEvent } from '../../event-bus/events/refund-state-transition-event'; import { PaymentState } from '../helpers/payment-state-machine/payment-state'; import { PaymentStateMachine } from '../helpers/payment-state-machine/payment-state-machine'; import { RefundStateMachine } from '../helpers/refund-state-machine/refund-state-machine'; import { PaymentMethodService } from './payment-method.service'; /** * @description * Contains methods relating to {@link Payment} entities. * * @docsCategory services */ @Injectable() export class PaymentService { constructor( private connection: TransactionalConnection, private paymentStateMachine: PaymentStateMachine, private refundStateMachine: RefundStateMachine, private paymentMethodService: PaymentMethodService, private eventBus: EventBus, ) {} async create(ctx: RequestContext, input: DeepPartial<Payment>): Promise<Payment> { const newPayment = new Payment({ ...input, state: this.paymentStateMachine.getInitialState(), }); return this.connection.getRepository(ctx, Payment).save(newPayment); } async findOneOrThrow(ctx: RequestContext, id: ID, relations: string[] = ['order']): Promise<Payment> { return await this.connection.getEntityOrThrow(ctx, Payment, id, { relations, }); } /** * @description * Transitions a Payment to the given state. * * When updating a Payment in the context of an Order, it is * preferable to use the {@link OrderService} `transitionPaymentToState()` method, which will also handle * updating the Order state too. */ async transitionToState( ctx: RequestContext, paymentId: ID, state: PaymentState, ): Promise<Payment | PaymentStateTransitionError> { if (state === 'Settled') { return this.settlePayment(ctx, paymentId); } if (state === 'Cancelled') { return this.cancelPayment(ctx, paymentId); } const payment = await this.findOneOrThrow(ctx, paymentId); const fromState = payment.state; return this.transitionStateAndSave(ctx, payment, fromState, state); } getNextStates(payment: Payment): readonly PaymentState[] { return this.paymentStateMachine.getNextStates(payment); } /** * @description * Creates a new Payment. * * When creating a Payment in the context of an Order, it is * preferable to use the {@link OrderService} `addPaymentToOrder()` method, which will also handle * updating the Order state too. */ async createPayment( ctx: RequestContext, order: Order, amount: number, method: string, metadata: any, ): Promise<Payment | IneligiblePaymentMethodError> { const { paymentMethod, handler, checker } = await this.paymentMethodService.getMethodAndOperations( ctx, method, ); if (paymentMethod.checker && checker) { const eligible = await checker.check(ctx, order, paymentMethod.checker.args, paymentMethod); if (eligible === false || typeof eligible === 'string') { return new IneligiblePaymentMethodError({ eligibilityCheckerMessage: typeof eligible === 'string' ? eligible : undefined, }); } } const result = await handler.createPayment( ctx, order, amount, paymentMethod.handler.args, metadata || {}, paymentMethod, ); const initialState = 'Created'; const payment = await this.connection .getRepository(ctx, Payment) .save(new Payment({ ...result, method, state: initialState })); const { finalize } = await this.paymentStateMachine.transition(ctx, order, payment, result.state); await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); await this.connection .getRepository(ctx, Order) .createQueryBuilder() .relation('payments') .of(order) .add(payment); await this.eventBus.publish( new PaymentStateTransitionEvent(initialState, result.state, ctx, payment, order), ); await finalize(); return payment; } /** * @description * Settles a Payment. * * When settling a Payment in the context of an Order, it is * preferable to use the {@link OrderService} `settlePayment()` method, which will also handle * updating the Order state too. */ async settlePayment(ctx: RequestContext, paymentId: ID): Promise<PaymentStateTransitionError | Payment> { const payment = await this.connection.getEntityOrThrow(ctx, Payment, paymentId, { relations: ['order'], }); const { paymentMethod, handler } = await this.paymentMethodService.getMethodAndOperations( ctx, payment.method, ); const settlePaymentResult = await handler.settlePayment( ctx, payment.order, payment, paymentMethod.handler.args, paymentMethod, ); const fromState = payment.state; let toState: PaymentState; payment.metadata = this.mergePaymentMetadata(payment.metadata, settlePaymentResult.metadata); if (settlePaymentResult.success) { toState = 'Settled'; } else { toState = settlePaymentResult.state || 'Error'; payment.errorMessage = settlePaymentResult.errorMessage; } return this.transitionStateAndSave(ctx, payment, fromState, toState); } async cancelPayment(ctx: RequestContext, paymentId: ID): Promise<PaymentStateTransitionError | Payment> { const payment = await this.connection.getEntityOrThrow(ctx, Payment, paymentId, { relations: ['order'], }); const { paymentMethod, handler } = await this.paymentMethodService.getMethodAndOperations( ctx, payment.method, ); const cancelPaymentResult = await handler.cancelPayment( ctx, payment.order, payment, paymentMethod.handler.args, paymentMethod, ); const fromState = payment.state; let toState: PaymentState; payment.metadata = this.mergePaymentMetadata(payment.metadata, cancelPaymentResult?.metadata); if (cancelPaymentResult == null || cancelPaymentResult.success) { toState = 'Cancelled'; } else { toState = cancelPaymentResult.state || 'Error'; payment.errorMessage = cancelPaymentResult.errorMessage; } return this.transitionStateAndSave(ctx, payment, fromState, toState); } private async transitionStateAndSave( ctx: RequestContext, payment: Payment, fromState: PaymentState, toState: PaymentState, ) { if (fromState === toState) { // in case metadata was changed await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); return payment; } let finalize: () => Promise<any>; try { const result = await this.paymentStateMachine.transition(ctx, payment.order, payment, toState); finalize = result.finalize; } catch (e: any) { const transitionError = ctx.translate(e.message, { fromState, toState }); return new PaymentStateTransitionError({ transitionError, fromState, toState }); } await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); await this.eventBus.publish( new PaymentStateTransitionEvent(fromState, toState, ctx, payment, payment.order), ); await finalize(); return payment; } /** * @description * Creates a Payment from the manual payment mutation in the Admin API * * When creating a manual Payment in the context of an Order, it is * preferable to use the {@link OrderService} `addManualPaymentToOrder()` method, which will also handle * updating the Order state too. */ async createManualPayment(ctx: RequestContext, order: Order, amount: number, input: ManualPaymentInput) { const initialState = 'Created'; const endState = 'Settled'; const payment = await this.connection.getRepository(ctx, Payment).save( new Payment({ amount, order, transactionId: input.transactionId, metadata: input.metadata, method: input.method, state: initialState, }), ); const { finalize } = await this.paymentStateMachine.transition(ctx, order, payment, endState); await this.connection.getRepository(ctx, Payment).save(payment, { reload: false }); await this.connection .getRepository(ctx, Order) .createQueryBuilder() .relation('payments') .of(order) .add(payment); await this.eventBus.publish( new PaymentStateTransitionEvent(initialState, endState, ctx, payment, order), ); await finalize(); return payment; } /** * @description * Creates a Refund against the specified Payment. If the amount to be refunded exceeds the value of the * specified Payment (in the case of multiple payments on a single Order), then the remaining outstanding * refund amount will be refunded against the next available Payment from the Order. * * When creating a Refund in the context of an Order, it is * preferable to use the {@link OrderService} `refundOrder()` method, which performs additional * validation. */ async createRefund( ctx: RequestContext, input: RefundOrderInput, order: Order, selectedPayment: Payment, ): Promise<Refund | RefundStateTransitionError | RefundAmountError> { const orderWithRefunds = await this.connection.getEntityOrThrow(ctx, Order, order.id, { relations: ['payments', 'payments.refunds'], }); if (input.amount) { const paymentToRefund = orderWithRefunds.payments.find(p => idsAreEqual(p.id, selectedPayment.id), ); if (!paymentToRefund) { throw new InternalServerError('Could not find a Payment to refund'); } const refundableAmount = paymentToRefund.amount - this.getPaymentRefundTotal(paymentToRefund); if (refundableAmount < input.amount) { return new RefundAmountError({ maximumRefundable: refundableAmount }); } } const refundsCreated: Refund[] = []; const refundablePayments = orderWithRefunds.payments.filter(p => { return this.getPaymentRefundTotal(p) < p.amount; }); let primaryRefund: Refund | undefined; const refundedPaymentIds: ID[] = []; const { total, orderLinesTotal } = await this.getRefundAmount(ctx, input); const refundMax = orderWithRefunds.payments ?.map(p => p.amount - this.getPaymentRefundTotal(p)) .reduce((sum, amount) => sum + amount, 0) ?? 0; let refundOutstanding = Math.min(total, refundMax); do { const paymentToRefund = (refundedPaymentIds.length === 0 && refundablePayments.find(p => idsAreEqual(p.id, selectedPayment.id))) || refundablePayments.find(p => !refundedPaymentIds.includes(p.id)); if (!paymentToRefund) { throw new InternalServerError('Could not find a Payment to refund'); } const amountNotRefunded = paymentToRefund.amount - this.getPaymentRefundTotal(paymentToRefund); const constrainedTotal = Math.min(amountNotRefunded, refundOutstanding); let refund = new Refund({ payment: paymentToRefund, total: constrainedTotal, reason: input.reason, method: selectedPayment.method, state: 'Pending', metadata: {}, items: orderLinesTotal, // deprecated adjustment: input.adjustment, // deprecated shipping: input.shipping, // deprecated }); let paymentMethod: PaymentMethod | undefined; let handler: PaymentMethodHandler | undefined; try { const methodAndHandler = await this.paymentMethodService.getMethodAndOperations( ctx, paymentToRefund.method, ); paymentMethod = methodAndHandler.paymentMethod; handler = methodAndHandler.handler; } catch (e) { Logger.warn( 'Could not find a corresponding PaymentMethodHandler ' + `when creating a refund for the Payment with method "${paymentToRefund.method}"`, ); } const createRefundResult = paymentMethod && handler ? await handler.createRefund( ctx, input, constrainedTotal, order, paymentToRefund, paymentMethod.handler.args, paymentMethod, ) : false; if (createRefundResult) { refund.transactionId = createRefundResult.transactionId || ''; refund.metadata = createRefundResult.metadata || {}; } refund = await this.connection.getRepository(ctx, Refund).save(refund); const refundLines: RefundLine[] = []; for (const { orderLineId, quantity } of input.lines) { const refundLine = await this.connection.getRepository(ctx, RefundLine).save( new RefundLine({ refund, orderLineId, quantity, }), ); refundLines.push(refundLine); } await this.connection .getRepository(ctx, Fulfillment) .createQueryBuilder() .relation('lines') .of(refund) .add(refundLines); if (createRefundResult) { let finalize: () => Promise<any>; const fromState = refund.state; try { const result = await this.refundStateMachine.transition( ctx, order, refund, createRefundResult.state, ); finalize = result.finalize; } catch (e: any) { return new RefundStateTransitionError({ transitionError: e.message, fromState, toState: createRefundResult.state, }); } await this.connection.getRepository(ctx, Refund).save(refund, { reload: false }); await finalize(); await this.eventBus.publish( new RefundStateTransitionEvent(fromState, createRefundResult.state, ctx, refund, order), ); } if (primaryRefund == null) { primaryRefund = refund; } refundsCreated.push(refund); refundedPaymentIds.push(paymentToRefund.id); refundOutstanding = total - summate(refundsCreated, 'total'); } while (0 < refundOutstanding); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return primaryRefund; } /** * @description * Returns the total amount of all Refunds against the given Payment. */ private getPaymentRefundTotal(payment: Payment): number { const nonFailedRefunds = payment.refunds?.filter(refund => refund.state !== 'Failed') ?? []; return summate(nonFailedRefunds, 'total'); } private async getRefundAmount( ctx: RequestContext, input: RefundOrderInput, ): Promise<{ orderLinesTotal: number; total: number }> { if (input.amount) { // This is the new way of getting the refund amount // after v2.2.0. It allows full control over the refund. return { orderLinesTotal: 0, total: input.amount }; } // This is the pre-v2.2.0 way of getting the refund amount. // It calculates the refund amount based on the order lines to be refunded // plus shipping and adjustment amounts. It is complex and prevents full // control over refund amounts, especially when multiple payment methods // are involved. // It is deprecated and will be removed in a future version. let refundOrderLinesTotal = 0; const orderLines = await this.connection .getRepository(ctx, OrderLine) .find({ where: { id: In(input.lines.map(l => l.orderLineId)) } }); for (const line of input.lines) { const orderLine = orderLines.find(l => idsAreEqual(l.id, line.orderLineId)); if (orderLine && 0 < orderLine.orderPlacedQuantity) { refundOrderLinesTotal += line.quantity * orderLine.proratedUnitPriceWithTax; } } const total = refundOrderLinesTotal + input.shipping + input.adjustment; return { orderLinesTotal: refundOrderLinesTotal, total }; } private mergePaymentMetadata(m1: PaymentMetadata, m2?: PaymentMetadata): PaymentMetadata { if (!m2) { return m1; } const merged = { ...m1, ...m2 }; if (m1.public && m1.public) { merged.public = { ...m1.public, ...m2.public }; } return merged; } }
import { Injectable } from '@nestjs/common'; import { CreateProductOptionGroupInput, DeletionResult, UpdateProductOptionGroupInput, } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { FindManyOptions, Like } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { Translated } from '../../common/types/locale-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { Logger } from '../../config/logger/vendure-logger'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Product } from '../../entity/product/product.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 { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { EventBus } from '../../event-bus'; import { ProductOptionGroupEvent } from '../../event-bus/events/product-option-group-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { ProductOptionService } from './product-option.service'; /** * @description * Contains methods relating to {@link ProductOptionGroup} entities. * * @docsCategory services */ @Injectable() export class ProductOptionGroupService { constructor( private connection: TransactionalConnection, private translatableSaver: TranslatableSaver, private customFieldRelationService: CustomFieldRelationService, private productOptionService: ProductOptionService, private eventBus: EventBus, private translator: TranslatorService, ) {} findAll( ctx: RequestContext, filterTerm?: string, relations?: RelationPaths<ProductOptionGroup>, ): Promise<Array<Translated<ProductOptionGroup>>> { const findOptions: FindManyOptions = { relations: relations ?? ['options'], }; if (filterTerm) { findOptions.where = { code: Like(`%${filterTerm}%`), }; } return this.connection .getRepository(ctx, ProductOptionGroup) .find(findOptions) .then(groups => groups.map(group => this.translator.translate(group, ctx, ['options']))); } findOne( ctx: RequestContext, id: ID, relations?: RelationPaths<ProductOptionGroup>, ): Promise<Translated<ProductOptionGroup> | undefined> { return this.connection .getRepository(ctx, ProductOptionGroup) .findOne({ where: { id }, relations: relations ?? ['options'], }) .then(group => (group && this.translator.translate(group, ctx, ['options'])) ?? undefined); } getOptionGroupsByProductId(ctx: RequestContext, id: ID): Promise<Array<Translated<ProductOptionGroup>>> { return this.connection .getRepository(ctx, ProductOptionGroup) .find({ relations: ['options'], where: { product: { id }, }, order: { id: 'ASC', }, }) .then(groups => groups.map(group => this.translator.translate(group, ctx, ['options']))); } async create( ctx: RequestContext, input: Omit<CreateProductOptionGroupInput, 'options'>, ): Promise<Translated<ProductOptionGroup>> { const group = await this.translatableSaver.create({ ctx, input, entityType: ProductOptionGroup, translationType: ProductOptionGroupTranslation, }); const groupWithRelations = await this.customFieldRelationService.updateRelations( ctx, ProductOptionGroup, input, group, ); await this.eventBus.publish(new ProductOptionGroupEvent(ctx, groupWithRelations, 'created', input)); return assertFound(this.findOne(ctx, group.id)); } async update( ctx: RequestContext, input: UpdateProductOptionGroupInput, ): Promise<Translated<ProductOptionGroup>> { const group = await this.translatableSaver.update({ ctx, input, entityType: ProductOptionGroup, translationType: ProductOptionGroupTranslation, }); await this.customFieldRelationService.updateRelations(ctx, ProductOptionGroup, input, group); await this.eventBus.publish(new ProductOptionGroupEvent(ctx, group, 'updated', input)); return assertFound(this.findOne(ctx, group.id)); } /** * @description * Deletes the ProductOptionGroup and any associated ProductOptions. If the ProductOptionGroup * is still referenced by a soft-deleted Product, then a soft-delete will be used to preserve * referential integrity. Otherwise a hard-delete will be performed. */ async deleteGroupAndOptionsFromProduct(ctx: RequestContext, id: ID, productId: ID) { const optionGroup = await this.connection.getEntityOrThrow(ctx, ProductOptionGroup, id, { relationLoadStrategy: 'query', loadEagerRelations: false, relations: ['options', 'product'], }); const deletedOptionGroup = new ProductOptionGroup(optionGroup); const inUseByActiveProducts = await this.isInUseByOtherProducts(ctx, optionGroup, productId); if (0 < inUseByActiveProducts) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.product-option-group-used', { code: optionGroup.code, count: inUseByActiveProducts, }), }; } const optionsToDelete = optionGroup.options && optionGroup.options.filter(group => !group.deletedAt); for (const option of optionsToDelete) { const { result, message } = await this.productOptionService.delete(ctx, option.id); if (result === DeletionResult.NOT_DELETED) { await this.connection.rollBackTransaction(ctx); return { result, message }; } } const hasOptionsWhichAreInUse = await this.groupOptionsAreInUse(ctx, optionGroup); if (0 < hasOptionsWhichAreInUse) { // soft delete optionGroup.deletedAt = new Date(); await this.connection.getRepository(ctx, ProductOptionGroup).save(optionGroup, { reload: false }); } else { // hard delete const product = await this.connection.getRepository(ctx, Product).findOne({ relationLoadStrategy: 'query', loadEagerRelations: false, where: { id: productId }, relations: ['optionGroups'], }); if (product) { product.optionGroups = product.optionGroups.filter(og => !idsAreEqual(og.id, id)); await this.connection.getRepository(ctx, Product).save(product, { reload: false }); } try { await this.connection.getRepository(ctx, ProductOptionGroup).remove(optionGroup); } catch (e: any) { Logger.error(e.message, undefined, e.stack); } } await this.eventBus.publish(new ProductOptionGroupEvent(ctx, deletedOptionGroup, 'deleted', id)); return { result: DeletionResult.DELETED, }; } private async isInUseByOtherProducts( ctx: RequestContext, productOptionGroup: ProductOptionGroup, targetProductId: ID, ): Promise<number> { return this.connection .getRepository(ctx, Product) .createQueryBuilder('product') .leftJoin('product.optionGroups', 'optionGroup') .where('product.deletedAt IS NULL') .andWhere('optionGroup.id = :id', { id: productOptionGroup.id }) .andWhere('product.id != :productId', { productId: targetProductId }) .getCount(); } private async groupOptionsAreInUse(ctx: RequestContext, productOptionGroup: ProductOptionGroup) { return this.connection .getRepository(ctx, ProductVariant) .createQueryBuilder('variant') .leftJoin('variant.options', 'option') .where('option.groupId = :groupId', { groupId: productOptionGroup.id }) .getCount(); } }
import { Injectable } from '@nestjs/common'; import { CreateGroupOptionInput, CreateProductOptionInput, DeletionResponse, DeletionResult, UpdateProductOptionInput, } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { Translated } from '../../common/types/locale-types'; import { assertFound } from '../../common/utils'; import { Logger } from '../../config/logger/vendure-logger'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { ProductOptionTranslation } from '../../entity/product-option/product-option-translation.entity'; import { ProductOption } from '../../entity/product-option/product-option.entity'; import { ProductOptionGroup } from '../../entity/product-option-group/product-option-group.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { EventBus } from '../../event-bus'; import { ProductOptionEvent } from '../../event-bus/events/product-option-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; /** * @description * Contains methods relating to {@link ProductOption} entities. * * @docsCategory services */ @Injectable() export class ProductOptionService { constructor( private connection: TransactionalConnection, private translatableSaver: TranslatableSaver, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private translator: TranslatorService, ) {} findAll(ctx: RequestContext): Promise<Array<Translated<ProductOption>>> { return this.connection .getRepository(ctx, ProductOption) .find({ relations: ['group'], }) .then(options => options.map(option => this.translator.translate(option, ctx))); } findOne(ctx: RequestContext, id: ID): Promise<Translated<ProductOption> | undefined> { return this.connection .getRepository(ctx, ProductOption) .findOne({ where: { id }, relations: ['group'], }) .then(option => (option && this.translator.translate(option, ctx)) ?? undefined); } async create( ctx: RequestContext, group: ProductOptionGroup | ID, input: CreateGroupOptionInput | CreateProductOptionInput, ): Promise<Translated<ProductOption>> { const productOptionGroup = group instanceof ProductOptionGroup ? group : await this.connection.getEntityOrThrow(ctx, ProductOptionGroup, group); const option = await this.translatableSaver.create({ ctx, input, entityType: ProductOption, translationType: ProductOptionTranslation, beforeSave: po => (po.group = productOptionGroup), }); const optionWithRelations = await this.customFieldRelationService.updateRelations( ctx, ProductOption, input as CreateProductOptionInput, option, ); await this.eventBus.publish(new ProductOptionEvent(ctx, optionWithRelations, 'created', input)); return assertFound(this.findOne(ctx, option.id)); } async update(ctx: RequestContext, input: UpdateProductOptionInput): Promise<Translated<ProductOption>> { const option = await this.translatableSaver.update({ ctx, input, entityType: ProductOption, translationType: ProductOptionTranslation, }); await this.customFieldRelationService.updateRelations(ctx, ProductOption, input, option); await this.eventBus.publish(new ProductOptionEvent(ctx, option, 'updated', input)); return assertFound(this.findOne(ctx, option.id)); } /** * @description * Deletes a ProductOption. * * - If the ProductOption is used by any ProductVariants, the deletion will fail. * - If the ProductOption is used only by soft-deleted ProductVariants, the option will itself * be soft-deleted. * - If the ProductOption is not used by any ProductVariant at all, it will be hard-deleted. */ async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const productOption = await this.connection.getEntityOrThrow(ctx, ProductOption, id); const deletedProductOption = new ProductOption(productOption); const inUseByActiveVariants = await this.isInUse(ctx, productOption, 'active'); if (0 < inUseByActiveVariants) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.product-option-used', { code: productOption.code, count: inUseByActiveVariants, }), }; } const isInUseBySoftDeletedVariants = await this.isInUse(ctx, productOption, 'soft-deleted'); if (0 < isInUseBySoftDeletedVariants) { // soft delete productOption.deletedAt = new Date(); await this.connection.getRepository(ctx, ProductOption).save(productOption, { reload: false }); } else { // hard delete try { await this.connection.getRepository(ctx, ProductOption).remove(productOption); } catch (e: any) { Logger.error(e.message, undefined, e.stack); } } await this.eventBus.publish(new ProductOptionEvent(ctx, deletedProductOption, 'deleted', id)); return { result: DeletionResult.DELETED, }; } private async isInUse( ctx: RequestContext, productOption: ProductOption, variantState: 'active' | 'soft-deleted', ): Promise<number> { return this.connection .getRepository(ctx, ProductVariant) .createQueryBuilder('variant') .leftJoin('variant.options', 'option') .where(variantState === 'active' ? 'variant.deletedAt IS NULL' : 'variant.deletedAt IS NOT NULL') .andWhere('option.id = :id', { id: productOption.id }) .getCount(); } }
import { Injectable } from '@nestjs/common'; import { AssignProductVariantsToChannelInput, CreateProductVariantInput, CurrencyCode, DeletionResponse, DeletionResult, GlobalFlag, Permission, ProductVariantFilterParameter, RemoveProductVariantsFromChannelInput, UpdateProductVariantInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { In, IsNull } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { RequestContextCacheService } from '../../cache/request-context-cache.service'; import { ForbiddenError, UserInputError } from '../../common/error/errors'; import { roundMoney } from '../../common/round-money'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { idsAreEqual } from '../../common/utils'; import { UpdatedProductVariantPrice } from '../../config/catalog/product-variant-price-update-strategy'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Channel, Order, OrderLine, ProductOptionGroup, ProductVariantPrice, TaxCategory, } from '../../entity'; import { FacetValue } from '../../entity/facet-value/facet-value.entity'; import { Product } from '../../entity/product/product.entity'; import { ProductOption } from '../../entity/product-option/product-option.entity'; import { ProductVariantTranslation } from '../../entity/product-variant/product-variant-translation.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { EventBus } from '../../event-bus/event-bus'; import { ProductVariantChannelEvent } from '../../event-bus/events/product-variant-channel-event'; import { ProductVariantEvent } from '../../event-bus/events/product-variant-event'; import { ProductVariantPriceEvent } from '../../event-bus/events/product-variant-price-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { ProductPriceApplicator } from '../helpers/product-price-applicator/product-price-applicator'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { samplesEach } from '../helpers/utils/samples-each'; import { AssetService } from './asset.service'; import { ChannelService } from './channel.service'; import { FacetValueService } from './facet-value.service'; import { GlobalSettingsService } from './global-settings.service'; import { RoleService } from './role.service'; import { StockLevelService } from './stock-level.service'; import { StockMovementService } from './stock-movement.service'; import { TaxCategoryService } from './tax-category.service'; /** * @description * Contains methods relating to {@link ProductVariant} entities. * * @docsCategory services */ @Injectable() export class ProductVariantService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private taxCategoryService: TaxCategoryService, private facetValueService: FacetValueService, private assetService: AssetService, private translatableSaver: TranslatableSaver, private eventBus: EventBus, private listQueryBuilder: ListQueryBuilder, private globalSettingsService: GlobalSettingsService, private stockMovementService: StockMovementService, private stockLevelService: StockLevelService, private channelService: ChannelService, private roleService: RoleService, private customFieldRelationService: CustomFieldRelationService, private requestCache: RequestContextCacheService, private productPriceApplicator: ProductPriceApplicator, private translator: TranslatorService, ) {} async findAll( ctx: RequestContext, options?: ListQueryOptions<ProductVariant>, ): Promise<PaginatedList<Translated<ProductVariant>>> { const relations = ['featuredAsset', 'taxCategory', 'channels']; const customPropertyMap: { [name: string]: string } = {}; const hasFacetValueIdFilter = this.listQueryBuilder.filterObjectHasProperty<ProductVariantFilterParameter>( options?.filter, 'facetValueId', ); if (hasFacetValueIdFilter) { relations.push('facetValues'); customPropertyMap.facetValueId = 'facetValues.id'; } return this.listQueryBuilder .build(ProductVariant, options, { relations, channelId: ctx.channelId, where: { deletedAt: IsNull() }, ctx, customPropertyMap, }) .getManyAndCount() .then(async ([variants, totalItems]) => { const items = await this.applyPricesAndTranslateVariants(ctx, variants); return { items, totalItems, }; }); } findOne( ctx: RequestContext, productVariantId: ID, relations?: RelationPaths<ProductVariant>, ): Promise<Translated<ProductVariant> | undefined> { return this.connection .findOneInChannel(ctx, ProductVariant, productVariantId, ctx.channelId, { relations: [ ...(relations || ['product', 'featuredAsset', 'product.featuredAsset']), 'taxCategory', ], where: { deletedAt: IsNull() }, }) .then(async result => { if (result) { return this.translator.translate(await this.applyChannelPriceAndTax(result, ctx), ctx, [ 'product', ]); } }); } findByIds(ctx: RequestContext, ids: ID[]): Promise<Array<Translated<ProductVariant>>> { return this.connection .findByIdsInChannel(ctx, ProductVariant, ids, ctx.channelId, { relations: [ 'options', 'facetValues', 'facetValues.facet', 'taxCategory', 'assets', 'featuredAsset', ], }) .then(variants => this.applyPricesAndTranslateVariants(ctx, variants)); } getVariantsByProductId( ctx: RequestContext, productId: ID, options: ListQueryOptions<ProductVariant> = {}, relations?: RelationPaths<ProductVariant>, ): Promise<PaginatedList<Translated<ProductVariant>>> { const qb = this.listQueryBuilder .build(ProductVariant, options, { relations: [ ...(relations || [ 'options', 'facetValues', 'facetValues.facet', 'assets', 'featuredAsset', ]), 'taxCategory', ], orderBy: { id: 'ASC' }, where: { deletedAt: IsNull() }, ctx, }) .innerJoinAndSelect('productvariant.channels', 'channel', 'channel.id = :channelId', { channelId: ctx.channelId, }) .innerJoinAndSelect('productvariant.product', 'product', 'product.id = :productId', { productId, }); if (ctx.apiType === 'shop') { qb.andWhere('productvariant.enabled = :enabled', { enabled: true }); } return qb.getManyAndCount().then(async ([variants, totalItems]) => { const items = await this.applyPricesAndTranslateVariants(ctx, variants); return { items, totalItems, }; }); } /** * @description * Returns a {@link PaginatedList} of all ProductVariants associated with the given Collection. */ getVariantsByCollectionId( ctx: RequestContext, collectionId: ID, options: ListQueryOptions<ProductVariant>, relations: RelationPaths<ProductVariant> = [], ): Promise<PaginatedList<Translated<ProductVariant>>> { const qb = this.listQueryBuilder .build(ProductVariant, options, { relations: unique([...relations, 'taxCategory']), channelId: ctx.channelId, ctx, }) .leftJoin('productvariant.collections', 'collection') .leftJoin('productvariant.product', 'product') .andWhere('product.deletedAt IS NULL') .andWhere('productvariant.deletedAt IS NULL') .andWhere('collection.id = :collectionId', { collectionId }); if (options && options.filter && options.filter.enabled && options.filter.enabled.eq === true) { qb.andWhere('product.enabled = :enabled', { enabled: true }); } return qb.getManyAndCount().then(async ([variants, totalItems]) => { const items = await this.applyPricesAndTranslateVariants(ctx, variants); return { items, totalItems, }; }); } /** * @description * Returns all Channels to which the ProductVariant is assigned. */ async getProductVariantChannels(ctx: RequestContext, productVariantId: ID): Promise<Channel[]> { const variant = await this.connection.getEntityOrThrow(ctx, ProductVariant, productVariantId, { relations: ['channels'], channelId: ctx.channelId, }); return variant.channels; } async getProductVariantPrices(ctx: RequestContext, productVariantId: ID): Promise<ProductVariantPrice[]> { return this.connection .getRepository(ctx, ProductVariantPrice) .createQueryBuilder('pvp') .where('pvp.productVariant = :productVariantId', { productVariantId }) .andWhere('pvp.channelId = :channelId', { channelId: ctx.channelId }) .getMany(); } /** * @description * Returns the ProductVariant associated with the given {@link OrderLine}. */ async getVariantByOrderLineId(ctx: RequestContext, orderLineId: ID): Promise<Translated<ProductVariant>> { const { productVariant } = await this.connection.getEntityOrThrow(ctx, OrderLine, orderLineId, { relations: ['productVariant', 'productVariant.taxCategory'], includeSoftDeleted: true, }); return this.translator.translate(await this.applyChannelPriceAndTax(productVariant, ctx), ctx); } /** * @description * Returns the {@link ProductOption}s for the given ProductVariant. */ getOptionsForVariant(ctx: RequestContext, variantId: ID): Promise<Array<Translated<ProductOption>>> { return this.connection .findOneInChannel(ctx, ProductVariant, variantId, ctx.channelId, { relations: ['options'], }) .then(variant => (!variant ? [] : variant.options.map(o => this.translator.translate(o, ctx)))); } getFacetValuesForVariant(ctx: RequestContext, variantId: ID): Promise<Array<Translated<FacetValue>>> { return this.connection .findOneInChannel(ctx, ProductVariant, variantId, ctx.channelId, { relations: ['facetValues', 'facetValues.facet', 'facetValues.channels'], }) .then(variant => !variant ? [] : variant.facetValues.map(o => this.translator.translate(o, ctx, ['facet'])), ); } /** * @description * Returns the Product associated with the ProductVariant. Whereas the `ProductService.findOne()` * method performs a large multi-table join with all the typical data needed for a "product detail" * page, this method returns only the Product itself. */ async getProductForVariant(ctx: RequestContext, variant: ProductVariant): Promise<Translated<Product>> { let product; if (!variant.product) { product = await this.connection.getEntityOrThrow(ctx, Product, variant.productId, { includeSoftDeleted: true, }); } else { product = variant.product; } return this.translator.translate(product, ctx); } /** * @description * Returns the number of saleable units of the ProductVariant, i.e. how many are available * for purchase by Customers. This is determined by the ProductVariant's `stockOnHand` value, * as well as the local and global `outOfStockThreshold` settings. */ async getSaleableStockLevel(ctx: RequestContext, variant: ProductVariant): Promise<number> { const { outOfStockThreshold, trackInventory } = await this.globalSettingsService.getSettings(ctx); const inventoryNotTracked = variant.trackInventory === GlobalFlag.FALSE || (variant.trackInventory === GlobalFlag.INHERIT && trackInventory === false); if (inventoryNotTracked) { return Number.MAX_SAFE_INTEGER; } const { stockOnHand, stockAllocated } = await this.stockLevelService.getAvailableStock( ctx, variant.id, ); const effectiveOutOfStockThreshold = variant.useGlobalOutOfStockThreshold ? outOfStockThreshold : variant.outOfStockThreshold; return stockOnHand - stockAllocated - effectiveOutOfStockThreshold; } private async getOutOfStockThreshold(ctx: RequestContext, variant: ProductVariant): Promise<number> { const { outOfStockThreshold, trackInventory } = await this.globalSettingsService.getSettings(ctx); const inventoryNotTracked = variant.trackInventory === GlobalFlag.FALSE || (variant.trackInventory === GlobalFlag.INHERIT && trackInventory === false); if (inventoryNotTracked) { return 0; } else { return variant.useGlobalOutOfStockThreshold ? outOfStockThreshold : variant.outOfStockThreshold; } } /** * @description * Returns the stockLevel to display to the customer, as specified by the configured * {@link StockDisplayStrategy}. */ async getDisplayStockLevel(ctx: RequestContext, variant: ProductVariant): Promise<string> { const { stockDisplayStrategy } = this.configService.catalogOptions; const saleableStockLevel = await this.getSaleableStockLevel(ctx, variant); return stockDisplayStrategy.getStockLevel(ctx, variant, saleableStockLevel); } /** * @description * Returns the number of fulfillable units of the ProductVariant, equivalent to stockOnHand * for those variants which are tracking inventory. */ async getFulfillableStockLevel(ctx: RequestContext, variant: ProductVariant): Promise<number> { const { outOfStockThreshold, trackInventory } = await this.globalSettingsService.getSettings(ctx); const inventoryNotTracked = variant.trackInventory === GlobalFlag.FALSE || (variant.trackInventory === GlobalFlag.INHERIT && trackInventory === false); if (inventoryNotTracked) { return Number.MAX_SAFE_INTEGER; } const { stockOnHand } = await this.stockLevelService.getAvailableStock(ctx, variant.id); return stockOnHand; } async create( ctx: RequestContext, input: CreateProductVariantInput[], ): Promise<Array<Translated<ProductVariant>>> { const ids: ID[] = []; for (const productInput of input) { const id = await this.createSingle(ctx, productInput); ids.push(id); } const createdVariants = await this.findByIds(ctx, ids); await this.eventBus.publish(new ProductVariantEvent(ctx, createdVariants, 'created', input)); return createdVariants; } async update( ctx: RequestContext, input: UpdateProductVariantInput[], ): Promise<Array<Translated<ProductVariant>>> { for (const productInput of input) { await this.updateSingle(ctx, productInput); } const updatedVariants = await this.findByIds( ctx, input.map(i => i.id), ); await this.eventBus.publish(new ProductVariantEvent(ctx, updatedVariants, 'updated', input)); return updatedVariants; } private async createSingle(ctx: RequestContext, input: CreateProductVariantInput): Promise<ID> { await this.validateVariantOptionIds(ctx, input.productId, input.optionIds); if (!input.optionIds) { input.optionIds = []; } if (input.price == null) { input.price = 0; } input.taxCategoryId = (await this.getTaxCategoryForNewVariant(ctx, input.taxCategoryId)).id; const inputWithoutPrice = { ...input, }; delete inputWithoutPrice.price; const createdVariant = await this.translatableSaver.create({ ctx, input: inputWithoutPrice, entityType: ProductVariant, translationType: ProductVariantTranslation, beforeSave: async variant => { const { optionIds } = input; if (optionIds && optionIds.length) { const selectedOptions = await this.connection .getRepository(ctx, ProductOption) .find({ where: { id: In(optionIds) } }); variant.options = selectedOptions; } if (input.facetValueIds) { variant.facetValues = await this.facetValueService.findByIds(ctx, input.facetValueIds); } variant.product = { id: input.productId } as any; variant.taxCategory = { id: input.taxCategoryId } as any; await this.assetService.updateFeaturedAsset(ctx, variant, input); await this.channelService.assignToCurrentChannel(variant, ctx); }, typeOrmSubscriberData: { channelId: ctx.channelId, taxCategoryId: input.taxCategoryId, }, }); await this.customFieldRelationService.updateRelations(ctx, ProductVariant, input, createdVariant); await this.assetService.updateEntityAssets(ctx, createdVariant, input); if (input.stockOnHand != null || input.stockLevels) { await this.stockMovementService.adjustProductVariantStock( ctx, createdVariant.id, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion input.stockLevels || input.stockOnHand!, ); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); await this.createOrUpdateProductVariantPrice(ctx, createdVariant.id, input.price, ctx.channelId); if (!idsAreEqual(ctx.channelId, defaultChannel.id)) { // When creating a ProductVariant _not_ in the default Channel, we still need to // create a ProductVariantPrice for it in the default Channel, otherwise errors will // result when trying to query it there. await this.createOrUpdateProductVariantPrice( ctx, createdVariant.id, input.price, defaultChannel.id, defaultChannel.defaultCurrencyCode, ); } return createdVariant.id; } private async updateSingle(ctx: RequestContext, input: UpdateProductVariantInput): Promise<ID> { const existingVariant = await this.connection.getEntityOrThrow(ctx, ProductVariant, input.id, { channelId: ctx.channelId, relations: ['facetValues', 'facetValues.channels'], }); const outOfStockThreshold = await this.getOutOfStockThreshold(ctx, existingVariant); if (input.stockOnHand && input.stockOnHand < outOfStockThreshold) { throw new UserInputError('error.stockonhand-cannot-be-negative'); } if (input.optionIds) { await this.validateVariantOptionIds(ctx, existingVariant.productId, input.optionIds); } const inputWithoutPriceAndStockLevels = { ...input, }; delete inputWithoutPriceAndStockLevels.price; delete inputWithoutPriceAndStockLevels.stockLevels; const updatedVariant = await this.translatableSaver.update({ ctx, input: inputWithoutPriceAndStockLevels, entityType: ProductVariant, translationType: ProductVariantTranslation, beforeSave: async v => { if (input.taxCategoryId) { const taxCategory = await this.taxCategoryService.findOne(ctx, input.taxCategoryId); if (taxCategory) { v.taxCategory = taxCategory; } } if (input.optionIds && input.optionIds.length) { const selectedOptions = await this.connection .getRepository(ctx, ProductOption) .find({ where: { id: In(input.optionIds) } }); v.options = selectedOptions; } if (input.facetValueIds) { const facetValuesInOtherChannels = existingVariant.facetValues.filter(fv => fv.channels.every(channel => !idsAreEqual(channel.id, ctx.channelId)), ); v.facetValues = [ ...facetValuesInOtherChannels, ...(await this.facetValueService.findByIds(ctx, input.facetValueIds)), ]; } if (input.stockOnHand != null || input.stockLevels) { await this.stockMovementService.adjustProductVariantStock( ctx, existingVariant.id, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion input.stockLevels || input.stockOnHand!, ); } await this.assetService.updateFeaturedAsset(ctx, v, input); await this.assetService.updateEntityAssets(ctx, v, input); }, typeOrmSubscriberData: { channelId: ctx.channelId, taxCategoryId: input.taxCategoryId, }, }); await this.customFieldRelationService.updateRelations(ctx, ProductVariant, input, updatedVariant); if (input.price != null) { await this.createOrUpdateProductVariantPrice(ctx, input.id, input.price, ctx.channelId); } if (input.prices) { for (const priceInput of input.prices) { if (priceInput.delete === true) { await this.deleteProductVariantPrice( ctx, input.id, ctx.channelId, priceInput.currencyCode, ); } else { await this.createOrUpdateProductVariantPrice( ctx, input.id, priceInput.price, ctx.channelId, priceInput.currencyCode, ); } } } return updatedVariant.id; } /** * @description * Creates a {@link ProductVariantPrice} for the given ProductVariant/Channel combination. * If the `currencyCode` is not specified, the default currency of the Channel will be used. */ async createOrUpdateProductVariantPrice( ctx: RequestContext, productVariantId: ID, price: number, channelId: ID, currencyCode?: CurrencyCode, ): Promise<ProductVariantPrice> { const { productVariantPriceUpdateStrategy } = this.configService.catalogOptions; const allPrices = await this.connection.getRepository(ctx, ProductVariantPrice).find({ where: { variant: { id: productVariantId }, }, }); let targetPrice = allPrices.find( p => idsAreEqual(p.channelId, channelId) && p.currencyCode === (currencyCode ?? ctx.channel.defaultCurrencyCode), ); if (currencyCode) { const channel = await this.channelService.findOne(ctx, channelId); if (!channel?.availableCurrencyCodes.includes(currencyCode)) { throw new UserInputError('error.currency-not-available-in-channel', { currencyCode, }); } } let additionalPricesToUpdate: UpdatedProductVariantPrice[] = []; if (!targetPrice) { const createdPrice = await this.connection.getRepository(ctx, ProductVariantPrice).save( new ProductVariantPrice({ channelId, price, variant: new ProductVariant({ id: productVariantId }), currencyCode: currencyCode ?? ctx.channel.defaultCurrencyCode, }), ); await this.eventBus.publish(new ProductVariantPriceEvent(ctx, [createdPrice], 'created')); additionalPricesToUpdate = await productVariantPriceUpdateStrategy.onPriceCreated( ctx, createdPrice, allPrices, ); targetPrice = createdPrice; } else { targetPrice.price = price; const updatedPrice = await this.connection .getRepository(ctx, ProductVariantPrice) .save(targetPrice); await this.eventBus.publish(new ProductVariantPriceEvent(ctx, [updatedPrice], 'updated')); additionalPricesToUpdate = await productVariantPriceUpdateStrategy.onPriceUpdated( ctx, updatedPrice, allPrices, ); } const uniqueAdditionalPricesToUpdate = unique(additionalPricesToUpdate, 'id').filter( p => // We don't save the targetPrice again unless it has been assigned // a different price by the ProductVariantPriceUpdateStrategy. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion !(idsAreEqual(p.id, targetPrice!.id) && p.price === targetPrice!.price), ); if (uniqueAdditionalPricesToUpdate.length) { const updatedAdditionalPrices = await this.connection .getRepository(ctx, ProductVariantPrice) .save(uniqueAdditionalPricesToUpdate); await this.eventBus.publish( new ProductVariantPriceEvent(ctx, updatedAdditionalPrices, 'updated'), ); } return targetPrice; } async deleteProductVariantPrice( ctx: RequestContext, variantId: ID, channelId: ID, currencyCode: CurrencyCode, ) { const variantPrice = await this.connection.getRepository(ctx, ProductVariantPrice).findOne({ where: { variant: { id: variantId }, channelId, currencyCode, }, }); if (variantPrice) { await this.connection.getRepository(ctx, ProductVariantPrice).remove(variantPrice); await this.eventBus.publish(new ProductVariantPriceEvent(ctx, [variantPrice], 'deleted')); const { productVariantPriceUpdateStrategy } = this.configService.catalogOptions; const allPrices = await this.connection.getRepository(ctx, ProductVariantPrice).find({ where: { variant: { id: variantId }, }, }); const additionalPricesToUpdate = await productVariantPriceUpdateStrategy.onPriceDeleted( ctx, variantPrice, allPrices, ); if (additionalPricesToUpdate.length) { const updatedAdditionalPrices = await this.connection .getRepository(ctx, ProductVariantPrice) .save(additionalPricesToUpdate); await this.eventBus.publish( new ProductVariantPriceEvent(ctx, updatedAdditionalPrices, 'updated'), ); } } } async softDelete(ctx: RequestContext, id: ID | ID[]): Promise<DeletionResponse> { const ids = Array.isArray(id) ? id : [id]; const variants = await this.connection .getRepository(ctx, ProductVariant) .find({ where: { id: In(ids) } }); for (const variant of variants) { variant.deletedAt = new Date(); } await this.connection.getRepository(ctx, ProductVariant).save(variants, { reload: false }); await this.eventBus.publish(new ProductVariantEvent(ctx, variants, 'deleted', id)); return { result: DeletionResult.DELETED, }; } /** * @description * This method is intended to be used by the ProductVariant GraphQL entity resolver to resolve the * price-related fields which need to be populated at run-time using the `applyChannelPriceAndTax` * method. * * Is optimized to make as few DB calls as possible using caching based on the open request. */ async hydratePriceFields<F extends 'currencyCode' | 'price' | 'priceWithTax' | 'taxRateApplied'>( ctx: RequestContext, variant: ProductVariant, priceField: F, ): Promise<ProductVariant[F]> { const cacheKey = `hydrate-variant-price-fields-${variant.id}`; let populatePricesPromise = this.requestCache.get<Promise<ProductVariant>>(ctx, cacheKey); if (!populatePricesPromise) { // eslint-disable-next-line @typescript-eslint/no-misused-promises populatePricesPromise = new Promise(async (resolve, reject) => { try { if (!variant.productVariantPrices?.length) { const variantWithPrices = await this.connection.getEntityOrThrow( ctx, ProductVariant, variant.id, { relations: ['productVariantPrices'], includeSoftDeleted: true }, ); variant.productVariantPrices = variantWithPrices.productVariantPrices; } if (!variant.taxCategory) { const variantWithTaxCategory = await this.connection.getEntityOrThrow( ctx, ProductVariant, variant.id, { relations: ['taxCategory'], includeSoftDeleted: true }, ); variant.taxCategory = variantWithTaxCategory.taxCategory; } resolve(await this.applyChannelPriceAndTax(variant, ctx, undefined, true)); } catch (e: any) { reject(e); } }); this.requestCache.set(ctx, cacheKey, populatePricesPromise); } const hydratedVariant = await populatePricesPromise; return hydratedVariant[priceField]; } /** * @description * Given an array of ProductVariants from the database, this method will apply the correct price and tax * and translate each item. */ private async applyPricesAndTranslateVariants( ctx: RequestContext, variants: ProductVariant[], ): Promise<Array<Translated<ProductVariant>>> { return await Promise.all( variants.map(async variant => { const variantWithPrices = await this.applyChannelPriceAndTax(variant, ctx); return this.translator.translate(variantWithPrices, ctx, [ 'options', 'facetValues', ['facetValues', 'facet'], ]); }), ); } /** * @description * Populates the `price` field with the price for the specified channel. */ async applyChannelPriceAndTax( variant: ProductVariant, ctx: RequestContext, order?: Order, throwIfNoPriceFound = false, ): Promise<ProductVariant> { return this.productPriceApplicator.applyChannelPriceAndTax(variant, ctx, order, throwIfNoPriceFound); } /** * @description * Assigns the specified ProductVariants to the specified Channel. In doing so, it will create a new * {@link ProductVariantPrice} and also assign the associated Product and any Assets to the Channel too. */ async assignProductVariantsToChannel( ctx: RequestContext, input: AssignProductVariantsToChannelInput, ): Promise<Array<Translated<ProductVariant>>> { const hasPermission = await this.roleService.userHasPermissionOnChannel( ctx, input.channelId, Permission.UpdateCatalog, ); if (!hasPermission) { throw new ForbiddenError(); } const variants = await this.connection.getRepository(ctx, ProductVariant).find({ where: { id: In(input.productVariantIds), }, relations: ['taxCategory', 'assets'], }); const priceFactor = input.priceFactor != null ? input.priceFactor : 1; const targetChannel = await this.connection.getEntityOrThrow(ctx, Channel, input.channelId); for (const variant of variants) { if (variant.deletedAt) { continue; } await this.applyChannelPriceAndTax(variant, ctx); await this.channelService.assignToChannels(ctx, Product, variant.productId, [input.channelId]); await this.channelService.assignToChannels(ctx, ProductVariant, variant.id, [input.channelId]); const price = targetChannel.pricesIncludeTax ? variant.priceWithTax : variant.price; await this.createOrUpdateProductVariantPrice( ctx, variant.id, roundMoney(price * priceFactor), input.channelId, targetChannel.defaultCurrencyCode, ); const assetIds = variant.assets?.map(a => a.assetId) || []; await this.assetService.assignToChannel(ctx, { channelId: input.channelId, assetIds }); } const result = await this.findByIds( ctx, variants.map(v => v.id), ); for (const variant of variants) { await this.eventBus.publish( new ProductVariantChannelEvent(ctx, variant, input.channelId, 'assigned'), ); } return result; } async removeProductVariantsFromChannel( ctx: RequestContext, input: RemoveProductVariantsFromChannelInput, ): Promise<Array<Translated<ProductVariant>>> { const hasPermission = await this.roleService.userHasPermissionOnChannel( ctx, input.channelId, Permission.UpdateCatalog, ); if (!hasPermission) { throw new ForbiddenError(); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); if (idsAreEqual(input.channelId, defaultChannel.id)) { throw new UserInputError('error.items-cannot-be-removed-from-default-channel'); } const variants = await this.connection .getRepository(ctx, ProductVariant) .find({ where: { id: In(input.productVariantIds) } }); for (const variant of variants) { await this.channelService.removeFromChannels(ctx, ProductVariant, variant.id, [input.channelId]); await this.connection.getRepository(ctx, ProductVariantPrice).delete({ channelId: input.channelId, variant: { id: variant.id }, }); // If none of the ProductVariants is assigned to the Channel, remove the Channel from Product const productVariants = await this.connection.getRepository(ctx, ProductVariant).find({ where: { productId: variant.productId, }, relations: ['channels'], }); const productChannelsFromVariants = ([] as Channel[]).concat( ...productVariants.map(pv => pv.channels), ); if (!productChannelsFromVariants.find(c => c.id === input.channelId)) { await this.channelService.removeFromChannels(ctx, Product, variant.productId, [ input.channelId, ]); } } const result = await this.findByIds( ctx, variants.map(v => v.id), ); // Publish the events at the latest possible stage to decrease the chance of race conditions // whereby an event listener triggers a query which does not yet have access to the changes // within the current transaction. for (const variant of variants) { await this.eventBus.publish( new ProductVariantChannelEvent(ctx, variant, input.channelId, 'removed'), ); } return result; } private async validateVariantOptionIds(ctx: RequestContext, productId: ID, optionIds: ID[] = []) { // this could be done with fewer queries but depending on the data, node will crash // https://github.com/vendure-ecommerce/vendure/issues/328 const optionGroups = ( await this.connection.getEntityOrThrow(ctx, Product, productId, { channelId: ctx.channelId, relations: ['optionGroups', 'optionGroups.options'], loadEagerRelations: false, }) ).optionGroups; const activeOptions = optionGroups && optionGroups.filter(group => !group.deletedAt); if (optionIds.length !== activeOptions.length) { this.throwIncompatibleOptionsError(optionGroups); } if ( !samplesEach( optionIds, activeOptions.map(g => g.options.map(o => o.id)), ) ) { this.throwIncompatibleOptionsError(optionGroups); } const product = await this.connection.getEntityOrThrow(ctx, Product, productId, { channelId: ctx.channelId, relations: ['variants', 'variants.options'], loadEagerRelations: true, }); const inputOptionIds = this.sortJoin(optionIds, ','); product.variants .filter(v => !v.deletedAt) .forEach(variant => { const variantOptionIds = this.sortJoin(variant.options, ',', 'id'); if (variantOptionIds === inputOptionIds) { throw new UserInputError('error.product-variant-options-combination-already-exists', { variantName: this.translator.translate(variant, ctx).name, }); } }); } private throwIncompatibleOptionsError(optionGroups: ProductOptionGroup[]) { throw new UserInputError('error.product-variant-option-ids-not-compatible', { groupNames: this.sortJoin(optionGroups, ', ', 'code'), }); } private sortJoin<T>(arr: T[], glue: string, prop?: keyof T): string { return arr .map(x => (prop ? x[prop] : x)) .sort() .join(glue); } private async getTaxCategoryForNewVariant( ctx: RequestContext, taxCategoryId: ID | null | undefined, ): Promise<TaxCategory> { let taxCategory: TaxCategory; if (taxCategoryId) { taxCategory = await this.connection.getEntityOrThrow(ctx, TaxCategory, taxCategoryId); } else { const taxCategories = await this.taxCategoryService.findAll(ctx); taxCategory = taxCategories.items.find(t => t.isDefault === true) ?? taxCategories.items[0]; } if (!taxCategory) { // there is no TaxCategory set up, so create a default taxCategory = await this.taxCategoryService.create(ctx, { name: 'Standard Tax' }); } return taxCategory; } }
import { Injectable } from '@nestjs/common'; import { AssignProductsToChannelInput, CreateProductInput, DeletionResponse, DeletionResult, ProductFilterParameter, ProductListOptions, RemoveOptionGroupFromProductResult, RemoveProductsFromChannelInput, UpdateProductInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { FindOptionsUtils, In, IsNull } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ErrorResultUnion } from '../../common/error/error-result'; import { EntityNotFoundError, InternalServerError, UserInputError } from '../../common/error/errors'; import { ProductOptionInUseError } from '../../common/error/generated-graphql-admin-errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Channel } from '../../entity/channel/channel.entity'; import { FacetValue } from '../../entity/facet-value/facet-value.entity'; import { ProductTranslation } from '../../entity/product/product-translation.entity'; import { Product } from '../../entity/product/product.entity'; import { ProductOptionGroup } from '../../entity/product-option-group/product-option-group.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { EventBus } from '../../event-bus/event-bus'; import { ProductChannelEvent } from '../../event-bus/events/product-channel-event'; import { ProductEvent } from '../../event-bus/events/product-event'; import { ProductOptionGroupChangeEvent } from '../../event-bus/events/product-option-group-change-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { SlugValidator } from '../helpers/slug-validator/slug-validator'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { AssetService } from './asset.service'; import { ChannelService } from './channel.service'; import { FacetValueService } from './facet-value.service'; import { ProductOptionGroupService } from './product-option-group.service'; import { ProductVariantService } from './product-variant.service'; /** * @description * Contains methods relating to {@link Product} entities. * * @docsCategory services */ @Injectable() export class ProductService { private readonly relations = ['featuredAsset', 'assets', 'channels', 'facetValues', 'facetValues.facet']; constructor( private connection: TransactionalConnection, private channelService: ChannelService, private assetService: AssetService, private productVariantService: ProductVariantService, private facetValueService: FacetValueService, private listQueryBuilder: ListQueryBuilder, private translatableSaver: TranslatableSaver, private eventBus: EventBus, private slugValidator: SlugValidator, private customFieldRelationService: CustomFieldRelationService, private translator: TranslatorService, private productOptionGroupService: ProductOptionGroupService, ) {} async findAll( ctx: RequestContext, options?: ListQueryOptions<Product>, relations?: RelationPaths<Product>, ): Promise<PaginatedList<Translated<Product>>> { const effectiveRelations = relations || this.relations; const customPropertyMap: { [name: string]: string } = {}; const hasFacetValueIdFilter = this.listQueryBuilder.filterObjectHasProperty<ProductFilterParameter>( options?.filter, 'facetValueId', ); const hasSkuFilter = this.listQueryBuilder.filterObjectHasProperty<ProductFilterParameter>( options?.filter, 'sku', ); if (hasFacetValueIdFilter) { effectiveRelations.push('facetValues'); customPropertyMap.facetValueId = 'facetValues.id'; } if (hasSkuFilter) { effectiveRelations.push('variants'); customPropertyMap.sku = 'variants.sku'; } return this.listQueryBuilder .build(Product, options, { relations: effectiveRelations, channelId: ctx.channelId, where: { deletedAt: IsNull() }, ctx, customPropertyMap, }) .getManyAndCount() .then(async ([products, totalItems]) => { const items = products.map(product => this.translator.translate(product, ctx, ['facetValues', ['facetValues', 'facet']]), ); return { items, totalItems, }; }); } async findOne( ctx: RequestContext, productId: ID, relations?: RelationPaths<Product>, ): Promise<Translated<Product> | undefined> { const effectiveRelations = relations ?? this.relations; if (relations && effectiveRelations.includes('facetValues')) { // We need the facet to determine with the FacetValues are public // when serving via the Shop API. effectiveRelations.push('facetValues.facet'); } const product = await this.connection.findOneInChannel(ctx, Product, productId, ctx.channelId, { relations: unique(effectiveRelations), where: { deletedAt: IsNull(), }, }); if (!product) { return; } return this.translator.translate(product, ctx, ['facetValues', ['facetValues', 'facet']]); } async findByIds( ctx: RequestContext, productIds: ID[], relations?: RelationPaths<Product>, ): Promise<Array<Translated<Product>>> { const qb = this.connection .getRepository(ctx, Product) .createQueryBuilder('product') .setFindOptions({ relations: (relations && false) || this.relations }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion FindOptionsUtils.joinEagerRelations(qb, qb.alias, qb.expressionMap.mainAlias!.metadata); return qb .leftJoin('product.channels', 'channel') .andWhere('product.deletedAt IS NULL') .andWhere('product.id IN (:...ids)', { ids: productIds }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .getMany() .then(products => products.map(product => this.translator.translate(product, ctx, ['facetValues', ['facetValues', 'facet']]), ), ); } /** * @description * Returns all Channels to which the Product is assigned. */ async getProductChannels(ctx: RequestContext, productId: ID): Promise<Channel[]> { const product = await this.connection.getEntityOrThrow(ctx, Product, productId, { relations: ['channels'], channelId: ctx.channelId, }); return product.channels; } getFacetValuesForProduct(ctx: RequestContext, productId: ID): Promise<Array<Translated<FacetValue>>> { return this.connection .getRepository(ctx, Product) .findOne({ where: { id: productId }, relations: ['facetValues'], }) .then(variant => !variant ? [] : variant.facetValues.map(o => this.translator.translate(o, ctx, ['facet'])), ); } async findOneBySlug( ctx: RequestContext, slug: string, relations?: RelationPaths<Product>, ): Promise<Translated<Product> | undefined> { const qb = this.connection.getRepository(ctx, Product).createQueryBuilder('product'); const translationQb = this.connection .getRepository(ctx, ProductTranslation) .createQueryBuilder('_product_translation') .select('_product_translation.baseId') .andWhere('_product_translation.slug = :slug', { slug }); qb.leftJoin('product.translations', 'translation') .andWhere('product.deletedAt IS NULL') .andWhere('product.id IN (' + translationQb.getQuery() + ')') .setParameters(translationQb.getParameters()) .select('product.id', 'id') .addSelect( // eslint-disable-next-line max-len `CASE translation.languageCode WHEN '${ctx.languageCode}' THEN 2 WHEN '${ctx.channel.defaultLanguageCode}' THEN 1 ELSE 0 END`, 'sort_order', ) .orderBy('sort_order', 'DESC'); // We use getRawOne here to simply get the ID as efficiently as possible, // which we then pass to the regular findOne() method which will handle // all the joins etc. const result = await qb.getRawOne(); if (result) { return this.findOne(ctx, result.id, relations); } else { return undefined; } } async create(ctx: RequestContext, input: CreateProductInput): Promise<Translated<Product>> { await this.slugValidator.validateSlugs(ctx, input, ProductTranslation); const product = await this.translatableSaver.create({ ctx, input, entityType: Product, translationType: ProductTranslation, beforeSave: async p => { await this.channelService.assignToCurrentChannel(p, ctx); if (input.facetValueIds) { p.facetValues = await this.facetValueService.findByIds(ctx, input.facetValueIds); } await this.assetService.updateFeaturedAsset(ctx, p, input); }, }); await this.customFieldRelationService.updateRelations(ctx, Product, input, product); await this.assetService.updateEntityAssets(ctx, product, input); await this.eventBus.publish(new ProductEvent(ctx, product, 'created', input)); return assertFound(this.findOne(ctx, product.id)); } async update(ctx: RequestContext, input: UpdateProductInput): Promise<Translated<Product>> { const product = await this.connection.getEntityOrThrow(ctx, Product, input.id, { channelId: ctx.channelId, relations: ['facetValues', 'facetValues.channels'], }); await this.slugValidator.validateSlugs(ctx, input, ProductTranslation); const updatedProduct = await this.translatableSaver.update({ ctx, input, entityType: Product, translationType: ProductTranslation, beforeSave: async p => { if (input.facetValueIds) { const facetValuesInOtherChannels = product.facetValues.filter(fv => fv.channels.every(channel => !idsAreEqual(channel.id, ctx.channelId)), ); p.facetValues = [ ...facetValuesInOtherChannels, ...(await this.facetValueService.findByIds(ctx, input.facetValueIds)), ]; } await this.assetService.updateFeaturedAsset(ctx, p, input); await this.assetService.updateEntityAssets(ctx, p, input); }, }); await this.customFieldRelationService.updateRelations(ctx, Product, input, updatedProduct); await this.eventBus.publish(new ProductEvent(ctx, updatedProduct, 'updated', input)); return assertFound(this.findOne(ctx, updatedProduct.id)); } async softDelete(ctx: RequestContext, productId: ID): Promise<DeletionResponse> { const product = await this.connection.getEntityOrThrow(ctx, Product, productId, { relationLoadStrategy: 'query', loadEagerRelations: false, channelId: ctx.channelId, relations: ['variants', 'optionGroups'], }); product.deletedAt = new Date(); await this.connection.getRepository(ctx, Product).save(product, { reload: false }); await this.eventBus.publish(new ProductEvent(ctx, product, 'deleted', productId)); const variantResult = await this.productVariantService.softDelete( ctx, product.variants.map(v => v.id), ); if (variantResult.result === DeletionResult.NOT_DELETED) { await this.connection.rollBackTransaction(ctx); return variantResult; } for (const optionGroup of product.optionGroups) { if (!optionGroup.deletedAt) { const groupResult = await this.productOptionGroupService.deleteGroupAndOptionsFromProduct( ctx, optionGroup.id, productId, ); if (groupResult.result === DeletionResult.NOT_DELETED) { await this.connection.rollBackTransaction(ctx); return groupResult; } } } return { result: DeletionResult.DELETED, }; } /** * @description * Assigns a Product to the specified Channel, and optionally uses a `priceFactor` to set the ProductVariantPrices * on the new Channel. * * Internally, this method will also call {@link ProductVariantService} `assignProductVariantsToChannel()` for * each of the Product's variants, and will assign the Product's Assets to the Channel too. */ async assignProductsToChannel( ctx: RequestContext, input: AssignProductsToChannelInput, ): Promise<Array<Translated<Product>>> { const productsWithVariants = await this.connection.getRepository(ctx, Product).find({ where: { id: In(input.productIds) }, relations: ['variants', 'assets'], }); await this.productVariantService.assignProductVariantsToChannel(ctx, { productVariantIds: ([] as ID[]).concat( ...productsWithVariants.map(p => p.variants.map(v => v.id)), ), channelId: input.channelId, priceFactor: input.priceFactor, }); const assetIds: ID[] = unique( ([] as ID[]).concat(...productsWithVariants.map(p => p.assets.map(a => a.assetId))), ); await this.assetService.assignToChannel(ctx, { channelId: input.channelId, assetIds }); const products = await this.connection .getRepository(ctx, Product) .find({ where: { id: In(input.productIds) } }); for (const product of products) { await this.eventBus.publish(new ProductChannelEvent(ctx, product, input.channelId, 'assigned')); } return this.findByIds( ctx, productsWithVariants.map(p => p.id), ); } async removeProductsFromChannel( ctx: RequestContext, input: RemoveProductsFromChannelInput, ): Promise<Array<Translated<Product>>> { const productsWithVariants = await this.connection.getRepository(ctx, Product).find({ where: { id: In(input.productIds) }, relations: ['variants'], }); await this.productVariantService.removeProductVariantsFromChannel(ctx, { productVariantIds: ([] as ID[]).concat( ...productsWithVariants.map(p => p.variants.map(v => v.id)), ), channelId: input.channelId, }); const products = await this.connection .getRepository(ctx, Product) .find({ where: { id: In(input.productIds) } }); for (const product of products) { await this.eventBus.publish(new ProductChannelEvent(ctx, product, input.channelId, 'removed')); } return this.findByIds( ctx, productsWithVariants.map(p => p.id), ); } async addOptionGroupToProduct( ctx: RequestContext, productId: ID, optionGroupId: ID, ): Promise<Translated<Product>> { const product = await this.getProductWithOptionGroups(ctx, productId); const optionGroup = await this.connection.getRepository(ctx, ProductOptionGroup).findOne({ where: { id: optionGroupId }, relations: ['product'], }); if (!optionGroup) { throw new EntityNotFoundError('ProductOptionGroup', optionGroupId); } if (optionGroup.product) { const translated = this.translator.translate(optionGroup.product, ctx); throw new UserInputError('error.product-option-group-already-assigned', { groupCode: optionGroup.code, productName: translated.name, }); } if (Array.isArray(product.optionGroups)) { product.optionGroups.push(optionGroup); } else { product.optionGroups = [optionGroup]; } await this.connection.getRepository(ctx, Product).save(product, { reload: false }); await this.eventBus.publish( new ProductOptionGroupChangeEvent(ctx, product, optionGroupId, 'assigned'), ); return assertFound(this.findOne(ctx, productId)); } async removeOptionGroupFromProduct( ctx: RequestContext, productId: ID, optionGroupId: ID, force?: boolean, ): Promise<ErrorResultUnion<RemoveOptionGroupFromProductResult, Translated<Product>>> { const product = await this.getProductWithOptionGroups(ctx, productId); const optionGroup = product.optionGroups.find(g => idsAreEqual(g.id, optionGroupId)); if (!optionGroup) { throw new EntityNotFoundError('ProductOptionGroup', optionGroupId); } const optionIsInUse = product.variants.some( variant => variant.deletedAt == null && variant.options.some(option => idsAreEqual(option.groupId, optionGroupId)), ); if (optionIsInUse) { if (!force) { return new ProductOptionInUseError({ optionGroupCode: optionGroup.code, productVariantCount: product.variants.length, }); } else { // We will force the removal of this ProductOptionGroup by first // removing all ProductOptions from the ProductVariants for (const variant of product.variants) { variant.options = variant.options.filter(o => !idsAreEqual(o.groupId, optionGroupId)); } await this.connection.getRepository(ctx, ProductVariant).save(product.variants, { reload: false, }); } } const result = await this.productOptionGroupService.deleteGroupAndOptionsFromProduct( ctx, optionGroupId, productId, ); product.optionGroups = product.optionGroups.filter(g => g.id !== optionGroupId); await this.connection.getRepository(ctx, Product).save(product, { reload: false }); if (result.result === DeletionResult.NOT_DELETED) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion throw new InternalServerError(result.message!); } await this.eventBus.publish( new ProductOptionGroupChangeEvent(ctx, product, optionGroupId, 'removed'), ); return assertFound(this.findOne(ctx, productId)); } private async getProductWithOptionGroups(ctx: RequestContext, productId: ID): Promise<Product> { const product = await this.connection.getRepository(ctx, Product).findOne({ relationLoadStrategy: 'query', loadEagerRelations: false, where: { id: productId, deletedAt: IsNull() }, relations: ['optionGroups', 'variants', 'variants.options'], }); if (!product) { throw new EntityNotFoundError('Product', productId); } return product; } }
import { Injectable } from '@nestjs/common'; import { ApplyCouponCodeResult } from '@vendure/common/lib/generated-shop-types'; import { AssignPromotionsToChannelInput, ConfigurableOperation, ConfigurableOperationDefinition, CreatePromotionInput, CreatePromotionResult, DeletionResponse, DeletionResult, RemovePromotionsFromChannelInput, UpdatePromotionInput, UpdatePromotionResult, } from '@vendure/common/lib/generated-types'; import { omit } from '@vendure/common/lib/omit'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { In, IsNull } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ErrorResultUnion, JustErrorResults } from '../../common/error/error-result'; import { IllegalOperationError, UserInputError } from '../../common/error/errors'; import { MissingConditionsError } from '../../common/error/generated-graphql-admin-errors'; import { CouponCodeExpiredError, CouponCodeInvalidError, CouponCodeLimitError, } from '../../common/error/generated-graphql-shop-errors'; import { AdjustmentSource } from '../../common/types/adjustment-source'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { PromotionAction } from '../../config/promotion/promotion-action'; import { PromotionCondition } from '../../config/promotion/promotion-condition'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Order } from '../../entity/order/order.entity'; import { PromotionTranslation } from '../../entity/promotion/promotion-translation.entity'; import { Promotion } from '../../entity/promotion/promotion.entity'; import { EventBus } from '../../event-bus'; import { PromotionEvent } from '../../event-bus/events/promotion-event'; import { ConfigArgService } from '../helpers/config-arg/config-arg.service'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { OrderState } from '../helpers/order-state-machine/order-state'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { patchEntity } from '../helpers/utils/patch-entity'; import { ChannelService } from './channel.service'; /** * @description * Contains methods relating to {@link Promotion} entities. * * @docsCategory services */ @Injectable() export class PromotionService { availableConditions: PromotionCondition[] = []; availableActions: PromotionAction[] = []; constructor( private connection: TransactionalConnection, private configService: ConfigService, private channelService: ChannelService, private listQueryBuilder: ListQueryBuilder, private configArgService: ConfigArgService, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private translatableSaver: TranslatableSaver, private translator: TranslatorService, ) { this.availableConditions = this.configService.promotionOptions.promotionConditions || []; this.availableActions = this.configService.promotionOptions.promotionActions || []; } findAll( ctx: RequestContext, options?: ListQueryOptions<Promotion>, relations: RelationPaths<Promotion> = [], ): Promise<PaginatedList<Promotion>> { return this.listQueryBuilder .build(Promotion, options, { where: { deletedAt: IsNull() }, channelId: ctx.channelId, relations, ctx, }) .getManyAndCount() .then(([promotions, totalItems]) => { const items = promotions.map(promotion => this.translator.translate(promotion, ctx)); return { items, totalItems, }; }); } async findOne( ctx: RequestContext, adjustmentSourceId: ID, relations: RelationPaths<Promotion> = [], ): Promise<Promotion | undefined> { return this.connection .findOneInChannel(ctx, Promotion, adjustmentSourceId, ctx.channelId, { where: { deletedAt: IsNull() }, relations, }) .then(promotion => (promotion && this.translator.translate(promotion, ctx)) ?? undefined); } getPromotionConditions(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.availableConditions.map(x => x.toGraphQlType(ctx)); } getPromotionActions(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.availableActions.map(x => x.toGraphQlType(ctx)); } async createPromotion( ctx: RequestContext, input: CreatePromotionInput, ): Promise<ErrorResultUnion<CreatePromotionResult, Promotion>> { const conditions = input.conditions.map(c => this.configArgService.parseInput('PromotionCondition', c), ); const actions = input.actions.map(a => this.configArgService.parseInput('PromotionAction', a)); this.validateRequiredConditions(conditions, actions); if (conditions.length === 0 && !input.couponCode) { return new MissingConditionsError(); } const newPromotion = await this.translatableSaver.create({ ctx, input, entityType: Promotion, translationType: PromotionTranslation, beforeSave: async p => { p.priorityScore = this.calculatePriorityScore(input); p.conditions = conditions; p.actions = actions; await this.channelService.assignToCurrentChannel(p, ctx); }, }); const promotionWithRelations = await this.customFieldRelationService.updateRelations( ctx, Promotion, input, newPromotion, ); await this.eventBus.publish(new PromotionEvent(ctx, promotionWithRelations, 'created', input)); return assertFound(this.findOne(ctx, newPromotion.id)); } async updatePromotion( ctx: RequestContext, input: UpdatePromotionInput, ): Promise<ErrorResultUnion<UpdatePromotionResult, Promotion>> { const promotion = await this.connection.getEntityOrThrow(ctx, Promotion, input.id, { channelId: ctx.channelId, }); const hasConditions = input.conditions ? input.conditions.length > 0 : promotion.conditions.length > 0; const hasCouponCode = input.couponCode != null ? !!input.couponCode : !!promotion.couponCode; if (!hasConditions && !hasCouponCode) { return new MissingConditionsError(); } const updatedPromotion = await this.translatableSaver.update({ ctx, input, entityType: Promotion, translationType: PromotionTranslation, beforeSave: async p => { p.priorityScore = this.calculatePriorityScore(input); if (input.conditions) { p.conditions = input.conditions.map(c => this.configArgService.parseInput('PromotionCondition', c), ); } if (input.actions) { p.actions = input.actions.map(a => this.configArgService.parseInput('PromotionAction', a), ); } }, }); await this.customFieldRelationService.updateRelations(ctx, Promotion, input, updatedPromotion); await this.eventBus.publish(new PromotionEvent(ctx, promotion, 'updated', input)); return assertFound(this.findOne(ctx, updatedPromotion.id)); } async softDeletePromotion(ctx: RequestContext, promotionId: ID): Promise<DeletionResponse> { const promotion = await this.connection.getEntityOrThrow(ctx, Promotion, promotionId); await this.connection .getRepository(ctx, Promotion) .update({ id: promotionId }, { deletedAt: new Date() }); await this.eventBus.publish(new PromotionEvent(ctx, promotion, 'deleted', promotionId)); return { result: DeletionResult.DELETED, }; } async assignPromotionsToChannel( ctx: RequestContext, input: AssignPromotionsToChannelInput, ): Promise<Promotion[]> { const promotions = await this.connection.findByIdsInChannel( ctx, Promotion, input.promotionIds, ctx.channelId, {}, ); for (const promotion of promotions) { await this.channelService.assignToChannels(ctx, Promotion, promotion.id, [input.channelId]); } return promotions.map(p => this.translator.translate(p, ctx)); } async removePromotionsFromChannel(ctx: RequestContext, input: RemovePromotionsFromChannelInput) { const promotions = await this.connection.findByIdsInChannel( ctx, Promotion, input.promotionIds, ctx.channelId, {}, ); for (const promotion of promotions) { await this.channelService.removeFromChannels(ctx, Promotion, promotion.id, [input.channelId]); } return promotions.map(p => this.translator.translate(p, ctx)); } /** * @description * Checks the validity of a coupon code, by checking that it is associated with an existing, * enabled and non-expired Promotion. Additionally, if there is a usage limit on the coupon code, * this method will enforce that limit against the specified Customer. */ async validateCouponCode( ctx: RequestContext, couponCode: string, customerId?: ID, ): Promise<JustErrorResults<ApplyCouponCodeResult> | Promotion> { const promotion = await this.connection.getRepository(ctx, Promotion).findOne({ where: { couponCode, enabled: true, deletedAt: IsNull(), }, relations: ['channels'], }); if ( !promotion || promotion.couponCode !== couponCode || !promotion.channels.find(c => idsAreEqual(c.id, ctx.channelId)) ) { return new CouponCodeInvalidError({ couponCode }); } if (promotion.endsAt && +promotion.endsAt < +new Date()) { return new CouponCodeExpiredError({ couponCode }); } if (customerId && promotion.perCustomerUsageLimit != null) { const usageCount = await this.countPromotionUsagesForCustomer(ctx, promotion.id, customerId); if (promotion.perCustomerUsageLimit <= usageCount) { return new CouponCodeLimitError({ couponCode, limit: promotion.perCustomerUsageLimit }); } } if (promotion.usageLimit !== null) { const usageCount = await this.countPromotionUsages(ctx, promotion.id); if (promotion.usageLimit <= usageCount) { return new CouponCodeLimitError({ couponCode, limit: promotion.usageLimit }); } } return promotion; } getActivePromotionsInChannel(ctx: RequestContext) { return this.connection .getRepository(ctx, Promotion) .createQueryBuilder('promotion') .leftJoin('promotion.channels', 'channel') .leftJoinAndSelect('promotion.translations', 'translation') .where('channel.id = :channelId', { channelId: ctx.channelId }) .andWhere('promotion.deletedAt IS NULL') .andWhere('promotion.enabled = :enabled', { enabled: true }) .orderBy('promotion.priorityScore', 'ASC') .getMany() .then(promotions => promotions.map(p => this.translator.translate(p, ctx))); } async getActivePromotionsOnOrder(ctx: RequestContext, orderId: ID): Promise<Promotion[]> { const order = await this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .leftJoinAndSelect('order.promotions', 'promotions') .where('order.id = :orderId', { orderId }) .getOne(); return order?.promotions ?? []; } async runPromotionSideEffects(ctx: RequestContext, order: Order, promotionsPre: Promotion[]) { const promotionsPost = order.promotions; for (const activePre of promotionsPre) { if (!promotionsPost.find(p => idsAreEqual(p.id, activePre.id))) { // activePre is no longer active, so call onDeactivate await activePre.deactivate(ctx, order); } } for (const activePost of promotionsPost) { if (!promotionsPre.find(p => idsAreEqual(p.id, activePost.id))) { // activePost was not previously active, so call onActivate await activePost.activate(ctx, order); } } } /** * @description * Used internally to associate a Promotion with an Order, once an Order has been placed. * * @deprecated This method is no longer used and will be removed in v2.0 */ async addPromotionsToOrder(ctx: RequestContext, order: Order): Promise<Order> { const allPromotionIds = order.discounts.map( a => AdjustmentSource.decodeSourceId(a.adjustmentSource).id, ); const promotionIds = unique(allPromotionIds); const promotions = await this.connection .getRepository(ctx, Promotion) .find({ where: { id: In(promotionIds) } }); order.promotions = promotions; return this.connection.getRepository(ctx, Order).save(order); } private async countPromotionUsagesForCustomer( ctx: RequestContext, promotionId: ID, customerId: ID, ): Promise<number> { const qb = this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .leftJoin('order.promotions', 'promotion') .where('promotion.id = :promotionId', { promotionId }) .andWhere('order.customer = :customerId', { customerId }) .andWhere('order.state != :state', { state: 'Cancelled' as OrderState }) .andWhere('order.active = :active', { active: false }); return qb.getCount(); } private async countPromotionUsages(ctx: RequestContext, promotionId: ID): Promise<number> { const qb = this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .leftJoin('order.promotions', 'promotion') .where('promotion.id = :promotionId', { promotionId }) .andWhere('order.state != :state', { state: 'Cancelled' as OrderState }) .andWhere('order.active = :active', { active: false }); return qb.getCount(); } private calculatePriorityScore(input: CreatePromotionInput | UpdatePromotionInput): number { const conditions = input.conditions ? input.conditions.map(c => this.configArgService.getByCode('PromotionCondition', c.code)) : []; const actions = input.actions ? input.actions.map(c => this.configArgService.getByCode('PromotionAction', c.code)) : []; return [...conditions, ...actions].reduce((score, op) => score + op.priorityValue, 0); } private validateRequiredConditions( conditions: ConfigurableOperation[], actions: ConfigurableOperation[], ) { const conditionCodes: Record<string, string> = conditions.reduce( (codeMap, { code }) => ({ ...codeMap, [code]: code }), {}, ); for (const { code: actionCode } of actions) { const actionDef = this.configArgService.getByCode('PromotionAction', actionCode); const actionDependencies: PromotionCondition[] = actionDef.conditions || []; if (!actionDependencies || actionDependencies.length === 0) { continue; } const missingConditions = actionDependencies.filter(condition => !conditionCodes[condition.code]); if (missingConditions.length) { throw new UserInputError('error.conditions-required-for-action', { action: actionCode, conditions: missingConditions.map(c => c.code).join(', '), }); } } } }
import { Injectable } from '@nestjs/common'; import { CreateProvinceInput, DeletionResponse, DeletionResult, UpdateProvinceInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList, Type } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Province } from '../../entity/region/province.entity'; import { RegionTranslation } from '../../entity/region/region-translation.entity'; import { Region } from '../../entity/region/region.entity'; import { EventBus } from '../../event-bus'; import { ProvinceEvent } from '../../event-bus/events/province-event'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; /** * @description * Contains methods relating to {@link Province} entities. * * @docsCategory services */ @Injectable() export class ProvinceService { constructor( private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder, private translatableSaver: TranslatableSaver, private eventBus: EventBus, private translator: TranslatorService, ) {} findAll( ctx: RequestContext, options?: ListQueryOptions<Province>, relations: RelationPaths<Province> = [], ): Promise<PaginatedList<Translated<Province>>> { return this.listQueryBuilder .build(Province as Type<Province>, options, { ctx, relations }) .getManyAndCount() .then(([provinces, totalItems]) => { const items = provinces.map(province => this.translator.translate(province, ctx)); return { items, totalItems, }; }); } findOne( ctx: RequestContext, provinceId: ID, relations: RelationPaths<Province> = [], ): Promise<Translated<Province> | undefined> { return this.connection .getRepository(ctx, Province) .findOne({ where: { id: provinceId }, relations }) .then(province => (province && this.translator.translate(province, ctx)) ?? undefined); } async create(ctx: RequestContext, input: CreateProvinceInput): Promise<Translated<Province>> { const province = await this.translatableSaver.create({ ctx, input, entityType: Province as Type<Region>, translationType: RegionTranslation, }); await this.eventBus.publish(new ProvinceEvent(ctx, province, 'created', input)); return assertFound(this.findOne(ctx, province.id)); } async update(ctx: RequestContext, input: UpdateProvinceInput): Promise<Translated<Province>> { const province = await this.translatableSaver.update({ ctx, input, entityType: Province as Type<Region>, translationType: RegionTranslation, }); await this.eventBus.publish(new ProvinceEvent(ctx, province, 'updated', input)); return assertFound(this.findOne(ctx, province.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const region = await this.connection.getEntityOrThrow(ctx, Province as Type<Province>, id); const deletedProvince = new Province(region); await this.connection.getRepository(ctx, Province).remove(region); await this.eventBus.publish(new ProvinceEvent(ctx, deletedProvince, 'deleted', id)); return { result: DeletionResult.DELETED, message: '', }; } }
import { Injectable } from '@nestjs/common'; import { CreateRoleInput, DeletionResponse, DeletionResult, Permission, UpdateRoleInput, } from '@vendure/common/lib/generated-types'; import { CUSTOMER_ROLE_CODE, CUSTOMER_ROLE_DESCRIPTION, SUPER_ADMIN_ROLE_CODE, SUPER_ADMIN_ROLE_DESCRIPTION, } from '@vendure/common/lib/shared-constants'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { getAllPermissionsMetadata } from '../../common/constants'; import { EntityNotFoundError, ForbiddenError, InternalServerError, UserInputError, } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Channel } from '../../entity/channel/channel.entity'; import { Role } from '../../entity/role/role.entity'; import { User } from '../../entity/user/user.entity'; import { EventBus } from '../../event-bus'; import { RoleEvent } from '../../event-bus/events/role-event'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { getChannelPermissions, getUserChannelsPermissions, } from '../helpers/utils/get-user-channels-permissions'; import { patchEntity } from '../helpers/utils/patch-entity'; import { ChannelService } from './channel.service'; /** * @description * Contains methods relating to {@link Role} entities. * * @docsCategory services */ @Injectable() export class RoleService { constructor( private connection: TransactionalConnection, private channelService: ChannelService, private listQueryBuilder: ListQueryBuilder, private configService: ConfigService, private eventBus: EventBus, ) {} async initRoles() { await this.ensureSuperAdminRoleExists(); await this.ensureCustomerRoleExists(); await this.ensureRolesHaveValidPermissions(); } findAll( ctx: RequestContext, options?: ListQueryOptions<Role>, relations?: RelationPaths<Role>, ): Promise<PaginatedList<Role>> { return this.listQueryBuilder .build(Role, options, { relations: unique([...(relations ?? []), 'channels']), ctx }) .getManyAndCount() .then(async ([items, totalItems]) => { const visibleRoles: Role[] = []; for (const item of items) { const canRead = await this.activeUserCanReadRole(ctx, item); if (canRead) { visibleRoles.push(item); } } return { items: visibleRoles, totalItems, }; }); } findOne(ctx: RequestContext, roleId: ID, relations?: RelationPaths<Role>): Promise<Role | undefined> { return this.connection .getRepository(ctx, Role) .findOne({ where: { id: roleId }, relations: unique([...(relations ?? []), 'channels']), }) .then(async result => { if (result && (await this.activeUserCanReadRole(ctx, result))) { return result; } }); } getChannelsForRole(ctx: RequestContext, roleId: ID): Promise<Channel[]> { return this.findOne(ctx, roleId).then(role => (role ? role.channels : [])); } /** * @description * Returns the special SuperAdmin Role, which always exists in Vendure. */ getSuperAdminRole(ctx?: RequestContext): Promise<Role> { return this.getRoleByCode(ctx, SUPER_ADMIN_ROLE_CODE).then(role => { if (!role) { throw new InternalServerError('error.super-admin-role-not-found'); } return role; }); } /** * @description * Returns the special Customer Role, which always exists in Vendure. */ getCustomerRole(ctx?: RequestContext): Promise<Role> { return this.getRoleByCode(ctx, CUSTOMER_ROLE_CODE).then(role => { if (!role) { throw new InternalServerError('error.customer-role-not-found'); } return role; }); } /** * @description * Returns all the valid Permission values */ getAllPermissions(): string[] { return Object.values(Permission); } /** * @description * Returns true if the User has the specified permission on that Channel */ async userHasPermissionOnChannel( ctx: RequestContext, channelId: ID, permission: Permission, ): Promise<boolean> { return this.userHasAnyPermissionsOnChannel(ctx, channelId, [permission]); } /** * @description * Returns true if the User has any of the specified permissions on that Channel */ async userHasAnyPermissionsOnChannel( ctx: RequestContext, channelId: ID, permissions: Permission[], ): Promise<boolean> { const permissionsOnChannel = await this.getActiveUserPermissionsOnChannel(ctx, channelId); for (const permission of permissions) { if (permissionsOnChannel.includes(permission)) { return true; } } return false; } private async activeUserCanReadRole(ctx: RequestContext, role: Role): Promise<boolean> { const permissionsRequired = getChannelPermissions([role]); for (const channelPermissions of permissionsRequired) { const activeUserHasRequiredPermissions = await this.userHasAllPermissionsOnChannel( ctx, channelPermissions.id, channelPermissions.permissions, ); if (!activeUserHasRequiredPermissions) { return false; } } return true; } /** * @description * Returns true if the User has all the specified permissions on that Channel */ async userHasAllPermissionsOnChannel( ctx: RequestContext, channelId: ID, permissions: Permission[], ): Promise<boolean> { const permissionsOnChannel = await this.getActiveUserPermissionsOnChannel(ctx, channelId); for (const permission of permissions) { if (!permissionsOnChannel.includes(permission)) { return false; } } return true; } private async getActiveUserPermissionsOnChannel( ctx: RequestContext, channelId: ID, ): Promise<Permission[]> { if (ctx.activeUserId == null) { return []; } const user = await this.connection.getEntityOrThrow(ctx, User, ctx.activeUserId, { relations: ['roles', 'roles.channels'], }); const userChannels = getUserChannelsPermissions(user); const channel = userChannels.find(c => idsAreEqual(c.id, channelId)); if (!channel) { return []; } return channel.permissions; } async create(ctx: RequestContext, input: CreateRoleInput): Promise<Role> { this.checkPermissionsAreValid(input.permissions); let targetChannels: Channel[] = []; if (input.channelIds) { targetChannels = await this.getPermittedChannels(ctx, input.channelIds); } else { targetChannels = [ctx.channel]; } await this.checkActiveUserHasSufficientPermissions(ctx, targetChannels, input.permissions); const role = await this.createRoleForChannels(ctx, input, targetChannels); await this.eventBus.publish(new RoleEvent(ctx, role, 'created', input)); return role; } async update(ctx: RequestContext, input: UpdateRoleInput): Promise<Role> { this.checkPermissionsAreValid(input.permissions); const role = await this.findOne(ctx, input.id); if (!role) { throw new EntityNotFoundError('Role', input.id); } if (role.code === SUPER_ADMIN_ROLE_CODE || role.code === CUSTOMER_ROLE_CODE) { throw new InternalServerError('error.cannot-modify-role', { roleCode: role.code }); } const targetChannels = input.channelIds ? await this.getPermittedChannels(ctx, input.channelIds) : undefined; if (input.permissions) { await this.checkActiveUserHasSufficientPermissions( ctx, targetChannels ?? role.channels, input.permissions, ); } const updatedRole = patchEntity(role, { code: input.code, description: input.description, permissions: input.permissions ? unique([Permission.Authenticated, ...input.permissions]) : undefined, }); if (targetChannels) { updatedRole.channels = targetChannels; } await this.connection.getRepository(ctx, Role).save(updatedRole, { reload: false }); await this.eventBus.publish(new RoleEvent(ctx, role, 'updated', input)); return await assertFound(this.findOne(ctx, role.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const role = await this.findOne(ctx, id); if (!role) { throw new EntityNotFoundError('Role', id); } if (role.code === SUPER_ADMIN_ROLE_CODE || role.code === CUSTOMER_ROLE_CODE) { throw new InternalServerError('error.cannot-delete-role', { roleCode: role.code }); } const deletedRole = new Role(role); await this.connection.getRepository(ctx, Role).remove(role); await this.eventBus.publish(new RoleEvent(ctx, deletedRole, 'deleted', id)); return { result: DeletionResult.DELETED, }; } async assignRoleToChannel(ctx: RequestContext, roleId: ID, channelId: ID) { await this.channelService.assignToChannels(ctx, Role, roleId, [channelId]); } private async getPermittedChannels(ctx: RequestContext, channelIds: ID[]): Promise<Channel[]> { let permittedChannels: Channel[] = []; for (const channelId of channelIds) { const channel = await this.connection.getEntityOrThrow(ctx, Channel, channelId); const hasPermission = await this.userHasPermissionOnChannel( ctx, channelId, Permission.CreateAdministrator, ); if (!hasPermission) { throw new ForbiddenError(); } permittedChannels = [...permittedChannels, channel]; } return permittedChannels; } private checkPermissionsAreValid(permissions?: Permission[] | null) { if (!permissions) { return; } const allAssignablePermissions = this.getAllAssignablePermissions(); for (const permission of permissions) { if (!allAssignablePermissions.includes(permission) || permission === Permission.SuperAdmin) { throw new UserInputError('error.permission-invalid', { permission }); } } } /** * @description * Checks that the active User has sufficient Permissions on the target Channels to create * a Role with the given Permissions. The rule is that an Administrator may only grant * Permissions that they themselves already possess. */ private async checkActiveUserHasSufficientPermissions( ctx: RequestContext, targetChannels: Channel[], permissions: Permission[], ) { const permissionsRequired = getChannelPermissions([ new Role({ permissions: unique([Permission.Authenticated, ...permissions]), channels: targetChannels, }), ]); for (const channelPermissions of permissionsRequired) { const activeUserHasRequiredPermissions = await this.userHasAllPermissionsOnChannel( ctx, channelPermissions.id, channelPermissions.permissions, ); if (!activeUserHasRequiredPermissions) { throw new UserInputError('error.active-user-does-not-have-sufficient-permissions'); } } } private getRoleByCode(ctx: RequestContext | undefined, code: string) { const repository = ctx ? this.connection.getRepository(ctx, Role) : this.connection.rawConnection.getRepository(Role); return repository.findOne({ where: { code }, }); } /** * Ensure that the SuperAdmin role exists and that it has all possible Permissions. */ private async ensureSuperAdminRoleExists() { const assignablePermissions = this.getAllAssignablePermissions(); try { const superAdminRole = await this.getSuperAdminRole(); superAdminRole.permissions = assignablePermissions; await this.connection.rawConnection.getRepository(Role).save(superAdminRole, { reload: false }); } catch (err: any) { const defaultChannel = await this.channelService.getDefaultChannel(); await this.createRoleForChannels( RequestContext.empty(), { code: SUPER_ADMIN_ROLE_CODE, description: SUPER_ADMIN_ROLE_DESCRIPTION, permissions: assignablePermissions, }, [defaultChannel], ); } } /** * The Customer Role is a special case which must always exist. */ private async ensureCustomerRoleExists() { try { await this.getCustomerRole(); } catch (err: any) { const defaultChannel = await this.channelService.getDefaultChannel(); await this.createRoleForChannels( RequestContext.empty(), { code: CUSTOMER_ROLE_CODE, description: CUSTOMER_ROLE_DESCRIPTION, permissions: [Permission.Authenticated], }, [defaultChannel], ); } } /** * Since custom permissions can be added and removed by config, there may exist one or more Roles with * invalid permissions (i.e. permissions that were set previously to a custom permission, which has been * subsequently removed from config). This method should run on startup to ensure that any such invalid * permissions are removed from those Roles. */ private async ensureRolesHaveValidPermissions() { const roles = await this.connection.rawConnection.getRepository(Role).find(); const assignablePermissions = this.getAllAssignablePermissions(); for (const role of roles) { const invalidPermissions = role.permissions.filter(p => !assignablePermissions.includes(p)); if (invalidPermissions.length) { role.permissions = role.permissions.filter(p => assignablePermissions.includes(p)); await this.connection.rawConnection.getRepository(Role).save(role); } } } private createRoleForChannels(ctx: RequestContext, input: CreateRoleInput, channels: Channel[]) { const role = new Role({ code: input.code, description: input.description, permissions: unique([Permission.Authenticated, ...input.permissions]), }); role.channels = channels; return this.connection.getRepository(ctx, Role).save(role); } private getAllAssignablePermissions(): Permission[] { return getAllPermissionsMetadata(this.configService.authOptions.customPermissions) .filter(p => p.assignable) .map(p => p.name as Permission); } }
import { Injectable } from '@nestjs/common'; import { JobState } from '@vendure/common/lib/generated-types'; import { RequestContext } from '../../api/common/request-context'; import { Logger } from '../../config/logger/vendure-logger'; import { Job } from '../../job-queue/job'; /** * @description * This service allows a concrete search service to override its behaviour * by passing itself to the `adopt()` method. * * @docsCategory services */ @Injectable() export class SearchService { private override: Pick<SearchService, 'reindex'> | undefined; /** * @description * Adopt a concrete search service implementation to pass through the * calls to. */ adopt(override: Pick<SearchService, 'reindex'>) { this.override = override; } async reindex(ctx: RequestContext): Promise<Job> { if (this.override) { return this.override.reindex(ctx); } if (!process.env.CI) { Logger.warn('The SearchService should be overridden by an appropriate search plugin.'); } return new Job({ queueName: 'error', data: {}, id: 'error', state: JobState.FAILED, progress: 0, }); } }
import { Injectable } from '@nestjs/common'; import { CreateSellerInput, DeletionResponse, DeletionResult, UpdateSellerInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Seller } from '../../entity/seller/seller.entity'; import { EventBus, SellerEvent } from '../../event-bus/index'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { patchEntity } from '../helpers/utils/patch-entity'; /** * @description * Contains methods relating to {@link Seller} entities. * * @docsCategory services */ @Injectable() export class SellerService { constructor( private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder, private eventBus: EventBus, private customFieldRelationService: CustomFieldRelationService, ) {} async initSellers() { await this.ensureDefaultSellerExists(); } findAll(ctx: RequestContext, options?: ListQueryOptions<Seller>): Promise<PaginatedList<Seller>> { return this.listQueryBuilder .build(Seller, options, { ctx }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } findOne(ctx: RequestContext, sellerId: ID): Promise<Seller | undefined> { return this.connection .getRepository(ctx, Seller) .findOne({ where: { id: sellerId } }) .then(result => result ?? undefined); } async create(ctx: RequestContext, input: CreateSellerInput) { const seller = await this.connection.getRepository(ctx, Seller).save(new Seller(input)); const sellerWithRelations = await this.customFieldRelationService.updateRelations( ctx, Seller, input, seller, ); await this.eventBus.publish(new SellerEvent(ctx, sellerWithRelations, 'created', input)); return assertFound(this.findOne(ctx, seller.id)); } async update(ctx: RequestContext, input: UpdateSellerInput) { const seller = await this.connection.getEntityOrThrow(ctx, Seller, input.id); const updatedSeller = patchEntity(seller, input); await this.connection.getRepository(ctx, Seller).save(updatedSeller); const sellerWithRelations = await this.customFieldRelationService.updateRelations( ctx, Seller, input, seller, ); await this.eventBus.publish(new SellerEvent(ctx, sellerWithRelations, 'updated', input)); return seller; } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const seller = await this.connection.getEntityOrThrow(ctx, Seller, id); await this.connection.getRepository(ctx, Seller).remove(seller); const deletedSeller = new Seller(seller); await this.eventBus.publish(new SellerEvent(ctx, deletedSeller, 'deleted', id)); return { result: DeletionResult.DELETED, }; } private async ensureDefaultSellerExists() { const sellers = await this.connection.rawConnection.getRepository(Seller).find(); if (sellers.length === 0) { await this.connection.rawConnection.getRepository(Seller).save( new Seller({ name: 'Default Seller', }), ); } } }
import { Injectable } from '@nestjs/common'; import { ID } from '@vendure/common/lib/shared-types'; import crypto from 'crypto'; import ms from 'ms'; import { EntitySubscriberInterface, InsertEvent, RemoveEvent, UpdateEvent } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { ConfigService } from '../../config/config.service'; import { CachedSession, SessionCacheStrategy } from '../../config/session-cache/session-cache-strategy'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Channel } from '../../entity/channel/channel.entity'; import { Order } from '../../entity/order/order.entity'; import { Role } from '../../entity/role/role.entity'; import { AnonymousSession } from '../../entity/session/anonymous-session.entity'; import { AuthenticatedSession } from '../../entity/session/authenticated-session.entity'; import { Session } from '../../entity/session/session.entity'; import { User } from '../../entity/user/user.entity'; import { getUserChannelsPermissions } from '../helpers/utils/get-user-channels-permissions'; import { OrderService } from './order.service'; /** * @description * Contains methods relating to {@link Session} entities. * * @docsCategory services */ @Injectable() export class SessionService implements EntitySubscriberInterface { private sessionCacheStrategy: SessionCacheStrategy; private readonly sessionDurationInMs: number; private readonly sessionCacheTimeoutMs = 50; constructor( private connection: TransactionalConnection, private configService: ConfigService, private orderService: OrderService, ) { this.sessionCacheStrategy = this.configService.authOptions.sessionCacheStrategy; this.sessionDurationInMs = ms(this.configService.authOptions.sessionDuration as string); // This allows us to register this class as a TypeORM Subscriber while also allowing // the injection on dependencies. See https://docs.nestjs.com/techniques/database#subscribers this.connection.rawConnection.subscribers.push(this); } /** @internal */ async afterInsert(event: InsertEvent<any>): Promise<any> { await this.clearSessionCacheOnDataChange(event); } /** @internal */ async afterRemove(event: RemoveEvent<any>): Promise<any> { await this.clearSessionCacheOnDataChange(event); } /** @internal */ async afterUpdate(event: UpdateEvent<any>): Promise<any> { await this.clearSessionCacheOnDataChange(event); } private async clearSessionCacheOnDataChange( event: InsertEvent<any> | RemoveEvent<any> | UpdateEvent<any>, ) { if (event.entity) { // If a Channel or Role changes, potentially all the cached permissions in the // session cache will be wrong, so we just clear the entire cache. It should however // be a very rare occurrence in normal operation, once initial setup is complete. if (event.entity instanceof Channel || event.entity instanceof Role) { await this.withTimeout(this.sessionCacheStrategy.clear()); } } } /** * @description * Creates a new {@link AuthenticatedSession}. To be used after successful authentication. */ async createNewAuthenticatedSession( ctx: RequestContext, user: User, authenticationStrategyName: string, ): Promise<AuthenticatedSession> { const token = await this.generateSessionToken(); const guestOrder = ctx.session && ctx.session.activeOrderId ? await this.orderService.findOne(ctx, ctx.session.activeOrderId) : undefined; const existingOrder = await this.orderService.getActiveOrderForUser(ctx, user.id); const activeOrder = await this.orderService.mergeOrders(ctx, user, guestOrder, existingOrder); const authenticatedSession = await this.connection.getRepository(ctx, AuthenticatedSession).save( new AuthenticatedSession({ token, user, activeOrder, authenticationStrategy: authenticationStrategyName, expires: this.getExpiryDate(this.sessionDurationInMs), invalidated: false, }), ); await this.withTimeout(this.sessionCacheStrategy.set(this.serializeSession(authenticatedSession))); return authenticatedSession; } /** * @description * Create an {@link AnonymousSession} and caches it using the configured {@link SessionCacheStrategy}, * and returns the cached session object. */ async createAnonymousSession(): Promise<CachedSession> { const token = await this.generateSessionToken(); const session = new AnonymousSession({ token, expires: this.getExpiryDate(this.sessionDurationInMs), invalidated: false, }); // save the new session const newSession = await this.connection.rawConnection.getRepository(AnonymousSession).save(session); const serializedSession = this.serializeSession(newSession); await this.withTimeout(this.sessionCacheStrategy.set(serializedSession)); return serializedSession; } /** * @description * Returns the cached session object matching the given session token. */ async getSessionFromToken(sessionToken: string): Promise<CachedSession | undefined> { let serializedSession = await this.withTimeout(this.sessionCacheStrategy.get(sessionToken)); const stale = !!(serializedSession && serializedSession.cacheExpiry < new Date().getTime() / 1000); const expired = !!(serializedSession && serializedSession.expires < new Date()); if (!serializedSession || stale || expired) { const session = await this.findSessionByToken(sessionToken); if (session) { serializedSession = this.serializeSession(session); await this.withTimeout(this.sessionCacheStrategy.set(serializedSession)); return serializedSession; } else { return; } } return serializedSession; } /** * @description * Serializes a {@link Session} instance into a simplified plain object suitable for caching. */ serializeSession(session: AuthenticatedSession | AnonymousSession): CachedSession { const expiry = Math.floor(new Date().getTime() / 1000) + this.configService.authOptions.sessionCacheTTL; const serializedSession: CachedSession = { cacheExpiry: expiry, id: session.id, token: session.token, expires: session.expires, activeOrderId: session.activeOrderId, activeChannelId: session.activeChannelId, }; if (this.isAuthenticatedSession(session)) { serializedSession.authenticationStrategy = session.authenticationStrategy; const { user } = session; serializedSession.user = { id: user.id, identifier: user.identifier, verified: user.verified, channelPermissions: getUserChannelsPermissions(user), }; } return serializedSession; } /** * If the session cache is taking longer than say 50ms then something is wrong - it is supposed to * be very fast after all! So we will return undefined and let the request continue without a cached session. */ private withTimeout<T>(maybeSlow: Promise<T> | T): Promise<T | undefined> { return Promise.race([ new Promise<undefined>(resolve => setTimeout(() => resolve(undefined), this.sessionCacheTimeoutMs), ), maybeSlow, ]); } /** * Looks for a valid session with the given token and returns one if found. */ private async findSessionByToken(token: string): Promise<Session | undefined> { const session = await this.connection.rawConnection .getRepository(Session) .createQueryBuilder('session') .leftJoinAndSelect('session.user', 'user') .leftJoinAndSelect('user.roles', 'roles') .leftJoinAndSelect('roles.channels', 'channels') .where('session.token = :token', { token }) .andWhere('session.invalidated = false') .getOne(); if (session && session.expires > new Date()) { await this.updateSessionExpiry(session); return session; } } /** * @description * Sets the `activeOrder` on the given cached session object and updates the cache. */ async setActiveOrder( ctx: RequestContext, serializedSession: CachedSession, order: Order, ): Promise<CachedSession> { const session = await this.connection.getRepository(ctx, Session).findOne({ where: { id: serializedSession.id }, relations: ['user', 'user.roles', 'user.roles.channels'], }); if (session) { session.activeOrder = order; await this.connection.getRepository(ctx, Session).save(session, { reload: false }); const updatedSerializedSession = this.serializeSession(session); await this.withTimeout(this.sessionCacheStrategy.set(updatedSerializedSession)); return updatedSerializedSession; } return serializedSession; } /** * @description * Clears the `activeOrder` on the given cached session object and updates the cache. */ async unsetActiveOrder(ctx: RequestContext, serializedSession: CachedSession): Promise<CachedSession> { if (serializedSession.activeOrderId) { const session = await this.connection.getRepository(ctx, Session).findOne({ where: { id: serializedSession.id }, relations: ['user', 'user.roles', 'user.roles.channels'], }); if (session) { session.activeOrder = null; await this.connection.getRepository(ctx, Session).save(session); const updatedSerializedSession = this.serializeSession(session); await this.configService.authOptions.sessionCacheStrategy.set(updatedSerializedSession); return updatedSerializedSession; } } return serializedSession; } /** * @description * Sets the `activeChannel` on the given cached session object and updates the cache. */ async setActiveChannel(serializedSession: CachedSession, channel: Channel): Promise<CachedSession> { const session = await this.connection.rawConnection.getRepository(Session).findOne({ where: { id: serializedSession.id }, relations: ['user', 'user.roles', 'user.roles.channels'], }); if (session) { session.activeChannel = channel; await this.connection.rawConnection.getRepository(Session).save(session, { reload: false }); const updatedSerializedSession = this.serializeSession(session); await this.withTimeout(this.sessionCacheStrategy.set(updatedSerializedSession)); return updatedSerializedSession; } return serializedSession; } /** * @description * Deletes all existing sessions for the given user. */ async deleteSessionsByUser(ctx: RequestContext, user: User): Promise<void> { const userSessions = await this.connection .getRepository(ctx, AuthenticatedSession) .find({ where: { user: { id: user.id } } }); await this.connection.getRepository(ctx, AuthenticatedSession).remove(userSessions); for (const session of userSessions) { await this.withTimeout(this.sessionCacheStrategy.delete(session.token)); } } /** * @description * Deletes all existing sessions with the given activeOrder. */ async deleteSessionsByActiveOrderId(ctx: RequestContext, activeOrderId: ID): Promise<void> { const sessions = await this.connection.getRepository(ctx, Session).find({ where: { activeOrderId } }); await this.connection.getRepository(ctx, Session).remove(sessions); for (const session of sessions) { await this.withTimeout(this.sessionCacheStrategy.delete(session.token)); } } /** * If we are over half way to the current session's expiry date, then we update it. * * This ensures that the session will not expire when in active use, but prevents us from * needing to run an update query on *every* request. */ private async updateSessionExpiry(session: Session) { const now = new Date().getTime(); if (session.expires.getTime() - now < this.sessionDurationInMs / 2) { const newExpiryDate = this.getExpiryDate(this.sessionDurationInMs); session.expires = newExpiryDate; await this.connection.rawConnection .getRepository(Session) .update({ id: session.id }, { expires: newExpiryDate }); } } /** * Returns a future expiry date according timeToExpireInMs in the future. */ private getExpiryDate(timeToExpireInMs: number): Date { return new Date(Date.now() + timeToExpireInMs); } /** * Generates a random session token. */ private generateSessionToken(): Promise<string> { return new Promise((resolve, reject) => { crypto.randomBytes(32, (err, buf) => { if (err) { reject(err); } resolve(buf.toString('hex')); }); }); } private isAuthenticatedSession(session: Session): session is AuthenticatedSession { return session.hasOwnProperty('user'); } }
import { Injectable } from '@nestjs/common'; import { AssignShippingMethodsToChannelInput, ConfigurableOperationDefinition, CreateShippingMethodInput, DeletionResponse, DeletionResult, Permission, RemoveShippingMethodsFromChannelInput, UpdateShippingMethodInput, } from '@vendure/common/lib/generated-types'; import { omit } from '@vendure/common/lib/omit'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { IsNull } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { EntityNotFoundError, ForbiddenError, UserInputError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { Translated } from '../../common/types/locale-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { Logger } from '../../config/logger/vendure-logger'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { ShippingMethodTranslation } from '../../entity/shipping-method/shipping-method-translation.entity'; import { ShippingMethod } from '../../entity/shipping-method/shipping-method.entity'; import { EventBus } from '../../event-bus'; import { ShippingMethodEvent } from '../../event-bus/events/shipping-method-event'; import { ConfigArgService } from '../helpers/config-arg/config-arg.service'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatableSaver } from '../helpers/translatable-saver/translatable-saver'; import { TranslatorService } from '../helpers/translator/translator.service'; import { ChannelService } from './channel.service'; import { RoleService } from './role.service'; /** * @description * Contains methods relating to {@link ShippingMethod} entities. * * @docsCategory services */ @Injectable() export class ShippingMethodService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private roleService: RoleService, private listQueryBuilder: ListQueryBuilder, private channelService: ChannelService, private configArgService: ConfigArgService, private translatableSaver: TranslatableSaver, private customFieldRelationService: CustomFieldRelationService, private eventBus: EventBus, private translator: TranslatorService, ) {} /** @internal */ async initShippingMethods() { if (this.configService.shippingOptions.fulfillmentHandlers.length === 0) { throw new Error( 'No FulfillmentHandlers were found.' + ' Please ensure the VendureConfig.shippingOptions.fulfillmentHandlers array contains at least one FulfillmentHandler.', ); } await this.verifyShippingMethods(); } findAll( ctx: RequestContext, options?: ListQueryOptions<ShippingMethod>, relations: RelationPaths<ShippingMethod> = [], ): Promise<PaginatedList<Translated<ShippingMethod>>> { return this.listQueryBuilder .build(ShippingMethod, options, { relations, where: { deletedAt: IsNull() }, channelId: ctx.channelId, ctx, }) .getManyAndCount() .then(([items, totalItems]) => ({ items: items.map(i => this.translator.translate(i, ctx)), totalItems, })); } async findOne( ctx: RequestContext, shippingMethodId: ID, includeDeleted = false, relations: RelationPaths<ShippingMethod> = [], ): Promise<Translated<ShippingMethod> | undefined> { const shippingMethod = await this.connection.findOneInChannel( ctx, ShippingMethod, shippingMethodId, ctx.channelId, { relations, ...(includeDeleted === false ? { where: { deletedAt: IsNull() } } : {}), }, ); return (shippingMethod && this.translator.translate(shippingMethod, ctx)) ?? undefined; } async create(ctx: RequestContext, input: CreateShippingMethodInput): Promise<Translated<ShippingMethod>> { const shippingMethod = await this.translatableSaver.create({ ctx, input, entityType: ShippingMethod, translationType: ShippingMethodTranslation, beforeSave: method => { method.fulfillmentHandlerCode = this.ensureValidFulfillmentHandlerCode( method.code, input.fulfillmentHandler, ); method.checker = this.configArgService.parseInput( 'ShippingEligibilityChecker', input.checker, ); method.calculator = this.configArgService.parseInput('ShippingCalculator', input.calculator); }, }); await this.channelService.assignToCurrentChannel(shippingMethod, ctx); const newShippingMethod = await this.connection .getRepository(ctx, ShippingMethod) .save(shippingMethod); const shippingMethodWithRelations = await this.customFieldRelationService.updateRelations( ctx, ShippingMethod, input, newShippingMethod, ); await this.eventBus.publish( new ShippingMethodEvent(ctx, shippingMethodWithRelations, 'created', input), ); return assertFound(this.findOne(ctx, newShippingMethod.id)); } async update(ctx: RequestContext, input: UpdateShippingMethodInput): Promise<Translated<ShippingMethod>> { const shippingMethod = await this.findOne(ctx, input.id); if (!shippingMethod) { throw new EntityNotFoundError('ShippingMethod', input.id); } const updatedShippingMethod = await this.translatableSaver.update({ ctx, input: omit(input, ['checker', 'calculator']), entityType: ShippingMethod, translationType: ShippingMethodTranslation, }); if (input.checker) { updatedShippingMethod.checker = this.configArgService.parseInput( 'ShippingEligibilityChecker', input.checker, ); } if (input.calculator) { updatedShippingMethod.calculator = this.configArgService.parseInput( 'ShippingCalculator', input.calculator, ); } if (input.fulfillmentHandler) { updatedShippingMethod.fulfillmentHandlerCode = this.ensureValidFulfillmentHandlerCode( updatedShippingMethod.code, input.fulfillmentHandler, ); } await this.connection .getRepository(ctx, ShippingMethod) .save(updatedShippingMethod, { reload: false }); await this.customFieldRelationService.updateRelations( ctx, ShippingMethod, input, updatedShippingMethod, ); await this.eventBus.publish(new ShippingMethodEvent(ctx, shippingMethod, 'updated', input)); return assertFound(this.findOne(ctx, shippingMethod.id)); } async softDelete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const shippingMethod = await this.connection.getEntityOrThrow(ctx, ShippingMethod, id, { channelId: ctx.channelId, where: { deletedAt: IsNull() }, }); shippingMethod.deletedAt = new Date(); await this.connection.getRepository(ctx, ShippingMethod).save(shippingMethod, { reload: false }); await this.eventBus.publish(new ShippingMethodEvent(ctx, shippingMethod, 'deleted', id)); return { result: DeletionResult.DELETED, }; } async assignShippingMethodsToChannel( ctx: RequestContext, input: AssignShippingMethodsToChannelInput, ): Promise<Array<Translated<ShippingMethod>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.UpdateShippingMethod, Permission.UpdateSettings, ]); if (!hasPermission) { throw new ForbiddenError(); } for (const shippingMethodId of input.shippingMethodIds) { const shippingMethod = await this.connection.findOneInChannel( ctx, ShippingMethod, shippingMethodId, ctx.channelId, ); await this.channelService.assignToChannels(ctx, ShippingMethod, shippingMethodId, [ input.channelId, ]); } return this.connection .findByIdsInChannel(ctx, ShippingMethod, input.shippingMethodIds, ctx.channelId, {}) .then(methods => methods.map(method => this.translator.translate(method, ctx))); } async removeShippingMethodsFromChannel( ctx: RequestContext, input: RemoveShippingMethodsFromChannelInput, ): Promise<Array<Translated<ShippingMethod>>> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.DeleteShippingMethod, Permission.DeleteSettings, ]); if (!hasPermission) { throw new ForbiddenError(); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); if (idsAreEqual(input.channelId, defaultChannel.id)) { throw new UserInputError('error.items-cannot-be-removed-from-default-channel'); } for (const shippingMethodId of input.shippingMethodIds) { const shippingMethod = await this.connection.getEntityOrThrow( ctx, ShippingMethod, shippingMethodId, ); await this.channelService.removeFromChannels(ctx, ShippingMethod, shippingMethodId, [ input.channelId, ]); } return this.connection .findByIdsInChannel(ctx, ShippingMethod, input.shippingMethodIds, ctx.channelId, {}) .then(methods => methods.map(method => this.translator.translate(method, ctx))); } getShippingEligibilityCheckers(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.configArgService .getDefinitions('ShippingEligibilityChecker') .map(x => x.toGraphQlType(ctx)); } getShippingCalculators(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.configArgService.getDefinitions('ShippingCalculator').map(x => x.toGraphQlType(ctx)); } getFulfillmentHandlers(ctx: RequestContext): ConfigurableOperationDefinition[] { return this.configArgService.getDefinitions('FulfillmentHandler').map(x => x.toGraphQlType(ctx)); } async getActiveShippingMethods(ctx: RequestContext): Promise<ShippingMethod[]> { const shippingMethods = await this.connection.getRepository(ctx, ShippingMethod).find({ relations: ['channels'], where: { deletedAt: IsNull() }, }); return shippingMethods .filter(sm => sm.channels.find(c => idsAreEqual(c.id, ctx.channelId))) .map(m => this.translator.translate(m, ctx)); } /** * Ensures that all ShippingMethods have a valid fulfillmentHandlerCode */ private async verifyShippingMethods() { const activeShippingMethods = await this.connection.rawConnection.getRepository(ShippingMethod).find({ where: { deletedAt: IsNull() }, }); for (const method of activeShippingMethods) { const handlerCode = method.fulfillmentHandlerCode; const verifiedHandlerCode = this.ensureValidFulfillmentHandlerCode(method.code, handlerCode); if (handlerCode !== verifiedHandlerCode) { method.fulfillmentHandlerCode = verifiedHandlerCode; await this.connection.rawConnection.getRepository(ShippingMethod).save(method); } } } private ensureValidFulfillmentHandlerCode( shippingMethodCode: string, fulfillmentHandlerCode: string, ): string { const { fulfillmentHandlers } = this.configService.shippingOptions; let handler = fulfillmentHandlers.find(h => h.code === fulfillmentHandlerCode); if (!handler) { handler = fulfillmentHandlers[0]; Logger.error( `The ShippingMethod "${shippingMethodCode}" references an invalid FulfillmentHandler.\n` + `The FulfillmentHandler with code "${fulfillmentHandlerCode}" was not found. Using "${handler.code}" instead.`, ); } return handler.code; } }
import { Injectable } from '@nestjs/common'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { AvailableStock } from '../../config/catalog/stock-location-strategy'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { StockLevel } from '../../entity/stock-level/stock-level.entity'; import { StockLocationService } from './stock-location.service'; /** * @description * The StockLevelService is responsible for managing the stock levels of ProductVariants. * Whenever you need to adjust the `stockOnHand` or `stockAllocated` for a ProductVariant, * you should use this service. * * @docsCategory services * @since 2.0.0 */ @Injectable() export class StockLevelService { constructor( private connection: TransactionalConnection, private stockLocationService: StockLocationService, private configService: ConfigService, ) {} /** * @description * Returns the StockLevel for the given {@link ProductVariant} and {@link StockLocation}. */ async getStockLevel(ctx: RequestContext, productVariantId: ID, stockLocationId: ID): Promise<StockLevel> { const stockLevel = await this.connection.getRepository(ctx, StockLevel).findOne({ where: { productVariantId, stockLocationId, }, }); if (stockLevel) { return stockLevel; } return this.connection.getRepository(ctx, StockLevel).save( new StockLevel({ productVariantId, stockLocationId, stockOnHand: 0, stockAllocated: 0, }), ); } async getStockLevelsForVariant(ctx: RequestContext, productVariantId: ID): Promise<StockLevel[]> { return this.connection .getRepository(ctx, StockLevel) .createQueryBuilder('stockLevel') .leftJoinAndSelect('stockLevel.stockLocation', 'stockLocation') .leftJoin('stockLocation.channels', 'channel') .where('stockLevel.productVariantId = :productVariantId', { productVariantId }) .andWhere('channel.id = :channelId', { channelId: ctx.channelId }) .getMany(); } /** * @description * Returns the available stock (on hand and allocated) for the given {@link ProductVariant}. This is determined * by the configured {@link StockLocationStrategy}. */ async getAvailableStock(ctx: RequestContext, productVariantId: ID): Promise<AvailableStock> { const { stockLocationStrategy } = this.configService.catalogOptions; const stockLevels = await this.connection.getRepository(ctx, StockLevel).find({ where: { productVariantId, }, }); return stockLocationStrategy.getAvailableStock(ctx, productVariantId, stockLevels); } /** * @description * Updates the `stockOnHand` for the given {@link ProductVariant} and {@link StockLocation}. */ async updateStockOnHandForLocation( ctx: RequestContext, productVariantId: ID, stockLocationId: ID, change: number, ) { const stockLevel = await this.connection.getRepository(ctx, StockLevel).findOne({ where: { productVariantId, stockLocationId, }, }); if (!stockLevel) { await this.connection.getRepository(ctx, StockLevel).save( new StockLevel({ productVariantId, stockLocationId, stockOnHand: change, stockAllocated: 0, }), ); } if (stockLevel) { await this.connection .getRepository(ctx, StockLevel) .update(stockLevel.id, { stockOnHand: stockLevel.stockOnHand + change }); } } /** * @description * Updates the `stockAllocated` for the given {@link ProductVariant} and {@link StockLocation}. */ async updateStockAllocatedForLocation( ctx: RequestContext, productVariantId: ID, stockLocationId: ID, change: number, ) { const stockLevel = await this.connection.getRepository(ctx, StockLevel).findOne({ where: { productVariantId, stockLocationId, }, }); if (stockLevel) { await this.connection .getRepository(ctx, StockLevel) .update(stockLevel.id, { stockAllocated: stockLevel.stockAllocated + change }); } } }
import { Injectable } from '@nestjs/common'; import { AssignStockLocationsToChannelInput, CreateStockLocationInput, DeleteStockLocationInput, DeletionResponse, DeletionResult, Permission, RemoveStockLocationsFromChannelInput, UpdateStockLocationInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { RequestContextCacheService } from '../../cache/request-context-cache.service'; import { EntityNotFoundError, ForbiddenError, UserInputError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound, idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { StockLevel } from '../../entity/stock-level/stock-level.entity'; import { StockLocation } from '../../entity/stock-location/stock-location.entity'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { RequestContextService } from '../helpers/request-context/request-context.service'; import { patchEntity } from '../helpers/utils/patch-entity'; import { ChannelService } from './channel.service'; import { RoleService } from './role.service'; @Injectable() export class StockLocationService { constructor( private requestContextService: RequestContextService, private connection: TransactionalConnection, private channelService: ChannelService, private roleService: RoleService, private listQueryBuilder: ListQueryBuilder, private configService: ConfigService, private requestContextCache: RequestContextCacheService, private customFieldRelationService: CustomFieldRelationService, ) {} async initStockLocations() { await this.ensureDefaultStockLocationExists(); } findOne(ctx: RequestContext, stockLocationId: ID): Promise<StockLocation | undefined> { return this.connection .findOneInChannel(ctx, StockLocation, stockLocationId, ctx.channelId) .then(result => result ?? undefined); } findAll( ctx: RequestContext, options?: ListQueryOptions<StockLocation>, relations?: RelationPaths<StockLocation>, ): Promise<PaginatedList<StockLocation>> { return this.listQueryBuilder .build(StockLocation, options, { channelId: ctx.channelId, relations, ctx, }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } async create(ctx: RequestContext, input: CreateStockLocationInput): Promise<StockLocation> { const stockLocation = await this.connection.getRepository(ctx, StockLocation).save( new StockLocation({ name: input.name, description: input.description ?? '', customFields: input.customFields ?? {}, }), ); await this.channelService.assignToCurrentChannel(stockLocation, ctx); await this.connection.getRepository(ctx, StockLocation).save(stockLocation); return stockLocation; } async update(ctx: RequestContext, input: UpdateStockLocationInput): Promise<StockLocation> { const stockLocation = await this.connection.getEntityOrThrow(ctx, StockLocation, input.id); const updatedStockLocation = patchEntity(stockLocation, input); await this.connection.getRepository(ctx, StockLocation).save(updatedStockLocation); await this.customFieldRelationService.updateRelations( ctx, StockLocation, input, updatedStockLocation, ); return assertFound(this.findOne(ctx, updatedStockLocation.id)); } async delete(ctx: RequestContext, input: DeleteStockLocationInput): Promise<DeletionResponse> { const stockLocation = await this.connection.findOneInChannel( ctx, StockLocation, input.id, ctx.channelId, ); if (!stockLocation) { throw new EntityNotFoundError('StockLocation', input.id); } // Do not allow the last StockLocation to be deleted const allStockLocations = await this.connection.getRepository(ctx, StockLocation).find(); if (allStockLocations.length === 1) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.cannot-delete-last-stock-location'), }; } if (input.transferToLocationId) { // This is inefficient, and it would be nice to be able to do this as a single // SQL `update` statement with a nested `select` subquery, but TypeORM doesn't // seem to have a good solution for that. If this proves a perf bottleneck, we // can look at implementing raw SQL with a switch over the DB type. const stockLevelsToTransfer = await this.connection .getRepository(ctx, StockLevel) .find({ where: { stockLocationId: stockLocation.id } }); for (const stockLevel of stockLevelsToTransfer) { const existingStockLevel = await this.connection.getRepository(ctx, StockLevel).findOne({ where: { stockLocationId: input.transferToLocationId, productVariantId: stockLevel.productVariantId, }, }); if (existingStockLevel) { existingStockLevel.stockOnHand += stockLevel.stockOnHand; existingStockLevel.stockAllocated += stockLevel.stockAllocated; await this.connection.getRepository(ctx, StockLevel).save(existingStockLevel); } else { const newStockLevel = new StockLevel({ productVariantId: stockLevel.productVariantId, stockLocationId: input.transferToLocationId, stockOnHand: stockLevel.stockOnHand, stockAllocated: stockLevel.stockAllocated, }); await this.connection.getRepository(ctx, StockLevel).save(newStockLevel); } await this.connection.getRepository(ctx, StockLevel).remove(stockLevel); } } try { await this.connection.getRepository(ctx, StockLocation).remove(stockLocation); } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.message, }; } return { result: DeletionResult.DELETED, }; } async assignStockLocationsToChannel( ctx: RequestContext, input: AssignStockLocationsToChannelInput, ): Promise<StockLocation[]> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.UpdateStockLocation, ]); if (!hasPermission) { throw new ForbiddenError(); } for (const stockLocationId of input.stockLocationIds) { const stockLocation = await this.connection.findOneInChannel( ctx, StockLocation, stockLocationId, ctx.channelId, ); await this.channelService.assignToChannels(ctx, StockLocation, stockLocationId, [ input.channelId, ]); } return this.connection.findByIdsInChannel( ctx, StockLocation, input.stockLocationIds, ctx.channelId, {}, ); } async removeStockLocationsFromChannel( ctx: RequestContext, input: RemoveStockLocationsFromChannelInput, ): Promise<StockLocation[]> { const hasPermission = await this.roleService.userHasAnyPermissionsOnChannel(ctx, input.channelId, [ Permission.DeleteStockLocation, ]); if (!hasPermission) { throw new ForbiddenError(); } const defaultChannel = await this.channelService.getDefaultChannel(ctx); if (idsAreEqual(input.channelId, defaultChannel.id)) { throw new UserInputError('error.items-cannot-be-removed-from-default-channel'); } for (const stockLocationId of input.stockLocationIds) { const stockLocation = await this.connection.getEntityOrThrow(ctx, StockLocation, stockLocationId); await this.channelService.removeFromChannels(ctx, StockLocation, stockLocationId, [ input.channelId, ]); } return this.connection.findByIdsInChannel( ctx, StockLocation, input.stockLocationIds, ctx.channelId, {}, ); } getAllStockLocations(ctx: RequestContext) { return this.requestContextCache.get(ctx, 'StockLocationService.getAllStockLocations', () => this.connection.getRepository(ctx, StockLocation).find(), ); } defaultStockLocation(ctx: RequestContext) { return this.connection .getRepository(ctx, StockLocation) .find({ order: { createdAt: 'ASC' } }) .then(items => items[0]); } async getAllocationLocations(ctx: RequestContext, orderLine: OrderLine, quantity: number) { const { stockLocationStrategy } = this.configService.catalogOptions; const stockLocations = await this.getAllStockLocations(ctx); const allocationLocations = await stockLocationStrategy.forAllocation( ctx, stockLocations, orderLine, quantity, ); return allocationLocations; } async getReleaseLocations(ctx: RequestContext, orderLine: OrderLine, quantity: number) { const { stockLocationStrategy } = this.configService.catalogOptions; const stockLocations = await this.getAllStockLocations(ctx); const releaseLocations = await stockLocationStrategy.forRelease( ctx, stockLocations, orderLine, quantity, ); return releaseLocations; } async getSaleLocations(ctx: RequestContext, orderLine: OrderLine, quantity: number) { const { stockLocationStrategy } = this.configService.catalogOptions; const stockLocations = await this.getAllStockLocations(ctx); const saleLocations = await stockLocationStrategy.forSale(ctx, stockLocations, orderLine, quantity); return saleLocations; } async getCancellationLocations(ctx: RequestContext, orderLine: OrderLine, quantity: number) { const { stockLocationStrategy } = this.configService.catalogOptions; const stockLocations = await this.getAllStockLocations(ctx); const cancellationLocations = await stockLocationStrategy.forCancellation( ctx, stockLocations, orderLine, quantity, ); return cancellationLocations; } private async ensureDefaultStockLocationExists() { const ctx = await this.requestContextService.create({ apiType: 'admin', }); const stockLocations = await this.connection.getRepository(ctx, StockLocation).find({ relations: { channels: true, }, }); if (stockLocations.length === 0) { const defaultStockLocation = await this.connection.getRepository(ctx, StockLocation).save( new StockLocation({ name: 'Default Stock Location', description: 'The default stock location', }), ); defaultStockLocation.channels = []; stockLocations.push(defaultStockLocation); await this.connection.getRepository(ctx, StockLocation).save(defaultStockLocation); } const defaultChannel = await this.channelService.getDefaultChannel(); for (const stockLocation of stockLocations) { if (!stockLocation.channels.find(c => c.id === defaultChannel.id)) { await this.channelService.assignToChannels(ctx, StockLocation, stockLocation.id, [ defaultChannel.id, ]); } } } }
import { Injectable } from '@nestjs/common'; import { GlobalFlag, OrderLineInput, StockLevelInput, StockMovementListOptions, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { In } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { idsAreEqual } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { ShippingCalculator } from '../../config/shipping-method/shipping-calculator'; import { ShippingEligibilityChecker } from '../../config/shipping-method/shipping-eligibility-checker'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Order } from '../../entity/order/order.entity'; import { OrderLine } from '../../entity/order-line/order-line.entity'; import { ProductVariant } from '../../entity/product-variant/product-variant.entity'; import { ShippingMethod } from '../../entity/shipping-method/shipping-method.entity'; import { Allocation } from '../../entity/stock-movement/allocation.entity'; import { Cancellation } from '../../entity/stock-movement/cancellation.entity'; import { Release } from '../../entity/stock-movement/release.entity'; import { Sale } from '../../entity/stock-movement/sale.entity'; import { StockAdjustment } from '../../entity/stock-movement/stock-adjustment.entity'; import { StockMovement } from '../../entity/stock-movement/stock-movement.entity'; import { EventBus } from '../../event-bus/event-bus'; import { StockMovementEvent } from '../../event-bus/events/stock-movement-event'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { GlobalSettingsService } from './global-settings.service'; import { StockLevelService } from './stock-level.service'; import { StockLocationService } from './stock-location.service'; /** * @description * Contains methods relating to {@link StockMovement} entities. * * @docsCategory services */ @Injectable() export class StockMovementService { shippingEligibilityCheckers: ShippingEligibilityChecker[]; shippingCalculators: ShippingCalculator[]; private activeShippingMethods: ShippingMethod[]; constructor( private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder, private globalSettingsService: GlobalSettingsService, private stockLevelService: StockLevelService, private eventBus: EventBus, private stockLocationService: StockLocationService, private configService: ConfigService, ) {} /** * @description * Returns a {@link PaginatedList} of all StockMovements associated with the specified ProductVariant. */ getStockMovementsByProductVariantId( ctx: RequestContext, productVariantId: ID, options: StockMovementListOptions, ): Promise<PaginatedList<StockMovement>> { return this.listQueryBuilder .build<StockMovement>(StockMovement as any, options, { ctx }) .leftJoin('stockmovement.productVariant', 'productVariant') .andWhere('productVariant.id = :productVariantId', { productVariantId }) .getManyAndCount() .then(async ([items, totalItems]) => { return { items, totalItems, }; }); } /** * @description * Adjusts the stock level of the ProductVariant, creating a new {@link StockAdjustment} entity * in the process. */ async adjustProductVariantStock( ctx: RequestContext, productVariantId: ID, stockOnHandNumberOrInput: number | StockLevelInput[], ): Promise<StockAdjustment[]> { let stockOnHandInputs: StockLevelInput[]; if (typeof stockOnHandNumberOrInput === 'number') { const defaultStockLocation = await this.stockLocationService.defaultStockLocation(ctx); stockOnHandInputs = [ { stockLocationId: defaultStockLocation.id, stockOnHand: stockOnHandNumberOrInput }, ]; } else { stockOnHandInputs = stockOnHandNumberOrInput; } const adjustments: StockAdjustment[] = []; for (const input of stockOnHandInputs) { const stockLevel = await this.stockLevelService.getStockLevel( ctx, productVariantId, input.stockLocationId, ); const oldStockLevel = stockLevel.stockOnHand; const newStockLevel = input.stockOnHand; if (oldStockLevel === newStockLevel) { continue; } const delta = newStockLevel - oldStockLevel; const adjustment = await this.connection.getRepository(ctx, StockAdjustment).save( new StockAdjustment({ quantity: delta, stockLocation: { id: input.stockLocationId }, productVariant: { id: productVariantId }, }), ); await this.stockLevelService.updateStockOnHandForLocation( ctx, productVariantId, input.stockLocationId, delta, ); await this.eventBus.publish(new StockMovementEvent(ctx, [adjustment])); adjustments.push(adjustment); } return adjustments; } /** * @description * Creates a new {@link Allocation} for each OrderLine in the Order. For ProductVariants * which are configured to track stock levels, the `ProductVariant.stockAllocated` value is * increased, indicating that this quantity of stock is allocated and cannot be sold. */ async createAllocationsForOrder(ctx: RequestContext, order: Order): Promise<Allocation[]> { const lines = order.lines.map(orderLine => ({ orderLineId: orderLine.id, quantity: orderLine.quantity, })); return this.createAllocationsForOrderLines(ctx, lines); } /** * @description * Creates a new {@link Allocation} for each of the given OrderLines. For ProductVariants * which are configured to track stock levels, the `ProductVariant.stockAllocated` value is * increased, indicating that this quantity of stock is allocated and cannot be sold. */ async createAllocationsForOrderLines( ctx: RequestContext, lines: OrderLineInput[], ): Promise<Allocation[]> { const allocations: Allocation[] = []; const globalTrackInventory = (await this.globalSettingsService.getSettings(ctx)).trackInventory; for (const { orderLineId, quantity } of lines) { const orderLine = await this.connection.getEntityOrThrow(ctx, OrderLine, orderLineId); const productVariant = await this.connection.getEntityOrThrow( ctx, ProductVariant, orderLine.productVariantId, ); const allocationLocations = await this.stockLocationService.getAllocationLocations( ctx, orderLine, quantity, ); for (const allocationLocation of allocationLocations) { const allocation = new Allocation({ productVariant: new ProductVariant({ id: orderLine.productVariantId }), stockLocation: allocationLocation.location, quantity: allocationLocation.quantity, orderLine, }); allocations.push(allocation); if (this.trackInventoryForVariant(productVariant, globalTrackInventory)) { await this.stockLevelService.updateStockAllocatedForLocation( ctx, orderLine.productVariantId, allocationLocation.location.id, allocationLocation.quantity, ); } } } const savedAllocations = await this.connection.getRepository(ctx, Allocation).save(allocations); if (savedAllocations.length) { await this.eventBus.publish(new StockMovementEvent(ctx, savedAllocations)); } return savedAllocations; } /** * @description * Creates {@link Sale}s for each OrderLine in the Order. For ProductVariants * which are configured to track stock levels, the `ProductVariant.stockAllocated` value is * reduced and the `stockOnHand` value is also reduced by the OrderLine quantity, indicating * that the stock is no longer allocated, but is actually sold and no longer available. */ async createSalesForOrder(ctx: RequestContext, lines: OrderLineInput[]): Promise<Sale[]> { const sales: Sale[] = []; const globalTrackInventory = (await this.globalSettingsService.getSettings(ctx)).trackInventory; const orderLines = await this.connection .getRepository(ctx, OrderLine) .find({ where: { id: In(lines.map(line => line.orderLineId)) } }); for (const lineRow of lines) { const orderLine = orderLines.find(line => idsAreEqual(line.id, lineRow.orderLineId)); if (!orderLine) { continue; } const productVariant = await this.connection.getEntityOrThrow( ctx, ProductVariant, orderLine.productVariantId, ); const saleLocations = await this.stockLocationService.getSaleLocations( ctx, orderLine, lineRow.quantity, ); for (const saleLocation of saleLocations) { const sale = new Sale({ productVariant, quantity: lineRow.quantity * -1, orderLine, stockLocation: saleLocation.location, }); sales.push(sale); if (this.trackInventoryForVariant(productVariant, globalTrackInventory)) { await this.stockLevelService.updateStockAllocatedForLocation( ctx, orderLine.productVariantId, saleLocation.location.id, -saleLocation.quantity, ); await this.stockLevelService.updateStockOnHandForLocation( ctx, orderLine.productVariantId, saleLocation.location.id, -saleLocation.quantity, ); } } } const savedSales = await this.connection.getRepository(ctx, Sale).save(sales); if (savedSales.length) { await this.eventBus.publish(new StockMovementEvent(ctx, savedSales)); } return savedSales; } /** * @description * Creates a {@link Cancellation} for each of the specified OrderItems. For ProductVariants * which are configured to track stock levels, the `ProductVariant.stockOnHand` value is * increased for each Cancellation, allowing that stock to be sold again. */ async createCancellationsForOrderLines( ctx: RequestContext, lineInputs: OrderLineInput[], ): Promise<Cancellation[]> { const orderLines = await this.connection.getRepository(ctx, OrderLine).find({ where: { id: In(lineInputs.map(l => l.orderLineId)), }, relations: ['productVariant'], }); const cancellations: Cancellation[] = []; const globalTrackInventory = (await this.globalSettingsService.getSettings(ctx)).trackInventory; for (const orderLine of orderLines) { const lineInput = lineInputs.find(l => idsAreEqual(l.orderLineId, orderLine.id)); if (!lineInput) { continue; } const cancellationLocations = await this.stockLocationService.getCancellationLocations( ctx, orderLine, lineInput.quantity, ); for (const cancellationLocation of cancellationLocations) { const cancellation = new Cancellation({ productVariant: orderLine.productVariant, quantity: lineInput.quantity, orderLine, stockLocation: cancellationLocation.location, }); cancellations.push(cancellation); if (this.trackInventoryForVariant(orderLine.productVariant, globalTrackInventory)) { await this.stockLevelService.updateStockOnHandForLocation( ctx, orderLine.productVariantId, cancellationLocation.location.id, cancellationLocation.quantity, ); } } } const savedCancellations = await this.connection.getRepository(ctx, Cancellation).save(cancellations); if (savedCancellations.length) { await this.eventBus.publish(new StockMovementEvent(ctx, savedCancellations)); } return savedCancellations; } /** * @description * Creates a {@link Release} for each of the specified OrderItems. For ProductVariants * which are configured to track stock levels, the `ProductVariant.stockAllocated` value is * reduced, indicating that this stock is once again available to buy. */ async createReleasesForOrderLines(ctx: RequestContext, lineInputs: OrderLineInput[]): Promise<Release[]> { const releases: Release[] = []; const orderLines = await this.connection.getRepository(ctx, OrderLine).find({ where: { id: In(lineInputs.map(l => l.orderLineId)) }, relations: ['productVariant'], }); const globalTrackInventory = (await this.globalSettingsService.getSettings(ctx)).trackInventory; const variantsMap = new Map<ID, ProductVariant>(); for (const orderLine of orderLines) { const lineInput = lineInputs.find(l => idsAreEqual(l.orderLineId, orderLine.id)); if (!lineInput) { continue; } const releaseLocations = await this.stockLocationService.getReleaseLocations( ctx, orderLine, lineInput.quantity, ); for (const releaseLocation of releaseLocations) { const release = new Release({ productVariant: orderLine.productVariant, quantity: lineInput.quantity, orderLine, stockLocation: releaseLocation.location, }); releases.push(release); if (this.trackInventoryForVariant(orderLine.productVariant, globalTrackInventory)) { await this.stockLevelService.updateStockAllocatedForLocation( ctx, orderLine.productVariantId, releaseLocation.location.id, -releaseLocation.quantity, ); } } } const savedReleases = await this.connection.getRepository(ctx, Release).save(releases); if (savedReleases.length) { await this.eventBus.publish(new StockMovementEvent(ctx, savedReleases)); } return savedReleases; } private trackInventoryForVariant(variant: ProductVariant, globalTrackInventory: boolean): boolean { return ( variant.trackInventory === GlobalFlag.TRUE || (variant.trackInventory === GlobalFlag.INHERIT && globalTrackInventory) ); } }
import { Injectable } from '@nestjs/common'; import { CreateTagInput, DeletionResponse, DeletionResult, UpdateTagInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList, Type } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { RequestContext } from '../../api/common/request-context'; import { ListQueryOptions, Taggable } from '../../common/types/common-types'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { VendureEntity } from '../../entity/base/base.entity'; import { Tag } from '../../entity/tag/tag.entity'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; /** * @description * Contains methods relating to {@link Tag} entities. * * @docsCategory services */ @Injectable() export class TagService { constructor(private connection: TransactionalConnection, private listQueryBuilder: ListQueryBuilder) {} findAll(ctx: RequestContext, options?: ListQueryOptions<Tag>): Promise<PaginatedList<Tag>> { return this.listQueryBuilder .build(Tag, options, { ctx }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } findOne(ctx: RequestContext, tagId: ID): Promise<Tag | undefined> { return this.connection .getRepository(ctx, Tag) .findOne({ where: { id: tagId } }) .then(result => result ?? undefined); } create(ctx: RequestContext, input: CreateTagInput) { return this.tagValueToTag(ctx, input.value); } async update(ctx: RequestContext, input: UpdateTagInput) { const tag = await this.connection.getEntityOrThrow(ctx, Tag, input.id); if (input.value) { tag.value = input.value; await this.connection.getRepository(ctx, Tag).save(tag); } return tag; } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const tag = await this.connection.getEntityOrThrow(ctx, Tag, id); await this.connection.getRepository(ctx, Tag).remove(tag); return { result: DeletionResult.DELETED, }; } async valuesToTags(ctx: RequestContext, values: string[]): Promise<Tag[]> { const tags: Tag[] = []; for (const value of unique(values)) { tags.push(await this.tagValueToTag(ctx, value)); } return tags; } getTagsForEntity(ctx: RequestContext, entity: Type<VendureEntity & Taggable>, id: ID): Promise<Tag[]> { return this.connection .getRepository(ctx, entity) .createQueryBuilder() .relation(entity, 'tags') .of(id) .loadMany(); } private async tagValueToTag(ctx: RequestContext, value: string): Promise<Tag> { const existing = await this.connection.getRepository(ctx, Tag).findOne({ where: { value } }); if (existing) { return existing; } return await this.connection.getRepository(ctx, Tag).save(new Tag({ value })); } }
import { Injectable } from '@nestjs/common'; import { CreateTaxCategoryInput, DeletionResponse, DeletionResult, UpdateTaxCategoryInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { EntityNotFoundError } from '../../common/error/errors'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound } from '../../common/utils'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { TaxCategory } from '../../entity/tax-category/tax-category.entity'; import { TaxRate } from '../../entity/tax-rate/tax-rate.entity'; import { EventBus } from '../../event-bus'; import { TaxCategoryEvent } from '../../event-bus/events/tax-category-event'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { patchEntity } from '../helpers/utils/patch-entity'; /** * @description * Contains methods relating to {@link TaxCategory} entities. * * @docsCategory services */ @Injectable() export class TaxCategoryService { constructor( private connection: TransactionalConnection, private eventBus: EventBus, private listQueryBuilder: ListQueryBuilder, ) {} findAll( ctx: RequestContext, options?: ListQueryOptions<TaxCategory>, ): Promise<PaginatedList<TaxCategory>> { return this.listQueryBuilder .build(TaxCategory, options, { ctx }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } findOne(ctx: RequestContext, taxCategoryId: ID): Promise<TaxCategory | undefined> { return this.connection .getRepository(ctx, TaxCategory) .findOne({ where: { id: taxCategoryId } }) .then(result => result ?? undefined); } async create(ctx: RequestContext, input: CreateTaxCategoryInput): Promise<TaxCategory> { const taxCategory = new TaxCategory(input); if (input.isDefault === true) { await this.connection .getRepository(ctx, TaxCategory) .update({ isDefault: true }, { isDefault: false }); } const newTaxCategory = await this.connection.getRepository(ctx, TaxCategory).save(taxCategory); await this.eventBus.publish(new TaxCategoryEvent(ctx, newTaxCategory, 'created', input)); return assertFound(this.findOne(ctx, newTaxCategory.id)); } async update(ctx: RequestContext, input: UpdateTaxCategoryInput): Promise<TaxCategory> { const taxCategory = await this.findOne(ctx, input.id); if (!taxCategory) { throw new EntityNotFoundError('TaxCategory', input.id); } const updatedTaxCategory = patchEntity(taxCategory, input); if (input.isDefault === true) { await this.connection .getRepository(ctx, TaxCategory) .update({ isDefault: true }, { isDefault: false }); } await this.connection.getRepository(ctx, TaxCategory).save(updatedTaxCategory, { reload: false }); await this.eventBus.publish(new TaxCategoryEvent(ctx, taxCategory, 'updated', input)); return assertFound(this.findOne(ctx, taxCategory.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const taxCategory = await this.connection.getEntityOrThrow(ctx, TaxCategory, id); const dependentRates = await this.connection .getRepository(ctx, TaxRate) .count({ where: { category: { id } } }); if (0 < dependentRates) { const message = ctx.translate('message.cannot-remove-tax-category-due-to-tax-rates', { name: taxCategory.name, count: dependentRates, }); return { result: DeletionResult.NOT_DELETED, message, }; } try { const deletedTaxCategory = new TaxCategory(taxCategory); await this.connection.getRepository(ctx, TaxCategory).remove(taxCategory); await this.eventBus.publish(new TaxCategoryEvent(ctx, deletedTaxCategory, 'deleted', id)); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.toString(), }; } } }
import { Injectable } from '@nestjs/common'; import { CreateTaxRateInput, DeletionResponse, DeletionResult, UpdateTaxRateInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { RelationPaths } from '../../api/decorators/relations.decorator'; import { EntityNotFoundError } from '../../common/error/errors'; import { createSelfRefreshingCache, SelfRefreshingCache } from '../../common/self-refreshing-cache'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { CustomerGroup } from '../../entity/customer-group/customer-group.entity'; import { TaxCategory } from '../../entity/tax-category/tax-category.entity'; import { TaxRate } from '../../entity/tax-rate/tax-rate.entity'; import { Zone } from '../../entity/zone/zone.entity'; import { EventBus } from '../../event-bus/event-bus'; import { TaxRateEvent } from '../../event-bus/events/tax-rate-event'; import { TaxRateModificationEvent } from '../../event-bus/events/tax-rate-modification-event'; import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { patchEntity } from '../helpers/utils/patch-entity'; /** * @description * Contains methods relating to {@link TaxRate} entities. * * @docsCategory services */ @Injectable() export class TaxRateService { private readonly defaultTaxRate = new TaxRate({ value: 0, enabled: true, name: 'No configured tax rate', id: '0', }); private activeTaxRates: SelfRefreshingCache<TaxRate[], [RequestContext]>; constructor( private connection: TransactionalConnection, private eventBus: EventBus, private listQueryBuilder: ListQueryBuilder, private configService: ConfigService, private customFieldRelationService: CustomFieldRelationService, ) {} /** * When the app is bootstrapped, ensure the tax rate cache gets created * @internal */ async initTaxRates() { await this.ensureCacheExists(); } findAll( ctx: RequestContext, options?: ListQueryOptions<TaxRate>, relations?: RelationPaths<TaxRate>, ): Promise<PaginatedList<TaxRate>> { return this.listQueryBuilder .build(TaxRate, options, { relations: relations ?? ['category', 'zone', 'customerGroup'], ctx }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems, })); } findOne( ctx: RequestContext, taxRateId: ID, relations?: RelationPaths<TaxRate>, ): Promise<TaxRate | undefined> { return this.connection .getRepository(ctx, TaxRate) .findOne({ where: { id: taxRateId }, relations: relations ?? ['category', 'zone', 'customerGroup'], }) .then(result => result ?? undefined); } async create(ctx: RequestContext, input: CreateTaxRateInput): Promise<TaxRate> { const taxRate = new TaxRate(input); taxRate.category = await this.connection.getEntityOrThrow(ctx, TaxCategory, input.categoryId); taxRate.zone = await this.connection.getEntityOrThrow(ctx, Zone, input.zoneId); if (input.customerGroupId) { taxRate.customerGroup = await this.connection.getEntityOrThrow( ctx, CustomerGroup, input.customerGroupId, ); } const newTaxRate = await this.connection.getRepository(ctx, TaxRate).save(taxRate); await this.customFieldRelationService.updateRelations(ctx, TaxRate, input, newTaxRate); await this.updateActiveTaxRates(ctx); await this.eventBus.publish(new TaxRateModificationEvent(ctx, newTaxRate)); await this.eventBus.publish(new TaxRateEvent(ctx, newTaxRate, 'created', input)); return assertFound(this.findOne(ctx, newTaxRate.id)); } async update(ctx: RequestContext, input: UpdateTaxRateInput): Promise<TaxRate> { const taxRate = await this.findOne(ctx, input.id); if (!taxRate) { throw new EntityNotFoundError('TaxRate', input.id); } const updatedTaxRate = patchEntity(taxRate, input); if (input.categoryId) { updatedTaxRate.category = await this.connection.getEntityOrThrow( ctx, TaxCategory, input.categoryId, ); } if (input.zoneId) { updatedTaxRate.zone = await this.connection.getEntityOrThrow(ctx, Zone, input.zoneId); } if (input.customerGroupId) { updatedTaxRate.customerGroup = await this.connection.getEntityOrThrow( ctx, CustomerGroup, input.customerGroupId, ); } await this.connection.getRepository(ctx, TaxRate).save(updatedTaxRate, { reload: false }); await this.customFieldRelationService.updateRelations(ctx, TaxRate, input, updatedTaxRate); await this.updateActiveTaxRates(ctx); // Commit the transaction so that the worker process can access the updated // TaxRate when updating its own tax rate cache. await this.connection.commitOpenTransaction(ctx); await this.eventBus.publish(new TaxRateModificationEvent(ctx, updatedTaxRate)); await this.eventBus.publish(new TaxRateEvent(ctx, updatedTaxRate, 'updated', input)); return assertFound(this.findOne(ctx, taxRate.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const taxRate = await this.connection.getEntityOrThrow(ctx, TaxRate, id); const deletedTaxRate = new TaxRate(taxRate); try { await this.connection.getRepository(ctx, TaxRate).remove(taxRate); await this.eventBus.publish(new TaxRateEvent(ctx, deletedTaxRate, 'deleted', id)); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.toString(), }; } } /** * @description * Returns the applicable TaxRate based on the specified Zone and TaxCategory. Used when calculating Order * prices. */ async getApplicableTaxRate(ctx: RequestContext, zone: Zone, taxCategory: TaxCategory): Promise<TaxRate> { const rate = (await this.getActiveTaxRates(ctx)).find(r => r.test(zone, taxCategory)); return rate || this.defaultTaxRate; } private async getActiveTaxRates(ctx: RequestContext): Promise<TaxRate[]> { return this.activeTaxRates.value(ctx); } private async updateActiveTaxRates(ctx: RequestContext) { await this.activeTaxRates.refresh(ctx); } private async findActiveTaxRates(ctx: RequestContext): Promise<TaxRate[]> { return await this.connection.getRepository(ctx, TaxRate).find({ relations: ['category', 'zone', 'customerGroup'], where: { enabled: true, }, }); } /** * Ensures taxRate cache exists. If not, this method creates one. */ private async ensureCacheExists() { if (this.activeTaxRates) { return; } this.activeTaxRates = await createSelfRefreshingCache({ name: 'TaxRateService.activeTaxRates', ttl: this.configService.entityOptions.taxRateCacheTtl, refresh: { fn: ctx => this.findActiveTaxRates(ctx), defaultArgs: [RequestContext.empty()] }, }); } }
import { Injectable } from '@nestjs/common'; import { ModuleRef } from '@nestjs/core'; import { VerifyCustomerAccountResult } from '@vendure/common/lib/generated-shop-types'; import { ID } from '@vendure/common/lib/shared-types'; import { RequestContext } from '../../api/common/request-context'; import { ErrorResultUnion, isGraphQlErrorResult } from '../../common/error/error-result'; import { EntityNotFoundError, InternalServerError } from '../../common/error/errors'; import { IdentifierChangeTokenExpiredError, IdentifierChangeTokenInvalidError, InvalidCredentialsError, MissingPasswordError, PasswordAlreadySetError, PasswordResetTokenExpiredError, PasswordResetTokenInvalidError, PasswordValidationError, VerificationTokenExpiredError, VerificationTokenInvalidError, } from '../../common/error/generated-graphql-shop-errors'; import { isEmailAddressLike, normalizeEmailAddress } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { NativeAuthenticationMethod } from '../../entity/authentication-method/native-authentication-method.entity'; import { User } from '../../entity/user/user.entity'; import { PasswordCipher } from '../helpers/password-cipher/password-cipher'; import { VerificationTokenGenerator } from '../helpers/verification-token-generator/verification-token-generator'; import { RoleService } from './role.service'; /** * @description * Contains methods relating to {@link User} entities. * * @docsCategory services */ @Injectable() export class UserService { constructor( private connection: TransactionalConnection, private configService: ConfigService, private roleService: RoleService, private passwordCipher: PasswordCipher, private verificationTokenGenerator: VerificationTokenGenerator, private moduleRef: ModuleRef, ) {} async getUserById(ctx: RequestContext, userId: ID): Promise<User | undefined> { return this.connection .getRepository(ctx, User) .findOne({ where: { id: userId }, relations: { roles: { channels: true, }, authenticationMethods: true, }, }) .then(result => result ?? undefined); } async getUserByEmailAddress( ctx: RequestContext, emailAddress: string, userType?: 'administrator' | 'customer', ): Promise<User | undefined> { const entity = userType ?? (ctx.apiType === 'admin' ? 'administrator' : 'customer'); const table = `${this.configService.dbConnectionOptions.entityPrefix ?? ''}${entity}`; const qb = this.connection .getRepository(ctx, User) .createQueryBuilder('user') .innerJoin(table, table, `${table}.userId = user.id`) .leftJoinAndSelect('user.roles', 'roles') .leftJoinAndSelect('roles.channels', 'channels') .leftJoinAndSelect('user.authenticationMethods', 'authenticationMethods') .where('user.deletedAt IS NULL'); if (isEmailAddressLike(emailAddress)) { qb.andWhere('LOWER(user.identifier) = :identifier', { identifier: normalizeEmailAddress(emailAddress), }); } else { qb.andWhere('user.identifier = :identifier', { identifier: emailAddress, }); } return qb.getOne().then(result => result ?? undefined); } /** * @description * Creates a new User with the special `customer` Role and using the {@link NativeAuthenticationStrategy}. */ async createCustomerUser( ctx: RequestContext, identifier: string, password?: string, ): Promise<User | PasswordValidationError> { const user = new User(); user.identifier = normalizeEmailAddress(identifier); const customerRole = await this.roleService.getCustomerRole(ctx); user.roles = [customerRole]; const addNativeAuthResult = await this.addNativeAuthenticationMethod(ctx, user, identifier, password); if (isGraphQlErrorResult(addNativeAuthResult)) { return addNativeAuthResult; } return this.connection.getRepository(ctx, User).save(addNativeAuthResult); } /** * @description * Adds a new {@link NativeAuthenticationMethod} to the User. If the {@link AuthOptions} `requireVerification` * is set to `true` (as is the default), the User will be marked as unverified until the email verification * flow is completed. */ async addNativeAuthenticationMethod( ctx: RequestContext, user: User, identifier: string, password?: string, ): Promise<User | PasswordValidationError> { const checkUser = user.id != null && (await this.getUserById(ctx, user.id)); if (checkUser) { if ( !!checkUser.authenticationMethods.find( (m): m is NativeAuthenticationMethod => m instanceof NativeAuthenticationMethod, ) ) { // User already has a NativeAuthenticationMethod registered, so just return. return user; } } const authenticationMethod = new NativeAuthenticationMethod(); if (this.configService.authOptions.requireVerification) { authenticationMethod.verificationToken = this.verificationTokenGenerator.generateVerificationToken(); user.verified = false; } else { user.verified = true; } if (password) { const passwordValidationResult = await this.validatePassword(ctx, password); if (passwordValidationResult !== true) { return passwordValidationResult; } authenticationMethod.passwordHash = await this.passwordCipher.hash(password); } else { authenticationMethod.passwordHash = ''; } authenticationMethod.identifier = normalizeEmailAddress(identifier); authenticationMethod.user = user; await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(authenticationMethod); user.authenticationMethods = [...(user.authenticationMethods ?? []), authenticationMethod]; return user; } /** * @description * Creates a new verified User using the {@link NativeAuthenticationStrategy}. */ async createAdminUser(ctx: RequestContext, identifier: string, password: string): Promise<User> { const user = new User({ identifier: normalizeEmailAddress(identifier), verified: true, }); const authenticationMethod = await this.connection .getRepository(ctx, NativeAuthenticationMethod) .save( new NativeAuthenticationMethod({ identifier: normalizeEmailAddress(identifier), passwordHash: await this.passwordCipher.hash(password), }), ); user.authenticationMethods = [authenticationMethod]; return this.connection.getRepository(ctx, User).save(user); } async softDelete(ctx: RequestContext, userId: ID) { // Dynamic import to avoid the circular dependency of SessionService await this.moduleRef .get((await import('./session.service.js')).SessionService) .deleteSessionsByUser(ctx, new User({ id: userId })); await this.connection.getEntityOrThrow(ctx, User, userId); await this.connection.getRepository(ctx, User).update({ id: userId }, { deletedAt: new Date() }); } /** * @description * Sets the {@link NativeAuthenticationMethod} `verificationToken` as part of the User email verification * flow. */ async setVerificationToken(ctx: RequestContext, user: User): Promise<User> { const nativeAuthMethod = user.getNativeAuthenticationMethod(); nativeAuthMethod.verificationToken = this.verificationTokenGenerator.generateVerificationToken(); user.verified = false; await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod); return this.connection.getRepository(ctx, User).save(user); } /** * @description * Verifies a verificationToken by looking for a User which has previously had it set using the * `setVerificationToken()` method, and checks that the token is valid and has not expired. * * If valid, the User will be set to `verified: true`. */ async verifyUserByToken( ctx: RequestContext, verificationToken: string, password?: string, ): Promise<ErrorResultUnion<VerifyCustomerAccountResult, User>> { const user = await this.connection .getRepository(ctx, User) .createQueryBuilder('user') .leftJoinAndSelect('user.authenticationMethods', 'aums') .leftJoin('user.authenticationMethods', 'authenticationMethod') .addSelect('aums.passwordHash') .where('authenticationMethod.verificationToken = :verificationToken', { verificationToken }) .getOne(); if (user) { if (this.verificationTokenGenerator.verifyVerificationToken(verificationToken)) { const nativeAuthMethod = user.getNativeAuthenticationMethod(); if (!password) { if (!nativeAuthMethod.passwordHash) { return new MissingPasswordError(); } } else { if (!!nativeAuthMethod.passwordHash) { return new PasswordAlreadySetError(); } const passwordValidationResult = await this.validatePassword(ctx, password); if (passwordValidationResult !== true) { return passwordValidationResult; } nativeAuthMethod.passwordHash = await this.passwordCipher.hash(password); } nativeAuthMethod.verificationToken = null; user.verified = true; await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod); return this.connection.getRepository(ctx, User).save(user); } else { return new VerificationTokenExpiredError(); } } else { return new VerificationTokenInvalidError(); } } /** * @description * Sets the {@link NativeAuthenticationMethod} `passwordResetToken` as part of the User password reset * flow. */ async setPasswordResetToken(ctx: RequestContext, emailAddress: string): Promise<User | undefined> { const user = await this.getUserByEmailAddress(ctx, emailAddress); if (!user) { return; } const nativeAuthMethod = user.getNativeAuthenticationMethod(false); if (!nativeAuthMethod) { return undefined; } nativeAuthMethod.passwordResetToken = this.verificationTokenGenerator.generateVerificationToken(); await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod); return user; } /** * @description * Verifies a passwordResetToken by looking for a User which has previously had it set using the * `setPasswordResetToken()` method, and checks that the token is valid and has not expired. * * If valid, the User's credentials will be updated with the new password. */ async resetPasswordByToken( ctx: RequestContext, passwordResetToken: string, password: string, ): Promise< User | PasswordResetTokenExpiredError | PasswordResetTokenInvalidError | PasswordValidationError > { const user = await this.connection .getRepository(ctx, User) .createQueryBuilder('user') .leftJoinAndSelect('user.authenticationMethods', 'aums') .leftJoin('user.authenticationMethods', 'authenticationMethod') .where('authenticationMethod.passwordResetToken = :passwordResetToken', { passwordResetToken }) .getOne(); if (!user) { return new PasswordResetTokenInvalidError(); } const passwordValidationResult = await this.validatePassword(ctx, password); if (passwordValidationResult !== true) { return passwordValidationResult; } if (this.verificationTokenGenerator.verifyVerificationToken(passwordResetToken)) { const nativeAuthMethod = user.getNativeAuthenticationMethod(); nativeAuthMethod.passwordHash = await this.passwordCipher.hash(password); nativeAuthMethod.passwordResetToken = null; await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod); if (user.verified === false && this.configService.authOptions.requireVerification) { // This code path represents an edge-case in which the Customer creates an account, // but prior to verifying their email address, they start the password reset flow. // Since the password reset flow makes the exact same guarantee as the email verification // flow (i.e. the person controls the specified email account), we can also consider it // a verification. user.verified = true; } return this.connection.getRepository(ctx, User).save(user); } else { return new PasswordResetTokenExpiredError(); } } /** * @description * Changes the User identifier without an email verification step, so this should be only used when * an Administrator is setting a new email address. */ async changeUserAndNativeIdentifier(ctx: RequestContext, userId: ID, newIdentifier: string) { const user = await this.getUserById(ctx, userId); if (!user) { return; } const nativeAuthMethod = user.authenticationMethods.find( (m): m is NativeAuthenticationMethod => m instanceof NativeAuthenticationMethod, ); if (nativeAuthMethod) { nativeAuthMethod.identifier = newIdentifier; nativeAuthMethod.identifierChangeToken = null; nativeAuthMethod.pendingIdentifier = null; await this.connection .getRepository(ctx, NativeAuthenticationMethod) .save(nativeAuthMethod, { reload: false }); } user.identifier = newIdentifier; await this.connection.getRepository(ctx, User).save(user, { reload: false }); } /** * @description * Sets the {@link NativeAuthenticationMethod} `identifierChangeToken` as part of the User email address change * flow. */ async setIdentifierChangeToken(ctx: RequestContext, user: User): Promise<User> { const nativeAuthMethod = user.getNativeAuthenticationMethod(); nativeAuthMethod.identifierChangeToken = this.verificationTokenGenerator.generateVerificationToken(); await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod); return user; } /** * @description * Changes the User identifier as part of the storefront flow used by Customers to set a * new email address, with the token previously set using the `setIdentifierChangeToken()` method. */ async changeIdentifierByToken( ctx: RequestContext, token: string, ): Promise< | { user: User; oldIdentifier: string } | IdentifierChangeTokenInvalidError | IdentifierChangeTokenExpiredError > { const user = await this.connection .getRepository(ctx, User) .createQueryBuilder('user') .leftJoinAndSelect('user.authenticationMethods', 'aums') .leftJoin('user.authenticationMethods', 'authenticationMethod') .where('authenticationMethod.identifierChangeToken = :identifierChangeToken', { identifierChangeToken: token, }) .getOne(); if (!user) { return new IdentifierChangeTokenInvalidError(); } if (!this.verificationTokenGenerator.verifyVerificationToken(token)) { return new IdentifierChangeTokenExpiredError(); } const nativeAuthMethod = user.getNativeAuthenticationMethod(); const pendingIdentifier = nativeAuthMethod.pendingIdentifier; if (!pendingIdentifier) { throw new InternalServerError('error.pending-identifier-missing'); } const oldIdentifier = user.identifier; user.identifier = pendingIdentifier; nativeAuthMethod.identifier = pendingIdentifier; nativeAuthMethod.identifierChangeToken = null; nativeAuthMethod.pendingIdentifier = null; await this.connection .getRepository(ctx, NativeAuthenticationMethod) .save(nativeAuthMethod, { reload: false }); await this.connection.getRepository(ctx, User).save(user, { reload: false }); return { user, oldIdentifier }; } /** * @description * Updates the password for a User with the {@link NativeAuthenticationMethod}. */ async updatePassword( ctx: RequestContext, userId: ID, currentPassword: string, newPassword: string, ): Promise<boolean | InvalidCredentialsError | PasswordValidationError> { const user = await this.connection .getRepository(ctx, User) .createQueryBuilder('user') .leftJoinAndSelect('user.authenticationMethods', 'authenticationMethods') .addSelect('authenticationMethods.passwordHash') .where('user.id = :id', { id: userId }) .getOne(); if (!user) { throw new EntityNotFoundError('User', userId); } const password = newPassword; const passwordValidationResult = await this.validatePassword(ctx, password); if (passwordValidationResult !== true) { return passwordValidationResult; } const nativeAuthMethod = user.getNativeAuthenticationMethod(); const matches = await this.passwordCipher.check(currentPassword, nativeAuthMethod.passwordHash); if (!matches) { return new InvalidCredentialsError({ authenticationError: '' }); } nativeAuthMethod.passwordHash = await this.passwordCipher.hash(newPassword); await this.connection .getRepository(ctx, NativeAuthenticationMethod) .save(nativeAuthMethod, { reload: false }); return true; } private async validatePassword( ctx: RequestContext, password: string, ): Promise<true | PasswordValidationError> { const passwordValidationResult = await this.configService.authOptions.passwordValidationStrategy.validate(ctx, password); if (passwordValidationResult !== true) { const message = typeof passwordValidationResult === 'string' ? passwordValidationResult : 'Password is invalid'; return new PasswordValidationError({ validationErrorMessage: message }); } else { return true; } } }
import { Injectable } from '@nestjs/common'; import { CreateZoneInput, DeletionResponse, DeletionResult, MutationAddMembersToZoneArgs, MutationRemoveMembersFromZoneArgs, UpdateZoneInput, } from '@vendure/common/lib/generated-types'; import { ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { unique } from '@vendure/common/lib/unique'; import { In } from 'typeorm'; import { RequestContext } from '../../api/common/request-context'; import { createSelfRefreshingCache, SelfRefreshingCache } from '../../common/self-refreshing-cache'; import { ListQueryOptions } from '../../common/types/common-types'; import { assertFound } from '../../common/utils'; import { ConfigService } from '../../config/config.service'; import { TransactionalConnection } from '../../connection/transactional-connection'; import { Channel, TaxRate } from '../../entity'; import { Country } from '../../entity/region/country.entity'; import { Zone } from '../../entity/zone/zone.entity'; import { EventBus } from '../../event-bus'; import { ZoneEvent } from '../../event-bus/events/zone-event'; import { ZoneMembersEvent } from '../../event-bus/events/zone-members-event'; import { ListQueryBuilder } from '../helpers/list-query-builder/list-query-builder'; import { TranslatorService } from '../helpers/translator/translator.service'; import { patchEntity } from '../helpers/utils/patch-entity'; /** * @description * Contains methods relating to {@link Zone} entities. * * @docsCategory services */ @Injectable() export class ZoneService { /** * We cache all Zones to avoid hitting the DB many times per request. */ private zones: SelfRefreshingCache<Zone[], [RequestContext]>; constructor( private connection: TransactionalConnection, private configService: ConfigService, private eventBus: EventBus, private translator: TranslatorService, private listQueryBuilder: ListQueryBuilder, ) {} /** @internal */ async initZones() { await this.ensureCacheExists(); } /** * Creates a zones cache, that can be used to reduce number of zones queries to database * * @internal */ async createCache(): Promise<SelfRefreshingCache<Zone[], [RequestContext]>> { return await createSelfRefreshingCache({ name: 'ZoneService.zones', ttl: this.configService.entityOptions.zoneCacheTtl, refresh: { fn: ctx => this.connection.getRepository(ctx, Zone).find({ relations: ['members'], }), defaultArgs: [RequestContext.empty()], }, }); } async findAll(ctx: RequestContext, options?: ListQueryOptions<Zone>): Promise<PaginatedList<Zone>> { return this.listQueryBuilder .build(Zone, options, { relations: ['members'], ctx }) .getManyAndCount() .then(([items, totalItems]) => { const translated = items.map((zone, i) => { const cloneZone = { ...zone }; cloneZone.members = zone.members.map(country => this.translator.translate(country, ctx)); return cloneZone; }); return { items: translated, totalItems, }; }); } findOne(ctx: RequestContext, zoneId: ID): Promise<Zone | undefined> { return this.connection .getRepository(ctx, Zone) .findOne({ where: { id: zoneId }, relations: ['members'], }) .then(zone => { if (zone) { zone.members = zone.members.map(country => this.translator.translate(country, ctx)); return zone; } }); } async getAllWithMembers(ctx: RequestContext): Promise<Zone[]> { return this.zones.memoize([], [ctx], zones => { return zones.map((zone, i) => { const cloneZone = { ...zone }; cloneZone.members = zone.members.map(country => this.translator.translate(country, ctx)); return cloneZone; }); }); } async create(ctx: RequestContext, input: CreateZoneInput): Promise<Zone> { const zone = new Zone(input); if (input.memberIds) { zone.members = await this.getCountriesFromIds(ctx, input.memberIds); } const newZone = await this.connection.getRepository(ctx, Zone).save(zone); await this.zones.refresh(ctx); await this.eventBus.publish(new ZoneEvent(ctx, newZone, 'created', input)); return assertFound(this.findOne(ctx, newZone.id)); } async update(ctx: RequestContext, input: UpdateZoneInput): Promise<Zone> { const zone = await this.connection.getEntityOrThrow(ctx, Zone, input.id); const updatedZone = patchEntity(zone, input); await this.connection.getRepository(ctx, Zone).save(updatedZone, { reload: false }); await this.zones.refresh(ctx); await this.eventBus.publish(new ZoneEvent(ctx, zone, 'updated', input)); return assertFound(this.findOne(ctx, zone.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const zone = await this.connection.getEntityOrThrow(ctx, Zone, id); const deletedZone = new Zone(zone); const channelsUsingZone = await this.connection .getRepository(ctx, Channel) .createQueryBuilder('channel') .where('channel.defaultTaxZone = :id', { id }) .orWhere('channel.defaultShippingZone = :id', { id }) .getMany(); if (0 < channelsUsingZone.length) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.zone-used-in-channels', { channelCodes: channelsUsingZone.map(t => t.code).join(', '), }), }; } const taxRatesUsingZone = await this.connection .getRepository(ctx, TaxRate) .createQueryBuilder('taxRate') .where('taxRate.zone = :id', { id }) .getMany(); if (0 < taxRatesUsingZone.length) { return { result: DeletionResult.NOT_DELETED, message: ctx.translate('message.zone-used-in-tax-rates', { taxRateNames: taxRatesUsingZone.map(t => t.name).join(', '), }), }; } else { await this.connection.getRepository(ctx, Zone).remove(zone); await this.zones.refresh(ctx); await this.eventBus.publish(new ZoneEvent(ctx, deletedZone, 'deleted', id)); return { result: DeletionResult.DELETED, message: '', }; } } async addMembersToZone( ctx: RequestContext, { memberIds, zoneId }: MutationAddMembersToZoneArgs, ): Promise<Zone> { const countries = await this.getCountriesFromIds(ctx, memberIds); const zone = await this.connection.getEntityOrThrow(ctx, Zone, zoneId, { relations: ['members'], }); const members = unique(zone.members.concat(countries), 'id'); zone.members = members; await this.connection.getRepository(ctx, Zone).save(zone, { reload: false }); await this.zones.refresh(ctx); await this.eventBus.publish(new ZoneMembersEvent(ctx, zone, 'assigned', memberIds)); return assertFound(this.findOne(ctx, zone.id)); } async removeMembersFromZone( ctx: RequestContext, { memberIds, zoneId }: MutationRemoveMembersFromZoneArgs, ): Promise<Zone> { const zone = await this.connection.getEntityOrThrow(ctx, Zone, zoneId, { relations: ['members'], }); zone.members = zone.members.filter(country => !memberIds.includes(country.id)); await this.connection.getRepository(ctx, Zone).save(zone, { reload: false }); await this.zones.refresh(ctx); await this.eventBus.publish(new ZoneMembersEvent(ctx, zone, 'removed', memberIds)); return assertFound(this.findOne(ctx, zone.id)); } private getCountriesFromIds(ctx: RequestContext, ids: ID[]): Promise<Country[]> { return this.connection.getRepository(ctx, Country).find({ where: { id: In(ids) } }); } /** * Ensures zones cache exists. If not, this method creates one. */ private async ensureCacheExists() { if (this.zones) { return; } this.zones = await this.createCache(); } }