content
stringlengths
28
1.34M
export interface CliOptions { logLevel: 'silent' | 'info' | 'verbose'; }
import { cancel, intro, isCancel, log, outro, select, spinner } from '@clack/prompts'; import pc from 'picocolors'; import { Messages } from '../../constants'; import { CliCommand } from '../../shared/cli-command'; import { pauseForPromptDisplay } from '../../utilities/utils'; import { addApiExtensionCommand } from './api-extension/add-api-extension'; import { addCodegenCommand } from './codegen/add-codegen'; import { addEntityCommand } from './entity/add-entity'; import { addJobQueueCommand } from './job-queue/add-job-queue'; import { createNewPluginCommand } from './plugin/create-new-plugin'; import { addServiceCommand } from './service/add-service'; import { addUiExtensionsCommand } from './ui-extensions/add-ui-extensions'; const cancelledMessage = 'Add feature cancelled.'; export async function addCommand() { // eslint-disable-next-line no-console console.log(`\n`); intro(pc.blue("✨ Let's add a new feature to your Vendure project!")); const addCommands: Array<CliCommand<any>> = [ createNewPluginCommand, addEntityCommand, addServiceCommand, addApiExtensionCommand, addJobQueueCommand, addUiExtensionsCommand, addCodegenCommand, ]; const featureType = await select({ message: 'Which feature would you like to add?', options: addCommands.map(c => ({ value: c.id, label: `[${c.category}] ${c.description}`, })), }); if (isCancel(featureType)) { cancel(cancelledMessage); process.exit(0); } try { const command = addCommands.find(c => c.id === featureType); if (!command) { throw new Error(`Could not find command with id "${featureType as string}"`); } const { modifiedSourceFiles, project } = await command.run(); if (modifiedSourceFiles.length) { const importsSpinner = spinner(); importsSpinner.start('Organizing imports...'); await pauseForPromptDisplay(); for (const sourceFile of modifiedSourceFiles) { sourceFile.organizeImports(); } await project.save(); importsSpinner.stop('Imports organized'); } outro('✅ Done!'); } catch (e: any) { log.error(e.message as string); const isCliMessage = Object.values(Messages).includes(e.message); if (!isCliMessage && e.stack) { log.error(e.stack); } outro('❌ Error'); } }
import { cancel, isCancel, log, spinner, text } from '@clack/prompts'; import { paramCase } from 'change-case'; import path from 'path'; import { ClassDeclaration, CodeBlockWriter, Expression, Node, Project, SourceFile, SyntaxKind, Type, VariableDeclaration, VariableDeclarationKind, } from 'ts-morph'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { EntityRef } from '../../../shared/entity-ref'; import { ServiceRef } from '../../../shared/service-ref'; import { analyzeProject, selectPlugin, selectServiceRef } from '../../../shared/shared-prompts'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { addImportsToFile, createFile, customizeCreateUpdateInputInterfaces, } from '../../../utilities/ast-utils'; import { pauseForPromptDisplay } from '../../../utilities/utils'; const cancelledMessage = 'Add API extension cancelled'; export interface AddApiExtensionOptions { plugin?: VendurePluginRef; } export const addApiExtensionCommand = new CliCommand({ id: 'add-api-extension', category: 'Plugin: API', description: 'Adds GraphQL API extensions to a plugin', run: options => addApiExtension(options), }); async function addApiExtension( options?: AddApiExtensionOptions, ): Promise<CliCommandReturnVal<{ serviceRef: ServiceRef }>> { const providedVendurePlugin = options?.plugin; const { project } = await analyzeProject({ providedVendurePlugin, cancelledMessage }); const plugin = providedVendurePlugin ?? (await selectPlugin(project, cancelledMessage)); const serviceRef = await selectServiceRef(project, plugin, false); const serviceEntityRef = serviceRef.crudEntityRef; const modifiedSourceFiles: SourceFile[] = []; let resolver: ClassDeclaration | undefined; let apiExtensions: VariableDeclaration | undefined; const scaffoldSpinner = spinner(); let queryName = ''; let mutationName = ''; if (!serviceEntityRef) { const queryNameResult = await text({ message: 'Enter a name for the new query', initialValue: 'myNewQuery', }); if (!isCancel(queryNameResult)) { queryName = queryNameResult; } const mutationNameResult = await text({ message: 'Enter a name for the new mutation', initialValue: 'myNewMutation', }); if (!isCancel(mutationNameResult)) { mutationName = mutationNameResult; } } scaffoldSpinner.start('Generating resolver file...'); await pauseForPromptDisplay(); if (serviceEntityRef) { resolver = createCrudResolver(project, plugin, serviceRef, serviceEntityRef); modifiedSourceFiles.push(resolver.getSourceFile()); } else { if (isCancel(queryName)) { cancel(cancelledMessage); process.exit(0); } resolver = createSimpleResolver(project, plugin, serviceRef, queryName, mutationName); if (queryName) { serviceRef.classDeclaration.addMethod({ name: queryName, parameters: [ { name: 'ctx', type: 'RequestContext' }, { name: 'id', type: 'ID' }, ], isAsync: true, returnType: 'Promise<boolean>', statements: `return true;`, }); } if (mutationName) { serviceRef.classDeclaration.addMethod({ name: mutationName, parameters: [ { name: 'ctx', type: 'RequestContext' }, { name: 'id', type: 'ID' }, ], isAsync: true, returnType: 'Promise<boolean>', statements: `return true;`, }); } addImportsToFile(serviceRef.classDeclaration.getSourceFile(), { namedImports: ['RequestContext', 'ID'], moduleSpecifier: '@vendure/core', }); modifiedSourceFiles.push(resolver.getSourceFile()); } scaffoldSpinner.message('Generating schema definitions...'); await pauseForPromptDisplay(); if (serviceEntityRef) { apiExtensions = createCrudApiExtension(project, plugin, serviceRef); } else { apiExtensions = createSimpleApiExtension(project, plugin, serviceRef, queryName, mutationName); } if (apiExtensions) { modifiedSourceFiles.push(apiExtensions.getSourceFile()); } scaffoldSpinner.message('Registering API extension with plugin...'); await pauseForPromptDisplay(); plugin.addAdminApiExtensions({ schema: apiExtensions, resolvers: [resolver], }); addImportsToFile(plugin.getSourceFile(), { namedImports: [resolver.getName() as string], moduleSpecifier: resolver.getSourceFile(), }); if (apiExtensions) { addImportsToFile(plugin.getSourceFile(), { namedImports: [apiExtensions.getName()], moduleSpecifier: apiExtensions.getSourceFile(), }); } scaffoldSpinner.stop(`API extensions added`); await project.save(); return { project, modifiedSourceFiles: [serviceRef.classDeclaration.getSourceFile(), ...modifiedSourceFiles], serviceRef, }; } function getResolverFileName( project: Project, serviceRef: ServiceRef, ): { resolverFileName: string; suffix: number | undefined } { let suffix: number | undefined; let resolverFileName = ''; let sourceFileExists = false; do { resolverFileName = paramCase(serviceRef.name).replace('-service', '') + `-admin.resolver${typeof suffix === 'number' ? `-${suffix?.toString()}` : ''}.ts`; sourceFileExists = !!project.getSourceFile(resolverFileName); if (sourceFileExists) { suffix = (suffix ?? 1) + 1; } } while (sourceFileExists); return { resolverFileName, suffix }; } function createSimpleResolver( project: Project, plugin: VendurePluginRef, serviceRef: ServiceRef, queryName: string, mutationName: string, ) { const { resolverFileName, suffix } = getResolverFileName(project, serviceRef); const resolverSourceFile = createFile( project, path.join(__dirname, 'templates/simple-resolver.template.ts'), path.join(plugin.getPluginDir().getPath(), 'api', resolverFileName), ); const resolverClassDeclaration = resolverSourceFile .getClasses() .find(cl => cl.getDecorator('Resolver') != null); if (!resolverClassDeclaration) { throw new Error('Could not find resolver class declaration'); } if (resolverClassDeclaration.getName() === 'SimpleAdminResolver') { resolverClassDeclaration.rename( serviceRef.name.replace(/Service$/, '') + 'AdminResolver' + (suffix ? suffix.toString() : ''), ); } if (queryName) { resolverSourceFile.getClass('TemplateService')?.getMethod('exampleQueryHandler')?.rename(queryName); resolverClassDeclaration.getMethod('exampleQuery')?.rename(queryName); } else { resolverSourceFile.getClass('TemplateService')?.getMethod('exampleQueryHandler')?.remove(); resolverClassDeclaration.getMethod('exampleQuery')?.remove(); } if (mutationName) { resolverSourceFile .getClass('TemplateService') ?.getMethod('exampleMutationHandler') ?.rename(mutationName); resolverClassDeclaration.getMethod('exampleMutation')?.rename(mutationName); } else { resolverSourceFile.getClass('TemplateService')?.getMethod('exampleMutationHandler')?.remove(); resolverClassDeclaration.getMethod('exampleMutation')?.remove(); } resolverClassDeclaration .getConstructors()[0] .getParameter('templateService') ?.rename(serviceRef.nameCamelCase) .setType(serviceRef.name); resolverSourceFile.getClass('TemplateService')?.remove(); addImportsToFile(resolverSourceFile, { namedImports: [serviceRef.name], moduleSpecifier: serviceRef.classDeclaration.getSourceFile(), }); return resolverClassDeclaration; } function createCrudResolver( project: Project, plugin: VendurePluginRef, serviceRef: ServiceRef, serviceEntityRef: EntityRef, ) { const resolverSourceFile = createFile( project, path.join(__dirname, 'templates/crud-resolver.template.ts'), path.join( plugin.getPluginDir().getPath(), 'api', paramCase(serviceEntityRef.name) + '-admin.resolver.ts', ), ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const resolverClassDeclaration = resolverSourceFile .getClass('EntityAdminResolver')! .rename(serviceEntityRef.name + 'AdminResolver'); if (serviceRef.features.findOne) { const findOneMethod = resolverClassDeclaration .getMethod('entity') ?.rename(serviceEntityRef.nameCamelCase); const serviceFindOneMethod = serviceRef.classDeclaration.getMethod('findOne'); if (serviceFindOneMethod) { if ( !serviceFindOneMethod .getParameters() .find(p => p.getName() === 'relations' && p.getType().getText().includes('RelationPaths')) ) { findOneMethod?.getParameters()[2].remove(); findOneMethod?.setBodyText(`return this.${serviceRef.nameCamelCase}.findOne(ctx, args.id);`); } } } else { resolverClassDeclaration.getMethod('entity')?.remove(); } if (serviceRef.features.findAll) { const findAllMethod = resolverClassDeclaration .getMethod('entities') ?.rename(serviceEntityRef.nameCamelCase + 's'); const serviceFindAllMethod = serviceRef.classDeclaration.getMethod('findAll'); if (serviceFindAllMethod) { if ( !serviceFindAllMethod .getParameters() .find(p => p.getName() === 'relations' && p.getType().getText().includes('RelationPaths')) ) { findAllMethod?.getParameters()[2].remove(); findAllMethod?.setBodyText( `return this.${serviceRef.nameCamelCase}.findAll(ctx, args.options || undefined);`, ); } } } else { resolverClassDeclaration.getMethod('entities')?.remove(); } if (serviceRef.features.create) { resolverClassDeclaration.getMethod('createEntity')?.rename('create' + serviceEntityRef.name); } else { resolverClassDeclaration.getMethod('createEntity')?.remove(); } if (serviceRef.features.update) { resolverClassDeclaration.getMethod('updateEntity')?.rename('update' + serviceEntityRef.name); } else { resolverClassDeclaration.getMethod('updateEntity')?.remove(); } if (serviceRef.features.delete) { resolverClassDeclaration.getMethod('deleteEntity')?.rename('delete' + serviceEntityRef.name); } else { resolverClassDeclaration.getMethod('deleteEntity')?.remove(); } customizeCreateUpdateInputInterfaces(resolverSourceFile, serviceEntityRef); resolverClassDeclaration .getConstructors()[0] .getParameter('templateService') ?.rename(serviceRef.nameCamelCase) .setType(serviceRef.name); resolverSourceFile.getClass('TemplateEntity')?.rename(serviceEntityRef.name).remove(); resolverSourceFile.getClass('TemplateService')?.remove(); addImportsToFile(resolverSourceFile, { namedImports: [serviceRef.name], moduleSpecifier: serviceRef.classDeclaration.getSourceFile(), }); addImportsToFile(resolverSourceFile, { namedImports: [serviceEntityRef.name], moduleSpecifier: serviceEntityRef.classDeclaration.getSourceFile(), }); return resolverClassDeclaration; } function createSimpleApiExtension( project: Project, plugin: VendurePluginRef, serviceRef: ServiceRef, queryName: string, mutationName: string, ) { const apiExtensionsFile = getOrCreateApiExtensionsFile(project, plugin); const adminApiExtensions = apiExtensionsFile.getVariableDeclaration('adminApiExtensions'); const insertAtIndex = adminApiExtensions?.getParent().getParent().getChildIndex() ?? 2; const schemaVariableName = `${serviceRef.nameCamelCase.replace(/Service$/, '')}AdminApiExtensions`; const existingSchemaVariable = apiExtensionsFile.getVariableStatement(schemaVariableName); if (!existingSchemaVariable) { apiExtensionsFile.insertVariableStatement(insertAtIndex, { declarationKind: VariableDeclarationKind.Const, declarations: [ { name: schemaVariableName, initializer: writer => { writer.writeLine(`gql\``); writer.indent(() => { if (queryName) { writer.writeLine(` extend type Query {`); writer.writeLine(` ${queryName}(id: ID!): Boolean!`); writer.writeLine(` }`); } writer.newLine(); if (mutationName) { writer.writeLine(` extend type Mutation {`); writer.writeLine(` ${mutationName}(id: ID!): Boolean!`); writer.writeLine(` }`); } }); writer.write(`\``); }, }, ], }); } else { const taggedTemplateLiteral = existingSchemaVariable .getDeclarations()[0] ?.getFirstChildByKind(SyntaxKind.TaggedTemplateExpression) ?.getChildren()[1]; if (!taggedTemplateLiteral) { log.error('Could not update schema automatically'); } else { appendToGqlTemplateLiteral(existingSchemaVariable.getDeclarations()[0], writer => { writer.indent(() => { if (queryName) { writer.writeLine(` extend type Query {`); writer.writeLine(` ${queryName}(id: ID!): Boolean!`); writer.writeLine(` }`); } writer.newLine(); if (mutationName) { writer.writeLine(` extend type Mutation {`); writer.writeLine(` ${mutationName}(id: ID!): Boolean!`); writer.writeLine(` }`); } }); }); } } addSchemaToApiExtensionsTemplateLiteral(adminApiExtensions, schemaVariableName); return adminApiExtensions; } function createCrudApiExtension(project: Project, plugin: VendurePluginRef, serviceRef: ServiceRef) { const apiExtensionsFile = getOrCreateApiExtensionsFile(project, plugin); const adminApiExtensions = apiExtensionsFile.getVariableDeclaration('adminApiExtensions'); const insertAtIndex = adminApiExtensions?.getParent().getParent().getChildIndex() ?? 2; const schemaVariableName = `${serviceRef.nameCamelCase.replace(/Service$/, '')}AdminApiExtensions`; apiExtensionsFile.insertVariableStatement(insertAtIndex, { declarationKind: VariableDeclarationKind.Const, declarations: [ { name: schemaVariableName, initializer: writer => { writer.writeLine(`gql\``); const entityRef = serviceRef.crudEntityRef; if (entityRef) { writer.indent(() => { if (entityRef.isTranslatable()) { const translationClass = entityRef.getTranslationClass(); if (translationClass) { writer.writeLine(` type ${translationClass.getName() ?? ''} {`); writer.writeLine(` id: ID!`); writer.writeLine(` createdAt: DateTime!`); writer.writeLine(` updatedAt: DateTime!`); writer.writeLine(` languageCode: LanguageCode!`); for (const { name, type, nullable } of entityRef.getProps()) { if (type.getText().includes('LocaleString')) { writer.writeLine(` ${name}: String${nullable ? '' : '!'}`); } } writer.writeLine(` }`); writer.newLine(); } } writer.writeLine(` type ${entityRef.name} implements Node {`); writer.writeLine(` id: ID!`); writer.writeLine(` createdAt: DateTime!`); writer.writeLine(` updatedAt: DateTime!`); for (const { name, type, nullable } of entityRef.getProps()) { const graphQlType = getGraphQLType(type); if (graphQlType) { writer.writeLine(` ${name}: ${graphQlType}${nullable ? '' : '!'}`); } } if (entityRef.isTranslatable()) { writer.writeLine( ` translations: [${entityRef.getTranslationClass()?.getName() ?? ''}!]!`, ); } writer.writeLine(` }`); writer.newLine(); writer.writeLine(` type ${entityRef.name}List implements PaginatedList {`); writer.writeLine(` items: [${entityRef.name}!]!`); writer.writeLine(` totalItems: Int!`); writer.writeLine(` }`); writer.newLine(); writer.writeLine(` # Generated at run-time by Vendure`); writer.writeLine(` input ${entityRef.name}ListOptions`); writer.newLine(); writer.writeLine(` extend type Query {`); if (serviceRef.features.findOne) { writer.writeLine( ` ${entityRef.nameCamelCase}(id: ID!): ${entityRef.name}`, ); } if (serviceRef.features.findAll) { writer.writeLine( ` ${entityRef.nameCamelCase}s(options: ${entityRef.name}ListOptions): ${entityRef.name}List!`, ); } writer.writeLine(` }`); writer.newLine(); if ( entityRef.isTranslatable() && (serviceRef.features.create || serviceRef.features.update) ) { writer.writeLine( ` input ${entityRef.getTranslationClass()?.getName() ?? ''}Input {`, ); writer.writeLine(` id: ID`); writer.writeLine(` languageCode: LanguageCode!`); for (const { name, type, nullable } of entityRef.getProps()) { if (type.getText().includes('LocaleString')) { writer.writeLine(` ${name}: String`); } } writer.writeLine(` }`); writer.newLine(); } if (serviceRef.features.create) { writer.writeLine(` input Create${entityRef.name}Input {`); for (const { name, type, nullable } of entityRef.getProps()) { const graphQlType = getGraphQLType(type); if (graphQlType) { writer.writeLine(` ${name}: ${graphQlType}${nullable ? '' : '!'}`); } } if (entityRef.isTranslatable()) { writer.writeLine( ` translations: [${entityRef.getTranslationClass()?.getName() ?? ''}Input!]!`, ); } writer.writeLine(` }`); writer.newLine(); } if (serviceRef.features.update) { writer.writeLine(` input Update${entityRef.name}Input {`); writer.writeLine(` id: ID!`); for (const { name, type } of entityRef.getProps()) { const graphQlType = getGraphQLType(type); if (graphQlType) { writer.writeLine(` ${name}: ${graphQlType}`); } } if (entityRef.isTranslatable()) { writer.writeLine( ` translations: [${entityRef.getTranslationClass()?.getName() ?? ''}Input!]`, ); } writer.writeLine(` }`); writer.newLine(); } if ( serviceRef.features.create || serviceRef.features.update || serviceRef.features.delete ) { writer.writeLine(` extend type Mutation {`); if (serviceRef.features.create) { writer.writeLine( ` create${entityRef.name}(input: Create${entityRef.name}Input!): ${entityRef.name}!`, ); } if (serviceRef.features.update) { writer.writeLine( ` update${entityRef.name}(input: Update${entityRef.name}Input!): ${entityRef.name}!`, ); } if (serviceRef.features.delete) { writer.writeLine( ` delete${entityRef.name}(id: ID!): DeletionResponse!`, ); } writer.writeLine(` }`); } }); } writer.write(`\``); }, }, ], }); addSchemaToApiExtensionsTemplateLiteral(adminApiExtensions, schemaVariableName); return adminApiExtensions; } function addSchemaToApiExtensionsTemplateLiteral( adminApiExtensions: VariableDeclaration | undefined, schemaVariableName: string, ) { if (adminApiExtensions) { if (adminApiExtensions.getText().includes(` \${${schemaVariableName}}`)) { return; } appendToGqlTemplateLiteral(adminApiExtensions, writer => { writer.writeLine(` \${${schemaVariableName}}`); }); } } function appendToGqlTemplateLiteral( variableDeclaration: VariableDeclaration, append: (writer: CodeBlockWriter) => void, ) { const initializer = variableDeclaration.getInitializer(); if (Node.isTaggedTemplateExpression(initializer)) { variableDeclaration .setInitializer(writer => { writer.write(`gql\``); const template = initializer.getTemplate(); if (Node.isNoSubstitutionTemplateLiteral(template)) { writer.write(`${template.getLiteralValue()}`); } else { writer.write(template.getText().replace(/^`/, '').replace(/`$/, '')); } append(writer); writer.write(`\``); }) .formatText(); } } function getGraphQLType(type: Type): string | undefined { if (type.isString()) { return 'String'; } if (type.isBoolean()) { return 'Boolean'; } if (type.isNumber()) { return 'Int'; } if (type.isObject() && type.getText() === 'Date') { return 'DateTime'; } if (type.getText().includes('LocaleString')) { return 'String'; } return; } function getOrCreateApiExtensionsFile(project: Project, plugin: VendurePluginRef): SourceFile { const existingApiExtensionsFile = project.getSourceFiles().find(sf => { const filePath = sf.getDirectory().getPath(); return ( sf.getBaseName() === 'api-extensions.ts' && filePath.includes(plugin.getPluginDir().getPath()) && filePath.endsWith('/api') ); }); if (existingApiExtensionsFile) { return existingApiExtensionsFile; } return createFile( project, path.join(__dirname, 'templates/api-extensions.template.ts'), path.join(plugin.getPluginDir().getPath(), 'api', 'api-extensions.ts'), ); }
import gql from 'graphql-tag'; export const adminApiExtensions = gql``;
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { DeletionResponse, Permission } from '@vendure/common/lib/generated-types'; import { CustomFieldsObject } from '@vendure/common/lib/shared-types'; import { Allow, Ctx, PaginatedList, RequestContext, Transaction, Relations, VendureEntity, ID, TranslationInput, ListQueryOptions, RelationPaths, } from '@vendure/core'; class TemplateEntity extends VendureEntity { constructor() { super(); } } class TemplateService { findAll(ctx: RequestContext, options?: any, relations?: any): Promise<PaginatedList<TemplateEntity>> { throw new Error('Method not implemented.'); } findOne(ctx: RequestContext, id: ID, relations?: any): Promise<TemplateEntity | null> { throw new Error('Method not implemented.'); } create(ctx: RequestContext, input: any): Promise<TemplateEntity> { throw new Error('Method not implemented.'); } update(ctx: RequestContext, input: any): Promise<TemplateEntity> { throw new Error('Method not implemented.'); } delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { throw new Error('Method not implemented.'); } } // These can be replaced by generated types if you set up code generation interface CreateEntityInput { // Define the input fields here customFields?: CustomFieldsObject; translations: Array<TranslationInput<TemplateEntity>>; } interface UpdateEntityInput { id: ID; // Define the input fields here customFields?: CustomFieldsObject; translations: Array<TranslationInput<TemplateEntity>>; } @Resolver() export class EntityAdminResolver { constructor(private templateService: TemplateService) {} @Query() @Allow(Permission.SuperAdmin) async entity( @Ctx() ctx: RequestContext, @Args() args: { id: ID }, @Relations(TemplateEntity) relations: RelationPaths<TemplateEntity>, ): Promise<TemplateEntity | null> { return this.templateService.findOne(ctx, args.id, relations); } @Query() @Allow(Permission.SuperAdmin) async entities( @Ctx() ctx: RequestContext, @Args() args: { options: ListQueryOptions<TemplateEntity> }, @Relations(TemplateEntity) relations: RelationPaths<TemplateEntity>, ): Promise<PaginatedList<TemplateEntity>> { return this.templateService.findAll(ctx, args.options || undefined, relations); } @Mutation() @Transaction() @Allow(Permission.SuperAdmin) async createEntity( @Ctx() ctx: RequestContext, @Args() args: { input: CreateEntityInput }, ): Promise<TemplateEntity> { return this.templateService.create(ctx, args.input); } @Mutation() @Transaction() @Allow(Permission.SuperAdmin) async updateEntity( @Ctx() ctx: RequestContext, @Args() args: { input: UpdateEntityInput }, ): Promise<TemplateEntity> { return this.templateService.update(ctx, args.input); } @Mutation() @Transaction() @Allow(Permission.SuperAdmin) async deleteEntity(@Ctx() ctx: RequestContext, @Args() args: { id: ID }): Promise<DeletionResponse> { return this.templateService.delete(ctx, args.id); } }
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { Permission } from '@vendure/common/lib/generated-types'; import { ID } from '@vendure/common/lib/shared-types'; import { Allow, Ctx, RequestContext, Transaction } from '@vendure/core'; class TemplateService { async exampleQueryHandler(ctx: RequestContext, id: ID) { return true; } async exampleMutationHandler(ctx: RequestContext, id: ID) { return true; } } @Resolver() export class SimpleAdminResolver { constructor(private templateService: TemplateService) {} @Query() @Allow(Permission.SuperAdmin) async exampleQuery(@Ctx() ctx: RequestContext, @Args() args: { id: ID }): Promise<boolean> { return this.templateService.exampleQueryHandler(ctx, args.id); } @Mutation() @Transaction() @Allow(Permission.SuperAdmin) async exampleMutation(@Ctx() ctx: RequestContext, @Args() args: { id: ID }): Promise<boolean> { return this.templateService.exampleMutationHandler(ctx, args.id); } }
import { cancel, log, note, outro, spinner } from '@clack/prompts'; import path from 'path'; import { StructureKind } from 'ts-morph'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { PackageJson } from '../../../shared/package-json-ref'; import { analyzeProject, selectMultiplePluginClasses } from '../../../shared/shared-prompts'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { getRelativeImportPath } from '../../../utilities/ast-utils'; import { pauseForPromptDisplay } from '../../../utilities/utils'; import { CodegenConfigRef } from './codegen-config-ref'; export interface AddCodegenOptions { plugin?: VendurePluginRef; } export const addCodegenCommand = new CliCommand({ id: 'add-codegen', category: 'Project: Codegen', description: 'Set up GraphQL code generation', run: addCodegen, }); async function addCodegen(options?: AddCodegenOptions): Promise<CliCommandReturnVal> { const providedVendurePlugin = options?.plugin; const { project } = await analyzeProject({ providedVendurePlugin, cancelledMessage: 'Add codegen cancelled', }); const plugins = providedVendurePlugin ? [providedVendurePlugin] : await selectMultiplePluginClasses(project, 'Add codegen cancelled'); const packageJson = new PackageJson(project); const installSpinner = spinner(); installSpinner.start(`Installing dependencies...`); const packagesToInstall = [ { pkg: '@graphql-codegen/cli', isDevDependency: true, }, { pkg: '@graphql-codegen/typescript', isDevDependency: true, }, ]; if (plugins.some(p => p.hasUiExtensions())) { packagesToInstall.push({ pkg: '@graphql-codegen/client-preset', isDevDependency: true, }); } const packageManager = packageJson.determinePackageManager(); const packageJsonFile = packageJson.locatePackageJsonWithVendureDependency(); log.info(`Detected package manager: ${packageManager}`); if (!packageJsonFile) { cancel(`Could not locate package.json file with a dependency on Vendure.`); process.exit(1); } log.info(`Detected package.json: ${packageJsonFile}`); try { await packageJson.installPackages(packagesToInstall); } catch (e: any) { log.error(`Failed to install dependencies: ${e.message as string}.`); } installSpinner.stop('Dependencies installed'); const configSpinner = spinner(); configSpinner.start('Configuring codegen file...'); await pauseForPromptDisplay(); const codegenFile = new CodegenConfigRef(project, packageJson.getPackageRootDir()); const rootDir = project.getDirectory('.'); if (!rootDir) { throw new Error('Could not find the root directory of the project'); } for (const plugin of plugins) { const relativePluginPath = getRelativeImportPath({ from: rootDir, to: plugin.classDeclaration.getSourceFile(), }); const generatedTypesPath = `${path.dirname(relativePluginPath)}/gql/generated.ts`; codegenFile.addEntryToGeneratesObject({ name: `'${generatedTypesPath}'`, kind: StructureKind.PropertyAssignment, initializer: `{ plugins: ['typescript'] }`, }); if (plugin.hasUiExtensions()) { const uiExtensionsPath = `${path.dirname(relativePluginPath)}/ui`; codegenFile.addEntryToGeneratesObject({ name: `'${uiExtensionsPath}/gql/'`, kind: StructureKind.PropertyAssignment, initializer: `{ preset: 'client', documents: '${uiExtensionsPath}/**/*.ts', presetConfig: { fragmentMasking: false, }, }`, }); } } packageJson.addScript('codegen', 'graphql-codegen --config codegen.ts'); configSpinner.stop('Configured codegen file'); await project.save(); const nextSteps = [ `You can run codegen by doing the following:`, `1. Ensure your dev server is running`, `2. Run "npm run codegen"`, ]; note(nextSteps.join('\n')); return { project, modifiedSourceFiles: [codegenFile.sourceFile], }; }
import fs from 'fs-extra'; import path from 'path'; import { Directory, ObjectLiteralExpression, ObjectLiteralExpressionPropertyStructures, Project, PropertyAssignmentStructure, SourceFile, SyntaxKind, } from 'ts-morph'; import { createFile, getTsMorphProject } from '../../../utilities/ast-utils'; export class CodegenConfigRef { public readonly sourceFile: SourceFile; private configObject: ObjectLiteralExpression | undefined; constructor( private readonly project: Project, rootDir: Directory, ) { const codegenFilePath = path.join(rootDir.getPath(), 'codegen.ts'); if (fs.existsSync(codegenFilePath)) { this.sourceFile = this.project.addSourceFileAtPath(codegenFilePath); } else { this.sourceFile = createFile( this.project, path.join(__dirname, 'templates/codegen.template.ts'), path.join(rootDir.getPath(), 'codegen.ts'), ); } } addEntryToGeneratesObject(structure: PropertyAssignmentStructure) { const generatesProp = this.getConfigObject() .getProperty('generates') ?.getFirstChildByKind(SyntaxKind.ObjectLiteralExpression); if (!generatesProp) { throw new Error('Could not find the generates property in the template codegen file'); } if (generatesProp.getProperty(structure.name)) { return; } generatesProp.addProperty(structure).formatText(); } getConfigObject() { if (this.configObject) { return this.configObject; } const codegenConfig = this.sourceFile .getVariableDeclaration('config') ?.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0]; if (!codegenConfig) { throw new Error('Could not find the config variable in the template codegen file'); } this.configObject = codegenConfig; return this.configObject; } save() { return this.project.save(); } }
import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { overwrite: true, // This assumes your server is running on the standard port // and with the default admin API path. Adjust accordingly. schema: 'http://localhost:3000/admin-api', config: { // This tells codegen that the `Money` scalar is a number scalars: { Money: 'number' }, // This ensures generated enums do not conflict with the built-in types. namingConvention: { enumValues: 'keep' }, }, generates: {}, }; export default config;
import { cancel, isCancel, multiselect, spinner, text } from '@clack/prompts'; import { paramCase, pascalCase } from 'change-case'; import path from 'path'; import { ClassDeclaration, SourceFile } from 'ts-morph'; import { pascalCaseRegex } from '../../../constants'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { EntityRef } from '../../../shared/entity-ref'; import { analyzeProject, selectPlugin } from '../../../shared/shared-prompts'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { createFile } from '../../../utilities/ast-utils'; import { pauseForPromptDisplay } from '../../../utilities/utils'; import { addEntityToPlugin } from './codemods/add-entity-to-plugin/add-entity-to-plugin'; const cancelledMessage = 'Add entity cancelled'; export interface AddEntityOptions { plugin?: VendurePluginRef; className: string; fileName: string; translationFileName: string; features: { customFields: boolean; translatable: boolean; }; } export const addEntityCommand = new CliCommand({ id: 'add-entity', category: 'Plugin: Entity', description: 'Add a new entity to a plugin', run: options => addEntity(options), }); async function addEntity( options?: Partial<AddEntityOptions>, ): Promise<CliCommandReturnVal<{ entityRef: EntityRef }>> { const providedVendurePlugin = options?.plugin; const { project } = await analyzeProject({ providedVendurePlugin, cancelledMessage }); const vendurePlugin = providedVendurePlugin ?? (await selectPlugin(project, cancelledMessage)); const modifiedSourceFiles: SourceFile[] = []; const customEntityName = options?.className ?? (await getCustomEntityName(cancelledMessage)); const context: AddEntityOptions = { className: customEntityName, fileName: paramCase(customEntityName) + '.entity', translationFileName: paramCase(customEntityName) + '-translation.entity', features: await getFeatures(options), }; const entitySpinner = spinner(); entitySpinner.start('Creating entity...'); await pauseForPromptDisplay(); const { entityClass, translationClass } = createEntity(vendurePlugin, context); addEntityToPlugin(vendurePlugin, entityClass); modifiedSourceFiles.push(entityClass.getSourceFile()); if (context.features.translatable) { addEntityToPlugin(vendurePlugin, translationClass); modifiedSourceFiles.push(translationClass.getSourceFile()); } entitySpinner.stop('Entity created'); await project.save(); return { project, modifiedSourceFiles, entityRef: new EntityRef(entityClass), }; } async function getFeatures(options?: Partial<AddEntityOptions>): Promise<AddEntityOptions['features']> { if (options?.features) { return options?.features; } const features = await multiselect({ message: 'Entity features (use ↑, ↓, space to select)', required: false, initialValues: ['customFields'], options: [ { label: 'Custom fields', value: 'customFields', hint: 'Adds support for custom fields on this entity', }, { label: 'Translatable', value: 'translatable', hint: 'Adds support for localized properties on this entity', }, ], }); if (isCancel(features)) { cancel(cancelledMessage); process.exit(0); } return { customFields: features.includes('customFields'), translatable: features.includes('translatable'), }; } function createEntity(plugin: VendurePluginRef, options: AddEntityOptions) { const entitiesDir = path.join(plugin.getPluginDir().getPath(), 'entities'); const entityFile = createFile( plugin.getSourceFile().getProject(), path.join(__dirname, 'templates/entity.template.ts'), path.join(entitiesDir, `${options.fileName}.ts`), ); const translationFile = createFile( plugin.getSourceFile().getProject(), path.join(__dirname, 'templates/entity-translation.template.ts'), path.join(entitiesDir, `${options.translationFileName}.ts`), ); const entityClass = entityFile.getClass('ScaffoldEntity'); const customFieldsClass = entityFile.getClass('ScaffoldEntityCustomFields'); const translationClass = translationFile.getClass('ScaffoldTranslation'); const translationCustomFieldsClass = translationFile.getClass('ScaffoldEntityCustomFieldsTranslation'); if (!options.features.customFields) { // Remove custom fields from entity customFieldsClass?.remove(); translationCustomFieldsClass?.remove(); removeCustomFieldsFromClass(entityClass); removeCustomFieldsFromClass(translationClass); } if (!options.features.translatable) { // Remove translatable fields from entity translationClass?.remove(); entityClass?.getProperty('localizedName')?.remove(); entityClass?.getProperty('translations')?.remove(); removeImplementsFromClass('Translatable', entityClass); translationFile.delete(); } else { entityFile .getImportDeclaration('./entity-translation.template') ?.setModuleSpecifier(`./${options.translationFileName}`); translationFile .getImportDeclaration('./entity.template') ?.setModuleSpecifier(`./${options.fileName}`); } // Rename the entity classes entityClass?.rename(options.className); if (!customFieldsClass?.wasForgotten()) { customFieldsClass?.rename(`${options.className}CustomFields`); } if (!translationClass?.wasForgotten()) { translationClass?.rename(`${options.className}Translation`); } if (!translationCustomFieldsClass?.wasForgotten()) { translationCustomFieldsClass?.rename(`${options.className}CustomFieldsTranslation`); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return { entityClass: entityClass!, translationClass: translationClass! }; } function removeCustomFieldsFromClass(entityClass?: ClassDeclaration) { entityClass?.getProperty('customFields')?.remove(); removeImplementsFromClass('HasCustomFields', entityClass); } function removeImplementsFromClass(implementsName: string, entityClass?: ClassDeclaration) { const index = entityClass?.getImplements().findIndex(i => i.getText() === implementsName) ?? -1; if (index > -1) { entityClass?.removeImplements(index); } } export async function getCustomEntityName(_cancelledMessage: string) { const entityName = await text({ message: 'What is the name of the custom entity?', initialValue: '', validate: input => { if (!input) { return 'The custom entity name cannot be empty'; } if (!pascalCaseRegex.test(input)) { return 'The custom entity name must be in PascalCase, e.g. "ProductReview"'; } }, }); if (isCancel(entityName)) { cancel(_cancelledMessage); process.exit(0); } return pascalCase(entityName); }
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import path from 'path'; import { Project } from 'ts-morph'; import { describe, expect, it } from 'vitest'; import { defaultManipulationSettings } from '../../../../../constants'; import { VendurePluginRef } from '../../../../../shared/vendure-plugin-ref'; import { createFile, getPluginClasses } from '../../../../../utilities/ast-utils'; import { expectSourceFileContentToMatch } from '../../../../../utilities/testing-utils'; import { addEntityToPlugin } from './add-entity-to-plugin'; describe('addEntityToPlugin', () => { function testAddEntityToPlugin(options: { fixtureFileName: string; expectedFileName: string }) { const project = new Project({ manipulationSettings: defaultManipulationSettings, }); project.addSourceFileAtPath(path.join(__dirname, 'fixtures', options.fixtureFileName)); const pluginClasses = getPluginClasses(project); expect(pluginClasses.length).toBe(1); const entityTemplatePath = path.join(__dirname, '../../templates/entity.template.ts'); const entityFile = createFile( project, entityTemplatePath, path.join(__dirname, 'fixtures', 'entity.ts'), ); const entityClass = entityFile.getClass('ScaffoldEntity'); addEntityToPlugin(new VendurePluginRef(pluginClasses[0]), entityClass!); expectSourceFileContentToMatch( pluginClasses[0].getSourceFile(), path.join(__dirname, 'fixtures', options.expectedFileName), ); } it('creates entity prop and imports', () => { testAddEntityToPlugin({ fixtureFileName: 'no-entity-prop.fixture.ts', expectedFileName: 'no-entity-prop.expected', }); }); it('adds to existing entity prop and imports', () => { testAddEntityToPlugin({ fixtureFileName: 'existing-entity-prop.fixture.ts', expectedFileName: 'existing-entity-prop.expected', }); }); });
import { ClassDeclaration } from 'ts-morph'; import { VendurePluginRef } from '../../../../../shared/vendure-plugin-ref'; import { addImportsToFile } from '../../../../../utilities/ast-utils'; export function addEntityToPlugin(plugin: VendurePluginRef, entityClass: ClassDeclaration) { if (!entityClass) { throw new Error('Could not find entity class'); } const entityClassName = entityClass.getName() as string; plugin.addEntity(entityClassName); addImportsToFile(plugin.classDeclaration.getSourceFile(), { moduleSpecifier: entityClass.getSourceFile(), namedImports: [entityClassName], }); }
import { PluginCommonModule, Type, VendurePlugin, Product } from '@vendure/core'; type PluginInitOptions = any; @VendurePlugin({ imports: [PluginCommonModule], entities: [Product], compatibility: '^2.0.0', }) export class TestOnePlugin { static options: PluginInitOptions; static init(options: PluginInitOptions): Type<TestOnePlugin> { this.options = options; return TestOnePlugin; } }
import { PluginCommonModule, Type, VendurePlugin } from '@vendure/core'; type PluginInitOptions = any; @VendurePlugin({ imports: [PluginCommonModule], compatibility: '^2.0.0', }) export class TestOnePlugin { static options: PluginInitOptions; static init(options: PluginInitOptions): Type<TestOnePlugin> { this.options = options; return TestOnePlugin; } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { DeepPartial } from '@vendure/common/lib/shared-types'; import { HasCustomFields, Translation, VendureEntity } from '@vendure/core'; import { Column, Entity, Index, ManyToOne } from 'typeorm'; import { ScaffoldEntity } from './entity.template'; export class ScaffoldEntityCustomFieldsTranslation {} @Entity() export class ScaffoldTranslation extends VendureEntity implements Translation<ScaffoldEntity>, HasCustomFields { constructor(input?: DeepPartial<Translation<ScaffoldTranslation>>) { super(input); } @Column('varchar') languageCode: LanguageCode; @Column() localizedName: string; @Index() @ManyToOne(type => ScaffoldEntity, base => base.translations, { onDelete: 'CASCADE' }) base: ScaffoldEntity; @Column(type => ScaffoldEntityCustomFieldsTranslation) customFields: ScaffoldEntityCustomFieldsTranslation; }
import { DeepPartial, HasCustomFields, LocaleString, Translatable, Translation, VendureEntity, } from '@vendure/core'; import { Column, Entity, OneToMany } from 'typeorm'; import { ScaffoldTranslation } from './entity-translation.template'; export class ScaffoldEntityCustomFields {} @Entity() export class ScaffoldEntity extends VendureEntity implements Translatable, HasCustomFields { constructor(input?: DeepPartial<ScaffoldEntity>) { super(input); } @Column() code: string; @Column(type => ScaffoldEntityCustomFields) customFields: ScaffoldEntityCustomFields; localizedName: LocaleString; @OneToMany(type => ScaffoldTranslation, translation => translation.base, { eager: true }) translations: Array<Translation<ScaffoldEntity>>; }
import { cancel, isCancel, log, text } from '@clack/prompts'; import { camelCase, pascalCase } from 'change-case'; import { Node, Scope } from 'ts-morph'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { ServiceRef } from '../../../shared/service-ref'; import { analyzeProject, selectPlugin, selectServiceRef } from '../../../shared/shared-prompts'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { addImportsToFile } from '../../../utilities/ast-utils'; const cancelledMessage = 'Add API extension cancelled'; export interface AddJobQueueOptions { plugin?: VendurePluginRef; } export const addJobQueueCommand = new CliCommand({ id: 'add-job-queue', category: 'Plugin: Job Queue', description: 'Defines an new job queue on a service', run: options => addJobQueue(options), }); async function addJobQueue( options?: AddJobQueueOptions, ): Promise<CliCommandReturnVal<{ serviceRef: ServiceRef }>> { const providedVendurePlugin = options?.plugin; const { project } = await analyzeProject({ providedVendurePlugin, cancelledMessage }); const plugin = providedVendurePlugin ?? (await selectPlugin(project, cancelledMessage)); const serviceRef = await selectServiceRef(project, plugin); const jobQueueName = await text({ message: 'What is the name of the job queue?', initialValue: 'my-background-task', validate: input => { if (!/^[a-z][a-z-0-9]+$/.test(input)) { return 'The job queue name must be lowercase and contain only letters, numbers and dashes'; } }, }); if (isCancel(jobQueueName)) { cancel(cancelledMessage); process.exit(0); } addImportsToFile(serviceRef.classDeclaration.getSourceFile(), { moduleSpecifier: '@vendure/core', namedImports: ['JobQueue', 'JobQueueService', 'SerializedRequestContext'], }); addImportsToFile(serviceRef.classDeclaration.getSourceFile(), { moduleSpecifier: '@vendure/common/lib/generated-types', namedImports: ['JobState'], }); addImportsToFile(serviceRef.classDeclaration.getSourceFile(), { moduleSpecifier: '@nestjs/common', namedImports: ['OnModuleInit'], }); serviceRef.injectDependency({ name: 'jobQueueService', type: 'JobQueueService', }); const jobQueuePropertyName = camelCase(jobQueueName) + 'Queue'; serviceRef.classDeclaration.insertProperty(0, { name: jobQueuePropertyName, scope: Scope.Private, type: writer => writer.write('JobQueue<{ ctx: SerializedRequestContext, someArg: string; }>'), }); serviceRef.classDeclaration.addImplements('OnModuleInit'); let onModuleInitMethod = serviceRef.classDeclaration.getMethod('onModuleInit'); if (!onModuleInitMethod) { // Add this after the constructor const constructor = serviceRef.classDeclaration.getConstructors()[0]; const constructorChildIndex = constructor?.getChildIndex() ?? 0; onModuleInitMethod = serviceRef.classDeclaration.insertMethod(constructorChildIndex + 1, { name: 'onModuleInit', isAsync: false, returnType: 'void', scope: Scope.Public, }); } onModuleInitMethod.setIsAsync(true); onModuleInitMethod.setReturnType('Promise<void>'); const body = onModuleInitMethod.getBody(); if (Node.isBlock(body)) { body.addStatements(writer => { writer .write( `this.${jobQueuePropertyName} = await this.jobQueueService.createQueue({ name: '${jobQueueName}', process: async job => { // Deserialize the RequestContext from the job data const ctx = RequestContext.deserialize(job.data.ctx); // The "someArg" property is passed in when the job is triggered const someArg = job.data.someArg; // Inside the \`process\` function we define how each job // in the queue will be processed. // Let's simulate some long-running task const totalItems = 10; for (let i = 0; i < totalItems; i++) { await new Promise(resolve => setTimeout(resolve, 500)); // You can optionally respond to the job being cancelled // during processing. This can be useful for very long-running // tasks which can be cancelled by the user. if (job.state === JobState.CANCELLED) { throw new Error('Job was cancelled'); } // Progress can be reported as a percentage like this job.setProgress(Math.floor(i / totalItems * 100)); } // The value returned from the \`process\` function is stored // as the "result" field of the job return { processedCount: totalItems, message: \`Successfully processed \${totalItems} items\`, }; }, })`, ) .newLine(); }).forEach(s => s.formatText()); } serviceRef.classDeclaration .addMethod({ name: `trigger${pascalCase(jobQueueName)}`, scope: Scope.Public, parameters: [{ name: 'ctx', type: 'RequestContext' }], statements: writer => { writer.write(`return this.${jobQueuePropertyName}.add({ ctx: ctx.serialize(), someArg: 'foo', })`); }, }) .formatText(); log.success(`New job queue created in ${serviceRef.name}`); await project.save(); return { project, modifiedSourceFiles: [serviceRef.classDeclaration.getSourceFile()], serviceRef }; }
import { cancel, intro, isCancel, log, select, spinner, text } from '@clack/prompts'; import { constantCase, paramCase, pascalCase } from 'change-case'; import * as fs from 'fs-extra'; import path from 'path'; import { Project, SourceFile } from 'ts-morph'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { analyzeProject } from '../../../shared/shared-prompts'; import { VendureConfigRef } from '../../../shared/vendure-config-ref'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { addImportsToFile, createFile, getPluginClasses } from '../../../utilities/ast-utils'; import { pauseForPromptDisplay } from '../../../utilities/utils'; import { addApiExtensionCommand } from '../api-extension/add-api-extension'; import { addCodegenCommand } from '../codegen/add-codegen'; import { addEntityCommand } from '../entity/add-entity'; import { addJobQueueCommand } from '../job-queue/add-job-queue'; import { addServiceCommand } from '../service/add-service'; import { addUiExtensionsCommand } from '../ui-extensions/add-ui-extensions'; import { GeneratePluginOptions, NewPluginTemplateContext } from './types'; export const createNewPluginCommand = new CliCommand({ id: 'create-new-plugin', category: 'Plugin', description: 'Create a new Vendure plugin', run: createNewPlugin, }); const cancelledMessage = 'Plugin setup cancelled.'; export async function createNewPlugin(): Promise<CliCommandReturnVal> { const options: GeneratePluginOptions = { name: '', customEntityName: '', pluginDir: '' } as any; intro('Adding a new Vendure plugin!'); const { project } = await analyzeProject({ cancelledMessage }); if (!options.name) { const name = await text({ message: 'What is the name of the plugin?', initialValue: 'my-new-feature', validate: input => { if (!/^[a-z][a-z-0-9]+$/.test(input)) { return 'The plugin name must be lowercase and contain only letters, numbers and dashes'; } }, }); if (isCancel(name)) { cancel(cancelledMessage); process.exit(0); } else { options.name = name; } } const existingPluginDir = findExistingPluginsDir(project); const pluginDir = getPluginDirName(options.name, existingPluginDir); const confirmation = await text({ message: 'Plugin location', initialValue: pluginDir, placeholder: '', validate: input => { if (fs.existsSync(input)) { return `A directory named "${input}" already exists. Please specify a different directory.`; } }, }); if (isCancel(confirmation)) { cancel(cancelledMessage); process.exit(0); } options.pluginDir = confirmation; const { plugin, modifiedSourceFiles } = await generatePlugin(project, options); const configSpinner = spinner(); configSpinner.start('Updating VendureConfig...'); await pauseForPromptDisplay(); const vendureConfig = new VendureConfigRef(project); vendureConfig.addToPluginsArray(`${plugin.name}.init({})`); addImportsToFile(vendureConfig.sourceFile, { moduleSpecifier: plugin.getSourceFile(), namedImports: [plugin.name], }); await vendureConfig.sourceFile.getProject().save(); configSpinner.stop('Updated VendureConfig'); let done = false; const followUpCommands = [ addEntityCommand, addServiceCommand, addApiExtensionCommand, addJobQueueCommand, addUiExtensionsCommand, addCodegenCommand, ]; let allModifiedSourceFiles = [...modifiedSourceFiles]; while (!done) { const featureType = await select({ message: `Add features to ${options.name}?`, options: [ { value: 'no', label: "[Finish] No, I'm done!" }, ...followUpCommands.map(c => ({ value: c.id, label: `[${c.category}] ${c.description}`, })), ], }); if (isCancel(featureType)) { done = true; } if (featureType === 'no') { done = true; } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const command = followUpCommands.find(c => c.id === featureType)!; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion try { const result = await command.run({ plugin }); allModifiedSourceFiles = result.modifiedSourceFiles; // We format all modified source files and re-load the // project to avoid issues with the project state for (const sourceFile of allModifiedSourceFiles) { sourceFile.organizeImports(); } } catch (e: any) { log.error(`Error adding feature "${command.id}"`); log.error(e.stack); } } } return { project, modifiedSourceFiles: [], }; } export async function generatePlugin( project: Project, options: GeneratePluginOptions, ): Promise<{ plugin: VendurePluginRef; modifiedSourceFiles: SourceFile[] }> { const nameWithoutPlugin = options.name.replace(/-?plugin$/i, ''); const normalizedName = nameWithoutPlugin + '-plugin'; const templateContext: NewPluginTemplateContext = { ...options, pluginName: pascalCase(normalizedName), pluginInitOptionsName: constantCase(normalizedName) + '_OPTIONS', }; const projectSpinner = spinner(); projectSpinner.start('Generating plugin scaffold...'); await pauseForPromptDisplay(); const pluginFile = createFile( project, path.join(__dirname, 'templates/plugin.template.ts'), path.join(options.pluginDir, paramCase(nameWithoutPlugin) + '.plugin.ts'), ); const pluginClass = pluginFile.getClass('TemplatePlugin'); if (!pluginClass) { throw new Error('Could not find the plugin class in the generated file'); } pluginFile.getImportDeclaration('./constants.template')?.setModuleSpecifier('./constants'); pluginFile.getImportDeclaration('./types.template')?.setModuleSpecifier('./types'); pluginClass.rename(templateContext.pluginName); const typesFile = createFile( project, path.join(__dirname, 'templates/types.template.ts'), path.join(options.pluginDir, 'types.ts'), ); const constantsFile = createFile( project, path.join(__dirname, 'templates/constants.template.ts'), path.join(options.pluginDir, 'constants.ts'), ); constantsFile .getVariableDeclaration('TEMPLATE_PLUGIN_OPTIONS') ?.rename(templateContext.pluginInitOptionsName) .set({ initializer: `Symbol('${templateContext.pluginInitOptionsName}')` }); constantsFile .getVariableDeclaration('loggerCtx') ?.set({ initializer: `'${templateContext.pluginName}'` }); projectSpinner.stop('Generated plugin scaffold'); await project.save(); return { modifiedSourceFiles: [pluginFile, typesFile, constantsFile], plugin: new VendurePluginRef(pluginClass), }; } function findExistingPluginsDir(project: Project): { prefix: string; suffix: string } | undefined { const pluginClasses = getPluginClasses(project); if (pluginClasses.length === 0) { return; } const pluginDirs = pluginClasses.map(c => { return c.getSourceFile().getDirectoryPath(); }); const prefix = findCommonPath(pluginDirs); const suffixStartIndex = prefix.length; const rest = pluginDirs[0].substring(suffixStartIndex).replace(/^\//, '').split('/'); const suffix = rest.length > 1 ? rest.slice(1).join('/') : ''; return { prefix, suffix }; } function getPluginDirName( name: string, existingPluginDirPattern: { prefix: string; suffix: string } | undefined, ) { const cwd = process.cwd(); const nameWithoutPlugin = name.replace(/-?plugin$/i, ''); if (existingPluginDirPattern) { return path.join( existingPluginDirPattern.prefix, paramCase(nameWithoutPlugin), existingPluginDirPattern.suffix, ); } else { return path.join(cwd, 'src', 'plugins', paramCase(nameWithoutPlugin)); } } function findCommonPath(paths: string[]): string { if (paths.length === 0) { return ''; // If no paths provided, return empty string } // Split each path into segments const pathSegmentsList = paths.map(p => p.split('/')); // Find the minimum length of path segments (to avoid out of bounds) const minLength = Math.min(...pathSegmentsList.map(segments => segments.length)); // Initialize the common path const commonPath: string[] = []; // Loop through each segment index up to the minimum length for (let i = 0; i < minLength; i++) { // Get the segment at the current index from the first path const currentSegment = pathSegmentsList[0][i]; // Check if this segment is common across all paths const isCommon = pathSegmentsList.every(segments => segments[i] === currentSegment); if (isCommon) { // If it's common, add this segment to the common path commonPath.push(currentSegment); } else { // If it's not common, break out of the loop break; } } // Join the common path segments back into a string return commonPath.join('/'); }
export interface GeneratePluginOptions { name: string; pluginDir: string; } export type NewPluginTemplateContext = GeneratePluginOptions & { pluginName: string; pluginInitOptionsName: string; };
export const TEMPLATE_PLUGIN_OPTIONS = Symbol('TEMPLATE_PLUGIN_OPTIONS'); export const loggerCtx = 'TemplatePlugin';
import { PluginCommonModule, Type, VendurePlugin } from '@vendure/core'; import { TEMPLATE_PLUGIN_OPTIONS } from './constants.template'; import { PluginInitOptions } from './types.template'; @VendurePlugin({ imports: [PluginCommonModule], providers: [{ provide: TEMPLATE_PLUGIN_OPTIONS, useFactory: () => TemplatePlugin.options }], configuration: config => { // Plugin-specific configuration // such as custom fields, custom permissions, // strategies etc. can be configured here by // modifying the `config` object. return config; }, compatibility: '^2.0.0', }) export class TemplatePlugin { static options: PluginInitOptions; static init(options: PluginInitOptions): Type<TemplatePlugin> { this.options = options; return TemplatePlugin; } }
/** * @description * The plugin can be configured using the following options: */ export interface PluginInitOptions { exampleOption?: string; }
import { cancel, isCancel, log, select, spinner, text } from '@clack/prompts'; import { paramCase } from 'change-case'; import path from 'path'; import { ClassDeclaration, Scope, SourceFile } from 'ts-morph'; import { Messages, pascalCaseRegex } from '../../../constants'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { EntityRef } from '../../../shared/entity-ref'; import { ServiceRef } from '../../../shared/service-ref'; import { analyzeProject, selectEntity, selectPlugin } from '../../../shared/shared-prompts'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { addImportsToFile, createFile, customizeCreateUpdateInputInterfaces, } from '../../../utilities/ast-utils'; import { pauseForPromptDisplay } from '../../../utilities/utils'; import { addEntityCommand } from '../entity/add-entity'; const cancelledMessage = 'Add service cancelled'; interface AddServiceOptions { plugin?: VendurePluginRef; type: 'basic' | 'entity'; serviceName: string; entityRef?: EntityRef; } export const addServiceCommand = new CliCommand({ id: 'add-service', category: 'Plugin: Service', description: 'Add a new service to a plugin', run: options => addService(options), }); async function addService( providedOptions?: Partial<AddServiceOptions>, ): Promise<CliCommandReturnVal<{ serviceRef: ServiceRef }>> { const providedVendurePlugin = providedOptions?.plugin; const { project } = await analyzeProject({ providedVendurePlugin, cancelledMessage }); const vendurePlugin = providedVendurePlugin ?? (await selectPlugin(project, cancelledMessage)); const modifiedSourceFiles: SourceFile[] = []; const type = providedOptions?.type ?? (await select({ message: 'What type of service would you like to add?', options: [ { value: 'basic', label: 'Basic empty service' }, { value: 'entity', label: 'Service to perform CRUD operations on an entity' }, ], maxItems: 10, })); if (isCancel(type)) { cancel('Cancelled'); process.exit(0); } const options: AddServiceOptions = { type: type as AddServiceOptions['type'], serviceName: 'MyService', }; if (type === 'entity') { let entityRef: EntityRef; try { entityRef = await selectEntity(vendurePlugin); } catch (e: any) { if (e.message === Messages.NoEntitiesFound) { log.info(`No entities found in plugin ${vendurePlugin.name}. Let's create one first.`); const result = await addEntityCommand.run({ plugin: vendurePlugin }); entityRef = result.entityRef; modifiedSourceFiles.push(...result.modifiedSourceFiles); } else { throw e; } } options.entityRef = entityRef; options.serviceName = `${entityRef.name}Service`; } const serviceSpinner = spinner(); let serviceSourceFile: SourceFile; let serviceClassDeclaration: ClassDeclaration; if (options.type === 'basic') { const name = await text({ message: 'What is the name of the new service?', initialValue: 'MyService', validate: input => { if (!input) { return 'The service name cannot be empty'; } if (!pascalCaseRegex.test(input)) { return 'The service name must be in PascalCase, e.g. "MyService"'; } }, }); if (isCancel(name)) { cancel(cancelledMessage); process.exit(0); } options.serviceName = name; serviceSpinner.start(`Creating ${options.serviceName}...`); const serviceSourceFilePath = getServiceFilePath(vendurePlugin, options.serviceName); await pauseForPromptDisplay(); serviceSourceFile = createFile( project, path.join(__dirname, 'templates/basic-service.template.ts'), serviceSourceFilePath, ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion serviceClassDeclaration = serviceSourceFile .getClass('BasicServiceTemplate')! .rename(options.serviceName); } else { serviceSpinner.start(`Creating ${options.serviceName}...`); await pauseForPromptDisplay(); const serviceSourceFilePath = getServiceFilePath(vendurePlugin, options.serviceName); serviceSourceFile = createFile( project, path.join(__dirname, 'templates/entity-service.template.ts'), serviceSourceFilePath, ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion serviceClassDeclaration = serviceSourceFile .getClass('EntityServiceTemplate')! .rename(options.serviceName); const entityRef = options.entityRef; if (!entityRef) { throw new Error('Entity class not found'); } const templateEntityClass = serviceSourceFile.getClass('TemplateEntity'); if (templateEntityClass) { templateEntityClass.rename(entityRef.name); templateEntityClass.remove(); } addImportsToFile(serviceClassDeclaration.getSourceFile(), { moduleSpecifier: entityRef.classDeclaration.getSourceFile(), namedImports: [entityRef.name], }); const templateTranslationEntityClass = serviceSourceFile.getClass('TemplateEntityTranslation'); if (entityRef.isTranslatable()) { const translationEntityClass = entityRef.getTranslationClass(); if (translationEntityClass && templateTranslationEntityClass) { templateTranslationEntityClass.rename(translationEntityClass?.getName() as string); templateTranslationEntityClass.remove(); addImportsToFile(serviceClassDeclaration.getSourceFile(), { moduleSpecifier: translationEntityClass.getSourceFile(), namedImports: [translationEntityClass.getName() as string], }); } } else { templateTranslationEntityClass?.remove(); } customizeCreateUpdateInputInterfaces(serviceSourceFile, entityRef); customizeFindOneMethod(serviceClassDeclaration, entityRef); customizeFindAllMethod(serviceClassDeclaration, entityRef); customizeCreateMethod(serviceClassDeclaration, entityRef); customizeUpdateMethod(serviceClassDeclaration, entityRef); removedUnusedConstructorArgs(serviceClassDeclaration, entityRef); } const pluginOptions = vendurePlugin.getPluginOptions(); if (pluginOptions) { addImportsToFile(serviceSourceFile, { moduleSpecifier: pluginOptions.constantDeclaration.getSourceFile(), namedImports: [pluginOptions.constantDeclaration.getName()], }); addImportsToFile(serviceSourceFile, { moduleSpecifier: pluginOptions.typeDeclaration.getSourceFile(), namedImports: [pluginOptions.typeDeclaration.getName()], }); addImportsToFile(serviceSourceFile, { moduleSpecifier: '@nestjs/common', namedImports: ['Inject'], }); serviceClassDeclaration .getConstructors()[0] ?.addParameter({ scope: Scope.Private, name: 'options', type: pluginOptions.typeDeclaration.getName(), decorators: [{ name: 'Inject', arguments: [pluginOptions.constantDeclaration.getName()] }], }) .formatText(); } modifiedSourceFiles.push(serviceSourceFile); serviceSpinner.message(`Registering service with plugin...`); vendurePlugin.addProvider(options.serviceName); addImportsToFile(vendurePlugin.classDeclaration.getSourceFile(), { moduleSpecifier: serviceSourceFile, namedImports: [options.serviceName], }); await project.save(); serviceSpinner.stop(`${options.serviceName} created`); return { project, modifiedSourceFiles, serviceRef: new ServiceRef(serviceClassDeclaration), }; } function getServiceFilePath(plugin: VendurePluginRef, serviceName: string) { const serviceFileName = paramCase(serviceName).replace(/-service$/, '.service'); return path.join(plugin.getPluginDir().getPath(), 'services', `${serviceFileName}.ts`); } function customizeFindOneMethod(serviceClassDeclaration: ClassDeclaration, entityRef: EntityRef) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const findOneMethod = serviceClassDeclaration.getMethod('findOne')!; findOneMethod .setBodyText(writer => { writer.write(` return this.connection .getRepository(ctx, ${entityRef.name}) .findOne({ where: { id }, relations, })`); if (entityRef.isTranslatable()) { writer.write(`.then(entity => entity && this.translator.translate(entity, ctx));`); } else { writer.write(`;`); } }) .formatText(); if (!entityRef.isTranslatable()) { findOneMethod.setReturnType(`Promise<${entityRef.name} | null>`); } } function customizeFindAllMethod(serviceClassDeclaration: ClassDeclaration, entityRef: EntityRef) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const findAllMethod = serviceClassDeclaration.getMethod('findAll')!; findAllMethod .setBodyText(writer => { writer.writeLine(`return this.listQueryBuilder`); writer.write(`.build(${entityRef.name}, options,`).block(() => { writer.writeLine('relations,'); writer.writeLine('ctx,'); }); writer.write(')'); writer.write('.getManyAndCount()'); writer.write('.then(([items, totalItems]) =>').block(() => { writer.write('return').block(() => { if (entityRef.isTranslatable()) { writer.writeLine('items: items.map(item => this.translator.translate(item, ctx)),'); } else { writer.writeLine('items,'); } writer.writeLine('totalItems,'); }); }); writer.write(');'); }) .formatText(); if (!entityRef.isTranslatable()) { findAllMethod.setReturnType(`Promise<PaginatedList<${entityRef.name}>>`); } } function customizeCreateMethod(serviceClassDeclaration: ClassDeclaration, entityRef: EntityRef) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const createMethod = serviceClassDeclaration.getMethod('create')!; createMethod .setBodyText(writer => { if (entityRef.isTranslatable()) { writer.write(`const newEntity = await this.translatableSaver.create({ ctx, input, entityType: ${entityRef.name}, translationType: ${entityRef.getTranslationClass()?.getName() as string}, beforeSave: async f => { // Any pre-save logic can go here }, });`); } else { writer.writeLine( `const newEntity = await this.connection.getRepository(ctx, ${entityRef.name}).save(input);`, ); } if (entityRef.hasCustomFields()) { writer.writeLine( `await this.customFieldRelationService.updateRelations(ctx, ${entityRef.name}, input, newEntity);`, ); } writer.writeLine(`return assertFound(this.findOne(ctx, newEntity.id));`); }) .formatText(); if (!entityRef.isTranslatable()) { createMethod.setReturnType(`Promise<${entityRef.name}>`); } } function customizeUpdateMethod(serviceClassDeclaration: ClassDeclaration, entityRef: EntityRef) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const updateMethod = serviceClassDeclaration.getMethod('update')!; updateMethod .setBodyText(writer => { if (entityRef.isTranslatable()) { writer.write(`const updatedEntity = await this.translatableSaver.update({ ctx, input, entityType: ${entityRef.name}, translationType: ${entityRef.getTranslationClass()?.getName() as string}, beforeSave: async f => { // Any pre-save logic can go here }, });`); } else { writer.writeLine( `const entity = await this.connection.getEntityOrThrow(ctx, ${entityRef.name}, input.id);`, ); writer.writeLine(`const updatedEntity = patchEntity(entity, input);`); writer.writeLine( `await this.connection.getRepository(ctx, ${entityRef.name}).save(updatedEntity, { reload: false });`, ); } if (entityRef.hasCustomFields()) { writer.writeLine( `await this.customFieldRelationService.updateRelations(ctx, ${entityRef.name}, input, updatedEntity);`, ); } writer.writeLine(`return assertFound(this.findOne(ctx, updatedEntity.id));`); }) .formatText(); if (!entityRef.isTranslatable()) { updateMethod.setReturnType(`Promise<${entityRef.name}>`); } } function removedUnusedConstructorArgs(serviceClassDeclaration: ClassDeclaration, entityRef: EntityRef) { const isTranslatable = entityRef.isTranslatable(); const hasCustomFields = entityRef.hasCustomFields(); serviceClassDeclaration.getConstructors().forEach(constructor => { constructor.getParameters().forEach(param => { const paramName = param.getName(); if ((paramName === 'translatableSaver' || paramName === 'translator') && !isTranslatable) { param.remove(); } if (paramName === 'customFieldRelationService' && !hasCustomFields) { param.remove(); } }); }); }
import { Injectable } from '@nestjs/common'; import { ID, Product, RequestContext, TransactionalConnection } from '@vendure/core'; @Injectable() export class BasicServiceTemplate { constructor(private connection: TransactionalConnection) {} async exampleMethod(ctx: RequestContext, id: ID) { // Add your method logic here const result = await this.connection.getRepository(ctx, Product).findOne({ where: { id } }); return result; } }
import { Injectable } from '@nestjs/common'; import { DeletionResponse, DeletionResult, LanguageCode } from '@vendure/common/lib/generated-types'; import { CustomFieldsObject, ID, PaginatedList } from '@vendure/common/lib/shared-types'; import { assertFound, CustomFieldRelationService, HasCustomFields, ListQueryBuilder, ListQueryOptions, RelationPaths, RequestContext, TransactionalConnection, Translatable, TranslatableSaver, Translated, Translation, TranslationInput, TranslatorService, VendureEntity, patchEntity, } from '@vendure/core'; // These can be replaced by generated types if you set up code generation interface CreateEntityInput { // Define the input fields here customFields?: CustomFieldsObject; translations: Array<TranslationInput<TemplateEntity>>; } interface UpdateEntityInput { id: ID; // Define the input fields here customFields?: CustomFieldsObject; translations: Array<TranslationInput<TemplateEntity>>; } class TemplateEntity extends VendureEntity implements Translatable, HasCustomFields { constructor() { super(); } customFields: CustomFieldsObject; translations: Array<Translation<TemplateEntity>>; } class TemplateEntityTranslation extends VendureEntity implements Translation<TemplateEntity> { constructor() { super(); } id: ID; languageCode: LanguageCode; base: TemplateEntity; customFields: CustomFieldsObject; } @Injectable() export class EntityServiceTemplate { constructor( private connection: TransactionalConnection, private translatableSaver: TranslatableSaver, private listQueryBuilder: ListQueryBuilder, private customFieldRelationService: CustomFieldRelationService, private translator: TranslatorService, ) {} findAll( ctx: RequestContext, options?: ListQueryOptions<TemplateEntity>, relations?: RelationPaths<TemplateEntity>, ): Promise<PaginatedList<Translated<TemplateEntity>>> { return this.listQueryBuilder .build(TemplateEntity, options, { relations, ctx, }) .getManyAndCount() .then(([_items, totalItems]) => { const items = _items.map(item => this.translator.translate(item, ctx)); return { items, totalItems, }; }); } findOne( ctx: RequestContext, id: ID, relations?: RelationPaths<TemplateEntity>, ): Promise<Translated<TemplateEntity> | null> { return this.connection .getRepository(ctx, TemplateEntity) .findOne({ where: { id }, relations, }) .then(entity => entity && this.translator.translate(entity, ctx)); } async create(ctx: RequestContext, input: CreateEntityInput): Promise<Translated<TemplateEntity>> { const newEntity = await this.translatableSaver.create({ ctx, input, entityType: TemplateEntity, translationType: TemplateEntityTranslation, beforeSave: async f => { // Any pre-save logic can go here }, }); // Ensure any custom field relations get saved await this.customFieldRelationService.updateRelations(ctx, TemplateEntity, input, newEntity); return assertFound(this.findOne(ctx, newEntity.id)); } async update(ctx: RequestContext, input: UpdateEntityInput): Promise<Translated<TemplateEntity>> { const updatedEntity = await this.translatableSaver.update({ ctx, input, entityType: TemplateEntity, translationType: TemplateEntityTranslation, beforeSave: async f => { // Any pre-save logic can go here }, }); // This is just here to stop the import being removed by the IDE patchEntity(updatedEntity, {}); await this.customFieldRelationService.updateRelations(ctx, TemplateEntity, input, updatedEntity); return assertFound(this.findOne(ctx, updatedEntity.id)); } async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> { const entity = await this.connection.getEntityOrThrow(ctx, TemplateEntity, id); try { await this.connection.getRepository(ctx, TemplateEntity).remove(entity); return { result: DeletionResult.DELETED, }; } catch (e: any) { return { result: DeletionResult.NOT_DELETED, message: e.toString(), }; } } }
import { cancel, log, note, outro, spinner } from '@clack/prompts'; import fs from 'fs-extra'; import path from 'path'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { PackageJson } from '../../../shared/package-json-ref'; import { analyzeProject, selectPlugin } from '../../../shared/shared-prompts'; import { VendureConfigRef } from '../../../shared/vendure-config-ref'; import { VendurePluginRef } from '../../../shared/vendure-plugin-ref'; import { createFile, getRelativeImportPath } from '../../../utilities/ast-utils'; import { addUiExtensionStaticProp } from './codemods/add-ui-extension-static-prop/add-ui-extension-static-prop'; import { updateAdminUiPluginInit } from './codemods/update-admin-ui-plugin-init/update-admin-ui-plugin-init'; export interface AddUiExtensionsOptions { plugin?: VendurePluginRef; } export const addUiExtensionsCommand = new CliCommand<AddUiExtensionsOptions>({ id: 'add-ui-extensions', category: 'Plugin: UI', description: 'Set up Admin UI extensions', run: options => addUiExtensions(options), }); async function addUiExtensions(options?: AddUiExtensionsOptions): Promise<CliCommandReturnVal> { const providedVendurePlugin = options?.plugin; const { project } = await analyzeProject({ providedVendurePlugin }); const vendurePlugin = providedVendurePlugin ?? (await selectPlugin(project, 'Add UI extensions cancelled')); const packageJson = new PackageJson(project); if (vendurePlugin.hasUiExtensions()) { outro('This plugin already has UI extensions configured'); return { project, modifiedSourceFiles: [] }; } addUiExtensionStaticProp(vendurePlugin); log.success('Updated the plugin class'); const installSpinner = spinner(); const packageManager = packageJson.determinePackageManager(); const packageJsonFile = packageJson.locatePackageJsonWithVendureDependency(); log.info(`Detected package manager: ${packageManager}`); if (!packageJsonFile) { cancel(`Could not locate package.json file with a dependency on Vendure.`); process.exit(1); } log.info(`Detected package.json: ${packageJsonFile}`); installSpinner.start(`Installing dependencies using ${packageManager}...`); try { const version = packageJson.determineVendureVersion(); await packageJson.installPackages([ { pkg: '@vendure/ui-devkit', isDevDependency: true, version, }, ]); } catch (e: any) { log.error(`Failed to install dependencies: ${e.message as string}.`); } installSpinner.stop('Dependencies installed'); const pluginDir = vendurePlugin.getPluginDir().getPath(); const providersFileDest = path.join(pluginDir, 'ui', 'providers.ts'); if (!fs.existsSync(providersFileDest)) { createFile(project, path.join(__dirname, 'templates/providers.template.ts'), providersFileDest); } const routesFileDest = path.join(pluginDir, 'ui', 'routes.ts'); if (!fs.existsSync(routesFileDest)) { createFile(project, path.join(__dirname, 'templates/routes.template.ts'), routesFileDest); } log.success('Created UI extension scaffold'); const vendureConfig = new VendureConfigRef(project); if (!vendureConfig) { log.warning( `Could not find the VendureConfig declaration in your project. You will need to manually set up the compileUiExtensions function.`, ); } else { const pluginClassName = vendurePlugin.name; const pluginPath = getRelativeImportPath({ to: vendurePlugin.classDeclaration.getSourceFile(), from: vendureConfig.sourceFile, }); const updated = updateAdminUiPluginInit(vendureConfig, { pluginClassName, pluginPath }); if (updated) { log.success('Updated VendureConfig file'); } else { log.warning(`Could not update \`AdminUiPlugin.init()\` options.`); note( `You will need to manually set up the compileUiExtensions function,\nadding ` + `the \`${pluginClassName}.ui\` object to the \`extensions\` array.`, 'Info', ); } } await project.save(); return { project, modifiedSourceFiles: [vendurePlugin.classDeclaration.getSourceFile()] }; }
import path from 'path'; import { Project } from 'ts-morph'; import { describe, expect, it } from 'vitest'; import { defaultManipulationSettings } from '../../../../../constants'; import { VendurePluginRef } from '../../../../../shared/vendure-plugin-ref'; import { getPluginClasses } from '../../../../../utilities/ast-utils'; import { expectSourceFileContentToMatch } from '../../../../../utilities/testing-utils'; import { addUiExtensionStaticProp } from './add-ui-extension-static-prop'; describe('addUiExtensionStaticProp', () => { it('add ui prop and imports', () => { const project = new Project({ manipulationSettings: defaultManipulationSettings, }); project.addSourceFileAtPath(path.join(__dirname, 'fixtures', 'no-ui-prop.fixture.ts')); const pluginClasses = getPluginClasses(project); expect(pluginClasses.length).toBe(1); addUiExtensionStaticProp(new VendurePluginRef(pluginClasses[0])); expectSourceFileContentToMatch( pluginClasses[0].getSourceFile(), path.join(__dirname, 'fixtures', 'no-ui-prop.expected'), ); }); });
import { paramCase } from 'change-case'; import { AdminUiExtensionTypeName } from '../../../../../constants'; import { VendurePluginRef } from '../../../../../shared/vendure-plugin-ref'; import { addImportsToFile } from '../../../../../utilities/ast-utils'; /** * @description * Adds the static `ui` property to the plugin class, and adds the required imports. */ export function addUiExtensionStaticProp(plugin: VendurePluginRef) { const pluginClass = plugin.classDeclaration; const adminUiExtensionType = AdminUiExtensionTypeName; const extensionId = paramCase(pluginClass.getName() as string).replace(/-plugin$/, ''); pluginClass .addProperty({ name: 'ui', isStatic: true, type: adminUiExtensionType, initializer: `{ id: '${extensionId}-ui', extensionPath: path.join(__dirname, 'ui'), routes: [{ route: '${extensionId}', filePath: 'routes.ts' }], providers: ['providers.ts'], }`, }) .formatText(); // Add the AdminUiExtension import if it doesn't already exist addImportsToFile(pluginClass.getSourceFile(), { moduleSpecifier: '@vendure/ui-devkit/compiler', namedImports: [adminUiExtensionType], order: 0, }); // Add the path import if it doesn't already exist addImportsToFile(pluginClass.getSourceFile(), { moduleSpecifier: 'path', namespaceImport: 'path', order: 0, }); }
import { PluginCommonModule, Type, VendurePlugin } from '@vendure/core'; type PluginInitOptions = any; @VendurePlugin({ imports: [PluginCommonModule], compatibility: '^2.0.0', }) export class TestOnePlugin { static options: PluginInitOptions; static init(options: PluginInitOptions): Type<TestOnePlugin> { this.options = options; return TestOnePlugin; } }
import path from 'path'; import { Project } from 'ts-morph'; import { describe, it } from 'vitest'; import { defaultManipulationSettings } from '../../../../../constants'; import { VendureConfigRef } from '../../../../../shared/vendure-config-ref'; import { expectSourceFileContentToMatch } from '../../../../../utilities/testing-utils'; import { updateAdminUiPluginInit } from './update-admin-ui-plugin-init'; describe('updateAdminUiPluginInit', () => { it('adds app prop', () => { const project = new Project({ manipulationSettings: defaultManipulationSettings, }); project.addSourceFileAtPath(path.join(__dirname, 'fixtures', 'no-app-prop.fixture.ts')); const vendureConfig = new VendureConfigRef(project, { checkFileName: false }); updateAdminUiPluginInit(vendureConfig, { pluginClassName: 'TestPlugin', pluginPath: './plugins/test-plugin/test.plugin', }); expectSourceFileContentToMatch( project.getSourceFiles()[0], path.join(__dirname, 'fixtures', 'no-app-prop.expected'), ); }); // TODO: figure out why failing in CI but passing locally it.skip('adds to existing ui extensions array', () => { const project = new Project({ manipulationSettings: defaultManipulationSettings, }); project.addSourceFileAtPath(path.join(__dirname, 'fixtures', 'existing-app-prop.fixture.ts')); const vendureConfig = new VendureConfigRef(project, { checkFileName: false }); updateAdminUiPluginInit(vendureConfig, { pluginClassName: 'TestPlugin', pluginPath: './plugins/test-plugin/test.plugin', }); expectSourceFileContentToMatch( project.getSourceFiles()[0], path.join(__dirname, 'fixtures', 'existing-app-prop.expected'), ); }); });
import { Node, ObjectLiteralExpression, StructureKind, SyntaxKind } from 'ts-morph'; import { AdminUiAppConfigName } from '../../../../../constants'; import { VendureConfigRef } from '../../../../../shared/vendure-config-ref'; import { addImportsToFile } from '../../../../../utilities/ast-utils'; export function updateAdminUiPluginInit( vendureConfig: VendureConfigRef, options: { pluginClassName: string; pluginPath: string }, ): boolean { const adminUiPlugin = vendureConfig .getPluginsArray() ?.getChildrenOfKind(SyntaxKind.CallExpression) .find(c => { return c.getExpression().getText() === 'AdminUiPlugin.init'; }); if (adminUiPlugin) { const initObject = adminUiPlugin .getArguments() .find((a): a is ObjectLiteralExpression => a.isKind(SyntaxKind.ObjectLiteralExpression)); const appProperty = initObject?.getProperty('app'); if (!appProperty) { initObject ?.addProperty({ name: 'app', kind: StructureKind.PropertyAssignment, initializer: `compileUiExtensions({ outputPath: path.join(__dirname, '../admin-ui'), extensions: [ ${options.pluginClassName}.ui, ], devMode: true, }),`, }) .formatText(); } else { const computeFnCall = appProperty.getFirstChildByKind(SyntaxKind.CallExpression); if (computeFnCall?.getType().getText().includes(AdminUiAppConfigName)) { const arg = computeFnCall.getArguments()[0]; if (arg && Node.isObjectLiteralExpression(arg)) { const extensionsProp = arg.getProperty('extensions'); if (extensionsProp) { extensionsProp .getFirstChildByKind(SyntaxKind.ArrayLiteralExpression) ?.addElement(`${options.pluginClassName}.ui`) .formatText(); } } } } addImportsToFile(vendureConfig.sourceFile, { moduleSpecifier: '@vendure/ui-devkit/compiler', namedImports: ['compileUiExtensions'], order: 0, }); addImportsToFile(vendureConfig.sourceFile, { moduleSpecifier: 'path', namespaceImport: 'path', order: 0, }); addImportsToFile(vendureConfig.sourceFile, { moduleSpecifier: options.pluginPath, namedImports: [options.pluginClassName], }); return true; } return false; }
import { AdminUiPlugin } from '@vendure/admin-ui-plugin'; import { DefaultJobQueuePlugin, dummyPaymentHandler, VendureConfig } from '@vendure/core'; import { compileUiExtensions } from '@vendure/ui-devkit/compiler'; import path from 'path'; export const config: VendureConfig = { apiOptions: { port: 3000, adminApiPath: 'admin-api', }, authOptions: { tokenMethod: ['bearer', 'cookie'], }, dbConnectionOptions: { synchronize: true, type: 'mariadb', host: '127.0.0.1', port: 3306, username: 'root', password: '', database: 'vendure-dev', }, paymentOptions: { paymentMethodHandlers: [dummyPaymentHandler], }, // When adding or altering custom field definitions, the database will // need to be updated. See the "Migrations" section in README.md. customFields: {}, plugins: [ DefaultJobQueuePlugin.init({ useDatabaseForBuffer: true }), AdminUiPlugin.init({ route: 'admin', port: 3002, adminUiConfig: { apiPort: 3000, }, app: compileUiExtensions({ outputPath: path.join(__dirname, '../admin-ui'), extensions: [ { id: 'existing-ui-plugin', extensionPath: path.join(__dirname, 'existing-ui-plugin'), providers: ['providers.ts'], }, ], devMode: true, }), }), ], };
import { AdminUiPlugin } from '@vendure/admin-ui-plugin'; import { DefaultJobQueuePlugin, dummyPaymentHandler, VendureConfig } from '@vendure/core'; export const config: VendureConfig = { apiOptions: { port: 3000, adminApiPath: 'admin-api', }, authOptions: { tokenMethod: ['bearer', 'cookie'], }, dbConnectionOptions: { synchronize: true, type: 'mariadb', host: '127.0.0.1', port: 3306, username: 'root', password: '', database: 'vendure-dev', }, paymentOptions: { paymentMethodHandlers: [dummyPaymentHandler], }, // When adding or altering custom field definitions, the database will // need to be updated. See the "Migrations" section in README.md. customFields: {}, plugins: [ DefaultJobQueuePlugin.init({ useDatabaseForBuffer: true }), AdminUiPlugin.init({ route: 'admin', port: 3002, adminUiConfig: { apiPort: 3000, }, }), ], };
export default [ // Add your providers here ];
export default [ // Add your custom routes here ];
import { VendureConfig } from '@vendure/core'; import path from 'node:path'; import { register } from 'ts-node'; import { VendureConfigRef } from '../../shared/vendure-config-ref'; import { selectTsConfigFile } from '../../utilities/ast-utils'; import { isRunningInTsNode } from '../../utilities/utils'; export async function loadVendureConfigFile( vendureConfig: VendureConfigRef, providedTsConfigPath?: string, ): Promise<VendureConfig> { await import('dotenv/config'); if (!isRunningInTsNode()) { let tsConfigPath: string; if (providedTsConfigPath) { tsConfigPath = providedTsConfigPath; } else { const tsConfigFile = await selectTsConfigFile(); tsConfigPath = path.join(process.cwd(), tsConfigFile); } // eslint-disable-next-line @typescript-eslint/no-var-requires const compilerOptions = require(tsConfigPath).compilerOptions; register({ compilerOptions: { ...compilerOptions, moduleResolution: 'NodeNext', module: 'NodeNext' }, transpileOnly: true, }); if (compilerOptions.paths) { // eslint-disable-next-line @typescript-eslint/no-var-requires const tsConfigPaths = require('tsconfig-paths'); tsConfigPaths.register({ baseUrl: './', paths: compilerOptions.paths, }); } } const exportedVarName = vendureConfig.getConfigObjectVariableName(); if (!exportedVarName) { throw new Error('Could not find the exported variable name in the VendureConfig file'); } // eslint-disable-next-line @typescript-eslint/no-var-requires const config = require(vendureConfig.sourceFile.getFilePath())[exportedVarName]; return config; }
import { cancel, intro, isCancel, log, outro, select } from '@clack/prompts'; import pc from 'picocolors'; import { generateMigrationCommand } from './generate-migration/generate-migration'; import { revertMigrationCommand } from './revert-migration/revert-migration'; import { runMigrationCommand } from './run-migration/run-migration'; const cancelledMessage = 'Migrate cancelled.'; /** * This command is currently not exposed due to unresolved issues which I think are related to * peculiarities in loading ESM modules vs CommonJS modules. More time is needed to dig into * this before we expose this command in the cli.ts file. */ export async function migrateCommand() { // eslint-disable-next-line no-console console.log(`\n`); intro(pc.blue('🛠️️ Vendure migrations')); const action = await select({ message: 'What would you like to do?', options: [ { value: 'generate', label: 'Generate a new migration' }, { value: 'run', label: 'Run pending migrations' }, { value: 'revert', label: 'Revert the last migration' }, ], }); if (isCancel(action)) { cancel(cancelledMessage); process.exit(0); } try { process.env.VENDURE_RUNNING_IN_CLI = 'true'; if (action === 'generate') { await generateMigrationCommand.run(); } if (action === 'run') { await runMigrationCommand.run(); } if (action === 'revert') { await revertMigrationCommand.run(); } outro('✅ Done!'); process.env.VENDURE_RUNNING_IN_CLI = undefined; } catch (e: any) { log.error(e.message as string); if (e.stack) { log.error(e.stack); } } }
import { cancel, isCancel, log, multiselect, select, spinner, text } from '@clack/prompts'; import { unique } from '@vendure/common/lib/unique'; import { generateMigration, VendureConfig } from '@vendure/core'; import * as fs from 'fs-extra'; import path from 'path'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { analyzeProject } from '../../../shared/shared-prompts'; import { VendureConfigRef } from '../../../shared/vendure-config-ref'; import { loadVendureConfigFile } from '../load-vendure-config-file'; const cancelledMessage = 'Generate migration cancelled'; export const generateMigrationCommand = new CliCommand({ id: 'generate-migration', category: 'Other', description: 'Generate a new database migration', run: () => runGenerateMigration(), }); async function runGenerateMigration(): Promise<CliCommandReturnVal> { const { project, tsConfigPath } = await analyzeProject({ cancelledMessage }); const vendureConfig = new VendureConfigRef(project); log.info('Using VendureConfig from ' + vendureConfig.getPathRelativeToProjectRoot()); const name = await text({ message: 'Enter a meaningful name for the migration', initialValue: '', placeholder: 'add-custom-fields', validate: input => { if (!/^[a-zA-Z][a-zA-Z-_0-9]+$/.test(input)) { return 'The plugin name must contain only letters, numbers, underscores and dashes'; } }, }); if (isCancel(name)) { cancel(cancelledMessage); process.exit(0); } const config = await loadVendureConfigFile(vendureConfig, tsConfigPath); const migrationsDirs = getMigrationsDir(vendureConfig, config); let migrationDir = migrationsDirs[0]; if (migrationsDirs.length > 1) { const migrationDirSelect = await select({ message: 'Migration file location', options: migrationsDirs .map(c => ({ value: c, label: c, })) .concat({ value: 'other', label: 'Other', }), }); if (isCancel(migrationDirSelect)) { cancel(cancelledMessage); process.exit(0); } migrationDir = migrationDirSelect as string; } if (migrationsDirs.length === 1 || migrationDir === 'other') { const confirmation = await text({ message: 'Migration file location', initialValue: migrationsDirs[0], placeholder: '', }); if (isCancel(confirmation)) { cancel(cancelledMessage); process.exit(0); } migrationDir = confirmation; } const migrationSpinner = spinner(); migrationSpinner.start('Generating migration...'); const migrationName = await generateMigration(config, { name, outputDir: migrationDir }); const report = typeof migrationName === 'string' ? `New migration generated: ${migrationName}` : 'No changes in database schema were found, so no migration was generated'; migrationSpinner.stop(report); return { project, modifiedSourceFiles: [], }; } function getMigrationsDir(vendureConfigRef: VendureConfigRef, config: VendureConfig): string[] { const options: string[] = []; if ( Array.isArray(config.dbConnectionOptions.migrations) && config.dbConnectionOptions.migrations.length ) { const firstEntry = config.dbConnectionOptions.migrations[0]; if (typeof firstEntry === 'string') { options.push(path.dirname(firstEntry)); } } const migrationFile = vendureConfigRef.sourceFile .getProject() .getSourceFiles() .find(sf => { return sf .getClasses() .find(c => c.getImplements().find(i => i.getText() === 'MigrationInterface')); }); if (migrationFile) { options.push(migrationFile.getDirectory().getPath()); } options.push(path.join(vendureConfigRef.sourceFile.getDirectory().getPath(), '../migrations')); return unique(options.map(p => path.normalize(p))); }
import { log, spinner } from '@clack/prompts'; import { revertLastMigration } from '@vendure/core'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { analyzeProject } from '../../../shared/shared-prompts'; import { VendureConfigRef } from '../../../shared/vendure-config-ref'; import { loadVendureConfigFile } from '../load-vendure-config-file'; const cancelledMessage = 'Revert migrations cancelled'; export const revertMigrationCommand = new CliCommand({ id: 'run-migration', category: 'Other', description: 'Run any pending database migrations', run: () => runRevertMigration(), }); async function runRevertMigration(): Promise<CliCommandReturnVal> { const { project } = await analyzeProject({ cancelledMessage }); const vendureConfig = new VendureConfigRef(project); log.info('Using VendureConfig from ' + vendureConfig.getPathRelativeToProjectRoot()); const config = await loadVendureConfigFile(vendureConfig); const runSpinner = spinner(); runSpinner.start('Reverting last migration...'); await revertLastMigration(config); runSpinner.stop(`Successfully reverted last migration`); return { project, modifiedSourceFiles: [], }; }
import { log, spinner } from '@clack/prompts'; import { runMigrations } from '@vendure/core'; import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command'; import { analyzeProject } from '../../../shared/shared-prompts'; import { VendureConfigRef } from '../../../shared/vendure-config-ref'; import { loadVendureConfigFile } from '../load-vendure-config-file'; const cancelledMessage = 'Run migrations cancelled'; export const runMigrationCommand = new CliCommand({ id: 'run-migration', category: 'Other', description: 'Run any pending database migrations', run: () => runRunMigration(), }); async function runRunMigration(): Promise<CliCommandReturnVal> { const { project } = await analyzeProject({ cancelledMessage }); const vendureConfig = new VendureConfigRef(project); log.info('Using VendureConfig from ' + vendureConfig.getPathRelativeToProjectRoot()); const config = await loadVendureConfigFile(vendureConfig); const runSpinner = spinner(); runSpinner.start('Running migrations...'); const migrationsRan = await runMigrations(config); const report = migrationsRan.length ? `Successfully ran ${migrationsRan.length} migrations` : 'No pending migrations found'; runSpinner.stop(report); return { project, modifiedSourceFiles: [], }; }
import { Project, SourceFile } from 'ts-morph'; import { VendurePluginRef } from './vendure-plugin-ref'; export type CommandCategory = | `Plugin` | `Plugin: UI` | `Plugin: Entity` | `Plugin: Service` | `Plugin: API` | `Plugin: Job Queue` | `Project: Codegen` | `Other`; export interface BaseCliCommandOptions { plugin?: VendurePluginRef; } export type CliCommandReturnVal<T extends Record<string, any> = Record<string, any>> = { project: Project; modifiedSourceFiles: SourceFile[]; } & T; export interface CliCommandOptions<T extends BaseCliCommandOptions, R extends CliCommandReturnVal> { id: string; category: CommandCategory; description: string; run: (options?: Partial<T>) => Promise<R>; } export class CliCommand<T extends Record<string, any>, R extends CliCommandReturnVal = CliCommandReturnVal> { constructor(private options: CliCommandOptions<T, R>) {} get id() { return this.options.id; } get category() { return this.options.category; } get description() { return this.options.description; } run(options?: Partial<T>): Promise<R> { return this.options.run(options); } }
import { ClassDeclaration, Node, SyntaxKind, Type } from 'ts-morph'; export class EntityRef { constructor(public classDeclaration: ClassDeclaration) {} get name(): string { return this.classDeclaration.getName() as string; } get nameCamelCase(): string { return this.name.charAt(0).toLowerCase() + this.name.slice(1); } isTranslatable() { return this.classDeclaration.getImplements().some(i => i.getText() === 'Translatable'); } isTranslation() { return this.classDeclaration.getImplements().some(i => i.getText().includes('Translation<')); } hasCustomFields() { return this.classDeclaration.getImplements().some(i => i.getText() === 'HasCustomFields'); } getProps(): Array<{ name: string; type: Type; nullable: boolean }> { return this.classDeclaration.getProperties().map(prop => { const propType = prop.getType(); const name = prop.getName(); return { name, type: propType.getNonNullableType(), nullable: propType.isNullable() }; }); } getTranslationClass(): ClassDeclaration | undefined { if (!this.isTranslatable()) { return; } const translationsDecoratorArgs = this.classDeclaration .getProperty('translations') ?.getDecorator('OneToMany') ?.getArguments(); if (translationsDecoratorArgs) { const typeFn = translationsDecoratorArgs[0]; if (Node.isArrowFunction(typeFn)) { const translationClass = typeFn.getReturnType().getSymbolOrThrow().getDeclarations()[0]; return translationClass as ClassDeclaration; } } } }
import { note } from '@clack/prompts'; import spawn from 'cross-spawn'; import fs from 'fs-extra'; import path from 'path'; import { Project } from 'ts-morph'; export interface PackageToInstall { pkg: string; version?: string; isDevDependency?: boolean; installInRoot?: boolean; } export class PackageJson { private _vendurePackageJsonPath: string | undefined; private _rootPackageJsonPath: string | undefined; constructor(private readonly project: Project) {} get vendurePackageJsonPath() { return this.locatePackageJsonWithVendureDependency(); } get rootPackageJsonPath() { return this.locateRootPackageJson(); } determineVendureVersion(): string | undefined { const packageJson = this.getPackageJsonContent(); return packageJson.dependencies['@vendure/core']; } async installPackages(requiredPackages: PackageToInstall[]) { const packageJson = this.getPackageJsonContent(); const packagesToInstall = requiredPackages.filter(({ pkg, version, isDevDependency }) => { const hasDependency = isDevDependency ? packageJson.devDependencies[pkg] : packageJson.dependencies[pkg]; return !hasDependency; }); const depsToInstall = packagesToInstall .filter(p => !p.isDevDependency && packageJson.dependencies?.[p.pkg] === undefined) .map(p => `${p.pkg}${p.version ? `@${p.version}` : ''}`); const devDepsToInstall = packagesToInstall .filter(p => p.isDevDependency && packageJson.devDependencies?.[p.pkg] === undefined) .map(p => `${p.pkg}${p.version ? `@${p.version}` : ''}`); if (depsToInstall.length) { await this.runPackageManagerInstall(depsToInstall, false); } if (devDepsToInstall.length) { await this.runPackageManagerInstall(devDepsToInstall, true); } } getPackageJsonContent() { const packageJsonPath = this.locatePackageJsonWithVendureDependency(); if (!packageJsonPath || !fs.existsSync(packageJsonPath)) { note( `Could not find a package.json in the current directory. Please run this command from the root of a Vendure project.`, ); return false; } return fs.readJsonSync(packageJsonPath); } determinePackageManager(): 'yarn' | 'npm' | 'pnpm' { const rootDir = this.getPackageRootDir().getPath(); const yarnLockPath = path.join(rootDir, 'yarn.lock'); const npmLockPath = path.join(rootDir, 'package-lock.json'); const pnpmLockPath = path.join(rootDir, 'pnpm-lock.yaml'); if (fs.existsSync(yarnLockPath)) { return 'yarn'; } if (fs.existsSync(npmLockPath)) { return 'npm'; } if (fs.existsSync(pnpmLockPath)) { return 'pnpm'; } return 'npm'; } addScript(scriptName: string, script: string) { const packageJson = this.getPackageJsonContent(); packageJson.scripts = packageJson.scripts || {}; packageJson.scripts[scriptName] = script; const packageJsonPath = this.vendurePackageJsonPath; if (packageJsonPath) { fs.writeJsonSync(packageJsonPath, packageJson, { spaces: 2 }); } } getPackageRootDir() { const rootDir = this.project.getDirectory('.'); if (!rootDir) { throw new Error('Could not find the root directory of the project'); } return rootDir; } locateRootPackageJson() { if (this._rootPackageJsonPath) { return this._rootPackageJsonPath; } const rootDir = this.getPackageRootDir().getPath(); const rootPackageJsonPath = path.join(rootDir, 'package.json'); if (fs.existsSync(rootPackageJsonPath)) { this._rootPackageJsonPath = rootPackageJsonPath; return rootPackageJsonPath; } return null; } locatePackageJsonWithVendureDependency() { if (this._vendurePackageJsonPath) { return this._vendurePackageJsonPath; } const rootDir = this.getPackageRootDir().getPath(); const potentialMonorepoDirs = ['packages', 'apps', 'libs']; const rootPackageJsonPath = path.join(this.getPackageRootDir().getPath(), 'package.json'); if (this.hasVendureDependency(rootPackageJsonPath)) { return rootPackageJsonPath; } for (const dir of potentialMonorepoDirs) { const monorepoDir = path.join(rootDir, dir); // Check for a package.json in all subdirs for (const subDir of fs.readdirSync(monorepoDir)) { const packageJsonPath = path.join(monorepoDir, subDir, 'package.json'); if (this.hasVendureDependency(packageJsonPath)) { this._vendurePackageJsonPath = packageJsonPath; return packageJsonPath; } } } return null; } private hasVendureDependency(packageJsonPath: string) { if (!fs.existsSync(packageJsonPath)) { return false; } const packageJson = fs.readJsonSync(packageJsonPath); return !!packageJson.dependencies?.['@vendure/core']; } private async runPackageManagerInstall(dependencies: string[], isDev: boolean) { return new Promise<void>((resolve, reject) => { const packageManager = this.determinePackageManager(); let command = ''; let args: string[] = []; if (packageManager === 'yarn') { command = 'yarnpkg'; args = ['add', '--exact', '--ignore-engines']; if (isDev) { args.push('--dev'); } args = args.concat(dependencies); } else if (packageManager === 'pnpm') { command = 'pnpm'; args = ['add', '--save-exact'].concat(dependencies); if (isDev) { args.push('--save-dev', '--workspace-root'); } } else { command = 'npm'; args = ['install', '--save', '--save-exact', '--loglevel', 'error'].concat(dependencies); if (isDev) { args.push('--save-dev'); } } const child = spawn(command, args, { stdio: 'ignore' }); child.on('close', code => { if (code !== 0) { const message = 'An error occurred when installing dependencies.'; reject({ message, command: `${command} ${args.join(' ')}`, }); return; } resolve(); }); }); } }
import { ClassDeclaration, Node, Scope, Type } from 'ts-morph'; import { EntityRef } from './entity-ref'; export interface ServiceFeatures { findOne: boolean; findAll: boolean; create: boolean; update: boolean; delete: boolean; } export class ServiceRef { readonly features: ServiceFeatures; readonly crudEntityRef?: EntityRef; get name(): string { return this.classDeclaration.getName() as string; } get nameCamelCase(): string { return this.name.charAt(0).toLowerCase() + this.name.slice(1); } get isCrudService(): boolean { return this.crudEntityRef !== undefined; } constructor(public readonly classDeclaration: ClassDeclaration) { this.features = { findOne: !!this.classDeclaration.getMethod('findOne'), findAll: !!this.classDeclaration.getMethod('findAll'), create: !!this.classDeclaration.getMethod('create'), update: !!this.classDeclaration.getMethod('update'), delete: !!this.classDeclaration.getMethod('delete'), }; this.crudEntityRef = this.getEntityRef(); } injectDependency(dependency: { scope?: Scope; name: string; type: string }) { for (const constructorDeclaration of this.classDeclaration.getConstructors()) { const existingParam = constructorDeclaration.getParameter(dependency.name); if (!existingParam) { constructorDeclaration.addParameter({ name: dependency.name, type: dependency.type, hasQuestionToken: false, isReadonly: false, scope: dependency.scope ?? Scope.Private, }); } } } private getEntityRef(): EntityRef | undefined { if (this.features.findOne) { const potentialCrudMethodNames = ['findOne', 'findAll', 'create', 'update', 'delete']; for (const methodName of potentialCrudMethodNames) { const findOneMethod = this.classDeclaration.getMethod(methodName); const returnType = findOneMethod?.getReturnType(); if (returnType) { const unwrappedReturnType = this.unwrapReturnType(returnType); const typeDeclaration = unwrappedReturnType.getSymbolOrThrow().getDeclarations()[0]; if (typeDeclaration && Node.isClassDeclaration(typeDeclaration)) { if (typeDeclaration.getExtends()?.getText() === 'VendureEntity') { return new EntityRef(typeDeclaration); } } } } } return; } private unwrapReturnType(returnType: Type): Type { if (returnType.isUnion()) { // get the non-null part of the union const nonNullType = returnType.getUnionTypes().find(t => !t.isNull() && !t.isUndefined()); if (!nonNullType) { throw new Error('Could not find non-null type in union'); } return this.unwrapReturnType(nonNullType); } const typeArguments = returnType.getTypeArguments(); if (typeArguments.length) { return this.unwrapReturnType(typeArguments[0]); } const aliasTypeArguments = returnType.getAliasTypeArguments(); if (aliasTypeArguments.length) { return this.unwrapReturnType(aliasTypeArguments[0]); } return returnType; } }
import { cancel, isCancel, multiselect, select, spinner } from '@clack/prompts'; import { ClassDeclaration, Project } from 'ts-morph'; import { addServiceCommand } from '../commands/add/service/add-service'; import { Messages } from '../constants'; import { getPluginClasses, getTsMorphProject, selectTsConfigFile } from '../utilities/ast-utils'; import { pauseForPromptDisplay } from '../utilities/utils'; import { EntityRef } from './entity-ref'; import { ServiceRef } from './service-ref'; import { VendurePluginRef } from './vendure-plugin-ref'; export async function analyzeProject(options: { providedVendurePlugin?: VendurePluginRef; cancelledMessage?: string; }) { const providedVendurePlugin = options.providedVendurePlugin; let project = providedVendurePlugin?.classDeclaration.getProject(); let tsConfigPath: string | undefined; if (!providedVendurePlugin) { const projectSpinner = spinner(); const tsConfigFile = await selectTsConfigFile(); projectSpinner.start('Analyzing project...'); await pauseForPromptDisplay(); const { project: _project, tsConfigPath: _tsConfigPath } = await getTsMorphProject({}, tsConfigFile); project = _project; tsConfigPath = _tsConfigPath; projectSpinner.stop('Project analyzed'); } return { project: project as Project, tsConfigPath }; } export async function selectPlugin(project: Project, cancelledMessage: string): Promise<VendurePluginRef> { const pluginClasses = getPluginClasses(project); if (pluginClasses.length === 0) { cancel(Messages.NoPluginsFound); process.exit(0); } const targetPlugin = await select({ message: 'To which plugin would you like to add the feature?', options: pluginClasses.map(c => ({ value: c, label: c.getName() as string, })), maxItems: 10, }); if (isCancel(targetPlugin)) { cancel(cancelledMessage); process.exit(0); } return new VendurePluginRef(targetPlugin as ClassDeclaration); } export async function selectEntity(plugin: VendurePluginRef): Promise<EntityRef> { const entities = plugin.getEntities(); if (entities.length === 0) { throw new Error(Messages.NoEntitiesFound); } const targetEntity = await select({ message: 'Select an entity', options: entities .filter(e => !e.isTranslation()) .map(e => ({ value: e, label: e.name, })), maxItems: 10, }); if (isCancel(targetEntity)) { cancel('Cancelled'); process.exit(0); } return targetEntity as EntityRef; } export async function selectMultiplePluginClasses( project: Project, cancelledMessage: string, ): Promise<VendurePluginRef[]> { const pluginClasses = getPluginClasses(project); if (pluginClasses.length === 0) { cancel(Messages.NoPluginsFound); process.exit(0); } const selectAll = await select({ message: 'To which plugin would you like to add the feature?', options: [ { value: 'all', label: 'All plugins', }, { value: 'specific', label: 'Specific plugins (you will be prompted to select the plugins)', }, ], }); if (isCancel(selectAll)) { cancel(cancelledMessage); process.exit(0); } if (selectAll === 'all') { return pluginClasses.map(pc => new VendurePluginRef(pc)); } const targetPlugins = await multiselect({ message: 'Select one or more plugins (use ↑, ↓, space to select)', options: pluginClasses.map(c => ({ value: c, label: c.getName() as string, })), }); if (isCancel(targetPlugins)) { cancel(cancelledMessage); process.exit(0); } return (targetPlugins as ClassDeclaration[]).map(pc => new VendurePluginRef(pc)); } export async function selectServiceRef( project: Project, plugin: VendurePluginRef, canCreateNew = true, ): Promise<ServiceRef> { const serviceRefs = getServices(project).filter(sr => { return sr.classDeclaration .getSourceFile() .getDirectoryPath() .includes(plugin.getSourceFile().getDirectoryPath()); }); if (serviceRefs.length === 0 && !canCreateNew) { throw new Error(Messages.NoServicesFound); } const result = await select({ message: 'Which service contains the business logic for this API extension?', maxItems: 8, options: [ ...(canCreateNew ? [ { value: 'new', label: `Create new generic service`, }, ] : []), ...serviceRefs.map(sr => { const features = sr.crudEntityRef ? `CRUD service for ${sr.crudEntityRef.name}` : `Generic service`; const label = `${sr.name}: (${features})`; return { value: sr, label, }; }), ], }); if (isCancel(result)) { cancel('Cancelled'); process.exit(0); } if (result === 'new') { return addServiceCommand.run({ type: 'basic', plugin }).then(r => r.serviceRef); } else { return result as ServiceRef; } } export function getServices(project: Project): ServiceRef[] { const servicesSourceFiles = project.getSourceFiles().filter(sf => { return ( sf.getDirectory().getPath().endsWith('/services') || sf.getDirectory().getPath().endsWith('/service') ); }); return servicesSourceFiles .flatMap(sf => sf.getClasses()) .filter(classDeclaration => classDeclaration.getDecorator('Injectable')) .map(classDeclaration => new ServiceRef(classDeclaration)); }
import fs from 'fs-extra'; import path from 'node:path'; import { Node, ObjectLiteralExpression, Project, SourceFile, SyntaxKind, VariableDeclaration, } from 'ts-morph'; export class VendureConfigRef { readonly sourceFile: SourceFile; readonly configObject: ObjectLiteralExpression; constructor( private project: Project, options: { checkFileName?: boolean } = {}, ) { const checkFileName = options.checkFileName ?? true; const getVendureConfigSourceFile = (sourceFiles: SourceFile[]) => { return sourceFiles.find(sf => { return ( (checkFileName ? sf.getFilePath().endsWith('vendure-config.ts') : true) && sf.getVariableDeclarations().find(v => this.isVendureConfigVariableDeclaration(v)) ); }); }; const findAndAddVendureConfigToProject = () => { // If the project does not contain a vendure-config.ts file, we'll look for a vendure-config.ts file // in the src directory. const srcDir = project.getDirectory('src'); if (srcDir) { const srcDirPath = srcDir.getPath(); const srcFiles = fs.readdirSync(srcDirPath); const filePath = srcFiles.find(file => file.includes('vendure-config.ts')); if (filePath) { project.addSourceFileAtPath(path.join(srcDirPath, filePath)); } } }; let vendureConfigFile = getVendureConfigSourceFile(project.getSourceFiles()); if (!vendureConfigFile) { findAndAddVendureConfigToProject(); vendureConfigFile = getVendureConfigSourceFile(project.getSourceFiles()); } if (!vendureConfigFile) { throw new Error('Could not find the VendureConfig declaration in your project.'); } this.sourceFile = vendureConfigFile; this.configObject = vendureConfigFile ?.getVariableDeclarations() .find(v => this.isVendureConfigVariableDeclaration(v)) ?.getChildren() .find(Node.isObjectLiteralExpression) as ObjectLiteralExpression; } getPathRelativeToProjectRoot() { return path.relative( this.project.getRootDirectories()[0]?.getPath() ?? '', this.sourceFile.getFilePath(), ); } getConfigObjectVariableName() { return this.sourceFile ?.getVariableDeclarations() .find(v => this.isVendureConfigVariableDeclaration(v)) ?.getName(); } getPluginsArray() { return this.configObject .getProperty('plugins') ?.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression); } addToPluginsArray(text: string) { this.getPluginsArray()?.addElement(text).formatText(); } private isVendureConfigVariableDeclaration(v: VariableDeclaration) { return v.getType().getText(v) === 'VendureConfig'; } }
import { ClassDeclaration, InterfaceDeclaration, Node, PropertyAssignment, StructureKind, SyntaxKind, Type, VariableDeclaration, } from 'ts-morph'; import { AdminUiExtensionTypeName } from '../constants'; import { EntityRef } from './entity-ref'; export class VendurePluginRef { constructor(public classDeclaration: ClassDeclaration) {} get name(): string { return this.classDeclaration.getName() as string; } getSourceFile() { return this.classDeclaration.getSourceFile(); } getPluginDir() { return this.classDeclaration.getSourceFile().getDirectory(); } getMetadataOptions() { const pluginDecorator = this.classDeclaration.getDecorator('VendurePlugin'); if (!pluginDecorator) { throw new Error('Could not find VendurePlugin decorator'); } const pluginOptions = pluginDecorator.getArguments()[0]; if (!pluginOptions || !Node.isObjectLiteralExpression(pluginOptions)) { throw new Error('Could not find VendurePlugin options'); } return pluginOptions; } getPluginOptions(): | { typeDeclaration: InterfaceDeclaration; constantDeclaration: VariableDeclaration } | undefined { const metadataOptions = this.getMetadataOptions(); const staticOptions = this.classDeclaration.getStaticProperty('options'); const typeDeclaration = staticOptions ?.getType() .getSymbolOrThrow() .getDeclarations() .find(d => Node.isInterfaceDeclaration(d)); if (!typeDeclaration || !Node.isInterfaceDeclaration(typeDeclaration)) { return; } const providersArray = metadataOptions .getProperty('providers') ?.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression); if (!providersArray) { return; } const elements = providersArray.getElements(); const optionsProviders = elements .filter(Node.isObjectLiteralExpression) .filter(el => el.getProperty('useFactory')?.getText().includes(`${this.name}.options`)); if (!optionsProviders.length) { return; } const optionsSymbol = optionsProviders[0].getProperty('provide') as PropertyAssignment; const initializer = optionsSymbol?.getInitializer(); if (!initializer || !Node.isIdentifier(initializer)) { return; } const constantDeclaration = initializer.getDefinitions()[0]?.getDeclarationNode(); if (!constantDeclaration || !Node.isVariableDeclaration(constantDeclaration)) { return; } return { typeDeclaration, constantDeclaration }; } addEntity(entityClassName: string) { const pluginOptions = this.getMetadataOptions(); const entityProperty = pluginOptions.getProperty('entities'); if (entityProperty) { const entitiesArray = entityProperty.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression); if (entitiesArray) { entitiesArray.addElement(entityClassName); } } else { pluginOptions.addPropertyAssignment({ name: 'entities', initializer: `[${entityClassName}]`, }); } } addProvider(providerClassName: string) { const pluginOptions = this.getMetadataOptions(); const providerProperty = pluginOptions.getProperty('providers'); if (providerProperty) { const providersArray = providerProperty.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression); if (providersArray) { providersArray.addElement(providerClassName); } } else { pluginOptions.addPropertyAssignment({ name: 'providers', initializer: `[${providerClassName}]`, }); } } addAdminApiExtensions(extension: { schema: VariableDeclaration | undefined; resolvers: ClassDeclaration[]; }) { const pluginOptions = this.getMetadataOptions(); const adminApiExtensionsProperty = pluginOptions .getProperty('adminApiExtensions') ?.getType() .getSymbolOrThrow() .getDeclarations()[0]; if ( extension.schema && adminApiExtensionsProperty && Node.isObjectLiteralExpression(adminApiExtensionsProperty) ) { const schemaProp = adminApiExtensionsProperty.getProperty('schema'); if (!schemaProp) { adminApiExtensionsProperty.addPropertyAssignment({ name: 'schema', initializer: extension.schema?.getName(), }); } const resolversProp = adminApiExtensionsProperty.getProperty('resolvers'); if (resolversProp) { const resolversArray = resolversProp.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression); if (resolversArray) { for (const resolver of extension.resolvers) { const resolverName = resolver.getName(); if (resolverName) { resolversArray.addElement(resolverName); } } } } else { adminApiExtensionsProperty.addPropertyAssignment({ name: 'resolvers', initializer: `[${extension.resolvers.map(r => r.getName()).join(', ')}]`, }); } } else if (extension.schema) { pluginOptions .addPropertyAssignment({ name: 'adminApiExtensions', initializer: `{ schema: ${extension.schema.getName()}, resolvers: [${extension.resolvers.map(r => r.getName()).join(', ')}] }`, }) .formatText(); } } getEntities(): EntityRef[] { const metadataOptions = this.getMetadataOptions(); const entitiesProperty = metadataOptions.getProperty('entities'); if (!entitiesProperty) { return []; } const entitiesArray = entitiesProperty.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression); if (!entitiesArray) { return []; } const entityNames = entitiesArray .getElements() .filter(Node.isIdentifier) .map(e => e.getText()); const entitySourceFiles = this.getSourceFile() .getImportDeclarations() .filter(imp => { for (const namedImport of imp.getNamedImports()) { if (entityNames.includes(namedImport.getName())) { return true; } } }) .map(imp => imp.getModuleSpecifierSourceFileOrThrow()); return entitySourceFiles .map(sourceFile => sourceFile.getClasses().filter(c => c.getExtends()?.getText() === 'VendureEntity'), ) .flat() .map(classDeclaration => new EntityRef(classDeclaration)); } hasUiExtensions(): boolean { return !!this.classDeclaration .getStaticProperties() .find(prop => prop.getType().getSymbol()?.getName() === AdminUiExtensionTypeName); } }
import { cancel, isCancel, log, select } from '@clack/prompts'; import fs from 'fs-extra'; import path from 'node:path'; import { Directory, Node, Project, ProjectOptions, ScriptKind, SourceFile } from 'ts-morph'; import { defaultManipulationSettings } from '../constants'; import { EntityRef } from '../shared/entity-ref'; export async function selectTsConfigFile() { const tsConfigFiles = fs.readdirSync(process.cwd()).filter(f => /^tsconfig.*\.json$/.test(f)); if (tsConfigFiles.length === 0) { throw new Error('No tsconfig files found in current directory'); } if (tsConfigFiles.length === 1) { return tsConfigFiles[0]; } const selectedConfigFile = await select({ message: 'Multiple tsconfig files found. Select one:', options: tsConfigFiles.map(c => ({ value: c, label: path.basename(c), })), maxItems: 10, }); if (isCancel(selectedConfigFile)) { cancel(); process.exit(0); } return selectedConfigFile as string; } export async function getTsMorphProject(options: ProjectOptions = {}, providedTsConfigPath?: string) { const tsConfigFile = providedTsConfigPath ?? (await selectTsConfigFile()); const tsConfigPath = path.join(process.cwd(), tsConfigFile); if (!fs.existsSync(tsConfigPath)) { throw new Error('No tsconfig.json found in current directory'); } const project = new Project({ tsConfigFilePath: tsConfigPath, manipulationSettings: defaultManipulationSettings, compilerOptions: { skipLibCheck: true, }, ...options, }); project.enableLogging(false); return { project, tsConfigPath }; } export function getPluginClasses(project: Project) { const sourceFiles = project.getSourceFiles(); const pluginClasses = sourceFiles .flatMap(sf => { return sf.getClasses(); }) .filter(c => { const hasPluginDecorator = c.getModifiers().find(m => { return Node.isDecorator(m) && m.getName() === 'VendurePlugin'; }); return !!hasPluginDecorator; }); return pluginClasses; } export function addImportsToFile( sourceFile: SourceFile, options: { moduleSpecifier: string | SourceFile; namedImports?: string[]; namespaceImport?: string; order?: number; }, ) { const moduleSpecifier = getModuleSpecifierString(options.moduleSpecifier, sourceFile); const existingDeclaration = sourceFile.getImportDeclaration( declaration => declaration.getModuleSpecifier().getLiteralValue() === moduleSpecifier, ); if (!existingDeclaration) { const importDeclaration = sourceFile.addImportDeclaration({ moduleSpecifier, ...(options.namespaceImport ? { namespaceImport: options.namespaceImport } : {}), ...(options.namedImports ? { namedImports: options.namedImports } : {}), }); if (options.order != null) { importDeclaration.setOrder(options.order); } } else { if ( options.namespaceImport && !existingDeclaration.getNamespaceImport() && !existingDeclaration.getDefaultImport() ) { existingDeclaration.setNamespaceImport(options.namespaceImport); } if (options.namedImports) { const existingNamedImports = existingDeclaration.getNamedImports(); for (const namedImport of options.namedImports) { if (!existingNamedImports.find(ni => ni.getName() === namedImport)) { existingDeclaration.addNamedImport(namedImport); } } } } } function getModuleSpecifierString(moduleSpecifier: string | SourceFile, sourceFile: SourceFile): string { if (typeof moduleSpecifier === 'string') { return moduleSpecifier; } return getRelativeImportPath({ from: sourceFile, to: moduleSpecifier }); } export function getRelativeImportPath(locations: { from: SourceFile | Directory; to: SourceFile | Directory; }): string { const fromPath = locations.from instanceof SourceFile ? locations.from.getFilePath() : locations.from.getPath(); const toPath = locations.to instanceof SourceFile ? locations.to.getFilePath() : locations.to.getPath(); const fromDir = /\.[a-z]+$/.test(fromPath) ? path.dirname(fromPath) : fromPath; return convertPathToRelativeImport(path.relative(fromDir, toPath)); } export function createFile(project: Project, templatePath: string, filePath: string) { const template = fs.readFileSync(templatePath, 'utf-8'); try { const file = project.createSourceFile(filePath, template, { overwrite: true, scriptKind: ScriptKind.TS, }); project.resolveSourceFileDependencies(); return file; } catch (e: any) { log.error(e.message); process.exit(1); } } function convertPathToRelativeImport(filePath: string): string { // Normalize the path separators const normalizedPath = filePath.replace(/\\/g, '/'); // Remove the file extension const parsedPath = path.parse(normalizedPath); const prefix = parsedPath.dir.startsWith('..') ? '' : './'; return `${prefix}${parsedPath.dir}/${parsedPath.name}`.replace(/\/\//g, '/'); } export function customizeCreateUpdateInputInterfaces(sourceFile: SourceFile, entityRef: EntityRef) { const createInputInterface = sourceFile .getInterface('CreateEntityInput') ?.rename(`Create${entityRef.name}Input`); const updateInputInterface = sourceFile .getInterface('UpdateEntityInput') ?.rename(`Update${entityRef.name}Input`); let index = 0; for (const { name, type, nullable } of entityRef.getProps()) { if ( type.isBoolean() || type.isString() || type.isNumber() || (type.isObject() && type.getText() === 'Date') ) { createInputInterface?.insertProperty(index, { name, type: writer => writer.write(type.getText()), hasQuestionToken: nullable, }); updateInputInterface?.insertProperty(index + 1, { name, type: writer => writer.write(type.getText()), hasQuestionToken: true, }); index++; } } if (!entityRef.hasCustomFields()) { createInputInterface?.getProperty('customFields')?.remove(); updateInputInterface?.getProperty('customFields')?.remove(); } if (entityRef.isTranslatable()) { createInputInterface ?.getProperty('translations') ?.setType(`Array<TranslationInput<${entityRef.name}>>`); updateInputInterface ?.getProperty('translations') ?.setType(`Array<TranslationInput<${entityRef.name}>>`); } else { createInputInterface?.getProperty('translations')?.remove(); updateInputInterface?.getProperty('translations')?.remove(); } }
import fs from 'fs-extra'; import { SourceFile } from 'ts-morph'; import { expect } from 'vitest'; export function expectSourceFileContentToMatch(sourceFile: SourceFile, expectedFilePath: string) { const result = sourceFile.getFullText(); const expected = fs.readFileSync(expectedFilePath, 'utf-8'); expect(normalizeLineFeeds(result)).toBe(normalizeLineFeeds(expected)); } function normalizeLineFeeds(text: string): string { return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); }
/** * Since the AST manipulation is blocking, prompts will not get a * chance to be displayed unless we give a small async pause. */ export async function pauseForPromptDisplay() { await new Promise(resolve => setTimeout(resolve, 100)); } export function isRunningInTsNode(): boolean { // @ts-ignore return process[Symbol.for('ts-node.register.instance')] != null; }
export type FetchPolicy = 'cache-first' | 'network-only' | 'cache-only' | 'no-cache' | 'standby'; export type WatchQueryFetchPolicy = FetchPolicy | 'cache-and-network'; export interface BaseExtensionMessage { requestId: string; type: string; data: any; } export interface ActiveRouteData { url: string; origin: string; pathname: string; params: { [key: string]: any }; queryParams: { [key: string]: any }; fragment: string | null; } export interface ActivatedRouteMessage extends BaseExtensionMessage { type: 'active-route'; } export interface QueryMessage extends BaseExtensionMessage { type: 'graphql-query'; data: { document: string; variables?: { [key: string]: any }; fetchPolicy?: WatchQueryFetchPolicy; }; } export interface MutationMessage extends BaseExtensionMessage { type: 'graphql-mutation'; data: { document: string; variables?: { [key: string]: any }; }; } export interface NotificationMessage extends BaseExtensionMessage { type: 'notification'; data: { message: string; translationVars?: { [key: string]: string | number }; type?: 'info' | 'success' | 'error' | 'warning'; duration?: number; }; } export interface CancellationMessage extends BaseExtensionMessage { type: 'cancellation'; data: null; } export interface DestroyMessage extends BaseExtensionMessage { type: 'destroy'; data: null; } export type ExtensionMessage = | ActivatedRouteMessage | QueryMessage | MutationMessage | NotificationMessage | CancellationMessage | DestroyMessage; export interface MessageResponse { requestId: string; data: any; complete: boolean; error: boolean; }
import { describe, expect, it } from 'vitest'; import { filterAsync } from './filter-async'; describe('filterAsync', () => { it('filters an array of promises', async () => { const a = Promise.resolve(true); const b = Promise.resolve(false); const c = Promise.resolve(true); const input = [a, b, c]; const result = await filterAsync(input, item => item); expect(result).toEqual([a, c]); }); it('filters a mixed array', async () => { const a = { value: Promise.resolve(true) }; const b = { value: Promise.resolve(false) }; const c = { value: true }; const input = [a, b, c]; const result = await filterAsync(input, item => item.value); expect(result).toEqual([a, c]); }); it('filters a sync array', async () => { const a = { value: true }; const b = { value: false }; const c = { value: true }; const input = [a, b, c]; const result = await filterAsync(input, item => item.value); expect(result).toEqual([a, c]); }); });
/** * Performs a filter operation where the predicate is an async function returning a Promise. */ export async function filterAsync<T>(arr: T[], predicate: (item: T, index: number) => Promise<boolean> | boolean): Promise<T[]> { const results: boolean[] = await Promise.all( arr.map(async (value, index) => predicate(value, index)), ); return arr.filter((_, i) => results[i]); }
/* eslint-disable */ export type Maybe<T> = T; export type InputMaybe<T> = T; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; export type MakeEmpty<T extends { [key: string]: unknown }, K extends keyof T> = { [_ in K]?: never }; export type Incremental<T> = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: { input: string | number; output: string | number; } String: { input: string; output: string; } Boolean: { input: boolean; output: boolean; } Int: { input: number; output: number; } Float: { input: number; output: number; } DateTime: { input: any; output: any; } JSON: { input: any; output: any; } Money: { input: number; output: number; } Upload: { input: any; output: any; } }; export type ActiveOrderResult = NoActiveOrderError | Order; export type AddPaymentToOrderResult = IneligiblePaymentMethodError | NoActiveOrderError | Order | OrderPaymentStateError | OrderStateTransitionError | PaymentDeclinedError | PaymentFailedError; export type Address = Node & { __typename?: 'Address'; city?: Maybe<Scalars['String']['output']>; company?: Maybe<Scalars['String']['output']>; country: Country; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; defaultBillingAddress?: Maybe<Scalars['Boolean']['output']>; defaultShippingAddress?: Maybe<Scalars['Boolean']['output']>; fullName?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; phoneNumber?: Maybe<Scalars['String']['output']>; postalCode?: Maybe<Scalars['String']['output']>; province?: Maybe<Scalars['String']['output']>; streetLine1: Scalars['String']['output']; streetLine2?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type Adjustment = { __typename?: 'Adjustment'; adjustmentSource: Scalars['String']['output']; amount: Scalars['Money']['output']; data?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; type: AdjustmentType; }; export enum AdjustmentType { DISTRIBUTED_ORDER_PROMOTION = 'DISTRIBUTED_ORDER_PROMOTION', OTHER = 'OTHER', PROMOTION = 'PROMOTION' } /** Returned when attempting to set the Customer for an Order when already logged in. */ export type AlreadyLoggedInError = ErrorResult & { __typename?: 'AlreadyLoggedInError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type ApplyCouponCodeResult = CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError | Order; export type Asset = Node & { __typename?: 'Asset'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; fileSize: Scalars['Int']['output']; focalPoint?: Maybe<Coordinate>; height: Scalars['Int']['output']; id: Scalars['ID']['output']; mimeType: Scalars['String']['output']; name: Scalars['String']['output']; preview: Scalars['String']['output']; source: Scalars['String']['output']; tags: Array<Tag>; type: AssetType; updatedAt: Scalars['DateTime']['output']; width: Scalars['Int']['output']; }; export type AssetList = PaginatedList & { __typename?: 'AssetList'; items: Array<Asset>; totalItems: Scalars['Int']['output']; }; export enum AssetType { BINARY = 'BINARY', IMAGE = 'IMAGE', VIDEO = 'VIDEO' } export type AuthenticationInput = { native?: InputMaybe<NativeAuthInput>; }; export type AuthenticationMethod = Node & { __typename?: 'AuthenticationMethod'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; strategy: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type AuthenticationResult = CurrentUser | InvalidCredentialsError | NotVerifiedError; export type BooleanCustomFieldConfig = CustomField & { __typename?: 'BooleanCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; /** Operators for filtering on a list of Boolean fields */ export type BooleanListOperators = { inList: Scalars['Boolean']['input']; }; /** Operators for filtering on a Boolean field */ export type BooleanOperators = { eq?: InputMaybe<Scalars['Boolean']['input']>; isNull?: InputMaybe<Scalars['Boolean']['input']>; }; export type Channel = Node & { __typename?: 'Channel'; availableCurrencyCodes: Array<CurrencyCode>; availableLanguageCodes?: Maybe<Array<LanguageCode>>; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; /** @deprecated Use defaultCurrencyCode instead */ currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; defaultCurrencyCode: CurrencyCode; defaultLanguageCode: LanguageCode; defaultShippingZone?: Maybe<Zone>; defaultTaxZone?: Maybe<Zone>; id: Scalars['ID']['output']; /** Not yet used - will be implemented in a future release. */ outOfStockThreshold?: Maybe<Scalars['Int']['output']>; pricesIncludeTax: Scalars['Boolean']['output']; seller?: Maybe<Seller>; token: Scalars['String']['output']; /** Not yet used - will be implemented in a future release. */ trackInventory?: Maybe<Scalars['Boolean']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type Collection = Node & { __typename?: 'Collection'; assets: Array<Asset>; breadcrumbs: Array<CollectionBreadcrumb>; children?: Maybe<Array<Collection>>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; featuredAsset?: Maybe<Asset>; filters: Array<ConfigurableOperation>; id: Scalars['ID']['output']; languageCode?: Maybe<LanguageCode>; name: Scalars['String']['output']; parent?: Maybe<Collection>; parentId: Scalars['ID']['output']; position: Scalars['Int']['output']; productVariants: ProductVariantList; slug: Scalars['String']['output']; translations: Array<CollectionTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type CollectionProductVariantsArgs = { options?: InputMaybe<ProductVariantListOptions>; }; export type CollectionBreadcrumb = { __typename?: 'CollectionBreadcrumb'; id: Scalars['ID']['output']; name: Scalars['String']['output']; slug: Scalars['String']['output']; }; export type CollectionFilterParameter = { _and?: InputMaybe<Array<CollectionFilterParameter>>; _or?: InputMaybe<Array<CollectionFilterParameter>>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; parentId?: InputMaybe<IdOperators>; position?: InputMaybe<NumberOperators>; slug?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type CollectionList = PaginatedList & { __typename?: 'CollectionList'; items: Array<Collection>; totalItems: Scalars['Int']['output']; }; export type CollectionListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<CollectionFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<CollectionSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; topLevelOnly?: InputMaybe<Scalars['Boolean']['input']>; }; /** * Which Collections are present in the products returned * by the search, and in what quantity. */ export type CollectionResult = { __typename?: 'CollectionResult'; collection: Collection; count: Scalars['Int']['output']; }; export type CollectionSortParameter = { createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; parentId?: InputMaybe<SortOrder>; position?: InputMaybe<SortOrder>; slug?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type CollectionTranslation = { __typename?: 'CollectionTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; slug: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ConfigArg = { __typename?: 'ConfigArg'; name: Scalars['String']['output']; value: Scalars['String']['output']; }; export type ConfigArgDefinition = { __typename?: 'ConfigArgDefinition'; defaultValue?: Maybe<Scalars['JSON']['output']>; description?: Maybe<Scalars['String']['output']>; label?: Maybe<Scalars['String']['output']>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; required: Scalars['Boolean']['output']; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type ConfigArgInput = { name: Scalars['String']['input']; /** A JSON stringified representation of the actual value */ value: Scalars['String']['input']; }; export type ConfigurableOperation = { __typename?: 'ConfigurableOperation'; args: Array<ConfigArg>; code: Scalars['String']['output']; }; export type ConfigurableOperationDefinition = { __typename?: 'ConfigurableOperationDefinition'; args: Array<ConfigArgDefinition>; code: Scalars['String']['output']; description: Scalars['String']['output']; }; export type ConfigurableOperationInput = { arguments: Array<ConfigArgInput>; code: Scalars['String']['input']; }; export type Coordinate = { __typename?: 'Coordinate'; x: Scalars['Float']['output']; y: Scalars['Float']['output']; }; export type Country = Node & Region & { __typename?: 'Country'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; parent?: Maybe<Region>; parentId?: Maybe<Scalars['ID']['output']>; translations: Array<RegionTranslation>; type: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type CountryList = PaginatedList & { __typename?: 'CountryList'; items: Array<Country>; totalItems: Scalars['Int']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeExpiredError = ErrorResult & { __typename?: 'CouponCodeExpiredError'; couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeInvalidError = ErrorResult & { __typename?: 'CouponCodeInvalidError'; couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeLimitError = ErrorResult & { __typename?: 'CouponCodeLimitError'; couponCode: Scalars['String']['output']; errorCode: ErrorCode; limit: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type CreateAddressInput = { city?: InputMaybe<Scalars['String']['input']>; company?: InputMaybe<Scalars['String']['input']>; countryCode: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; defaultBillingAddress?: InputMaybe<Scalars['Boolean']['input']>; defaultShippingAddress?: InputMaybe<Scalars['Boolean']['input']>; fullName?: InputMaybe<Scalars['String']['input']>; phoneNumber?: InputMaybe<Scalars['String']['input']>; postalCode?: InputMaybe<Scalars['String']['input']>; province?: InputMaybe<Scalars['String']['input']>; streetLine1: Scalars['String']['input']; streetLine2?: InputMaybe<Scalars['String']['input']>; }; export type CreateCustomerInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; emailAddress: Scalars['String']['input']; firstName: Scalars['String']['input']; lastName: Scalars['String']['input']; phoneNumber?: InputMaybe<Scalars['String']['input']>; title?: InputMaybe<Scalars['String']['input']>; }; /** * @description * ISO 4217 currency code * * @docsCategory common */ export enum CurrencyCode { /** United Arab Emirates dirham */ AED = 'AED', /** Afghan afghani */ AFN = 'AFN', /** Albanian lek */ ALL = 'ALL', /** Armenian dram */ AMD = 'AMD', /** Netherlands Antillean guilder */ ANG = 'ANG', /** Angolan kwanza */ AOA = 'AOA', /** Argentine peso */ ARS = 'ARS', /** Australian dollar */ AUD = 'AUD', /** Aruban florin */ AWG = 'AWG', /** Azerbaijani manat */ AZN = 'AZN', /** Bosnia and Herzegovina convertible mark */ BAM = 'BAM', /** Barbados dollar */ BBD = 'BBD', /** Bangladeshi taka */ BDT = 'BDT', /** Bulgarian lev */ BGN = 'BGN', /** Bahraini dinar */ BHD = 'BHD', /** Burundian franc */ BIF = 'BIF', /** Bermudian dollar */ BMD = 'BMD', /** Brunei dollar */ BND = 'BND', /** Boliviano */ BOB = 'BOB', /** Brazilian real */ BRL = 'BRL', /** Bahamian dollar */ BSD = 'BSD', /** Bhutanese ngultrum */ BTN = 'BTN', /** Botswana pula */ BWP = 'BWP', /** Belarusian ruble */ BYN = 'BYN', /** Belize dollar */ BZD = 'BZD', /** Canadian dollar */ CAD = 'CAD', /** Congolese franc */ CDF = 'CDF', /** Swiss franc */ CHF = 'CHF', /** Chilean peso */ CLP = 'CLP', /** Renminbi (Chinese) yuan */ CNY = 'CNY', /** Colombian peso */ COP = 'COP', /** Costa Rican colon */ CRC = 'CRC', /** Cuban convertible peso */ CUC = 'CUC', /** Cuban peso */ CUP = 'CUP', /** Cape Verde escudo */ CVE = 'CVE', /** Czech koruna */ CZK = 'CZK', /** Djiboutian franc */ DJF = 'DJF', /** Danish krone */ DKK = 'DKK', /** Dominican peso */ DOP = 'DOP', /** Algerian dinar */ DZD = 'DZD', /** Egyptian pound */ EGP = 'EGP', /** Eritrean nakfa */ ERN = 'ERN', /** Ethiopian birr */ ETB = 'ETB', /** Euro */ EUR = 'EUR', /** Fiji dollar */ FJD = 'FJD', /** Falkland Islands pound */ FKP = 'FKP', /** Pound sterling */ GBP = 'GBP', /** Georgian lari */ GEL = 'GEL', /** Ghanaian cedi */ GHS = 'GHS', /** Gibraltar pound */ GIP = 'GIP', /** Gambian dalasi */ GMD = 'GMD', /** Guinean franc */ GNF = 'GNF', /** Guatemalan quetzal */ GTQ = 'GTQ', /** Guyanese dollar */ GYD = 'GYD', /** Hong Kong dollar */ HKD = 'HKD', /** Honduran lempira */ HNL = 'HNL', /** Croatian kuna */ HRK = 'HRK', /** Haitian gourde */ HTG = 'HTG', /** Hungarian forint */ HUF = 'HUF', /** Indonesian rupiah */ IDR = 'IDR', /** Israeli new shekel */ ILS = 'ILS', /** Indian rupee */ INR = 'INR', /** Iraqi dinar */ IQD = 'IQD', /** Iranian rial */ IRR = 'IRR', /** Icelandic króna */ ISK = 'ISK', /** Jamaican dollar */ JMD = 'JMD', /** Jordanian dinar */ JOD = 'JOD', /** Japanese yen */ JPY = 'JPY', /** Kenyan shilling */ KES = 'KES', /** Kyrgyzstani som */ KGS = 'KGS', /** Cambodian riel */ KHR = 'KHR', /** Comoro franc */ KMF = 'KMF', /** North Korean won */ KPW = 'KPW', /** South Korean won */ KRW = 'KRW', /** Kuwaiti dinar */ KWD = 'KWD', /** Cayman Islands dollar */ KYD = 'KYD', /** Kazakhstani tenge */ KZT = 'KZT', /** Lao kip */ LAK = 'LAK', /** Lebanese pound */ LBP = 'LBP', /** Sri Lankan rupee */ LKR = 'LKR', /** Liberian dollar */ LRD = 'LRD', /** Lesotho loti */ LSL = 'LSL', /** Libyan dinar */ LYD = 'LYD', /** Moroccan dirham */ MAD = 'MAD', /** Moldovan leu */ MDL = 'MDL', /** Malagasy ariary */ MGA = 'MGA', /** Macedonian denar */ MKD = 'MKD', /** Myanmar kyat */ MMK = 'MMK', /** Mongolian tögrög */ MNT = 'MNT', /** Macanese pataca */ MOP = 'MOP', /** Mauritanian ouguiya */ MRU = 'MRU', /** Mauritian rupee */ MUR = 'MUR', /** Maldivian rufiyaa */ MVR = 'MVR', /** Malawian kwacha */ MWK = 'MWK', /** Mexican peso */ MXN = 'MXN', /** Malaysian ringgit */ MYR = 'MYR', /** Mozambican metical */ MZN = 'MZN', /** Namibian dollar */ NAD = 'NAD', /** Nigerian naira */ NGN = 'NGN', /** Nicaraguan córdoba */ NIO = 'NIO', /** Norwegian krone */ NOK = 'NOK', /** Nepalese rupee */ NPR = 'NPR', /** New Zealand dollar */ NZD = 'NZD', /** Omani rial */ OMR = 'OMR', /** Panamanian balboa */ PAB = 'PAB', /** Peruvian sol */ PEN = 'PEN', /** Papua New Guinean kina */ PGK = 'PGK', /** Philippine peso */ PHP = 'PHP', /** Pakistani rupee */ PKR = 'PKR', /** Polish złoty */ PLN = 'PLN', /** Paraguayan guaraní */ PYG = 'PYG', /** Qatari riyal */ QAR = 'QAR', /** Romanian leu */ RON = 'RON', /** Serbian dinar */ RSD = 'RSD', /** Russian ruble */ RUB = 'RUB', /** Rwandan franc */ RWF = 'RWF', /** Saudi riyal */ SAR = 'SAR', /** Solomon Islands dollar */ SBD = 'SBD', /** Seychelles rupee */ SCR = 'SCR', /** Sudanese pound */ SDG = 'SDG', /** Swedish krona/kronor */ SEK = 'SEK', /** Singapore dollar */ SGD = 'SGD', /** Saint Helena pound */ SHP = 'SHP', /** Sierra Leonean leone */ SLL = 'SLL', /** Somali shilling */ SOS = 'SOS', /** Surinamese dollar */ SRD = 'SRD', /** South Sudanese pound */ SSP = 'SSP', /** São Tomé and Príncipe dobra */ STN = 'STN', /** Salvadoran colón */ SVC = 'SVC', /** Syrian pound */ SYP = 'SYP', /** Swazi lilangeni */ SZL = 'SZL', /** Thai baht */ THB = 'THB', /** Tajikistani somoni */ TJS = 'TJS', /** Turkmenistan manat */ TMT = 'TMT', /** Tunisian dinar */ TND = 'TND', /** Tongan paʻanga */ TOP = 'TOP', /** Turkish lira */ TRY = 'TRY', /** Trinidad and Tobago dollar */ TTD = 'TTD', /** New Taiwan dollar */ TWD = 'TWD', /** Tanzanian shilling */ TZS = 'TZS', /** Ukrainian hryvnia */ UAH = 'UAH', /** Ugandan shilling */ UGX = 'UGX', /** United States dollar */ USD = 'USD', /** Uruguayan peso */ UYU = 'UYU', /** Uzbekistan som */ UZS = 'UZS', /** Venezuelan bolívar soberano */ VES = 'VES', /** Vietnamese đồng */ VND = 'VND', /** Vanuatu vatu */ VUV = 'VUV', /** Samoan tala */ WST = 'WST', /** CFA franc BEAC */ XAF = 'XAF', /** East Caribbean dollar */ XCD = 'XCD', /** CFA franc BCEAO */ XOF = 'XOF', /** CFP franc (franc Pacifique) */ XPF = 'XPF', /** Yemeni rial */ YER = 'YER', /** South African rand */ ZAR = 'ZAR', /** Zambian kwacha */ ZMW = 'ZMW', /** Zimbabwean dollar */ ZWL = 'ZWL' } export type CurrentUser = { __typename?: 'CurrentUser'; channels: Array<CurrentUserChannel>; id: Scalars['ID']['output']; identifier: Scalars['String']['output']; }; export type CurrentUserChannel = { __typename?: 'CurrentUserChannel'; code: Scalars['String']['output']; id: Scalars['ID']['output']; permissions: Array<Permission>; token: Scalars['String']['output']; }; export type CustomField = { description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type CustomFieldConfig = BooleanCustomFieldConfig | DateTimeCustomFieldConfig | FloatCustomFieldConfig | IntCustomFieldConfig | LocaleStringCustomFieldConfig | LocaleTextCustomFieldConfig | RelationCustomFieldConfig | StringCustomFieldConfig | TextCustomFieldConfig; export type Customer = Node & { __typename?: 'Customer'; addresses?: Maybe<Array<Address>>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; emailAddress: Scalars['String']['output']; firstName: Scalars['String']['output']; id: Scalars['ID']['output']; lastName: Scalars['String']['output']; orders: OrderList; phoneNumber?: Maybe<Scalars['String']['output']>; title?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; user?: Maybe<User>; }; export type CustomerOrdersArgs = { options?: InputMaybe<OrderListOptions>; }; export type CustomerFilterParameter = { _and?: InputMaybe<Array<CustomerFilterParameter>>; _or?: InputMaybe<Array<CustomerFilterParameter>>; createdAt?: InputMaybe<DateOperators>; emailAddress?: InputMaybe<StringOperators>; firstName?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; lastName?: InputMaybe<StringOperators>; phoneNumber?: InputMaybe<StringOperators>; title?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type CustomerGroup = Node & { __typename?: 'CustomerGroup'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; customers: CustomerList; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type CustomerGroupCustomersArgs = { options?: InputMaybe<CustomerListOptions>; }; export type CustomerList = PaginatedList & { __typename?: 'CustomerList'; items: Array<Customer>; totalItems: Scalars['Int']['output']; }; export type CustomerListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<CustomerFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<CustomerSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type CustomerSortParameter = { createdAt?: InputMaybe<SortOrder>; emailAddress?: InputMaybe<SortOrder>; firstName?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; lastName?: InputMaybe<SortOrder>; phoneNumber?: InputMaybe<SortOrder>; title?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; /** Operators for filtering on a list of Date fields */ export type DateListOperators = { inList: Scalars['DateTime']['input']; }; /** Operators for filtering on a DateTime field */ export type DateOperators = { after?: InputMaybe<Scalars['DateTime']['input']>; before?: InputMaybe<Scalars['DateTime']['input']>; between?: InputMaybe<DateRange>; eq?: InputMaybe<Scalars['DateTime']['input']>; isNull?: InputMaybe<Scalars['Boolean']['input']>; }; export type DateRange = { end: Scalars['DateTime']['input']; start: Scalars['DateTime']['input']; }; /** * Expects the same validation formats as the `<input type="datetime-local">` HTML element. * See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local#Additional_attributes */ export type DateTimeCustomFieldConfig = CustomField & { __typename?: 'DateTimeCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; max?: Maybe<Scalars['String']['output']>; min?: Maybe<Scalars['String']['output']>; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; step?: Maybe<Scalars['Int']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type DeletionResponse = { __typename?: 'DeletionResponse'; message?: Maybe<Scalars['String']['output']>; result: DeletionResult; }; export enum DeletionResult { /** The entity was successfully deleted */ DELETED = 'DELETED', /** Deletion did not take place, reason given in message */ NOT_DELETED = 'NOT_DELETED' } export type Discount = { __typename?: 'Discount'; adjustmentSource: Scalars['String']['output']; amount: Scalars['Money']['output']; amountWithTax: Scalars['Money']['output']; description: Scalars['String']['output']; type: AdjustmentType; }; /** Returned when attempting to create a Customer with an email address already registered to an existing User. */ export type EmailAddressConflictError = ErrorResult & { __typename?: 'EmailAddressConflictError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export enum ErrorCode { ALREADY_LOGGED_IN_ERROR = 'ALREADY_LOGGED_IN_ERROR', COUPON_CODE_EXPIRED_ERROR = 'COUPON_CODE_EXPIRED_ERROR', COUPON_CODE_INVALID_ERROR = 'COUPON_CODE_INVALID_ERROR', COUPON_CODE_LIMIT_ERROR = 'COUPON_CODE_LIMIT_ERROR', EMAIL_ADDRESS_CONFLICT_ERROR = 'EMAIL_ADDRESS_CONFLICT_ERROR', GUEST_CHECKOUT_ERROR = 'GUEST_CHECKOUT_ERROR', IDENTIFIER_CHANGE_TOKEN_EXPIRED_ERROR = 'IDENTIFIER_CHANGE_TOKEN_EXPIRED_ERROR', IDENTIFIER_CHANGE_TOKEN_INVALID_ERROR = 'IDENTIFIER_CHANGE_TOKEN_INVALID_ERROR', INELIGIBLE_PAYMENT_METHOD_ERROR = 'INELIGIBLE_PAYMENT_METHOD_ERROR', INELIGIBLE_SHIPPING_METHOD_ERROR = 'INELIGIBLE_SHIPPING_METHOD_ERROR', INSUFFICIENT_STOCK_ERROR = 'INSUFFICIENT_STOCK_ERROR', INVALID_CREDENTIALS_ERROR = 'INVALID_CREDENTIALS_ERROR', MISSING_PASSWORD_ERROR = 'MISSING_PASSWORD_ERROR', NATIVE_AUTH_STRATEGY_ERROR = 'NATIVE_AUTH_STRATEGY_ERROR', NEGATIVE_QUANTITY_ERROR = 'NEGATIVE_QUANTITY_ERROR', NOT_VERIFIED_ERROR = 'NOT_VERIFIED_ERROR', NO_ACTIVE_ORDER_ERROR = 'NO_ACTIVE_ORDER_ERROR', ORDER_LIMIT_ERROR = 'ORDER_LIMIT_ERROR', ORDER_MODIFICATION_ERROR = 'ORDER_MODIFICATION_ERROR', ORDER_PAYMENT_STATE_ERROR = 'ORDER_PAYMENT_STATE_ERROR', ORDER_STATE_TRANSITION_ERROR = 'ORDER_STATE_TRANSITION_ERROR', PASSWORD_ALREADY_SET_ERROR = 'PASSWORD_ALREADY_SET_ERROR', PASSWORD_RESET_TOKEN_EXPIRED_ERROR = 'PASSWORD_RESET_TOKEN_EXPIRED_ERROR', PASSWORD_RESET_TOKEN_INVALID_ERROR = 'PASSWORD_RESET_TOKEN_INVALID_ERROR', PASSWORD_VALIDATION_ERROR = 'PASSWORD_VALIDATION_ERROR', PAYMENT_DECLINED_ERROR = 'PAYMENT_DECLINED_ERROR', PAYMENT_FAILED_ERROR = 'PAYMENT_FAILED_ERROR', UNKNOWN_ERROR = 'UNKNOWN_ERROR', VERIFICATION_TOKEN_EXPIRED_ERROR = 'VERIFICATION_TOKEN_EXPIRED_ERROR', VERIFICATION_TOKEN_INVALID_ERROR = 'VERIFICATION_TOKEN_INVALID_ERROR' } export type ErrorResult = { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Facet = Node & { __typename?: 'Facet'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<FacetTranslation>; updatedAt: Scalars['DateTime']['output']; /** Returns a paginated, sortable, filterable list of the Facet's values. Added in v2.1.0. */ valueList: FacetValueList; values: Array<FacetValue>; }; export type FacetValueListArgs = { options?: InputMaybe<FacetValueListOptions>; }; export type FacetFilterParameter = { _and?: InputMaybe<Array<FacetFilterParameter>>; _or?: InputMaybe<Array<FacetFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type FacetList = PaginatedList & { __typename?: 'FacetList'; items: Array<Facet>; totalItems: Scalars['Int']['output']; }; export type FacetListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<FacetFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<FacetSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type FacetSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type FacetTranslation = { __typename?: 'FacetTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type FacetValue = Node & { __typename?: 'FacetValue'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; facet: Facet; facetId: Scalars['ID']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<FacetValueTranslation>; updatedAt: Scalars['DateTime']['output']; }; /** * Used to construct boolean expressions for filtering search results * by FacetValue ID. Examples: * * * ID=1 OR ID=2: `{ facetValueFilters: [{ or: [1,2] }] }` * * ID=1 AND ID=2: `{ facetValueFilters: [{ and: 1 }, { and: 2 }] }` * * ID=1 AND (ID=2 OR ID=3): `{ facetValueFilters: [{ and: 1 }, { or: [2,3] }] }` */ export type FacetValueFilterInput = { and?: InputMaybe<Scalars['ID']['input']>; or?: InputMaybe<Array<Scalars['ID']['input']>>; }; export type FacetValueFilterParameter = { _and?: InputMaybe<Array<FacetValueFilterParameter>>; _or?: InputMaybe<Array<FacetValueFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; facetId?: InputMaybe<IdOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type FacetValueList = PaginatedList & { __typename?: 'FacetValueList'; items: Array<FacetValue>; totalItems: Scalars['Int']['output']; }; export type FacetValueListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<FacetValueFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<FacetValueSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; /** * Which FacetValues are present in the products returned * by the search, and in what quantity. */ export type FacetValueResult = { __typename?: 'FacetValueResult'; count: Scalars['Int']['output']; facetValue: FacetValue; }; export type FacetValueSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; facetId?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type FacetValueTranslation = { __typename?: 'FacetValueTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type FloatCustomFieldConfig = CustomField & { __typename?: 'FloatCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; max?: Maybe<Scalars['Float']['output']>; min?: Maybe<Scalars['Float']['output']>; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; step?: Maybe<Scalars['Float']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type Fulfillment = Node & { __typename?: 'Fulfillment'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; lines: Array<FulfillmentLine>; method: Scalars['String']['output']; state: Scalars['String']['output']; /** @deprecated Use the `lines` field instead */ summary: Array<FulfillmentLine>; trackingCode?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type FulfillmentLine = { __typename?: 'FulfillmentLine'; fulfillment: Fulfillment; fulfillmentId: Scalars['ID']['output']; orderLine: OrderLine; orderLineId: Scalars['ID']['output']; quantity: Scalars['Int']['output']; }; export enum GlobalFlag { FALSE = 'FALSE', INHERIT = 'INHERIT', TRUE = 'TRUE' } /** Returned when attempting to set the Customer on a guest checkout when the configured GuestCheckoutStrategy does not allow it. */ export type GuestCheckoutError = ErrorResult & { __typename?: 'GuestCheckoutError'; errorCode: ErrorCode; errorDetail: Scalars['String']['output']; message: Scalars['String']['output']; }; export type HistoryEntry = Node & { __typename?: 'HistoryEntry'; createdAt: Scalars['DateTime']['output']; data: Scalars['JSON']['output']; id: Scalars['ID']['output']; type: HistoryEntryType; updatedAt: Scalars['DateTime']['output']; }; export type HistoryEntryFilterParameter = { _and?: InputMaybe<Array<HistoryEntryFilterParameter>>; _or?: InputMaybe<Array<HistoryEntryFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type HistoryEntryList = PaginatedList & { __typename?: 'HistoryEntryList'; items: Array<HistoryEntry>; totalItems: Scalars['Int']['output']; }; export type HistoryEntryListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<HistoryEntryFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<HistoryEntrySortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type HistoryEntrySortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export enum HistoryEntryType { CUSTOMER_ADDED_TO_GROUP = 'CUSTOMER_ADDED_TO_GROUP', CUSTOMER_ADDRESS_CREATED = 'CUSTOMER_ADDRESS_CREATED', CUSTOMER_ADDRESS_DELETED = 'CUSTOMER_ADDRESS_DELETED', CUSTOMER_ADDRESS_UPDATED = 'CUSTOMER_ADDRESS_UPDATED', CUSTOMER_DETAIL_UPDATED = 'CUSTOMER_DETAIL_UPDATED', CUSTOMER_EMAIL_UPDATE_REQUESTED = 'CUSTOMER_EMAIL_UPDATE_REQUESTED', CUSTOMER_EMAIL_UPDATE_VERIFIED = 'CUSTOMER_EMAIL_UPDATE_VERIFIED', CUSTOMER_NOTE = 'CUSTOMER_NOTE', CUSTOMER_PASSWORD_RESET_REQUESTED = 'CUSTOMER_PASSWORD_RESET_REQUESTED', CUSTOMER_PASSWORD_RESET_VERIFIED = 'CUSTOMER_PASSWORD_RESET_VERIFIED', CUSTOMER_PASSWORD_UPDATED = 'CUSTOMER_PASSWORD_UPDATED', CUSTOMER_REGISTERED = 'CUSTOMER_REGISTERED', CUSTOMER_REMOVED_FROM_GROUP = 'CUSTOMER_REMOVED_FROM_GROUP', CUSTOMER_VERIFIED = 'CUSTOMER_VERIFIED', ORDER_CANCELLATION = 'ORDER_CANCELLATION', ORDER_COUPON_APPLIED = 'ORDER_COUPON_APPLIED', ORDER_COUPON_REMOVED = 'ORDER_COUPON_REMOVED', ORDER_CUSTOMER_UPDATED = 'ORDER_CUSTOMER_UPDATED', ORDER_FULFILLMENT = 'ORDER_FULFILLMENT', ORDER_FULFILLMENT_TRANSITION = 'ORDER_FULFILLMENT_TRANSITION', ORDER_MODIFIED = 'ORDER_MODIFIED', ORDER_NOTE = 'ORDER_NOTE', ORDER_PAYMENT_TRANSITION = 'ORDER_PAYMENT_TRANSITION', ORDER_REFUND_TRANSITION = 'ORDER_REFUND_TRANSITION', ORDER_STATE_TRANSITION = 'ORDER_STATE_TRANSITION' } /** Operators for filtering on a list of ID fields */ export type IdListOperators = { inList: Scalars['ID']['input']; }; /** Operators for filtering on an ID field */ export type IdOperators = { eq?: InputMaybe<Scalars['String']['input']>; in?: InputMaybe<Array<Scalars['String']['input']>>; isNull?: InputMaybe<Scalars['Boolean']['input']>; notEq?: InputMaybe<Scalars['String']['input']>; notIn?: InputMaybe<Array<Scalars['String']['input']>>; }; /** * Returned if the token used to change a Customer's email address is valid, but has * expired according to the `verificationTokenDuration` setting in the AuthOptions. */ export type IdentifierChangeTokenExpiredError = ErrorResult & { __typename?: 'IdentifierChangeTokenExpiredError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * Returned if the token used to change a Customer's email address is either * invalid or does not match any expected tokens. */ export type IdentifierChangeTokenInvalidError = ErrorResult & { __typename?: 'IdentifierChangeTokenInvalidError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to add a Payment using a PaymentMethod for which the Order is not eligible. */ export type IneligiblePaymentMethodError = ErrorResult & { __typename?: 'IneligiblePaymentMethodError'; eligibilityCheckerMessage?: Maybe<Scalars['String']['output']>; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to set a ShippingMethod for which the Order is not eligible */ export type IneligibleShippingMethodError = ErrorResult & { __typename?: 'IneligibleShippingMethodError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to add more items to the Order than are available */ export type InsufficientStockError = ErrorResult & { __typename?: 'InsufficientStockError'; errorCode: ErrorCode; message: Scalars['String']['output']; order: Order; quantityAvailable: Scalars['Int']['output']; }; export type IntCustomFieldConfig = CustomField & { __typename?: 'IntCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; max?: Maybe<Scalars['Int']['output']>; min?: Maybe<Scalars['Int']['output']>; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; step?: Maybe<Scalars['Int']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; /** Returned if the user authentication credentials are not valid */ export type InvalidCredentialsError = ErrorResult & { __typename?: 'InvalidCredentialsError'; authenticationError: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * @description * Languages in the form of a ISO 639-1 language code with optional * region or script modifier (e.g. de_AT). The selection available is based * on the [Unicode CLDR summary list](https://unicode-org.github.io/cldr-staging/charts/37/summary/root.html) * and includes the major spoken languages of the world and any widely-used variants. * * @docsCategory common */ export enum LanguageCode { /** Afrikaans */ af = 'af', /** Akan */ ak = 'ak', /** Amharic */ am = 'am', /** Arabic */ ar = 'ar', /** Assamese */ as = 'as', /** Azerbaijani */ az = 'az', /** Belarusian */ be = 'be', /** Bulgarian */ bg = 'bg', /** Bambara */ bm = 'bm', /** Bangla */ bn = 'bn', /** Tibetan */ bo = 'bo', /** Breton */ br = 'br', /** Bosnian */ bs = 'bs', /** Catalan */ ca = 'ca', /** Chechen */ ce = 'ce', /** Corsican */ co = 'co', /** Czech */ cs = 'cs', /** Church Slavic */ cu = 'cu', /** Welsh */ cy = 'cy', /** Danish */ da = 'da', /** German */ de = 'de', /** Austrian German */ de_AT = 'de_AT', /** Swiss High German */ de_CH = 'de_CH', /** Dzongkha */ dz = 'dz', /** Ewe */ ee = 'ee', /** Greek */ el = 'el', /** English */ en = 'en', /** Australian English */ en_AU = 'en_AU', /** Canadian English */ en_CA = 'en_CA', /** British English */ en_GB = 'en_GB', /** American English */ en_US = 'en_US', /** Esperanto */ eo = 'eo', /** Spanish */ es = 'es', /** European Spanish */ es_ES = 'es_ES', /** Mexican Spanish */ es_MX = 'es_MX', /** Estonian */ et = 'et', /** Basque */ eu = 'eu', /** Persian */ fa = 'fa', /** Dari */ fa_AF = 'fa_AF', /** Fulah */ ff = 'ff', /** Finnish */ fi = 'fi', /** Faroese */ fo = 'fo', /** French */ fr = 'fr', /** Canadian French */ fr_CA = 'fr_CA', /** Swiss French */ fr_CH = 'fr_CH', /** Western Frisian */ fy = 'fy', /** Irish */ ga = 'ga', /** Scottish Gaelic */ gd = 'gd', /** Galician */ gl = 'gl', /** Gujarati */ gu = 'gu', /** Manx */ gv = 'gv', /** Hausa */ ha = 'ha', /** Hebrew */ he = 'he', /** Hindi */ hi = 'hi', /** Croatian */ hr = 'hr', /** Haitian Creole */ ht = 'ht', /** Hungarian */ hu = 'hu', /** Armenian */ hy = 'hy', /** Interlingua */ ia = 'ia', /** Indonesian */ id = 'id', /** Igbo */ ig = 'ig', /** Sichuan Yi */ ii = 'ii', /** Icelandic */ is = 'is', /** Italian */ it = 'it', /** Japanese */ ja = 'ja', /** Javanese */ jv = 'jv', /** Georgian */ ka = 'ka', /** Kikuyu */ ki = 'ki', /** Kazakh */ kk = 'kk', /** Kalaallisut */ kl = 'kl', /** Khmer */ km = 'km', /** Kannada */ kn = 'kn', /** Korean */ ko = 'ko', /** Kashmiri */ ks = 'ks', /** Kurdish */ ku = 'ku', /** Cornish */ kw = 'kw', /** Kyrgyz */ ky = 'ky', /** Latin */ la = 'la', /** Luxembourgish */ lb = 'lb', /** Ganda */ lg = 'lg', /** Lingala */ ln = 'ln', /** Lao */ lo = 'lo', /** Lithuanian */ lt = 'lt', /** Luba-Katanga */ lu = 'lu', /** Latvian */ lv = 'lv', /** Malagasy */ mg = 'mg', /** Maori */ mi = 'mi', /** Macedonian */ mk = 'mk', /** Malayalam */ ml = 'ml', /** Mongolian */ mn = 'mn', /** Marathi */ mr = 'mr', /** Malay */ ms = 'ms', /** Maltese */ mt = 'mt', /** Burmese */ my = 'my', /** Norwegian Bokmål */ nb = 'nb', /** North Ndebele */ nd = 'nd', /** Nepali */ ne = 'ne', /** Dutch */ nl = 'nl', /** Flemish */ nl_BE = 'nl_BE', /** Norwegian Nynorsk */ nn = 'nn', /** Nyanja */ ny = 'ny', /** Oromo */ om = 'om', /** Odia */ or = 'or', /** Ossetic */ os = 'os', /** Punjabi */ pa = 'pa', /** Polish */ pl = 'pl', /** Pashto */ ps = 'ps', /** Portuguese */ pt = 'pt', /** Brazilian Portuguese */ pt_BR = 'pt_BR', /** European Portuguese */ pt_PT = 'pt_PT', /** Quechua */ qu = 'qu', /** Romansh */ rm = 'rm', /** Rundi */ rn = 'rn', /** Romanian */ ro = 'ro', /** Moldavian */ ro_MD = 'ro_MD', /** Russian */ ru = 'ru', /** Kinyarwanda */ rw = 'rw', /** Sanskrit */ sa = 'sa', /** Sindhi */ sd = 'sd', /** Northern Sami */ se = 'se', /** Sango */ sg = 'sg', /** Sinhala */ si = 'si', /** Slovak */ sk = 'sk', /** Slovenian */ sl = 'sl', /** Samoan */ sm = 'sm', /** Shona */ sn = 'sn', /** Somali */ so = 'so', /** Albanian */ sq = 'sq', /** Serbian */ sr = 'sr', /** Southern Sotho */ st = 'st', /** Sundanese */ su = 'su', /** Swedish */ sv = 'sv', /** Swahili */ sw = 'sw', /** Congo Swahili */ sw_CD = 'sw_CD', /** Tamil */ ta = 'ta', /** Telugu */ te = 'te', /** Tajik */ tg = 'tg', /** Thai */ th = 'th', /** Tigrinya */ ti = 'ti', /** Turkmen */ tk = 'tk', /** Tongan */ to = 'to', /** Turkish */ tr = 'tr', /** Tatar */ tt = 'tt', /** Uyghur */ ug = 'ug', /** Ukrainian */ uk = 'uk', /** Urdu */ ur = 'ur', /** Uzbek */ uz = 'uz', /** Vietnamese */ vi = 'vi', /** Volapük */ vo = 'vo', /** Wolof */ wo = 'wo', /** Xhosa */ xh = 'xh', /** Yiddish */ yi = 'yi', /** Yoruba */ yo = 'yo', /** Chinese */ zh = 'zh', /** Simplified Chinese */ zh_Hans = 'zh_Hans', /** Traditional Chinese */ zh_Hant = 'zh_Hant', /** Zulu */ zu = 'zu' } export type LocaleStringCustomFieldConfig = CustomField & { __typename?: 'LocaleStringCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; length?: Maybe<Scalars['Int']['output']>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; pattern?: Maybe<Scalars['String']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type LocaleTextCustomFieldConfig = CustomField & { __typename?: 'LocaleTextCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type LocalizedString = { __typename?: 'LocalizedString'; languageCode: LanguageCode; value: Scalars['String']['output']; }; export enum LogicalOperator { AND = 'AND', OR = 'OR' } /** Returned when attempting to register or verify a customer account without a password, when one is required. */ export type MissingPasswordError = ErrorResult & { __typename?: 'MissingPasswordError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Mutation = { __typename?: 'Mutation'; /** Adds an item to the order. If custom fields are defined on the OrderLine entity, a third argument 'customFields' will be available. */ addItemToOrder: UpdateOrderItemsResult; /** Add a Payment to the Order */ addPaymentToOrder: AddPaymentToOrderResult; /** Adjusts an OrderLine. If custom fields are defined on the OrderLine entity, a third argument 'customFields' of type `OrderLineCustomFieldsInput` will be available. */ adjustOrderLine: UpdateOrderItemsResult; /** Applies the given coupon code to the active Order */ applyCouponCode: ApplyCouponCodeResult; /** Authenticates the user using a named authentication strategy */ authenticate: AuthenticationResult; /** Create a new Customer Address */ createCustomerAddress: Address; /** Delete an existing Address */ deleteCustomerAddress: Success; /** Authenticates the user using the native authentication strategy. This mutation is an alias for `authenticate({ native: { ... }})` */ login: NativeAuthenticationResult; /** End the current authenticated session */ logout: Success; /** Regenerate and send a verification token for a new Customer registration. Only applicable if `authOptions.requireVerification` is set to true. */ refreshCustomerVerification: RefreshCustomerVerificationResult; /** * Register a Customer account with the given credentials. There are three possible registration flows: * * _If `authOptions.requireVerification` is set to `true`:_ * * 1. **The Customer is registered _with_ a password**. A verificationToken will be created (and typically emailed to the Customer). That * verificationToken would then be passed to the `verifyCustomerAccount` mutation _without_ a password. The Customer is then * verified and authenticated in one step. * 2. **The Customer is registered _without_ a password**. A verificationToken will be created (and typically emailed to the Customer). That * verificationToken would then be passed to the `verifyCustomerAccount` mutation _with_ the chosen password of the Customer. The Customer is then * verified and authenticated in one step. * * _If `authOptions.requireVerification` is set to `false`:_ * * 3. The Customer _must_ be registered _with_ a password. No further action is needed - the Customer is able to authenticate immediately. */ registerCustomerAccount: RegisterCustomerAccountResult; /** Remove all OrderLine from the Order */ removeAllOrderLines: RemoveOrderItemsResult; /** Removes the given coupon code from the active Order */ removeCouponCode?: Maybe<Order>; /** Remove an OrderLine from the Order */ removeOrderLine: RemoveOrderItemsResult; /** Requests a password reset email to be sent */ requestPasswordReset?: Maybe<RequestPasswordResetResult>; /** * Request to update the emailAddress of the active Customer. If `authOptions.requireVerification` is enabled * (as is the default), then the `identifierChangeToken` will be assigned to the current User and * a IdentifierChangeRequestEvent will be raised. This can then be used e.g. by the EmailPlugin to email * that verification token to the Customer, which is then used to verify the change of email address. */ requestUpdateCustomerEmailAddress: RequestUpdateCustomerEmailAddressResult; /** Resets a Customer's password based on the provided token */ resetPassword: ResetPasswordResult; /** Set the Customer for the Order. Required only if the Customer is not currently logged in */ setCustomerForOrder: SetCustomerForOrderResult; /** Sets the billing address for this order */ setOrderBillingAddress: ActiveOrderResult; /** Allows any custom fields to be set for the active order */ setOrderCustomFields: ActiveOrderResult; /** Sets the shipping address for this order */ setOrderShippingAddress: ActiveOrderResult; /** * Sets the shipping method by id, which can be obtained with the `eligibleShippingMethods` query. * An Order can have multiple shipping methods, in which case you can pass an array of ids. In this case, * you should configure a custom ShippingLineAssignmentStrategy in order to know which OrderLines each * shipping method will apply to. */ setOrderShippingMethod: SetOrderShippingMethodResult; /** Transitions an Order to a new state. Valid next states can be found by querying `nextOrderStates` */ transitionOrderToState?: Maybe<TransitionOrderToStateResult>; /** Update an existing Customer */ updateCustomer: Customer; /** Update an existing Address */ updateCustomerAddress: Address; /** * Confirm the update of the emailAddress with the provided token, which has been generated by the * `requestUpdateCustomerEmailAddress` mutation. */ updateCustomerEmailAddress: UpdateCustomerEmailAddressResult; /** Update the password of the active Customer */ updateCustomerPassword: UpdateCustomerPasswordResult; /** * Verify a Customer email address with the token sent to that address. Only applicable if `authOptions.requireVerification` is set to true. * * If the Customer was not registered with a password in the `registerCustomerAccount` mutation, the password _must_ be * provided here. */ verifyCustomerAccount: VerifyCustomerAccountResult; }; export type MutationAddItemToOrderArgs = { productVariantId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type MutationAddPaymentToOrderArgs = { input: PaymentInput; }; export type MutationAdjustOrderLineArgs = { orderLineId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type MutationApplyCouponCodeArgs = { couponCode: Scalars['String']['input']; }; export type MutationAuthenticateArgs = { input: AuthenticationInput; rememberMe?: InputMaybe<Scalars['Boolean']['input']>; }; export type MutationCreateCustomerAddressArgs = { input: CreateAddressInput; }; export type MutationDeleteCustomerAddressArgs = { id: Scalars['ID']['input']; }; export type MutationLoginArgs = { password: Scalars['String']['input']; rememberMe?: InputMaybe<Scalars['Boolean']['input']>; username: Scalars['String']['input']; }; export type MutationRefreshCustomerVerificationArgs = { emailAddress: Scalars['String']['input']; }; export type MutationRegisterCustomerAccountArgs = { input: RegisterCustomerInput; }; export type MutationRemoveCouponCodeArgs = { couponCode: Scalars['String']['input']; }; export type MutationRemoveOrderLineArgs = { orderLineId: Scalars['ID']['input']; }; export type MutationRequestPasswordResetArgs = { emailAddress: Scalars['String']['input']; }; export type MutationRequestUpdateCustomerEmailAddressArgs = { newEmailAddress: Scalars['String']['input']; password: Scalars['String']['input']; }; export type MutationResetPasswordArgs = { password: Scalars['String']['input']; token: Scalars['String']['input']; }; export type MutationSetCustomerForOrderArgs = { input: CreateCustomerInput; }; export type MutationSetOrderBillingAddressArgs = { input: CreateAddressInput; }; export type MutationSetOrderCustomFieldsArgs = { input: UpdateOrderInput; }; export type MutationSetOrderShippingAddressArgs = { input: CreateAddressInput; }; export type MutationSetOrderShippingMethodArgs = { shippingMethodId: Array<Scalars['ID']['input']>; }; export type MutationTransitionOrderToStateArgs = { state: Scalars['String']['input']; }; export type MutationUpdateCustomerArgs = { input: UpdateCustomerInput; }; export type MutationUpdateCustomerAddressArgs = { input: UpdateAddressInput; }; export type MutationUpdateCustomerEmailAddressArgs = { token: Scalars['String']['input']; }; export type MutationUpdateCustomerPasswordArgs = { currentPassword: Scalars['String']['input']; newPassword: Scalars['String']['input']; }; export type MutationVerifyCustomerAccountArgs = { password?: InputMaybe<Scalars['String']['input']>; token: Scalars['String']['input']; }; export type NativeAuthInput = { password: Scalars['String']['input']; username: Scalars['String']['input']; }; /** Returned when attempting an operation that relies on the NativeAuthStrategy, if that strategy is not configured. */ export type NativeAuthStrategyError = ErrorResult & { __typename?: 'NativeAuthStrategyError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type NativeAuthenticationResult = CurrentUser | InvalidCredentialsError | NativeAuthStrategyError | NotVerifiedError; /** Returned when attempting to set a negative OrderLine quantity. */ export type NegativeQuantityError = ErrorResult & { __typename?: 'NegativeQuantityError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * Returned when invoking a mutation which depends on there being an active Order on the * current session. */ export type NoActiveOrderError = ErrorResult & { __typename?: 'NoActiveOrderError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Node = { id: Scalars['ID']['output']; }; /** * Returned if `authOptions.requireVerification` is set to `true` (which is the default) * and an unverified user attempts to authenticate. */ export type NotVerifiedError = ErrorResult & { __typename?: 'NotVerifiedError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Operators for filtering on a list of Number fields */ export type NumberListOperators = { inList: Scalars['Float']['input']; }; /** Operators for filtering on a Int or Float field */ export type NumberOperators = { between?: InputMaybe<NumberRange>; eq?: InputMaybe<Scalars['Float']['input']>; gt?: InputMaybe<Scalars['Float']['input']>; gte?: InputMaybe<Scalars['Float']['input']>; isNull?: InputMaybe<Scalars['Boolean']['input']>; lt?: InputMaybe<Scalars['Float']['input']>; lte?: InputMaybe<Scalars['Float']['input']>; }; export type NumberRange = { end: Scalars['Float']['input']; start: Scalars['Float']['input']; }; export type Order = Node & { __typename?: 'Order'; /** An order is active as long as the payment process has not been completed */ active: Scalars['Boolean']['output']; billingAddress?: Maybe<OrderAddress>; /** A unique code for the Order */ code: Scalars['String']['output']; /** An array of all coupon codes applied to the Order */ couponCodes: Array<Scalars['String']['output']>; createdAt: Scalars['DateTime']['output']; currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; customer?: Maybe<Customer>; discounts: Array<Discount>; fulfillments?: Maybe<Array<Fulfillment>>; history: HistoryEntryList; id: Scalars['ID']['output']; lines: Array<OrderLine>; /** * The date & time that the Order was placed, i.e. the Customer * completed the checkout and the Order is no longer "active" */ orderPlacedAt?: Maybe<Scalars['DateTime']['output']>; payments?: Maybe<Array<Payment>>; /** Promotions applied to the order. Only gets populated after the payment process has completed. */ promotions: Array<Promotion>; shipping: Scalars['Money']['output']; shippingAddress?: Maybe<OrderAddress>; shippingLines: Array<ShippingLine>; shippingWithTax: Scalars['Money']['output']; state: Scalars['String']['output']; /** * The subTotal is the total of all OrderLines in the Order. This figure also includes any Order-level * discounts which have been prorated (proportionally distributed) amongst the items of each OrderLine. * To get a total of all OrderLines which does not account for prorated discounts, use the * sum of `OrderLine.discountedLinePrice` values. */ subTotal: Scalars['Money']['output']; /** Same as subTotal, but inclusive of tax */ subTotalWithTax: Scalars['Money']['output']; /** * Surcharges are arbitrary modifications to the Order total which are neither * ProductVariants nor discounts resulting from applied Promotions. For example, * one-off discounts based on customer interaction, or surcharges based on payment * methods. */ surcharges: Array<Surcharge>; /** A summary of the taxes being applied to this Order */ taxSummary: Array<OrderTaxSummary>; /** Equal to subTotal plus shipping */ total: Scalars['Money']['output']; totalQuantity: Scalars['Int']['output']; /** The final payable amount. Equal to subTotalWithTax plus shippingWithTax */ totalWithTax: Scalars['Money']['output']; type: OrderType; updatedAt: Scalars['DateTime']['output']; }; export type OrderHistoryArgs = { options?: InputMaybe<HistoryEntryListOptions>; }; export type OrderAddress = { __typename?: 'OrderAddress'; city?: Maybe<Scalars['String']['output']>; company?: Maybe<Scalars['String']['output']>; country?: Maybe<Scalars['String']['output']>; countryCode?: Maybe<Scalars['String']['output']>; customFields?: Maybe<Scalars['JSON']['output']>; fullName?: Maybe<Scalars['String']['output']>; phoneNumber?: Maybe<Scalars['String']['output']>; postalCode?: Maybe<Scalars['String']['output']>; province?: Maybe<Scalars['String']['output']>; streetLine1?: Maybe<Scalars['String']['output']>; streetLine2?: Maybe<Scalars['String']['output']>; }; export type OrderFilterParameter = { _and?: InputMaybe<Array<OrderFilterParameter>>; _or?: InputMaybe<Array<OrderFilterParameter>>; active?: InputMaybe<BooleanOperators>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; currencyCode?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; orderPlacedAt?: InputMaybe<DateOperators>; shipping?: InputMaybe<NumberOperators>; shippingWithTax?: InputMaybe<NumberOperators>; state?: InputMaybe<StringOperators>; subTotal?: InputMaybe<NumberOperators>; subTotalWithTax?: InputMaybe<NumberOperators>; total?: InputMaybe<NumberOperators>; totalQuantity?: InputMaybe<NumberOperators>; totalWithTax?: InputMaybe<NumberOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; /** Returned when the maximum order size limit has been reached. */ export type OrderLimitError = ErrorResult & { __typename?: 'OrderLimitError'; errorCode: ErrorCode; maxItems: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type OrderLine = Node & { __typename?: 'OrderLine'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; /** The price of the line including discounts, excluding tax */ discountedLinePrice: Scalars['Money']['output']; /** The price of the line including discounts and tax */ discountedLinePriceWithTax: Scalars['Money']['output']; /** * The price of a single unit including discounts, excluding tax. * * If Order-level discounts have been applied, this will not be the * actual taxable unit price (see `proratedUnitPrice`), but is generally the * correct price to display to customers to avoid confusion * about the internal handling of distributed Order-level discounts. */ discountedUnitPrice: Scalars['Money']['output']; /** The price of a single unit including discounts and tax */ discountedUnitPriceWithTax: Scalars['Money']['output']; discounts: Array<Discount>; featuredAsset?: Maybe<Asset>; fulfillmentLines?: Maybe<Array<FulfillmentLine>>; id: Scalars['ID']['output']; /** The total price of the line excluding tax and discounts. */ linePrice: Scalars['Money']['output']; /** The total price of the line including tax but excluding discounts. */ linePriceWithTax: Scalars['Money']['output']; /** The total tax on this line */ lineTax: Scalars['Money']['output']; order: Order; /** The quantity at the time the Order was placed */ orderPlacedQuantity: Scalars['Int']['output']; productVariant: ProductVariant; /** * The actual line price, taking into account both item discounts _and_ prorated (proportionally-distributed) * Order-level discounts. This value is the true economic value of the OrderLine, and is used in tax * and refund calculations. */ proratedLinePrice: Scalars['Money']['output']; /** The proratedLinePrice including tax */ proratedLinePriceWithTax: Scalars['Money']['output']; /** * The actual unit price, taking into account both item discounts _and_ prorated (proportionally-distributed) * Order-level discounts. This value is the true economic value of the OrderItem, and is used in tax * and refund calculations. */ proratedUnitPrice: Scalars['Money']['output']; /** The proratedUnitPrice including tax */ proratedUnitPriceWithTax: Scalars['Money']['output']; /** The quantity of items purchased */ quantity: Scalars['Int']['output']; taxLines: Array<TaxLine>; taxRate: Scalars['Float']['output']; /** The price of a single unit, excluding tax and discounts */ unitPrice: Scalars['Money']['output']; /** Non-zero if the unitPrice has changed since it was initially added to Order */ unitPriceChangeSinceAdded: Scalars['Money']['output']; /** The price of a single unit, including tax but excluding discounts */ unitPriceWithTax: Scalars['Money']['output']; /** Non-zero if the unitPriceWithTax has changed since it was initially added to Order */ unitPriceWithTaxChangeSinceAdded: Scalars['Money']['output']; updatedAt: Scalars['DateTime']['output']; }; export type OrderList = PaginatedList & { __typename?: 'OrderList'; items: Array<Order>; totalItems: Scalars['Int']['output']; }; export type OrderListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<OrderFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<OrderSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; /** Returned when attempting to modify the contents of an Order that is not in the `AddingItems` state. */ export type OrderModificationError = ErrorResult & { __typename?: 'OrderModificationError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to add a Payment to an Order that is not in the `ArrangingPayment` state. */ export type OrderPaymentStateError = ErrorResult & { __typename?: 'OrderPaymentStateError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type OrderSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; orderPlacedAt?: InputMaybe<SortOrder>; shipping?: InputMaybe<SortOrder>; shippingWithTax?: InputMaybe<SortOrder>; state?: InputMaybe<SortOrder>; subTotal?: InputMaybe<SortOrder>; subTotalWithTax?: InputMaybe<SortOrder>; total?: InputMaybe<SortOrder>; totalQuantity?: InputMaybe<SortOrder>; totalWithTax?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; /** Returned if there is an error in transitioning the Order state */ export type OrderStateTransitionError = ErrorResult & { __typename?: 'OrderStateTransitionError'; errorCode: ErrorCode; fromState: Scalars['String']['output']; message: Scalars['String']['output']; toState: Scalars['String']['output']; transitionError: Scalars['String']['output']; }; /** * A summary of the taxes being applied to this order, grouped * by taxRate. */ export type OrderTaxSummary = { __typename?: 'OrderTaxSummary'; /** A description of this tax */ description: Scalars['String']['output']; /** The total net price of OrderLines to which this taxRate applies */ taxBase: Scalars['Money']['output']; /** The taxRate as a percentage */ taxRate: Scalars['Float']['output']; /** The total tax being applied to the Order at this taxRate */ taxTotal: Scalars['Money']['output']; }; export enum OrderType { Aggregate = 'Aggregate', Regular = 'Regular', Seller = 'Seller' } export type PaginatedList = { items: Array<Node>; totalItems: Scalars['Int']['output']; }; /** Returned when attempting to verify a customer account with a password, when a password has already been set. */ export type PasswordAlreadySetError = ErrorResult & { __typename?: 'PasswordAlreadySetError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * Returned if the token used to reset a Customer's password is valid, but has * expired according to the `verificationTokenDuration` setting in the AuthOptions. */ export type PasswordResetTokenExpiredError = ErrorResult & { __typename?: 'PasswordResetTokenExpiredError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * Returned if the token used to reset a Customer's password is either * invalid or does not match any expected tokens. */ export type PasswordResetTokenInvalidError = ErrorResult & { __typename?: 'PasswordResetTokenInvalidError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to register or verify a customer account where the given password fails password validation. */ export type PasswordValidationError = ErrorResult & { __typename?: 'PasswordValidationError'; errorCode: ErrorCode; message: Scalars['String']['output']; validationErrorMessage: Scalars['String']['output']; }; export type Payment = Node & { __typename?: 'Payment'; amount: Scalars['Money']['output']; createdAt: Scalars['DateTime']['output']; errorMessage?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; metadata?: Maybe<Scalars['JSON']['output']>; method: Scalars['String']['output']; refunds: Array<Refund>; state: Scalars['String']['output']; transactionId?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; /** Returned when a Payment is declined by the payment provider. */ export type PaymentDeclinedError = ErrorResult & { __typename?: 'PaymentDeclinedError'; errorCode: ErrorCode; message: Scalars['String']['output']; paymentErrorMessage: Scalars['String']['output']; }; /** Returned when a Payment fails due to an error. */ export type PaymentFailedError = ErrorResult & { __typename?: 'PaymentFailedError'; errorCode: ErrorCode; message: Scalars['String']['output']; paymentErrorMessage: Scalars['String']['output']; }; /** Passed as input to the `addPaymentToOrder` mutation. */ export type PaymentInput = { /** * This field should contain arbitrary data passed to the specified PaymentMethodHandler's `createPayment()` method * as the "metadata" argument. For example, it could contain an ID for the payment and other * data generated by the payment provider. */ metadata: Scalars['JSON']['input']; /** This field should correspond to the `code` property of a PaymentMethod. */ method: Scalars['String']['input']; }; export type PaymentMethod = Node & { __typename?: 'PaymentMethod'; checker?: Maybe<ConfigurableOperation>; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; handler: ConfigurableOperation; id: Scalars['ID']['output']; name: Scalars['String']['output']; translations: Array<PaymentMethodTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type PaymentMethodQuote = { __typename?: 'PaymentMethodQuote'; code: Scalars['String']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; eligibilityMessage?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; isEligible: Scalars['Boolean']['output']; name: Scalars['String']['output']; }; export type PaymentMethodTranslation = { __typename?: 'PaymentMethodTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; /** * @description * Permissions for administrators and customers. Used to control access to * GraphQL resolvers via the {@link Allow} decorator. * * ## Understanding Permission.Owner * * `Permission.Owner` is a special permission which is used in some Vendure resolvers to indicate that that resolver should only * be accessible to the "owner" of that resource. * * For example, the Shop API `activeCustomer` query resolver should only return the Customer object for the "owner" of that Customer, i.e. * based on the activeUserId of the current session. As a result, the resolver code looks like this: * * @example * ```TypeScript * \@Query() * \@Allow(Permission.Owner) * async activeCustomer(\@Ctx() ctx: RequestContext): Promise<Customer | undefined> { * const userId = ctx.activeUserId; * if (userId) { * return this.customerService.findOneByUserId(ctx, userId); * } * } * ``` * * Here we can see that the "ownership" must be enforced by custom logic inside the resolver. Since "ownership" cannot be defined generally * nor statically encoded at build-time, any resolvers using `Permission.Owner` **must** include logic to enforce that only the owner * of the resource has access. If not, then it is the equivalent of using `Permission.Public`. * * * @docsCategory common */ export enum Permission { /** Authenticated means simply that the user is logged in */ Authenticated = 'Authenticated', /** Grants permission to create Administrator */ CreateAdministrator = 'CreateAdministrator', /** Grants permission to create Asset */ CreateAsset = 'CreateAsset', /** Grants permission to create Products, Facets, Assets, Collections */ CreateCatalog = 'CreateCatalog', /** Grants permission to create Channel */ CreateChannel = 'CreateChannel', /** Grants permission to create Collection */ CreateCollection = 'CreateCollection', /** Grants permission to create Country */ CreateCountry = 'CreateCountry', /** Grants permission to create Customer */ CreateCustomer = 'CreateCustomer', /** Grants permission to create CustomerGroup */ CreateCustomerGroup = 'CreateCustomerGroup', /** Grants permission to create Facet */ CreateFacet = 'CreateFacet', /** Grants permission to create Order */ CreateOrder = 'CreateOrder', /** Grants permission to create PaymentMethod */ CreatePaymentMethod = 'CreatePaymentMethod', /** Grants permission to create Product */ CreateProduct = 'CreateProduct', /** Grants permission to create Promotion */ CreatePromotion = 'CreatePromotion', /** Grants permission to create Seller */ CreateSeller = 'CreateSeller', /** Grants permission to create PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ CreateSettings = 'CreateSettings', /** Grants permission to create ShippingMethod */ CreateShippingMethod = 'CreateShippingMethod', /** Grants permission to create StockLocation */ CreateStockLocation = 'CreateStockLocation', /** Grants permission to create System */ CreateSystem = 'CreateSystem', /** Grants permission to create Tag */ CreateTag = 'CreateTag', /** Grants permission to create TaxCategory */ CreateTaxCategory = 'CreateTaxCategory', /** Grants permission to create TaxRate */ CreateTaxRate = 'CreateTaxRate', /** Grants permission to create Zone */ CreateZone = 'CreateZone', /** Grants permission to delete Administrator */ DeleteAdministrator = 'DeleteAdministrator', /** Grants permission to delete Asset */ DeleteAsset = 'DeleteAsset', /** Grants permission to delete Products, Facets, Assets, Collections */ DeleteCatalog = 'DeleteCatalog', /** Grants permission to delete Channel */ DeleteChannel = 'DeleteChannel', /** Grants permission to delete Collection */ DeleteCollection = 'DeleteCollection', /** Grants permission to delete Country */ DeleteCountry = 'DeleteCountry', /** Grants permission to delete Customer */ DeleteCustomer = 'DeleteCustomer', /** Grants permission to delete CustomerGroup */ DeleteCustomerGroup = 'DeleteCustomerGroup', /** Grants permission to delete Facet */ DeleteFacet = 'DeleteFacet', /** Grants permission to delete Order */ DeleteOrder = 'DeleteOrder', /** Grants permission to delete PaymentMethod */ DeletePaymentMethod = 'DeletePaymentMethod', /** Grants permission to delete Product */ DeleteProduct = 'DeleteProduct', /** Grants permission to delete Promotion */ DeletePromotion = 'DeletePromotion', /** Grants permission to delete Seller */ DeleteSeller = 'DeleteSeller', /** Grants permission to delete PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ DeleteSettings = 'DeleteSettings', /** Grants permission to delete ShippingMethod */ DeleteShippingMethod = 'DeleteShippingMethod', /** Grants permission to delete StockLocation */ DeleteStockLocation = 'DeleteStockLocation', /** Grants permission to delete System */ DeleteSystem = 'DeleteSystem', /** Grants permission to delete Tag */ DeleteTag = 'DeleteTag', /** Grants permission to delete TaxCategory */ DeleteTaxCategory = 'DeleteTaxCategory', /** Grants permission to delete TaxRate */ DeleteTaxRate = 'DeleteTaxRate', /** Grants permission to delete Zone */ DeleteZone = 'DeleteZone', /** Owner means the user owns this entity, e.g. a Customer's own Order */ Owner = 'Owner', /** Public means any unauthenticated user may perform the operation */ Public = 'Public', /** Grants permission to read Administrator */ ReadAdministrator = 'ReadAdministrator', /** Grants permission to read Asset */ ReadAsset = 'ReadAsset', /** Grants permission to read Products, Facets, Assets, Collections */ ReadCatalog = 'ReadCatalog', /** Grants permission to read Channel */ ReadChannel = 'ReadChannel', /** Grants permission to read Collection */ ReadCollection = 'ReadCollection', /** Grants permission to read Country */ ReadCountry = 'ReadCountry', /** Grants permission to read Customer */ ReadCustomer = 'ReadCustomer', /** Grants permission to read CustomerGroup */ ReadCustomerGroup = 'ReadCustomerGroup', /** Grants permission to read Facet */ ReadFacet = 'ReadFacet', /** Grants permission to read Order */ ReadOrder = 'ReadOrder', /** Grants permission to read PaymentMethod */ ReadPaymentMethod = 'ReadPaymentMethod', /** Grants permission to read Product */ ReadProduct = 'ReadProduct', /** Grants permission to read Promotion */ ReadPromotion = 'ReadPromotion', /** Grants permission to read Seller */ ReadSeller = 'ReadSeller', /** Grants permission to read PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ ReadSettings = 'ReadSettings', /** Grants permission to read ShippingMethod */ ReadShippingMethod = 'ReadShippingMethod', /** Grants permission to read StockLocation */ ReadStockLocation = 'ReadStockLocation', /** Grants permission to read System */ ReadSystem = 'ReadSystem', /** Grants permission to read Tag */ ReadTag = 'ReadTag', /** Grants permission to read TaxCategory */ ReadTaxCategory = 'ReadTaxCategory', /** Grants permission to read TaxRate */ ReadTaxRate = 'ReadTaxRate', /** Grants permission to read Zone */ ReadZone = 'ReadZone', /** SuperAdmin has unrestricted access to all operations */ SuperAdmin = 'SuperAdmin', /** Grants permission to update Administrator */ UpdateAdministrator = 'UpdateAdministrator', /** Grants permission to update Asset */ UpdateAsset = 'UpdateAsset', /** Grants permission to update Products, Facets, Assets, Collections */ UpdateCatalog = 'UpdateCatalog', /** Grants permission to update Channel */ UpdateChannel = 'UpdateChannel', /** Grants permission to update Collection */ UpdateCollection = 'UpdateCollection', /** Grants permission to update Country */ UpdateCountry = 'UpdateCountry', /** Grants permission to update Customer */ UpdateCustomer = 'UpdateCustomer', /** Grants permission to update CustomerGroup */ UpdateCustomerGroup = 'UpdateCustomerGroup', /** Grants permission to update Facet */ UpdateFacet = 'UpdateFacet', /** Grants permission to update GlobalSettings */ UpdateGlobalSettings = 'UpdateGlobalSettings', /** Grants permission to update Order */ UpdateOrder = 'UpdateOrder', /** Grants permission to update PaymentMethod */ UpdatePaymentMethod = 'UpdatePaymentMethod', /** Grants permission to update Product */ UpdateProduct = 'UpdateProduct', /** Grants permission to update Promotion */ UpdatePromotion = 'UpdatePromotion', /** Grants permission to update Seller */ UpdateSeller = 'UpdateSeller', /** Grants permission to update PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ UpdateSettings = 'UpdateSettings', /** Grants permission to update ShippingMethod */ UpdateShippingMethod = 'UpdateShippingMethod', /** Grants permission to update StockLocation */ UpdateStockLocation = 'UpdateStockLocation', /** Grants permission to update System */ UpdateSystem = 'UpdateSystem', /** Grants permission to update Tag */ UpdateTag = 'UpdateTag', /** Grants permission to update TaxCategory */ UpdateTaxCategory = 'UpdateTaxCategory', /** Grants permission to update TaxRate */ UpdateTaxRate = 'UpdateTaxRate', /** Grants permission to update Zone */ UpdateZone = 'UpdateZone' } /** The price range where the result has more than one price */ export type PriceRange = { __typename?: 'PriceRange'; max: Scalars['Money']['output']; min: Scalars['Money']['output']; }; export type Product = Node & { __typename?: 'Product'; assets: Array<Asset>; collections: Array<Collection>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; facetValues: Array<FacetValue>; featuredAsset?: Maybe<Asset>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; optionGroups: Array<ProductOptionGroup>; slug: Scalars['String']['output']; translations: Array<ProductTranslation>; updatedAt: Scalars['DateTime']['output']; /** Returns a paginated, sortable, filterable list of ProductVariants */ variantList: ProductVariantList; /** Returns all ProductVariants */ variants: Array<ProductVariant>; }; export type ProductVariantListArgs = { options?: InputMaybe<ProductVariantListOptions>; }; export type ProductFilterParameter = { _and?: InputMaybe<Array<ProductFilterParameter>>; _or?: InputMaybe<Array<ProductFilterParameter>>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; enabled?: InputMaybe<BooleanOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; slug?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ProductList = PaginatedList & { __typename?: 'ProductList'; items: Array<Product>; totalItems: Scalars['Int']['output']; }; export type ProductListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ProductFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ProductSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ProductOption = Node & { __typename?: 'ProductOption'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; group: ProductOptionGroup; groupId: Scalars['ID']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<ProductOptionTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionGroup = Node & { __typename?: 'ProductOptionGroup'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; options: Array<ProductOption>; translations: Array<ProductOptionGroupTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionGroupTranslation = { __typename?: 'ProductOptionGroupTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionTranslation = { __typename?: 'ProductOptionTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductSortParameter = { createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; slug?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ProductTranslation = { __typename?: 'ProductTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; slug: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductVariant = Node & { __typename?: 'ProductVariant'; assets: Array<Asset>; createdAt: Scalars['DateTime']['output']; currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; facetValues: Array<FacetValue>; featuredAsset?: Maybe<Asset>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; options: Array<ProductOption>; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; product: Product; productId: Scalars['ID']['output']; sku: Scalars['String']['output']; stockLevel: Scalars['String']['output']; taxCategory: TaxCategory; taxRateApplied: TaxRate; translations: Array<ProductVariantTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ProductVariantFilterParameter = { _and?: InputMaybe<Array<ProductVariantFilterParameter>>; _or?: InputMaybe<Array<ProductVariantFilterParameter>>; createdAt?: InputMaybe<DateOperators>; currencyCode?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; price?: InputMaybe<NumberOperators>; priceWithTax?: InputMaybe<NumberOperators>; productId?: InputMaybe<IdOperators>; sku?: InputMaybe<StringOperators>; stockLevel?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ProductVariantList = PaginatedList & { __typename?: 'ProductVariantList'; items: Array<ProductVariant>; totalItems: Scalars['Int']['output']; }; export type ProductVariantListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ProductVariantFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ProductVariantSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ProductVariantSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; price?: InputMaybe<SortOrder>; priceWithTax?: InputMaybe<SortOrder>; productId?: InputMaybe<SortOrder>; sku?: InputMaybe<SortOrder>; stockLevel?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ProductVariantTranslation = { __typename?: 'ProductVariantTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type Promotion = Node & { __typename?: 'Promotion'; actions: Array<ConfigurableOperation>; conditions: Array<ConfigurableOperation>; couponCode?: Maybe<Scalars['String']['output']>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; endsAt?: Maybe<Scalars['DateTime']['output']>; id: Scalars['ID']['output']; name: Scalars['String']['output']; perCustomerUsageLimit?: Maybe<Scalars['Int']['output']>; startsAt?: Maybe<Scalars['DateTime']['output']>; translations: Array<PromotionTranslation>; updatedAt: Scalars['DateTime']['output']; usageLimit?: Maybe<Scalars['Int']['output']>; }; export type PromotionList = PaginatedList & { __typename?: 'PromotionList'; items: Array<Promotion>; totalItems: Scalars['Int']['output']; }; export type PromotionTranslation = { __typename?: 'PromotionTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type Province = Node & Region & { __typename?: 'Province'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; parent?: Maybe<Region>; parentId?: Maybe<Scalars['ID']['output']>; translations: Array<RegionTranslation>; type: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProvinceList = PaginatedList & { __typename?: 'ProvinceList'; items: Array<Province>; totalItems: Scalars['Int']['output']; }; export type Query = { __typename?: 'Query'; /** The active Channel */ activeChannel: Channel; /** The active Customer */ activeCustomer?: Maybe<Customer>; /** * The active Order. Will be `null` until an Order is created via `addItemToOrder`. Once an Order reaches the * state of `PaymentAuthorized` or `PaymentSettled`, then that Order is no longer considered "active" and this * query will once again return `null`. */ activeOrder?: Maybe<Order>; /** An array of supported Countries */ availableCountries: Array<Country>; /** Returns a Collection either by its id or slug. If neither 'id' nor 'slug' is specified, an error will result. */ collection?: Maybe<Collection>; /** A list of Collections available to the shop */ collections: CollectionList; /** Returns a list of payment methods and their eligibility based on the current active Order */ eligiblePaymentMethods: Array<PaymentMethodQuote>; /** Returns a list of eligible shipping methods based on the current active Order */ eligibleShippingMethods: Array<ShippingMethodQuote>; /** Returns a Facet by its id */ facet?: Maybe<Facet>; /** A list of Facets available to the shop */ facets: FacetList; /** Returns information about the current authenticated User */ me?: Maybe<CurrentUser>; /** Returns the possible next states that the activeOrder can transition to */ nextOrderStates: Array<Scalars['String']['output']>; /** * Returns an Order based on the id. Note that in the Shop API, only orders belonging to the * currently-authenticated User may be queried. */ order?: Maybe<Order>; /** * Returns an Order based on the order `code`. For guest Orders (i.e. Orders placed by non-authenticated Customers) * this query will only return the Order within 2 hours of the Order being placed. This allows an Order confirmation * screen to be shown immediately after completion of a guest checkout, yet prevents security risks of allowing * general anonymous access to Order data. */ orderByCode?: Maybe<Order>; /** Get a Product either by id or slug. If neither 'id' nor 'slug' is specified, an error will result. */ product?: Maybe<Product>; /** Get a list of Products */ products: ProductList; /** Search Products based on the criteria set by the `SearchInput` */ search: SearchResponse; }; export type QueryCollectionArgs = { id?: InputMaybe<Scalars['ID']['input']>; slug?: InputMaybe<Scalars['String']['input']>; }; export type QueryCollectionsArgs = { options?: InputMaybe<CollectionListOptions>; }; export type QueryFacetArgs = { id: Scalars['ID']['input']; }; export type QueryFacetsArgs = { options?: InputMaybe<FacetListOptions>; }; export type QueryOrderArgs = { id: Scalars['ID']['input']; }; export type QueryOrderByCodeArgs = { code: Scalars['String']['input']; }; export type QueryProductArgs = { id?: InputMaybe<Scalars['ID']['input']>; slug?: InputMaybe<Scalars['String']['input']>; }; export type QueryProductsArgs = { options?: InputMaybe<ProductListOptions>; }; export type QuerySearchArgs = { input: SearchInput; }; export type RefreshCustomerVerificationResult = NativeAuthStrategyError | Success; export type Refund = Node & { __typename?: 'Refund'; adjustment: Scalars['Money']['output']; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; items: Scalars['Money']['output']; lines: Array<RefundLine>; metadata?: Maybe<Scalars['JSON']['output']>; method?: Maybe<Scalars['String']['output']>; paymentId: Scalars['ID']['output']; reason?: Maybe<Scalars['String']['output']>; shipping: Scalars['Money']['output']; state: Scalars['String']['output']; total: Scalars['Money']['output']; transactionId?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type RefundLine = { __typename?: 'RefundLine'; orderLine: OrderLine; orderLineId: Scalars['ID']['output']; quantity: Scalars['Int']['output']; refund: Refund; refundId: Scalars['ID']['output']; }; export type Region = { code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; parent?: Maybe<Region>; parentId?: Maybe<Scalars['ID']['output']>; translations: Array<RegionTranslation>; type: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type RegionTranslation = { __typename?: 'RegionTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type RegisterCustomerAccountResult = MissingPasswordError | NativeAuthStrategyError | PasswordValidationError | Success; export type RegisterCustomerInput = { emailAddress: Scalars['String']['input']; firstName?: InputMaybe<Scalars['String']['input']>; lastName?: InputMaybe<Scalars['String']['input']>; password?: InputMaybe<Scalars['String']['input']>; phoneNumber?: InputMaybe<Scalars['String']['input']>; title?: InputMaybe<Scalars['String']['input']>; }; export type RelationCustomFieldConfig = CustomField & { __typename?: 'RelationCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; entity: Scalars['String']['output']; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; scalarFields: Array<Scalars['String']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type RemoveOrderItemsResult = Order | OrderModificationError; export type RequestPasswordResetResult = NativeAuthStrategyError | Success; export type RequestUpdateCustomerEmailAddressResult = EmailAddressConflictError | InvalidCredentialsError | NativeAuthStrategyError | Success; export type ResetPasswordResult = CurrentUser | NativeAuthStrategyError | NotVerifiedError | PasswordResetTokenExpiredError | PasswordResetTokenInvalidError | PasswordValidationError; export type Role = Node & { __typename?: 'Role'; channels: Array<Channel>; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; permissions: Array<Permission>; updatedAt: Scalars['DateTime']['output']; }; export type RoleList = PaginatedList & { __typename?: 'RoleList'; items: Array<Role>; totalItems: Scalars['Int']['output']; }; export type SearchInput = { collectionId?: InputMaybe<Scalars['ID']['input']>; collectionSlug?: InputMaybe<Scalars['String']['input']>; facetValueFilters?: InputMaybe<Array<FacetValueFilterInput>>; /** @deprecated Use `facetValueFilters` instead */ facetValueIds?: InputMaybe<Array<Scalars['ID']['input']>>; /** @deprecated Use `facetValueFilters` instead */ facetValueOperator?: InputMaybe<LogicalOperator>; groupByProduct?: InputMaybe<Scalars['Boolean']['input']>; skip?: InputMaybe<Scalars['Int']['input']>; sort?: InputMaybe<SearchResultSortParameter>; take?: InputMaybe<Scalars['Int']['input']>; term?: InputMaybe<Scalars['String']['input']>; }; export type SearchReindexResponse = { __typename?: 'SearchReindexResponse'; success: Scalars['Boolean']['output']; }; export type SearchResponse = { __typename?: 'SearchResponse'; collections: Array<CollectionResult>; facetValues: Array<FacetValueResult>; items: Array<SearchResult>; totalItems: Scalars['Int']['output']; }; export type SearchResult = { __typename?: 'SearchResult'; /** An array of ids of the Collections in which this result appears */ collectionIds: Array<Scalars['ID']['output']>; currencyCode: CurrencyCode; description: Scalars['String']['output']; facetIds: Array<Scalars['ID']['output']>; facetValueIds: Array<Scalars['ID']['output']>; price: SearchResultPrice; priceWithTax: SearchResultPrice; productAsset?: Maybe<SearchResultAsset>; productId: Scalars['ID']['output']; productName: Scalars['String']['output']; productVariantAsset?: Maybe<SearchResultAsset>; productVariantId: Scalars['ID']['output']; productVariantName: Scalars['String']['output']; /** A relevance score for the result. Differs between database implementations */ score: Scalars['Float']['output']; sku: Scalars['String']['output']; slug: Scalars['String']['output']; }; export type SearchResultAsset = { __typename?: 'SearchResultAsset'; focalPoint?: Maybe<Coordinate>; id: Scalars['ID']['output']; preview: Scalars['String']['output']; }; /** The price of a search result product, either as a range or as a single price */ export type SearchResultPrice = PriceRange | SinglePrice; export type SearchResultSortParameter = { name?: InputMaybe<SortOrder>; price?: InputMaybe<SortOrder>; }; export type Seller = Node & { __typename?: 'Seller'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type SetCustomerForOrderResult = AlreadyLoggedInError | EmailAddressConflictError | GuestCheckoutError | NoActiveOrderError | Order; export type SetOrderShippingMethodResult = IneligibleShippingMethodError | NoActiveOrderError | Order | OrderModificationError; export type ShippingLine = { __typename?: 'ShippingLine'; discountedPrice: Scalars['Money']['output']; discountedPriceWithTax: Scalars['Money']['output']; discounts: Array<Discount>; id: Scalars['ID']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; shippingMethod: ShippingMethod; }; export type ShippingMethod = Node & { __typename?: 'ShippingMethod'; calculator: ConfigurableOperation; checker: ConfigurableOperation; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; fulfillmentHandlerCode: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<ShippingMethodTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ShippingMethodList = PaginatedList & { __typename?: 'ShippingMethodList'; items: Array<ShippingMethod>; totalItems: Scalars['Int']['output']; }; export type ShippingMethodQuote = { __typename?: 'ShippingMethodQuote'; code: Scalars['String']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; id: Scalars['ID']['output']; /** Any optional metadata returned by the ShippingCalculator in the ShippingCalculationResult */ metadata?: Maybe<Scalars['JSON']['output']>; name: Scalars['String']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; }; export type ShippingMethodTranslation = { __typename?: 'ShippingMethodTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; /** The price value where the result has a single price */ export type SinglePrice = { __typename?: 'SinglePrice'; value: Scalars['Money']['output']; }; export enum SortOrder { ASC = 'ASC', DESC = 'DESC' } export type StringCustomFieldConfig = CustomField & { __typename?: 'StringCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; length?: Maybe<Scalars['Int']['output']>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; options?: Maybe<Array<StringFieldOption>>; pattern?: Maybe<Scalars['String']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type StringFieldOption = { __typename?: 'StringFieldOption'; label?: Maybe<Array<LocalizedString>>; value: Scalars['String']['output']; }; /** Operators for filtering on a list of String fields */ export type StringListOperators = { inList: Scalars['String']['input']; }; /** Operators for filtering on a String field */ export type StringOperators = { contains?: InputMaybe<Scalars['String']['input']>; eq?: InputMaybe<Scalars['String']['input']>; in?: InputMaybe<Array<Scalars['String']['input']>>; isNull?: InputMaybe<Scalars['Boolean']['input']>; notContains?: InputMaybe<Scalars['String']['input']>; notEq?: InputMaybe<Scalars['String']['input']>; notIn?: InputMaybe<Array<Scalars['String']['input']>>; regex?: InputMaybe<Scalars['String']['input']>; }; /** Indicates that an operation succeeded, where we do not want to return any more specific information. */ export type Success = { __typename?: 'Success'; success: Scalars['Boolean']['output']; }; export type Surcharge = Node & { __typename?: 'Surcharge'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; sku?: Maybe<Scalars['String']['output']>; taxLines: Array<TaxLine>; taxRate: Scalars['Float']['output']; updatedAt: Scalars['DateTime']['output']; }; export type Tag = Node & { __typename?: 'Tag'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; updatedAt: Scalars['DateTime']['output']; value: Scalars['String']['output']; }; export type TagList = PaginatedList & { __typename?: 'TagList'; items: Array<Tag>; totalItems: Scalars['Int']['output']; }; export type TaxCategory = Node & { __typename?: 'TaxCategory'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; isDefault: Scalars['Boolean']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type TaxLine = { __typename?: 'TaxLine'; description: Scalars['String']['output']; taxRate: Scalars['Float']['output']; }; export type TaxRate = Node & { __typename?: 'TaxRate'; category: TaxCategory; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; customerGroup?: Maybe<CustomerGroup>; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; value: Scalars['Float']['output']; zone: Zone; }; export type TaxRateList = PaginatedList & { __typename?: 'TaxRateList'; items: Array<TaxRate>; totalItems: Scalars['Int']['output']; }; export type TextCustomFieldConfig = CustomField & { __typename?: 'TextCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type TransitionOrderToStateResult = Order | OrderStateTransitionError; export type UpdateAddressInput = { city?: InputMaybe<Scalars['String']['input']>; company?: InputMaybe<Scalars['String']['input']>; countryCode?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; defaultBillingAddress?: InputMaybe<Scalars['Boolean']['input']>; defaultShippingAddress?: InputMaybe<Scalars['Boolean']['input']>; fullName?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; phoneNumber?: InputMaybe<Scalars['String']['input']>; postalCode?: InputMaybe<Scalars['String']['input']>; province?: InputMaybe<Scalars['String']['input']>; streetLine1?: InputMaybe<Scalars['String']['input']>; streetLine2?: InputMaybe<Scalars['String']['input']>; }; export type UpdateCustomerEmailAddressResult = IdentifierChangeTokenExpiredError | IdentifierChangeTokenInvalidError | NativeAuthStrategyError | Success; export type UpdateCustomerInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; firstName?: InputMaybe<Scalars['String']['input']>; lastName?: InputMaybe<Scalars['String']['input']>; phoneNumber?: InputMaybe<Scalars['String']['input']>; title?: InputMaybe<Scalars['String']['input']>; }; export type UpdateCustomerPasswordResult = InvalidCredentialsError | NativeAuthStrategyError | PasswordValidationError | Success; export type UpdateOrderInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; }; export type UpdateOrderItemsResult = InsufficientStockError | NegativeQuantityError | Order | OrderLimitError | OrderModificationError; export type User = Node & { __typename?: 'User'; authenticationMethods: Array<AuthenticationMethod>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; identifier: Scalars['String']['output']; lastLogin?: Maybe<Scalars['DateTime']['output']>; roles: Array<Role>; updatedAt: Scalars['DateTime']['output']; verified: Scalars['Boolean']['output']; }; /** * Returned if the verification token (used to verify a Customer's email address) is valid, but has * expired according to the `verificationTokenDuration` setting in the AuthOptions. */ export type VerificationTokenExpiredError = ErrorResult & { __typename?: 'VerificationTokenExpiredError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * Returned if the verification token (used to verify a Customer's email address) is either * invalid or does not match any expected tokens. */ export type VerificationTokenInvalidError = ErrorResult & { __typename?: 'VerificationTokenInvalidError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type VerifyCustomerAccountResult = CurrentUser | MissingPasswordError | NativeAuthStrategyError | PasswordAlreadySetError | PasswordValidationError | VerificationTokenExpiredError | VerificationTokenInvalidError; export type Zone = Node & { __typename?: 'Zone'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; members: Array<Region>; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; };
/* eslint-disable */ export type Maybe<T> = T; export type InputMaybe<T> = T; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; export type MakeEmpty<T extends { [key: string]: unknown }, K extends keyof T> = { [_ in K]?: never }; export type Incremental<T> = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: { input: string | number; output: string | number; } String: { input: string; output: string; } Boolean: { input: boolean; output: boolean; } Int: { input: number; output: number; } Float: { input: number; output: number; } DateTime: { input: any; output: any; } JSON: { input: any; output: any; } Money: { input: number; output: number; } Upload: { input: any; output: any; } }; export type AddFulfillmentToOrderResult = CreateFulfillmentError | EmptyOrderLineSelectionError | Fulfillment | FulfillmentStateTransitionError | InsufficientStockOnHandError | InvalidFulfillmentHandlerError | ItemsAlreadyFulfilledError; export type AddItemInput = { productVariantId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type AddItemToDraftOrderInput = { productVariantId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type AddManualPaymentToOrderResult = ManualPaymentStateError | Order; export type AddNoteToCustomerInput = { id: Scalars['ID']['input']; isPublic: Scalars['Boolean']['input']; note: Scalars['String']['input']; }; export type AddNoteToOrderInput = { id: Scalars['ID']['input']; isPublic: Scalars['Boolean']['input']; note: Scalars['String']['input']; }; export type Address = Node & { __typename?: 'Address'; city?: Maybe<Scalars['String']['output']>; company?: Maybe<Scalars['String']['output']>; country: Country; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; defaultBillingAddress?: Maybe<Scalars['Boolean']['output']>; defaultShippingAddress?: Maybe<Scalars['Boolean']['output']>; fullName?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; phoneNumber?: Maybe<Scalars['String']['output']>; postalCode?: Maybe<Scalars['String']['output']>; province?: Maybe<Scalars['String']['output']>; streetLine1: Scalars['String']['output']; streetLine2?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type AdjustDraftOrderLineInput = { orderLineId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type Adjustment = { __typename?: 'Adjustment'; adjustmentSource: Scalars['String']['output']; amount: Scalars['Money']['output']; data?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; type: AdjustmentType; }; export enum AdjustmentType { DISTRIBUTED_ORDER_PROMOTION = 'DISTRIBUTED_ORDER_PROMOTION', OTHER = 'OTHER', PROMOTION = 'PROMOTION' } export type Administrator = Node & { __typename?: 'Administrator'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; emailAddress: Scalars['String']['output']; firstName: Scalars['String']['output']; id: Scalars['ID']['output']; lastName: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; user: User; }; export type AdministratorFilterParameter = { _and?: InputMaybe<Array<AdministratorFilterParameter>>; _or?: InputMaybe<Array<AdministratorFilterParameter>>; createdAt?: InputMaybe<DateOperators>; emailAddress?: InputMaybe<StringOperators>; firstName?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; lastName?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type AdministratorList = PaginatedList & { __typename?: 'AdministratorList'; items: Array<Administrator>; totalItems: Scalars['Int']['output']; }; export type AdministratorListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<AdministratorFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<AdministratorSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type AdministratorPaymentInput = { metadata?: InputMaybe<Scalars['JSON']['input']>; paymentMethod?: InputMaybe<Scalars['String']['input']>; }; export type AdministratorRefundInput = { /** * The amount to be refunded to this particular Payment. This was introduced in * v2.2.0 as the preferred way to specify the refund amount. The `lines`, `shipping` and `adjustment` * fields will be removed in a future version. */ amount?: InputMaybe<Scalars['Money']['input']>; paymentId: Scalars['ID']['input']; reason?: InputMaybe<Scalars['String']['input']>; }; export type AdministratorSortParameter = { createdAt?: InputMaybe<SortOrder>; emailAddress?: InputMaybe<SortOrder>; firstName?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; lastName?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type Allocation = Node & StockMovement & { __typename?: 'Allocation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; orderLine: OrderLine; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; /** Returned if an attempting to refund an OrderItem which has already been refunded */ export type AlreadyRefundedError = ErrorResult & { __typename?: 'AlreadyRefundedError'; errorCode: ErrorCode; message: Scalars['String']['output']; refundId: Scalars['ID']['output']; }; export type ApplyCouponCodeResult = CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError | Order; export type Asset = Node & { __typename?: 'Asset'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; fileSize: Scalars['Int']['output']; focalPoint?: Maybe<Coordinate>; height: Scalars['Int']['output']; id: Scalars['ID']['output']; mimeType: Scalars['String']['output']; name: Scalars['String']['output']; preview: Scalars['String']['output']; source: Scalars['String']['output']; tags: Array<Tag>; type: AssetType; updatedAt: Scalars['DateTime']['output']; width: Scalars['Int']['output']; }; export type AssetFilterParameter = { _and?: InputMaybe<Array<AssetFilterParameter>>; _or?: InputMaybe<Array<AssetFilterParameter>>; createdAt?: InputMaybe<DateOperators>; fileSize?: InputMaybe<NumberOperators>; height?: InputMaybe<NumberOperators>; id?: InputMaybe<IdOperators>; mimeType?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; preview?: InputMaybe<StringOperators>; source?: InputMaybe<StringOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; width?: InputMaybe<NumberOperators>; }; export type AssetList = PaginatedList & { __typename?: 'AssetList'; items: Array<Asset>; totalItems: Scalars['Int']['output']; }; export type AssetListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<AssetFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<AssetSortParameter>; tags?: InputMaybe<Array<Scalars['String']['input']>>; tagsOperator?: InputMaybe<LogicalOperator>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type AssetSortParameter = { createdAt?: InputMaybe<SortOrder>; fileSize?: InputMaybe<SortOrder>; height?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; mimeType?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; preview?: InputMaybe<SortOrder>; source?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; width?: InputMaybe<SortOrder>; }; export enum AssetType { BINARY = 'BINARY', IMAGE = 'IMAGE', VIDEO = 'VIDEO' } export type AssignAssetsToChannelInput = { assetIds: Array<Scalars['ID']['input']>; channelId: Scalars['ID']['input']; }; export type AssignCollectionsToChannelInput = { channelId: Scalars['ID']['input']; collectionIds: Array<Scalars['ID']['input']>; }; export type AssignFacetsToChannelInput = { channelId: Scalars['ID']['input']; facetIds: Array<Scalars['ID']['input']>; }; export type AssignPaymentMethodsToChannelInput = { channelId: Scalars['ID']['input']; paymentMethodIds: Array<Scalars['ID']['input']>; }; export type AssignProductVariantsToChannelInput = { channelId: Scalars['ID']['input']; priceFactor?: InputMaybe<Scalars['Float']['input']>; productVariantIds: Array<Scalars['ID']['input']>; }; export type AssignProductsToChannelInput = { channelId: Scalars['ID']['input']; priceFactor?: InputMaybe<Scalars['Float']['input']>; productIds: Array<Scalars['ID']['input']>; }; export type AssignPromotionsToChannelInput = { channelId: Scalars['ID']['input']; promotionIds: Array<Scalars['ID']['input']>; }; export type AssignShippingMethodsToChannelInput = { channelId: Scalars['ID']['input']; shippingMethodIds: Array<Scalars['ID']['input']>; }; export type AssignStockLocationsToChannelInput = { channelId: Scalars['ID']['input']; stockLocationIds: Array<Scalars['ID']['input']>; }; export type AuthenticationInput = { native?: InputMaybe<NativeAuthInput>; }; export type AuthenticationMethod = Node & { __typename?: 'AuthenticationMethod'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; strategy: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type AuthenticationResult = CurrentUser | InvalidCredentialsError; export type BooleanCustomFieldConfig = CustomField & { __typename?: 'BooleanCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; /** Operators for filtering on a list of Boolean fields */ export type BooleanListOperators = { inList: Scalars['Boolean']['input']; }; /** Operators for filtering on a Boolean field */ export type BooleanOperators = { eq?: InputMaybe<Scalars['Boolean']['input']>; isNull?: InputMaybe<Scalars['Boolean']['input']>; }; /** Returned if an attempting to cancel lines from an Order which is still active */ export type CancelActiveOrderError = ErrorResult & { __typename?: 'CancelActiveOrderError'; errorCode: ErrorCode; message: Scalars['String']['output']; orderState: Scalars['String']['output']; }; export type CancelOrderInput = { /** Specify whether the shipping charges should also be cancelled. Defaults to false */ cancelShipping?: InputMaybe<Scalars['Boolean']['input']>; /** Optionally specify which OrderLines to cancel. If not provided, all OrderLines will be cancelled */ lines?: InputMaybe<Array<OrderLineInput>>; /** The id of the order to be cancelled */ orderId: Scalars['ID']['input']; reason?: InputMaybe<Scalars['String']['input']>; }; export type CancelOrderResult = CancelActiveOrderError | EmptyOrderLineSelectionError | MultipleOrderError | Order | OrderStateTransitionError | QuantityTooGreatError; /** Returned if the Payment cancellation fails */ export type CancelPaymentError = ErrorResult & { __typename?: 'CancelPaymentError'; errorCode: ErrorCode; message: Scalars['String']['output']; paymentErrorMessage: Scalars['String']['output']; }; export type CancelPaymentResult = CancelPaymentError | Payment | PaymentStateTransitionError; export type Cancellation = Node & StockMovement & { __typename?: 'Cancellation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; orderLine: OrderLine; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type Channel = Node & { __typename?: 'Channel'; availableCurrencyCodes: Array<CurrencyCode>; availableLanguageCodes?: Maybe<Array<LanguageCode>>; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; /** @deprecated Use defaultCurrencyCode instead */ currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; defaultCurrencyCode: CurrencyCode; defaultLanguageCode: LanguageCode; defaultShippingZone?: Maybe<Zone>; defaultTaxZone?: Maybe<Zone>; id: Scalars['ID']['output']; /** Not yet used - will be implemented in a future release. */ outOfStockThreshold?: Maybe<Scalars['Int']['output']>; pricesIncludeTax: Scalars['Boolean']['output']; seller?: Maybe<Seller>; token: Scalars['String']['output']; /** Not yet used - will be implemented in a future release. */ trackInventory?: Maybe<Scalars['Boolean']['output']>; updatedAt: Scalars['DateTime']['output']; }; /** * Returned when the default LanguageCode of a Channel is no longer found in the `availableLanguages` * of the GlobalSettings */ export type ChannelDefaultLanguageError = ErrorResult & { __typename?: 'ChannelDefaultLanguageError'; channelCode: Scalars['String']['output']; errorCode: ErrorCode; language: Scalars['String']['output']; message: Scalars['String']['output']; }; export type ChannelFilterParameter = { _and?: InputMaybe<Array<ChannelFilterParameter>>; _or?: InputMaybe<Array<ChannelFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; currencyCode?: InputMaybe<StringOperators>; defaultCurrencyCode?: InputMaybe<StringOperators>; defaultLanguageCode?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; outOfStockThreshold?: InputMaybe<NumberOperators>; pricesIncludeTax?: InputMaybe<BooleanOperators>; token?: InputMaybe<StringOperators>; trackInventory?: InputMaybe<BooleanOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ChannelList = PaginatedList & { __typename?: 'ChannelList'; items: Array<Channel>; totalItems: Scalars['Int']['output']; }; export type ChannelListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ChannelFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ChannelSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ChannelSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; outOfStockThreshold?: InputMaybe<SortOrder>; token?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type Collection = Node & { __typename?: 'Collection'; assets: Array<Asset>; breadcrumbs: Array<CollectionBreadcrumb>; children?: Maybe<Array<Collection>>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; featuredAsset?: Maybe<Asset>; filters: Array<ConfigurableOperation>; id: Scalars['ID']['output']; inheritFilters: Scalars['Boolean']['output']; isPrivate: Scalars['Boolean']['output']; languageCode?: Maybe<LanguageCode>; name: Scalars['String']['output']; parent?: Maybe<Collection>; parentId: Scalars['ID']['output']; position: Scalars['Int']['output']; productVariants: ProductVariantList; slug: Scalars['String']['output']; translations: Array<CollectionTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type CollectionProductVariantsArgs = { options?: InputMaybe<ProductVariantListOptions>; }; export type CollectionBreadcrumb = { __typename?: 'CollectionBreadcrumb'; id: Scalars['ID']['output']; name: Scalars['String']['output']; slug: Scalars['String']['output']; }; export type CollectionFilterParameter = { _and?: InputMaybe<Array<CollectionFilterParameter>>; _or?: InputMaybe<Array<CollectionFilterParameter>>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; inheritFilters?: InputMaybe<BooleanOperators>; isPrivate?: InputMaybe<BooleanOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; parentId?: InputMaybe<IdOperators>; position?: InputMaybe<NumberOperators>; slug?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type CollectionList = PaginatedList & { __typename?: 'CollectionList'; items: Array<Collection>; totalItems: Scalars['Int']['output']; }; export type CollectionListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<CollectionFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<CollectionSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; topLevelOnly?: InputMaybe<Scalars['Boolean']['input']>; }; /** * Which Collections are present in the products returned * by the search, and in what quantity. */ export type CollectionResult = { __typename?: 'CollectionResult'; collection: Collection; count: Scalars['Int']['output']; }; export type CollectionSortParameter = { createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; parentId?: InputMaybe<SortOrder>; position?: InputMaybe<SortOrder>; slug?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type CollectionTranslation = { __typename?: 'CollectionTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; slug: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ConfigArg = { __typename?: 'ConfigArg'; name: Scalars['String']['output']; value: Scalars['String']['output']; }; export type ConfigArgDefinition = { __typename?: 'ConfigArgDefinition'; defaultValue?: Maybe<Scalars['JSON']['output']>; description?: Maybe<Scalars['String']['output']>; label?: Maybe<Scalars['String']['output']>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; required: Scalars['Boolean']['output']; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type ConfigArgInput = { name: Scalars['String']['input']; /** A JSON stringified representation of the actual value */ value: Scalars['String']['input']; }; export type ConfigurableOperation = { __typename?: 'ConfigurableOperation'; args: Array<ConfigArg>; code: Scalars['String']['output']; }; export type ConfigurableOperationDefinition = { __typename?: 'ConfigurableOperationDefinition'; args: Array<ConfigArgDefinition>; code: Scalars['String']['output']; description: Scalars['String']['output']; }; export type ConfigurableOperationInput = { arguments: Array<ConfigArgInput>; code: Scalars['String']['input']; }; export type Coordinate = { __typename?: 'Coordinate'; x: Scalars['Float']['output']; y: Scalars['Float']['output']; }; export type CoordinateInput = { x: Scalars['Float']['input']; y: Scalars['Float']['input']; }; /** * A Country of the world which your shop operates in. * * The `code` field is typically a 2-character ISO code such as "GB", "US", "DE" etc. This code is used in certain inputs such as * `UpdateAddressInput` and `CreateAddressInput` to specify the country. */ export type Country = Node & Region & { __typename?: 'Country'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; parent?: Maybe<Region>; parentId?: Maybe<Scalars['ID']['output']>; translations: Array<RegionTranslation>; type: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type CountryFilterParameter = { _and?: InputMaybe<Array<CountryFilterParameter>>; _or?: InputMaybe<Array<CountryFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; enabled?: InputMaybe<BooleanOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; parentId?: InputMaybe<IdOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type CountryList = PaginatedList & { __typename?: 'CountryList'; items: Array<Country>; totalItems: Scalars['Int']['output']; }; export type CountryListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<CountryFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<CountrySortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type CountrySortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; parentId?: InputMaybe<SortOrder>; type?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type CountryTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeExpiredError = ErrorResult & { __typename?: 'CouponCodeExpiredError'; couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeInvalidError = ErrorResult & { __typename?: 'CouponCodeInvalidError'; couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeLimitError = ErrorResult & { __typename?: 'CouponCodeLimitError'; couponCode: Scalars['String']['output']; errorCode: ErrorCode; limit: Scalars['Int']['output']; message: Scalars['String']['output']; }; /** * Input used to create an Address. * * The countryCode must correspond to a `code` property of a Country that has been defined in the * Vendure server. The `code` property is typically a 2-character ISO code such as "GB", "US", "DE" etc. * If an invalid code is passed, the mutation will fail. */ export type CreateAddressInput = { city?: InputMaybe<Scalars['String']['input']>; company?: InputMaybe<Scalars['String']['input']>; countryCode: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; defaultBillingAddress?: InputMaybe<Scalars['Boolean']['input']>; defaultShippingAddress?: InputMaybe<Scalars['Boolean']['input']>; fullName?: InputMaybe<Scalars['String']['input']>; phoneNumber?: InputMaybe<Scalars['String']['input']>; postalCode?: InputMaybe<Scalars['String']['input']>; province?: InputMaybe<Scalars['String']['input']>; streetLine1: Scalars['String']['input']; streetLine2?: InputMaybe<Scalars['String']['input']>; }; export type CreateAdministratorInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; emailAddress: Scalars['String']['input']; firstName: Scalars['String']['input']; lastName: Scalars['String']['input']; password: Scalars['String']['input']; roleIds: Array<Scalars['ID']['input']>; }; export type CreateAssetInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; file: Scalars['Upload']['input']; tags?: InputMaybe<Array<Scalars['String']['input']>>; }; export type CreateAssetResult = Asset | MimeTypeError; export type CreateChannelInput = { availableCurrencyCodes?: InputMaybe<Array<CurrencyCode>>; availableLanguageCodes?: InputMaybe<Array<LanguageCode>>; code: Scalars['String']['input']; /** @deprecated Use defaultCurrencyCode instead */ currencyCode?: InputMaybe<CurrencyCode>; customFields?: InputMaybe<Scalars['JSON']['input']>; defaultCurrencyCode?: InputMaybe<CurrencyCode>; defaultLanguageCode: LanguageCode; defaultShippingZoneId: Scalars['ID']['input']; defaultTaxZoneId: Scalars['ID']['input']; outOfStockThreshold?: InputMaybe<Scalars['Int']['input']>; pricesIncludeTax: Scalars['Boolean']['input']; sellerId?: InputMaybe<Scalars['ID']['input']>; token: Scalars['String']['input']; trackInventory?: InputMaybe<Scalars['Boolean']['input']>; }; export type CreateChannelResult = Channel | LanguageNotAvailableError; export type CreateCollectionInput = { assetIds?: InputMaybe<Array<Scalars['ID']['input']>>; customFields?: InputMaybe<Scalars['JSON']['input']>; featuredAssetId?: InputMaybe<Scalars['ID']['input']>; filters: Array<ConfigurableOperationInput>; inheritFilters?: InputMaybe<Scalars['Boolean']['input']>; isPrivate?: InputMaybe<Scalars['Boolean']['input']>; parentId?: InputMaybe<Scalars['ID']['input']>; translations: Array<CreateCollectionTranslationInput>; }; export type CreateCollectionTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description: Scalars['String']['input']; languageCode: LanguageCode; name: Scalars['String']['input']; slug: Scalars['String']['input']; }; export type CreateCountryInput = { code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled: Scalars['Boolean']['input']; translations: Array<CountryTranslationInput>; }; export type CreateCustomerGroupInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; customerIds?: InputMaybe<Array<Scalars['ID']['input']>>; name: Scalars['String']['input']; }; export type CreateCustomerInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; emailAddress: Scalars['String']['input']; firstName: Scalars['String']['input']; lastName: Scalars['String']['input']; phoneNumber?: InputMaybe<Scalars['String']['input']>; title?: InputMaybe<Scalars['String']['input']>; }; export type CreateCustomerResult = Customer | EmailAddressConflictError; export type CreateFacetInput = { code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; isPrivate: Scalars['Boolean']['input']; translations: Array<FacetTranslationInput>; values?: InputMaybe<Array<CreateFacetValueWithFacetInput>>; }; export type CreateFacetValueInput = { code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; facetId: Scalars['ID']['input']; translations: Array<FacetValueTranslationInput>; }; export type CreateFacetValueWithFacetInput = { code: Scalars['String']['input']; translations: Array<FacetValueTranslationInput>; }; /** Returned if an error is thrown in a FulfillmentHandler's createFulfillment method */ export type CreateFulfillmentError = ErrorResult & { __typename?: 'CreateFulfillmentError'; errorCode: ErrorCode; fulfillmentHandlerError: Scalars['String']['output']; message: Scalars['String']['output']; }; export type CreateGroupOptionInput = { code: Scalars['String']['input']; translations: Array<ProductOptionGroupTranslationInput>; }; export type CreatePaymentMethodInput = { checker?: InputMaybe<ConfigurableOperationInput>; code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled: Scalars['Boolean']['input']; handler: ConfigurableOperationInput; translations: Array<PaymentMethodTranslationInput>; }; export type CreateProductInput = { assetIds?: InputMaybe<Array<Scalars['ID']['input']>>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; facetValueIds?: InputMaybe<Array<Scalars['ID']['input']>>; featuredAssetId?: InputMaybe<Scalars['ID']['input']>; translations: Array<ProductTranslationInput>; }; export type CreateProductOptionGroupInput = { code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; options: Array<CreateGroupOptionInput>; translations: Array<ProductOptionGroupTranslationInput>; }; export type CreateProductOptionInput = { code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; productOptionGroupId: Scalars['ID']['input']; translations: Array<ProductOptionGroupTranslationInput>; }; export type CreateProductVariantInput = { assetIds?: InputMaybe<Array<Scalars['ID']['input']>>; customFields?: InputMaybe<Scalars['JSON']['input']>; facetValueIds?: InputMaybe<Array<Scalars['ID']['input']>>; featuredAssetId?: InputMaybe<Scalars['ID']['input']>; optionIds?: InputMaybe<Array<Scalars['ID']['input']>>; outOfStockThreshold?: InputMaybe<Scalars['Int']['input']>; price?: InputMaybe<Scalars['Money']['input']>; productId: Scalars['ID']['input']; sku: Scalars['String']['input']; stockLevels?: InputMaybe<Array<StockLevelInput>>; stockOnHand?: InputMaybe<Scalars['Int']['input']>; taxCategoryId?: InputMaybe<Scalars['ID']['input']>; trackInventory?: InputMaybe<GlobalFlag>; translations: Array<ProductVariantTranslationInput>; useGlobalOutOfStockThreshold?: InputMaybe<Scalars['Boolean']['input']>; }; export type CreateProductVariantOptionInput = { code: Scalars['String']['input']; optionGroupId: Scalars['ID']['input']; translations: Array<ProductOptionTranslationInput>; }; export type CreatePromotionInput = { actions: Array<ConfigurableOperationInput>; conditions: Array<ConfigurableOperationInput>; couponCode?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled: Scalars['Boolean']['input']; endsAt?: InputMaybe<Scalars['DateTime']['input']>; perCustomerUsageLimit?: InputMaybe<Scalars['Int']['input']>; startsAt?: InputMaybe<Scalars['DateTime']['input']>; translations: Array<PromotionTranslationInput>; usageLimit?: InputMaybe<Scalars['Int']['input']>; }; export type CreatePromotionResult = MissingConditionsError | Promotion; export type CreateProvinceInput = { code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled: Scalars['Boolean']['input']; translations: Array<ProvinceTranslationInput>; }; export type CreateRoleInput = { channelIds?: InputMaybe<Array<Scalars['ID']['input']>>; code: Scalars['String']['input']; description: Scalars['String']['input']; permissions: Array<Permission>; }; export type CreateSellerInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; name: Scalars['String']['input']; }; export type CreateShippingMethodInput = { calculator: ConfigurableOperationInput; checker: ConfigurableOperationInput; code: Scalars['String']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; fulfillmentHandler: Scalars['String']['input']; translations: Array<ShippingMethodTranslationInput>; }; export type CreateStockLocationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; name: Scalars['String']['input']; }; export type CreateTagInput = { value: Scalars['String']['input']; }; export type CreateTaxCategoryInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; isDefault?: InputMaybe<Scalars['Boolean']['input']>; name: Scalars['String']['input']; }; export type CreateTaxRateInput = { categoryId: Scalars['ID']['input']; customFields?: InputMaybe<Scalars['JSON']['input']>; customerGroupId?: InputMaybe<Scalars['ID']['input']>; enabled: Scalars['Boolean']['input']; name: Scalars['String']['input']; value: Scalars['Float']['input']; zoneId: Scalars['ID']['input']; }; export type CreateZoneInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; memberIds?: InputMaybe<Array<Scalars['ID']['input']>>; name: Scalars['String']['input']; }; /** * @description * ISO 4217 currency code * * @docsCategory common */ export enum CurrencyCode { /** United Arab Emirates dirham */ AED = 'AED', /** Afghan afghani */ AFN = 'AFN', /** Albanian lek */ ALL = 'ALL', /** Armenian dram */ AMD = 'AMD', /** Netherlands Antillean guilder */ ANG = 'ANG', /** Angolan kwanza */ AOA = 'AOA', /** Argentine peso */ ARS = 'ARS', /** Australian dollar */ AUD = 'AUD', /** Aruban florin */ AWG = 'AWG', /** Azerbaijani manat */ AZN = 'AZN', /** Bosnia and Herzegovina convertible mark */ BAM = 'BAM', /** Barbados dollar */ BBD = 'BBD', /** Bangladeshi taka */ BDT = 'BDT', /** Bulgarian lev */ BGN = 'BGN', /** Bahraini dinar */ BHD = 'BHD', /** Burundian franc */ BIF = 'BIF', /** Bermudian dollar */ BMD = 'BMD', /** Brunei dollar */ BND = 'BND', /** Boliviano */ BOB = 'BOB', /** Brazilian real */ BRL = 'BRL', /** Bahamian dollar */ BSD = 'BSD', /** Bhutanese ngultrum */ BTN = 'BTN', /** Botswana pula */ BWP = 'BWP', /** Belarusian ruble */ BYN = 'BYN', /** Belize dollar */ BZD = 'BZD', /** Canadian dollar */ CAD = 'CAD', /** Congolese franc */ CDF = 'CDF', /** Swiss franc */ CHF = 'CHF', /** Chilean peso */ CLP = 'CLP', /** Renminbi (Chinese) yuan */ CNY = 'CNY', /** Colombian peso */ COP = 'COP', /** Costa Rican colon */ CRC = 'CRC', /** Cuban convertible peso */ CUC = 'CUC', /** Cuban peso */ CUP = 'CUP', /** Cape Verde escudo */ CVE = 'CVE', /** Czech koruna */ CZK = 'CZK', /** Djiboutian franc */ DJF = 'DJF', /** Danish krone */ DKK = 'DKK', /** Dominican peso */ DOP = 'DOP', /** Algerian dinar */ DZD = 'DZD', /** Egyptian pound */ EGP = 'EGP', /** Eritrean nakfa */ ERN = 'ERN', /** Ethiopian birr */ ETB = 'ETB', /** Euro */ EUR = 'EUR', /** Fiji dollar */ FJD = 'FJD', /** Falkland Islands pound */ FKP = 'FKP', /** Pound sterling */ GBP = 'GBP', /** Georgian lari */ GEL = 'GEL', /** Ghanaian cedi */ GHS = 'GHS', /** Gibraltar pound */ GIP = 'GIP', /** Gambian dalasi */ GMD = 'GMD', /** Guinean franc */ GNF = 'GNF', /** Guatemalan quetzal */ GTQ = 'GTQ', /** Guyanese dollar */ GYD = 'GYD', /** Hong Kong dollar */ HKD = 'HKD', /** Honduran lempira */ HNL = 'HNL', /** Croatian kuna */ HRK = 'HRK', /** Haitian gourde */ HTG = 'HTG', /** Hungarian forint */ HUF = 'HUF', /** Indonesian rupiah */ IDR = 'IDR', /** Israeli new shekel */ ILS = 'ILS', /** Indian rupee */ INR = 'INR', /** Iraqi dinar */ IQD = 'IQD', /** Iranian rial */ IRR = 'IRR', /** Icelandic króna */ ISK = 'ISK', /** Jamaican dollar */ JMD = 'JMD', /** Jordanian dinar */ JOD = 'JOD', /** Japanese yen */ JPY = 'JPY', /** Kenyan shilling */ KES = 'KES', /** Kyrgyzstani som */ KGS = 'KGS', /** Cambodian riel */ KHR = 'KHR', /** Comoro franc */ KMF = 'KMF', /** North Korean won */ KPW = 'KPW', /** South Korean won */ KRW = 'KRW', /** Kuwaiti dinar */ KWD = 'KWD', /** Cayman Islands dollar */ KYD = 'KYD', /** Kazakhstani tenge */ KZT = 'KZT', /** Lao kip */ LAK = 'LAK', /** Lebanese pound */ LBP = 'LBP', /** Sri Lankan rupee */ LKR = 'LKR', /** Liberian dollar */ LRD = 'LRD', /** Lesotho loti */ LSL = 'LSL', /** Libyan dinar */ LYD = 'LYD', /** Moroccan dirham */ MAD = 'MAD', /** Moldovan leu */ MDL = 'MDL', /** Malagasy ariary */ MGA = 'MGA', /** Macedonian denar */ MKD = 'MKD', /** Myanmar kyat */ MMK = 'MMK', /** Mongolian tögrög */ MNT = 'MNT', /** Macanese pataca */ MOP = 'MOP', /** Mauritanian ouguiya */ MRU = 'MRU', /** Mauritian rupee */ MUR = 'MUR', /** Maldivian rufiyaa */ MVR = 'MVR', /** Malawian kwacha */ MWK = 'MWK', /** Mexican peso */ MXN = 'MXN', /** Malaysian ringgit */ MYR = 'MYR', /** Mozambican metical */ MZN = 'MZN', /** Namibian dollar */ NAD = 'NAD', /** Nigerian naira */ NGN = 'NGN', /** Nicaraguan córdoba */ NIO = 'NIO', /** Norwegian krone */ NOK = 'NOK', /** Nepalese rupee */ NPR = 'NPR', /** New Zealand dollar */ NZD = 'NZD', /** Omani rial */ OMR = 'OMR', /** Panamanian balboa */ PAB = 'PAB', /** Peruvian sol */ PEN = 'PEN', /** Papua New Guinean kina */ PGK = 'PGK', /** Philippine peso */ PHP = 'PHP', /** Pakistani rupee */ PKR = 'PKR', /** Polish złoty */ PLN = 'PLN', /** Paraguayan guaraní */ PYG = 'PYG', /** Qatari riyal */ QAR = 'QAR', /** Romanian leu */ RON = 'RON', /** Serbian dinar */ RSD = 'RSD', /** Russian ruble */ RUB = 'RUB', /** Rwandan franc */ RWF = 'RWF', /** Saudi riyal */ SAR = 'SAR', /** Solomon Islands dollar */ SBD = 'SBD', /** Seychelles rupee */ SCR = 'SCR', /** Sudanese pound */ SDG = 'SDG', /** Swedish krona/kronor */ SEK = 'SEK', /** Singapore dollar */ SGD = 'SGD', /** Saint Helena pound */ SHP = 'SHP', /** Sierra Leonean leone */ SLL = 'SLL', /** Somali shilling */ SOS = 'SOS', /** Surinamese dollar */ SRD = 'SRD', /** South Sudanese pound */ SSP = 'SSP', /** São Tomé and Príncipe dobra */ STN = 'STN', /** Salvadoran colón */ SVC = 'SVC', /** Syrian pound */ SYP = 'SYP', /** Swazi lilangeni */ SZL = 'SZL', /** Thai baht */ THB = 'THB', /** Tajikistani somoni */ TJS = 'TJS', /** Turkmenistan manat */ TMT = 'TMT', /** Tunisian dinar */ TND = 'TND', /** Tongan paʻanga */ TOP = 'TOP', /** Turkish lira */ TRY = 'TRY', /** Trinidad and Tobago dollar */ TTD = 'TTD', /** New Taiwan dollar */ TWD = 'TWD', /** Tanzanian shilling */ TZS = 'TZS', /** Ukrainian hryvnia */ UAH = 'UAH', /** Ugandan shilling */ UGX = 'UGX', /** United States dollar */ USD = 'USD', /** Uruguayan peso */ UYU = 'UYU', /** Uzbekistan som */ UZS = 'UZS', /** Venezuelan bolívar soberano */ VES = 'VES', /** Vietnamese đồng */ VND = 'VND', /** Vanuatu vatu */ VUV = 'VUV', /** Samoan tala */ WST = 'WST', /** CFA franc BEAC */ XAF = 'XAF', /** East Caribbean dollar */ XCD = 'XCD', /** CFA franc BCEAO */ XOF = 'XOF', /** CFP franc (franc Pacifique) */ XPF = 'XPF', /** Yemeni rial */ YER = 'YER', /** South African rand */ ZAR = 'ZAR', /** Zambian kwacha */ ZMW = 'ZMW', /** Zimbabwean dollar */ ZWL = 'ZWL' } export type CurrentUser = { __typename?: 'CurrentUser'; channels: Array<CurrentUserChannel>; id: Scalars['ID']['output']; identifier: Scalars['String']['output']; }; export type CurrentUserChannel = { __typename?: 'CurrentUserChannel'; code: Scalars['String']['output']; id: Scalars['ID']['output']; permissions: Array<Permission>; token: Scalars['String']['output']; }; export type CustomField = { description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type CustomFieldConfig = BooleanCustomFieldConfig | DateTimeCustomFieldConfig | FloatCustomFieldConfig | IntCustomFieldConfig | LocaleStringCustomFieldConfig | LocaleTextCustomFieldConfig | RelationCustomFieldConfig | StringCustomFieldConfig | TextCustomFieldConfig; /** * This type is deprecated in v2.2 in favor of the EntityCustomFields type, * which allows custom fields to be defined on user-supplies entities. */ export type CustomFields = { __typename?: 'CustomFields'; Address: Array<CustomFieldConfig>; Administrator: Array<CustomFieldConfig>; Asset: Array<CustomFieldConfig>; Channel: Array<CustomFieldConfig>; Collection: Array<CustomFieldConfig>; Customer: Array<CustomFieldConfig>; CustomerGroup: Array<CustomFieldConfig>; Facet: Array<CustomFieldConfig>; FacetValue: Array<CustomFieldConfig>; Fulfillment: Array<CustomFieldConfig>; GlobalSettings: Array<CustomFieldConfig>; Order: Array<CustomFieldConfig>; OrderLine: Array<CustomFieldConfig>; PaymentMethod: Array<CustomFieldConfig>; Product: Array<CustomFieldConfig>; ProductOption: Array<CustomFieldConfig>; ProductOptionGroup: Array<CustomFieldConfig>; ProductVariant: Array<CustomFieldConfig>; ProductVariantPrice: Array<CustomFieldConfig>; Promotion: Array<CustomFieldConfig>; Region: Array<CustomFieldConfig>; Seller: Array<CustomFieldConfig>; ShippingMethod: Array<CustomFieldConfig>; StockLocation: Array<CustomFieldConfig>; TaxCategory: Array<CustomFieldConfig>; TaxRate: Array<CustomFieldConfig>; User: Array<CustomFieldConfig>; Zone: Array<CustomFieldConfig>; }; export type Customer = Node & { __typename?: 'Customer'; addresses?: Maybe<Array<Address>>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; emailAddress: Scalars['String']['output']; firstName: Scalars['String']['output']; groups: Array<CustomerGroup>; history: HistoryEntryList; id: Scalars['ID']['output']; lastName: Scalars['String']['output']; orders: OrderList; phoneNumber?: Maybe<Scalars['String']['output']>; title?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; user?: Maybe<User>; }; export type CustomerHistoryArgs = { options?: InputMaybe<HistoryEntryListOptions>; }; export type CustomerOrdersArgs = { options?: InputMaybe<OrderListOptions>; }; export type CustomerFilterParameter = { _and?: InputMaybe<Array<CustomerFilterParameter>>; _or?: InputMaybe<Array<CustomerFilterParameter>>; createdAt?: InputMaybe<DateOperators>; emailAddress?: InputMaybe<StringOperators>; firstName?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; lastName?: InputMaybe<StringOperators>; phoneNumber?: InputMaybe<StringOperators>; postalCode?: InputMaybe<StringOperators>; title?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type CustomerGroup = Node & { __typename?: 'CustomerGroup'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; customers: CustomerList; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type CustomerGroupCustomersArgs = { options?: InputMaybe<CustomerListOptions>; }; export type CustomerGroupFilterParameter = { _and?: InputMaybe<Array<CustomerGroupFilterParameter>>; _or?: InputMaybe<Array<CustomerGroupFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type CustomerGroupList = PaginatedList & { __typename?: 'CustomerGroupList'; items: Array<CustomerGroup>; totalItems: Scalars['Int']['output']; }; export type CustomerGroupListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<CustomerGroupFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<CustomerGroupSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type CustomerGroupSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type CustomerList = PaginatedList & { __typename?: 'CustomerList'; items: Array<Customer>; totalItems: Scalars['Int']['output']; }; export type CustomerListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<CustomerFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<CustomerSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type CustomerSortParameter = { createdAt?: InputMaybe<SortOrder>; emailAddress?: InputMaybe<SortOrder>; firstName?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; lastName?: InputMaybe<SortOrder>; phoneNumber?: InputMaybe<SortOrder>; title?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; /** Operators for filtering on a list of Date fields */ export type DateListOperators = { inList: Scalars['DateTime']['input']; }; /** Operators for filtering on a DateTime field */ export type DateOperators = { after?: InputMaybe<Scalars['DateTime']['input']>; before?: InputMaybe<Scalars['DateTime']['input']>; between?: InputMaybe<DateRange>; eq?: InputMaybe<Scalars['DateTime']['input']>; isNull?: InputMaybe<Scalars['Boolean']['input']>; }; export type DateRange = { end: Scalars['DateTime']['input']; start: Scalars['DateTime']['input']; }; /** * Expects the same validation formats as the `<input type="datetime-local">` HTML element. * See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local#Additional_attributes */ export type DateTimeCustomFieldConfig = CustomField & { __typename?: 'DateTimeCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; max?: Maybe<Scalars['String']['output']>; min?: Maybe<Scalars['String']['output']>; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; step?: Maybe<Scalars['Int']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type DeleteAssetInput = { assetId: Scalars['ID']['input']; deleteFromAllChannels?: InputMaybe<Scalars['Boolean']['input']>; force?: InputMaybe<Scalars['Boolean']['input']>; }; export type DeleteAssetsInput = { assetIds: Array<Scalars['ID']['input']>; deleteFromAllChannels?: InputMaybe<Scalars['Boolean']['input']>; force?: InputMaybe<Scalars['Boolean']['input']>; }; export type DeleteStockLocationInput = { id: Scalars['ID']['input']; transferToLocationId?: InputMaybe<Scalars['ID']['input']>; }; export type DeletionResponse = { __typename?: 'DeletionResponse'; message?: Maybe<Scalars['String']['output']>; result: DeletionResult; }; export enum DeletionResult { /** The entity was successfully deleted */ DELETED = 'DELETED', /** Deletion did not take place, reason given in message */ NOT_DELETED = 'NOT_DELETED' } export type Discount = { __typename?: 'Discount'; adjustmentSource: Scalars['String']['output']; amount: Scalars['Money']['output']; amountWithTax: Scalars['Money']['output']; description: Scalars['String']['output']; type: AdjustmentType; }; export type DuplicateEntityError = ErrorResult & { __typename?: 'DuplicateEntityError'; duplicationError: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type DuplicateEntityInput = { duplicatorInput: ConfigurableOperationInput; entityId: Scalars['ID']['input']; entityName: Scalars['String']['input']; }; export type DuplicateEntityResult = DuplicateEntityError | DuplicateEntitySuccess; export type DuplicateEntitySuccess = { __typename?: 'DuplicateEntitySuccess'; newEntityId: Scalars['ID']['output']; }; /** Returned when attempting to create a Customer with an email address already registered to an existing User. */ export type EmailAddressConflictError = ErrorResult & { __typename?: 'EmailAddressConflictError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if no OrderLines have been specified for the operation */ export type EmptyOrderLineSelectionError = ErrorResult & { __typename?: 'EmptyOrderLineSelectionError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type EntityCustomFields = { __typename?: 'EntityCustomFields'; customFields: Array<CustomFieldConfig>; entityName: Scalars['String']['output']; }; export type EntityDuplicatorDefinition = { __typename?: 'EntityDuplicatorDefinition'; args: Array<ConfigArgDefinition>; code: Scalars['String']['output']; description: Scalars['String']['output']; forEntities: Array<Scalars['String']['output']>; requiresPermission: Array<Permission>; }; export enum ErrorCode { ALREADY_REFUNDED_ERROR = 'ALREADY_REFUNDED_ERROR', CANCEL_ACTIVE_ORDER_ERROR = 'CANCEL_ACTIVE_ORDER_ERROR', CANCEL_PAYMENT_ERROR = 'CANCEL_PAYMENT_ERROR', CHANNEL_DEFAULT_LANGUAGE_ERROR = 'CHANNEL_DEFAULT_LANGUAGE_ERROR', COUPON_CODE_EXPIRED_ERROR = 'COUPON_CODE_EXPIRED_ERROR', COUPON_CODE_INVALID_ERROR = 'COUPON_CODE_INVALID_ERROR', COUPON_CODE_LIMIT_ERROR = 'COUPON_CODE_LIMIT_ERROR', CREATE_FULFILLMENT_ERROR = 'CREATE_FULFILLMENT_ERROR', DUPLICATE_ENTITY_ERROR = 'DUPLICATE_ENTITY_ERROR', EMAIL_ADDRESS_CONFLICT_ERROR = 'EMAIL_ADDRESS_CONFLICT_ERROR', EMPTY_ORDER_LINE_SELECTION_ERROR = 'EMPTY_ORDER_LINE_SELECTION_ERROR', FACET_IN_USE_ERROR = 'FACET_IN_USE_ERROR', FULFILLMENT_STATE_TRANSITION_ERROR = 'FULFILLMENT_STATE_TRANSITION_ERROR', GUEST_CHECKOUT_ERROR = 'GUEST_CHECKOUT_ERROR', INELIGIBLE_SHIPPING_METHOD_ERROR = 'INELIGIBLE_SHIPPING_METHOD_ERROR', INSUFFICIENT_STOCK_ERROR = 'INSUFFICIENT_STOCK_ERROR', INSUFFICIENT_STOCK_ON_HAND_ERROR = 'INSUFFICIENT_STOCK_ON_HAND_ERROR', INVALID_CREDENTIALS_ERROR = 'INVALID_CREDENTIALS_ERROR', INVALID_FULFILLMENT_HANDLER_ERROR = 'INVALID_FULFILLMENT_HANDLER_ERROR', ITEMS_ALREADY_FULFILLED_ERROR = 'ITEMS_ALREADY_FULFILLED_ERROR', LANGUAGE_NOT_AVAILABLE_ERROR = 'LANGUAGE_NOT_AVAILABLE_ERROR', MANUAL_PAYMENT_STATE_ERROR = 'MANUAL_PAYMENT_STATE_ERROR', MIME_TYPE_ERROR = 'MIME_TYPE_ERROR', MISSING_CONDITIONS_ERROR = 'MISSING_CONDITIONS_ERROR', MULTIPLE_ORDER_ERROR = 'MULTIPLE_ORDER_ERROR', NATIVE_AUTH_STRATEGY_ERROR = 'NATIVE_AUTH_STRATEGY_ERROR', NEGATIVE_QUANTITY_ERROR = 'NEGATIVE_QUANTITY_ERROR', NOTHING_TO_REFUND_ERROR = 'NOTHING_TO_REFUND_ERROR', NO_ACTIVE_ORDER_ERROR = 'NO_ACTIVE_ORDER_ERROR', NO_CHANGES_SPECIFIED_ERROR = 'NO_CHANGES_SPECIFIED_ERROR', ORDER_LIMIT_ERROR = 'ORDER_LIMIT_ERROR', ORDER_MODIFICATION_ERROR = 'ORDER_MODIFICATION_ERROR', ORDER_MODIFICATION_STATE_ERROR = 'ORDER_MODIFICATION_STATE_ERROR', ORDER_STATE_TRANSITION_ERROR = 'ORDER_STATE_TRANSITION_ERROR', PAYMENT_METHOD_MISSING_ERROR = 'PAYMENT_METHOD_MISSING_ERROR', PAYMENT_ORDER_MISMATCH_ERROR = 'PAYMENT_ORDER_MISMATCH_ERROR', PAYMENT_STATE_TRANSITION_ERROR = 'PAYMENT_STATE_TRANSITION_ERROR', PRODUCT_OPTION_IN_USE_ERROR = 'PRODUCT_OPTION_IN_USE_ERROR', QUANTITY_TOO_GREAT_ERROR = 'QUANTITY_TOO_GREAT_ERROR', REFUND_AMOUNT_ERROR = 'REFUND_AMOUNT_ERROR', REFUND_ORDER_STATE_ERROR = 'REFUND_ORDER_STATE_ERROR', REFUND_PAYMENT_ID_MISSING_ERROR = 'REFUND_PAYMENT_ID_MISSING_ERROR', REFUND_STATE_TRANSITION_ERROR = 'REFUND_STATE_TRANSITION_ERROR', SETTLE_PAYMENT_ERROR = 'SETTLE_PAYMENT_ERROR', UNKNOWN_ERROR = 'UNKNOWN_ERROR' } export type ErrorResult = { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Facet = Node & { __typename?: 'Facet'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; isPrivate: Scalars['Boolean']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<FacetTranslation>; updatedAt: Scalars['DateTime']['output']; /** Returns a paginated, sortable, filterable list of the Facet's values. Added in v2.1.0. */ valueList: FacetValueList; values: Array<FacetValue>; }; export type FacetValueListArgs = { options?: InputMaybe<FacetValueListOptions>; }; export type FacetFilterParameter = { _and?: InputMaybe<Array<FacetFilterParameter>>; _or?: InputMaybe<Array<FacetFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; isPrivate?: InputMaybe<BooleanOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type FacetInUseError = ErrorResult & { __typename?: 'FacetInUseError'; errorCode: ErrorCode; facetCode: Scalars['String']['output']; message: Scalars['String']['output']; productCount: Scalars['Int']['output']; variantCount: Scalars['Int']['output']; }; export type FacetList = PaginatedList & { __typename?: 'FacetList'; items: Array<Facet>; totalItems: Scalars['Int']['output']; }; export type FacetListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<FacetFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<FacetSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type FacetSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type FacetTranslation = { __typename?: 'FacetTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type FacetTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; export type FacetValue = Node & { __typename?: 'FacetValue'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; facet: Facet; facetId: Scalars['ID']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<FacetValueTranslation>; updatedAt: Scalars['DateTime']['output']; }; /** * Used to construct boolean expressions for filtering search results * by FacetValue ID. Examples: * * * ID=1 OR ID=2: `{ facetValueFilters: [{ or: [1,2] }] }` * * ID=1 AND ID=2: `{ facetValueFilters: [{ and: 1 }, { and: 2 }] }` * * ID=1 AND (ID=2 OR ID=3): `{ facetValueFilters: [{ and: 1 }, { or: [2,3] }] }` */ export type FacetValueFilterInput = { and?: InputMaybe<Scalars['ID']['input']>; or?: InputMaybe<Array<Scalars['ID']['input']>>; }; export type FacetValueFilterParameter = { _and?: InputMaybe<Array<FacetValueFilterParameter>>; _or?: InputMaybe<Array<FacetValueFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; facetId?: InputMaybe<IdOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type FacetValueList = PaginatedList & { __typename?: 'FacetValueList'; items: Array<FacetValue>; totalItems: Scalars['Int']['output']; }; export type FacetValueListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<FacetValueFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<FacetValueSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; /** * Which FacetValues are present in the products returned * by the search, and in what quantity. */ export type FacetValueResult = { __typename?: 'FacetValueResult'; count: Scalars['Int']['output']; facetValue: FacetValue; }; export type FacetValueSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; facetId?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type FacetValueTranslation = { __typename?: 'FacetValueTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type FacetValueTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; export type FloatCustomFieldConfig = CustomField & { __typename?: 'FloatCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; max?: Maybe<Scalars['Float']['output']>; min?: Maybe<Scalars['Float']['output']>; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; step?: Maybe<Scalars['Float']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type FulfillOrderInput = { handler: ConfigurableOperationInput; lines: Array<OrderLineInput>; }; export type Fulfillment = Node & { __typename?: 'Fulfillment'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; lines: Array<FulfillmentLine>; method: Scalars['String']['output']; nextStates: Array<Scalars['String']['output']>; state: Scalars['String']['output']; /** @deprecated Use the `lines` field instead */ summary: Array<FulfillmentLine>; trackingCode?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type FulfillmentLine = { __typename?: 'FulfillmentLine'; fulfillment: Fulfillment; fulfillmentId: Scalars['ID']['output']; orderLine: OrderLine; orderLineId: Scalars['ID']['output']; quantity: Scalars['Int']['output']; }; /** Returned when there is an error in transitioning the Fulfillment state */ export type FulfillmentStateTransitionError = ErrorResult & { __typename?: 'FulfillmentStateTransitionError'; errorCode: ErrorCode; fromState: Scalars['String']['output']; message: Scalars['String']['output']; toState: Scalars['String']['output']; transitionError: Scalars['String']['output']; }; export enum GlobalFlag { FALSE = 'FALSE', INHERIT = 'INHERIT', TRUE = 'TRUE' } export type GlobalSettings = { __typename?: 'GlobalSettings'; availableLanguages: Array<LanguageCode>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; outOfStockThreshold: Scalars['Int']['output']; serverConfig: ServerConfig; trackInventory: Scalars['Boolean']['output']; updatedAt: Scalars['DateTime']['output']; }; /** Returned when attempting to set the Customer on a guest checkout when the configured GuestCheckoutStrategy does not allow it. */ export type GuestCheckoutError = ErrorResult & { __typename?: 'GuestCheckoutError'; errorCode: ErrorCode; errorDetail: Scalars['String']['output']; message: Scalars['String']['output']; }; export type HistoryEntry = Node & { __typename?: 'HistoryEntry'; administrator?: Maybe<Administrator>; createdAt: Scalars['DateTime']['output']; data: Scalars['JSON']['output']; id: Scalars['ID']['output']; isPublic: Scalars['Boolean']['output']; type: HistoryEntryType; updatedAt: Scalars['DateTime']['output']; }; export type HistoryEntryFilterParameter = { _and?: InputMaybe<Array<HistoryEntryFilterParameter>>; _or?: InputMaybe<Array<HistoryEntryFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; isPublic?: InputMaybe<BooleanOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type HistoryEntryList = PaginatedList & { __typename?: 'HistoryEntryList'; items: Array<HistoryEntry>; totalItems: Scalars['Int']['output']; }; export type HistoryEntryListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<HistoryEntryFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<HistoryEntrySortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type HistoryEntrySortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export enum HistoryEntryType { CUSTOMER_ADDED_TO_GROUP = 'CUSTOMER_ADDED_TO_GROUP', CUSTOMER_ADDRESS_CREATED = 'CUSTOMER_ADDRESS_CREATED', CUSTOMER_ADDRESS_DELETED = 'CUSTOMER_ADDRESS_DELETED', CUSTOMER_ADDRESS_UPDATED = 'CUSTOMER_ADDRESS_UPDATED', CUSTOMER_DETAIL_UPDATED = 'CUSTOMER_DETAIL_UPDATED', CUSTOMER_EMAIL_UPDATE_REQUESTED = 'CUSTOMER_EMAIL_UPDATE_REQUESTED', CUSTOMER_EMAIL_UPDATE_VERIFIED = 'CUSTOMER_EMAIL_UPDATE_VERIFIED', CUSTOMER_NOTE = 'CUSTOMER_NOTE', CUSTOMER_PASSWORD_RESET_REQUESTED = 'CUSTOMER_PASSWORD_RESET_REQUESTED', CUSTOMER_PASSWORD_RESET_VERIFIED = 'CUSTOMER_PASSWORD_RESET_VERIFIED', CUSTOMER_PASSWORD_UPDATED = 'CUSTOMER_PASSWORD_UPDATED', CUSTOMER_REGISTERED = 'CUSTOMER_REGISTERED', CUSTOMER_REMOVED_FROM_GROUP = 'CUSTOMER_REMOVED_FROM_GROUP', CUSTOMER_VERIFIED = 'CUSTOMER_VERIFIED', ORDER_CANCELLATION = 'ORDER_CANCELLATION', ORDER_COUPON_APPLIED = 'ORDER_COUPON_APPLIED', ORDER_COUPON_REMOVED = 'ORDER_COUPON_REMOVED', ORDER_CUSTOMER_UPDATED = 'ORDER_CUSTOMER_UPDATED', ORDER_FULFILLMENT = 'ORDER_FULFILLMENT', ORDER_FULFILLMENT_TRANSITION = 'ORDER_FULFILLMENT_TRANSITION', ORDER_MODIFIED = 'ORDER_MODIFIED', ORDER_NOTE = 'ORDER_NOTE', ORDER_PAYMENT_TRANSITION = 'ORDER_PAYMENT_TRANSITION', ORDER_REFUND_TRANSITION = 'ORDER_REFUND_TRANSITION', ORDER_STATE_TRANSITION = 'ORDER_STATE_TRANSITION' } /** Operators for filtering on a list of ID fields */ export type IdListOperators = { inList: Scalars['ID']['input']; }; /** Operators for filtering on an ID field */ export type IdOperators = { eq?: InputMaybe<Scalars['String']['input']>; in?: InputMaybe<Array<Scalars['String']['input']>>; isNull?: InputMaybe<Scalars['Boolean']['input']>; notEq?: InputMaybe<Scalars['String']['input']>; notIn?: InputMaybe<Array<Scalars['String']['input']>>; }; export type ImportInfo = { __typename?: 'ImportInfo'; errors?: Maybe<Array<Scalars['String']['output']>>; imported: Scalars['Int']['output']; processed: Scalars['Int']['output']; }; /** Returned when attempting to set a ShippingMethod for which the Order is not eligible */ export type IneligibleShippingMethodError = ErrorResult & { __typename?: 'IneligibleShippingMethodError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to add more items to the Order than are available */ export type InsufficientStockError = ErrorResult & { __typename?: 'InsufficientStockError'; errorCode: ErrorCode; message: Scalars['String']['output']; order: Order; quantityAvailable: Scalars['Int']['output']; }; /** * Returned if attempting to create a Fulfillment when there is insufficient * stockOnHand of a ProductVariant to satisfy the requested quantity. */ export type InsufficientStockOnHandError = ErrorResult & { __typename?: 'InsufficientStockOnHandError'; errorCode: ErrorCode; message: Scalars['String']['output']; productVariantId: Scalars['ID']['output']; productVariantName: Scalars['String']['output']; stockOnHand: Scalars['Int']['output']; }; export type IntCustomFieldConfig = CustomField & { __typename?: 'IntCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; max?: Maybe<Scalars['Int']['output']>; min?: Maybe<Scalars['Int']['output']>; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; step?: Maybe<Scalars['Int']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; /** Returned if the user authentication credentials are not valid */ export type InvalidCredentialsError = ErrorResult & { __typename?: 'InvalidCredentialsError'; authenticationError: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the specified FulfillmentHandler code is not valid */ export type InvalidFulfillmentHandlerError = ErrorResult & { __typename?: 'InvalidFulfillmentHandlerError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the specified items are already part of a Fulfillment */ export type ItemsAlreadyFulfilledError = ErrorResult & { __typename?: 'ItemsAlreadyFulfilledError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Job = Node & { __typename?: 'Job'; attempts: Scalars['Int']['output']; createdAt: Scalars['DateTime']['output']; data?: Maybe<Scalars['JSON']['output']>; duration: Scalars['Int']['output']; error?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; isSettled: Scalars['Boolean']['output']; progress: Scalars['Float']['output']; queueName: Scalars['String']['output']; result?: Maybe<Scalars['JSON']['output']>; retries: Scalars['Int']['output']; settledAt?: Maybe<Scalars['DateTime']['output']>; startedAt?: Maybe<Scalars['DateTime']['output']>; state: JobState; }; export type JobBufferSize = { __typename?: 'JobBufferSize'; bufferId: Scalars['String']['output']; size: Scalars['Int']['output']; }; export type JobFilterParameter = { _and?: InputMaybe<Array<JobFilterParameter>>; _or?: InputMaybe<Array<JobFilterParameter>>; attempts?: InputMaybe<NumberOperators>; createdAt?: InputMaybe<DateOperators>; duration?: InputMaybe<NumberOperators>; id?: InputMaybe<IdOperators>; isSettled?: InputMaybe<BooleanOperators>; progress?: InputMaybe<NumberOperators>; queueName?: InputMaybe<StringOperators>; retries?: InputMaybe<NumberOperators>; settledAt?: InputMaybe<DateOperators>; startedAt?: InputMaybe<DateOperators>; state?: InputMaybe<StringOperators>; }; export type JobList = PaginatedList & { __typename?: 'JobList'; items: Array<Job>; totalItems: Scalars['Int']['output']; }; export type JobListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<JobFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<JobSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type JobQueue = { __typename?: 'JobQueue'; name: Scalars['String']['output']; running: Scalars['Boolean']['output']; }; export type JobSortParameter = { attempts?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; duration?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; progress?: InputMaybe<SortOrder>; queueName?: InputMaybe<SortOrder>; retries?: InputMaybe<SortOrder>; settledAt?: InputMaybe<SortOrder>; startedAt?: InputMaybe<SortOrder>; }; /** * @description * The state of a Job in the JobQueue * * @docsCategory common */ export enum JobState { CANCELLED = 'CANCELLED', COMPLETED = 'COMPLETED', FAILED = 'FAILED', PENDING = 'PENDING', RETRYING = 'RETRYING', RUNNING = 'RUNNING' } /** * @description * Languages in the form of a ISO 639-1 language code with optional * region or script modifier (e.g. de_AT). The selection available is based * on the [Unicode CLDR summary list](https://unicode-org.github.io/cldr-staging/charts/37/summary/root.html) * and includes the major spoken languages of the world and any widely-used variants. * * @docsCategory common */ export enum LanguageCode { /** Afrikaans */ af = 'af', /** Akan */ ak = 'ak', /** Amharic */ am = 'am', /** Arabic */ ar = 'ar', /** Assamese */ as = 'as', /** Azerbaijani */ az = 'az', /** Belarusian */ be = 'be', /** Bulgarian */ bg = 'bg', /** Bambara */ bm = 'bm', /** Bangla */ bn = 'bn', /** Tibetan */ bo = 'bo', /** Breton */ br = 'br', /** Bosnian */ bs = 'bs', /** Catalan */ ca = 'ca', /** Chechen */ ce = 'ce', /** Corsican */ co = 'co', /** Czech */ cs = 'cs', /** Church Slavic */ cu = 'cu', /** Welsh */ cy = 'cy', /** Danish */ da = 'da', /** German */ de = 'de', /** Austrian German */ de_AT = 'de_AT', /** Swiss High German */ de_CH = 'de_CH', /** Dzongkha */ dz = 'dz', /** Ewe */ ee = 'ee', /** Greek */ el = 'el', /** English */ en = 'en', /** Australian English */ en_AU = 'en_AU', /** Canadian English */ en_CA = 'en_CA', /** British English */ en_GB = 'en_GB', /** American English */ en_US = 'en_US', /** Esperanto */ eo = 'eo', /** Spanish */ es = 'es', /** European Spanish */ es_ES = 'es_ES', /** Mexican Spanish */ es_MX = 'es_MX', /** Estonian */ et = 'et', /** Basque */ eu = 'eu', /** Persian */ fa = 'fa', /** Dari */ fa_AF = 'fa_AF', /** Fulah */ ff = 'ff', /** Finnish */ fi = 'fi', /** Faroese */ fo = 'fo', /** French */ fr = 'fr', /** Canadian French */ fr_CA = 'fr_CA', /** Swiss French */ fr_CH = 'fr_CH', /** Western Frisian */ fy = 'fy', /** Irish */ ga = 'ga', /** Scottish Gaelic */ gd = 'gd', /** Galician */ gl = 'gl', /** Gujarati */ gu = 'gu', /** Manx */ gv = 'gv', /** Hausa */ ha = 'ha', /** Hebrew */ he = 'he', /** Hindi */ hi = 'hi', /** Croatian */ hr = 'hr', /** Haitian Creole */ ht = 'ht', /** Hungarian */ hu = 'hu', /** Armenian */ hy = 'hy', /** Interlingua */ ia = 'ia', /** Indonesian */ id = 'id', /** Igbo */ ig = 'ig', /** Sichuan Yi */ ii = 'ii', /** Icelandic */ is = 'is', /** Italian */ it = 'it', /** Japanese */ ja = 'ja', /** Javanese */ jv = 'jv', /** Georgian */ ka = 'ka', /** Kikuyu */ ki = 'ki', /** Kazakh */ kk = 'kk', /** Kalaallisut */ kl = 'kl', /** Khmer */ km = 'km', /** Kannada */ kn = 'kn', /** Korean */ ko = 'ko', /** Kashmiri */ ks = 'ks', /** Kurdish */ ku = 'ku', /** Cornish */ kw = 'kw', /** Kyrgyz */ ky = 'ky', /** Latin */ la = 'la', /** Luxembourgish */ lb = 'lb', /** Ganda */ lg = 'lg', /** Lingala */ ln = 'ln', /** Lao */ lo = 'lo', /** Lithuanian */ lt = 'lt', /** Luba-Katanga */ lu = 'lu', /** Latvian */ lv = 'lv', /** Malagasy */ mg = 'mg', /** Maori */ mi = 'mi', /** Macedonian */ mk = 'mk', /** Malayalam */ ml = 'ml', /** Mongolian */ mn = 'mn', /** Marathi */ mr = 'mr', /** Malay */ ms = 'ms', /** Maltese */ mt = 'mt', /** Burmese */ my = 'my', /** Norwegian Bokmål */ nb = 'nb', /** North Ndebele */ nd = 'nd', /** Nepali */ ne = 'ne', /** Dutch */ nl = 'nl', /** Flemish */ nl_BE = 'nl_BE', /** Norwegian Nynorsk */ nn = 'nn', /** Nyanja */ ny = 'ny', /** Oromo */ om = 'om', /** Odia */ or = 'or', /** Ossetic */ os = 'os', /** Punjabi */ pa = 'pa', /** Polish */ pl = 'pl', /** Pashto */ ps = 'ps', /** Portuguese */ pt = 'pt', /** Brazilian Portuguese */ pt_BR = 'pt_BR', /** European Portuguese */ pt_PT = 'pt_PT', /** Quechua */ qu = 'qu', /** Romansh */ rm = 'rm', /** Rundi */ rn = 'rn', /** Romanian */ ro = 'ro', /** Moldavian */ ro_MD = 'ro_MD', /** Russian */ ru = 'ru', /** Kinyarwanda */ rw = 'rw', /** Sanskrit */ sa = 'sa', /** Sindhi */ sd = 'sd', /** Northern Sami */ se = 'se', /** Sango */ sg = 'sg', /** Sinhala */ si = 'si', /** Slovak */ sk = 'sk', /** Slovenian */ sl = 'sl', /** Samoan */ sm = 'sm', /** Shona */ sn = 'sn', /** Somali */ so = 'so', /** Albanian */ sq = 'sq', /** Serbian */ sr = 'sr', /** Southern Sotho */ st = 'st', /** Sundanese */ su = 'su', /** Swedish */ sv = 'sv', /** Swahili */ sw = 'sw', /** Congo Swahili */ sw_CD = 'sw_CD', /** Tamil */ ta = 'ta', /** Telugu */ te = 'te', /** Tajik */ tg = 'tg', /** Thai */ th = 'th', /** Tigrinya */ ti = 'ti', /** Turkmen */ tk = 'tk', /** Tongan */ to = 'to', /** Turkish */ tr = 'tr', /** Tatar */ tt = 'tt', /** Uyghur */ ug = 'ug', /** Ukrainian */ uk = 'uk', /** Urdu */ ur = 'ur', /** Uzbek */ uz = 'uz', /** Vietnamese */ vi = 'vi', /** Volapük */ vo = 'vo', /** Wolof */ wo = 'wo', /** Xhosa */ xh = 'xh', /** Yiddish */ yi = 'yi', /** Yoruba */ yo = 'yo', /** Chinese */ zh = 'zh', /** Simplified Chinese */ zh_Hans = 'zh_Hans', /** Traditional Chinese */ zh_Hant = 'zh_Hant', /** Zulu */ zu = 'zu' } /** Returned if attempting to set a Channel's defaultLanguageCode to a language which is not enabled in GlobalSettings */ export type LanguageNotAvailableError = ErrorResult & { __typename?: 'LanguageNotAvailableError'; errorCode: ErrorCode; languageCode: Scalars['String']['output']; message: Scalars['String']['output']; }; export type LocaleStringCustomFieldConfig = CustomField & { __typename?: 'LocaleStringCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; length?: Maybe<Scalars['Int']['output']>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; pattern?: Maybe<Scalars['String']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type LocaleTextCustomFieldConfig = CustomField & { __typename?: 'LocaleTextCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type LocalizedString = { __typename?: 'LocalizedString'; languageCode: LanguageCode; value: Scalars['String']['output']; }; export enum LogicalOperator { AND = 'AND', OR = 'OR' } export type ManualPaymentInput = { metadata?: InputMaybe<Scalars['JSON']['input']>; method: Scalars['String']['input']; orderId: Scalars['ID']['input']; transactionId?: InputMaybe<Scalars['String']['input']>; }; /** * Returned when a call to addManualPaymentToOrder is made but the Order * is not in the required state. */ export type ManualPaymentStateError = ErrorResult & { __typename?: 'ManualPaymentStateError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export enum MetricInterval { Daily = 'Daily' } export type MetricSummary = { __typename?: 'MetricSummary'; entries: Array<MetricSummaryEntry>; interval: MetricInterval; title: Scalars['String']['output']; type: MetricType; }; export type MetricSummaryEntry = { __typename?: 'MetricSummaryEntry'; label: Scalars['String']['output']; value: Scalars['Float']['output']; }; export type MetricSummaryInput = { interval: MetricInterval; refresh?: InputMaybe<Scalars['Boolean']['input']>; types: Array<MetricType>; }; export enum MetricType { AverageOrderValue = 'AverageOrderValue', OrderCount = 'OrderCount', OrderTotal = 'OrderTotal' } export type MimeTypeError = ErrorResult & { __typename?: 'MimeTypeError'; errorCode: ErrorCode; fileName: Scalars['String']['output']; message: Scalars['String']['output']; mimeType: Scalars['String']['output']; }; /** Returned if a PromotionCondition has neither a couponCode nor any conditions set */ export type MissingConditionsError = ErrorResult & { __typename?: 'MissingConditionsError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type ModifyOrderInput = { addItems?: InputMaybe<Array<AddItemInput>>; adjustOrderLines?: InputMaybe<Array<OrderLineInput>>; couponCodes?: InputMaybe<Array<Scalars['String']['input']>>; dryRun: Scalars['Boolean']['input']; note?: InputMaybe<Scalars['String']['input']>; options?: InputMaybe<ModifyOrderOptions>; orderId: Scalars['ID']['input']; /** * Deprecated in v2.2.0. Use `refunds` instead to allow multiple refunds to be * applied in the case that multiple payment methods have been used on the order. */ refund?: InputMaybe<AdministratorRefundInput>; refunds?: InputMaybe<Array<AdministratorRefundInput>>; /** Added in v2.2 */ shippingMethodIds?: InputMaybe<Array<Scalars['ID']['input']>>; surcharges?: InputMaybe<Array<SurchargeInput>>; updateBillingAddress?: InputMaybe<UpdateOrderAddressInput>; updateShippingAddress?: InputMaybe<UpdateOrderAddressInput>; }; export type ModifyOrderOptions = { freezePromotions?: InputMaybe<Scalars['Boolean']['input']>; recalculateShipping?: InputMaybe<Scalars['Boolean']['input']>; }; export type ModifyOrderResult = CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError | IneligibleShippingMethodError | InsufficientStockError | NegativeQuantityError | NoChangesSpecifiedError | Order | OrderLimitError | OrderModificationStateError | PaymentMethodMissingError | RefundPaymentIdMissingError; export type MoveCollectionInput = { collectionId: Scalars['ID']['input']; index: Scalars['Int']['input']; parentId: Scalars['ID']['input']; }; /** Returned if an operation has specified OrderLines from multiple Orders */ export type MultipleOrderError = ErrorResult & { __typename?: 'MultipleOrderError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Mutation = { __typename?: 'Mutation'; /** Add Customers to a CustomerGroup */ addCustomersToGroup: CustomerGroup; addFulfillmentToOrder: AddFulfillmentToOrderResult; /** Adds an item to the draft Order. */ addItemToDraftOrder: UpdateOrderItemsResult; /** * Used to manually create a new Payment against an Order. * This can be used by an Administrator when an Order is in the ArrangingPayment state. * * It is also used when a completed Order * has been modified (using `modifyOrder`) and the price has increased. The extra payment * can then be manually arranged by the administrator, and the details used to create a new * Payment. */ addManualPaymentToOrder: AddManualPaymentToOrderResult; /** Add members to a Zone */ addMembersToZone: Zone; addNoteToCustomer: Customer; addNoteToOrder: Order; /** Add an OptionGroup to a Product */ addOptionGroupToProduct: Product; /** Adjusts a draft OrderLine. If custom fields are defined on the OrderLine entity, a third argument 'customFields' of type `OrderLineCustomFieldsInput` will be available. */ adjustDraftOrderLine: UpdateOrderItemsResult; /** Applies the given coupon code to the draft Order */ applyCouponCodeToDraftOrder: ApplyCouponCodeResult; /** Assign assets to channel */ assignAssetsToChannel: Array<Asset>; /** Assigns Collections to the specified Channel */ assignCollectionsToChannel: Array<Collection>; /** Assigns Facets to the specified Channel */ assignFacetsToChannel: Array<Facet>; /** Assigns PaymentMethods to the specified Channel */ assignPaymentMethodsToChannel: Array<PaymentMethod>; /** Assigns ProductVariants to the specified Channel */ assignProductVariantsToChannel: Array<ProductVariant>; /** Assigns all ProductVariants of Product to the specified Channel */ assignProductsToChannel: Array<Product>; /** Assigns Promotions to the specified Channel */ assignPromotionsToChannel: Array<Promotion>; /** Assign a Role to an Administrator */ assignRoleToAdministrator: Administrator; /** Assigns ShippingMethods to the specified Channel */ assignShippingMethodsToChannel: Array<ShippingMethod>; /** Assigns StockLocations to the specified Channel */ assignStockLocationsToChannel: Array<StockLocation>; /** Authenticates the user using a named authentication strategy */ authenticate: AuthenticationResult; cancelJob: Job; cancelOrder: CancelOrderResult; cancelPayment: CancelPaymentResult; /** Create a new Administrator */ createAdministrator: Administrator; /** Create a new Asset */ createAssets: Array<CreateAssetResult>; /** Create a new Channel */ createChannel: CreateChannelResult; /** Create a new Collection */ createCollection: Collection; /** Create a new Country */ createCountry: Country; /** Create a new Customer. If a password is provided, a new User will also be created an linked to the Customer. */ createCustomer: CreateCustomerResult; /** Create a new Address and associate it with the Customer specified by customerId */ createCustomerAddress: Address; /** Create a new CustomerGroup */ createCustomerGroup: CustomerGroup; /** Creates a draft Order */ createDraftOrder: Order; /** Create a new Facet */ createFacet: Facet; /** Create one or more FacetValues */ createFacetValues: Array<FacetValue>; /** Create existing PaymentMethod */ createPaymentMethod: PaymentMethod; /** Create a new Product */ createProduct: Product; /** Create a new ProductOption within a ProductOptionGroup */ createProductOption: ProductOption; /** Create a new ProductOptionGroup */ createProductOptionGroup: ProductOptionGroup; /** Create a set of ProductVariants based on the OptionGroups assigned to the given Product */ createProductVariants: Array<Maybe<ProductVariant>>; createPromotion: CreatePromotionResult; /** Create a new Province */ createProvince: Province; /** Create a new Role */ createRole: Role; /** Create a new Seller */ createSeller: Seller; /** Create a new ShippingMethod */ createShippingMethod: ShippingMethod; createStockLocation: StockLocation; /** Create a new Tag */ createTag: Tag; /** Create a new TaxCategory */ createTaxCategory: TaxCategory; /** Create a new TaxRate */ createTaxRate: TaxRate; /** Create a new Zone */ createZone: Zone; /** Delete an Administrator */ deleteAdministrator: DeletionResponse; /** Delete multiple Administrators */ deleteAdministrators: Array<DeletionResponse>; /** Delete an Asset */ deleteAsset: DeletionResponse; /** Delete multiple Assets */ deleteAssets: DeletionResponse; /** Delete a Channel */ deleteChannel: DeletionResponse; /** Delete multiple Channels */ deleteChannels: Array<DeletionResponse>; /** Delete a Collection and all of its descendants */ deleteCollection: DeletionResponse; /** Delete multiple Collections and all of their descendants */ deleteCollections: Array<DeletionResponse>; /** Delete multiple Countries */ deleteCountries: Array<DeletionResponse>; /** Delete a Country */ deleteCountry: DeletionResponse; /** Delete a Customer */ deleteCustomer: DeletionResponse; /** Update an existing Address */ deleteCustomerAddress: Success; /** Delete a CustomerGroup */ deleteCustomerGroup: DeletionResponse; /** Delete multiple CustomerGroups */ deleteCustomerGroups: Array<DeletionResponse>; deleteCustomerNote: DeletionResponse; /** Deletes Customers */ deleteCustomers: Array<DeletionResponse>; /** Deletes a draft Order */ deleteDraftOrder: DeletionResponse; /** Delete an existing Facet */ deleteFacet: DeletionResponse; /** Delete one or more FacetValues */ deleteFacetValues: Array<DeletionResponse>; /** Delete multiple existing Facets */ deleteFacets: Array<DeletionResponse>; deleteOrderNote: DeletionResponse; /** Delete a PaymentMethod */ deletePaymentMethod: DeletionResponse; /** Delete multiple PaymentMethods */ deletePaymentMethods: Array<DeletionResponse>; /** Delete a Product */ deleteProduct: DeletionResponse; /** Delete a ProductOption */ deleteProductOption: DeletionResponse; /** Delete a ProductVariant */ deleteProductVariant: DeletionResponse; /** Delete multiple ProductVariants */ deleteProductVariants: Array<DeletionResponse>; /** Delete multiple Products */ deleteProducts: Array<DeletionResponse>; deletePromotion: DeletionResponse; deletePromotions: Array<DeletionResponse>; /** Delete a Province */ deleteProvince: DeletionResponse; /** Delete an existing Role */ deleteRole: DeletionResponse; /** Delete multiple Roles */ deleteRoles: Array<DeletionResponse>; /** Delete a Seller */ deleteSeller: DeletionResponse; /** Delete multiple Sellers */ deleteSellers: Array<DeletionResponse>; /** Delete a ShippingMethod */ deleteShippingMethod: DeletionResponse; /** Delete multiple ShippingMethods */ deleteShippingMethods: Array<DeletionResponse>; deleteStockLocation: DeletionResponse; deleteStockLocations: Array<DeletionResponse>; /** Delete an existing Tag */ deleteTag: DeletionResponse; /** Deletes multiple TaxCategories */ deleteTaxCategories: Array<DeletionResponse>; /** Deletes a TaxCategory */ deleteTaxCategory: DeletionResponse; /** Delete a TaxRate */ deleteTaxRate: DeletionResponse; /** Delete multiple TaxRates */ deleteTaxRates: Array<DeletionResponse>; /** Delete a Zone */ deleteZone: DeletionResponse; /** Delete a Zone */ deleteZones: Array<DeletionResponse>; duplicateEntity: DuplicateEntityResult; flushBufferedJobs: Success; importProducts?: Maybe<ImportInfo>; /** Authenticates the user using the native authentication strategy. This mutation is an alias for `authenticate({ native: { ... }})` */ login: NativeAuthenticationResult; logout: Success; /** * Allows an Order to be modified after it has been completed by the Customer. The Order must first * be in the `Modifying` state. */ modifyOrder: ModifyOrderResult; /** Move a Collection to a different parent or index */ moveCollection: Collection; refundOrder: RefundOrderResult; reindex: Job; /** Removes Collections from the specified Channel */ removeCollectionsFromChannel: Array<Collection>; /** Removes the given coupon code from the draft Order */ removeCouponCodeFromDraftOrder?: Maybe<Order>; /** Remove Customers from a CustomerGroup */ removeCustomersFromGroup: CustomerGroup; /** Remove an OrderLine from the draft Order */ removeDraftOrderLine: RemoveOrderItemsResult; /** Removes Facets from the specified Channel */ removeFacetsFromChannel: Array<RemoveFacetFromChannelResult>; /** Remove members from a Zone */ removeMembersFromZone: Zone; /** * Remove an OptionGroup from a Product. If the OptionGroup is in use by any ProductVariants * the mutation will return a ProductOptionInUseError, and the OptionGroup will not be removed. * Setting the `force` argument to `true` will override this and remove the OptionGroup anyway, * as well as removing any of the group's options from the Product's ProductVariants. */ removeOptionGroupFromProduct: RemoveOptionGroupFromProductResult; /** Removes PaymentMethods from the specified Channel */ removePaymentMethodsFromChannel: Array<PaymentMethod>; /** Removes ProductVariants from the specified Channel */ removeProductVariantsFromChannel: Array<ProductVariant>; /** Removes all ProductVariants of Product from the specified Channel */ removeProductsFromChannel: Array<Product>; /** Removes Promotions from the specified Channel */ removePromotionsFromChannel: Array<Promotion>; /** Remove all settled jobs in the given queues older than the given date. Returns the number of jobs deleted. */ removeSettledJobs: Scalars['Int']['output']; /** Removes ShippingMethods from the specified Channel */ removeShippingMethodsFromChannel: Array<ShippingMethod>; /** Removes StockLocations from the specified Channel */ removeStockLocationsFromChannel: Array<StockLocation>; runPendingSearchIndexUpdates: Success; setCustomerForDraftOrder: SetCustomerForDraftOrderResult; /** Sets the billing address for a draft Order */ setDraftOrderBillingAddress: Order; /** Allows any custom fields to be set for the active order */ setDraftOrderCustomFields: Order; /** Sets the shipping address for a draft Order */ setDraftOrderShippingAddress: Order; /** Sets the shipping method by id, which can be obtained with the `eligibleShippingMethodsForDraftOrder` query */ setDraftOrderShippingMethod: SetOrderShippingMethodResult; setOrderCustomFields?: Maybe<Order>; /** Allows a different Customer to be assigned to an Order. Added in v2.2.0. */ setOrderCustomer?: Maybe<Order>; settlePayment: SettlePaymentResult; settleRefund: SettleRefundResult; transitionFulfillmentToState: TransitionFulfillmentToStateResult; transitionOrderToState?: Maybe<TransitionOrderToStateResult>; transitionPaymentToState: TransitionPaymentToStateResult; /** Update the active (currently logged-in) Administrator */ updateActiveAdministrator: Administrator; /** Update an existing Administrator */ updateAdministrator: Administrator; /** Update an existing Asset */ updateAsset: Asset; /** Update an existing Channel */ updateChannel: UpdateChannelResult; /** Update an existing Collection */ updateCollection: Collection; /** Update an existing Country */ updateCountry: Country; /** Update an existing Customer */ updateCustomer: UpdateCustomerResult; /** Update an existing Address */ updateCustomerAddress: Address; /** Update an existing CustomerGroup */ updateCustomerGroup: CustomerGroup; updateCustomerNote: HistoryEntry; /** Update an existing Facet */ updateFacet: Facet; /** Update one or more FacetValues */ updateFacetValues: Array<FacetValue>; updateGlobalSettings: UpdateGlobalSettingsResult; updateOrderNote: HistoryEntry; /** Update an existing PaymentMethod */ updatePaymentMethod: PaymentMethod; /** Update an existing Product */ updateProduct: Product; /** Create a new ProductOption within a ProductOptionGroup */ updateProductOption: ProductOption; /** Update an existing ProductOptionGroup */ updateProductOptionGroup: ProductOptionGroup; /** Update existing ProductVariants */ updateProductVariants: Array<Maybe<ProductVariant>>; /** Update multiple existing Products */ updateProducts: Array<Product>; updatePromotion: UpdatePromotionResult; /** Update an existing Province */ updateProvince: Province; /** Update an existing Role */ updateRole: Role; /** Update an existing Seller */ updateSeller: Seller; /** Update an existing ShippingMethod */ updateShippingMethod: ShippingMethod; updateStockLocation: StockLocation; /** Update an existing Tag */ updateTag: Tag; /** Update an existing TaxCategory */ updateTaxCategory: TaxCategory; /** Update an existing TaxRate */ updateTaxRate: TaxRate; /** Update an existing Zone */ updateZone: Zone; }; export type MutationAddCustomersToGroupArgs = { customerGroupId: Scalars['ID']['input']; customerIds: Array<Scalars['ID']['input']>; }; export type MutationAddFulfillmentToOrderArgs = { input: FulfillOrderInput; }; export type MutationAddItemToDraftOrderArgs = { input: AddItemToDraftOrderInput; orderId: Scalars['ID']['input']; }; export type MutationAddManualPaymentToOrderArgs = { input: ManualPaymentInput; }; export type MutationAddMembersToZoneArgs = { memberIds: Array<Scalars['ID']['input']>; zoneId: Scalars['ID']['input']; }; export type MutationAddNoteToCustomerArgs = { input: AddNoteToCustomerInput; }; export type MutationAddNoteToOrderArgs = { input: AddNoteToOrderInput; }; export type MutationAddOptionGroupToProductArgs = { optionGroupId: Scalars['ID']['input']; productId: Scalars['ID']['input']; }; export type MutationAdjustDraftOrderLineArgs = { input: AdjustDraftOrderLineInput; orderId: Scalars['ID']['input']; }; export type MutationApplyCouponCodeToDraftOrderArgs = { couponCode: Scalars['String']['input']; orderId: Scalars['ID']['input']; }; export type MutationAssignAssetsToChannelArgs = { input: AssignAssetsToChannelInput; }; export type MutationAssignCollectionsToChannelArgs = { input: AssignCollectionsToChannelInput; }; export type MutationAssignFacetsToChannelArgs = { input: AssignFacetsToChannelInput; }; export type MutationAssignPaymentMethodsToChannelArgs = { input: AssignPaymentMethodsToChannelInput; }; export type MutationAssignProductVariantsToChannelArgs = { input: AssignProductVariantsToChannelInput; }; export type MutationAssignProductsToChannelArgs = { input: AssignProductsToChannelInput; }; export type MutationAssignPromotionsToChannelArgs = { input: AssignPromotionsToChannelInput; }; export type MutationAssignRoleToAdministratorArgs = { administratorId: Scalars['ID']['input']; roleId: Scalars['ID']['input']; }; export type MutationAssignShippingMethodsToChannelArgs = { input: AssignShippingMethodsToChannelInput; }; export type MutationAssignStockLocationsToChannelArgs = { input: AssignStockLocationsToChannelInput; }; export type MutationAuthenticateArgs = { input: AuthenticationInput; rememberMe?: InputMaybe<Scalars['Boolean']['input']>; }; export type MutationCancelJobArgs = { jobId: Scalars['ID']['input']; }; export type MutationCancelOrderArgs = { input: CancelOrderInput; }; export type MutationCancelPaymentArgs = { id: Scalars['ID']['input']; }; export type MutationCreateAdministratorArgs = { input: CreateAdministratorInput; }; export type MutationCreateAssetsArgs = { input: Array<CreateAssetInput>; }; export type MutationCreateChannelArgs = { input: CreateChannelInput; }; export type MutationCreateCollectionArgs = { input: CreateCollectionInput; }; export type MutationCreateCountryArgs = { input: CreateCountryInput; }; export type MutationCreateCustomerArgs = { input: CreateCustomerInput; password?: InputMaybe<Scalars['String']['input']>; }; export type MutationCreateCustomerAddressArgs = { customerId: Scalars['ID']['input']; input: CreateAddressInput; }; export type MutationCreateCustomerGroupArgs = { input: CreateCustomerGroupInput; }; export type MutationCreateFacetArgs = { input: CreateFacetInput; }; export type MutationCreateFacetValuesArgs = { input: Array<CreateFacetValueInput>; }; export type MutationCreatePaymentMethodArgs = { input: CreatePaymentMethodInput; }; export type MutationCreateProductArgs = { input: CreateProductInput; }; export type MutationCreateProductOptionArgs = { input: CreateProductOptionInput; }; export type MutationCreateProductOptionGroupArgs = { input: CreateProductOptionGroupInput; }; export type MutationCreateProductVariantsArgs = { input: Array<CreateProductVariantInput>; }; export type MutationCreatePromotionArgs = { input: CreatePromotionInput; }; export type MutationCreateProvinceArgs = { input: CreateProvinceInput; }; export type MutationCreateRoleArgs = { input: CreateRoleInput; }; export type MutationCreateSellerArgs = { input: CreateSellerInput; }; export type MutationCreateShippingMethodArgs = { input: CreateShippingMethodInput; }; export type MutationCreateStockLocationArgs = { input: CreateStockLocationInput; }; export type MutationCreateTagArgs = { input: CreateTagInput; }; export type MutationCreateTaxCategoryArgs = { input: CreateTaxCategoryInput; }; export type MutationCreateTaxRateArgs = { input: CreateTaxRateInput; }; export type MutationCreateZoneArgs = { input: CreateZoneInput; }; export type MutationDeleteAdministratorArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteAdministratorsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteAssetArgs = { input: DeleteAssetInput; }; export type MutationDeleteAssetsArgs = { input: DeleteAssetsInput; }; export type MutationDeleteChannelArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteChannelsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteCollectionArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteCollectionsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteCountriesArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteCountryArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteCustomerArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteCustomerAddressArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteCustomerGroupArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteCustomerGroupsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteCustomerNoteArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteCustomersArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteDraftOrderArgs = { orderId: Scalars['ID']['input']; }; export type MutationDeleteFacetArgs = { force?: InputMaybe<Scalars['Boolean']['input']>; id: Scalars['ID']['input']; }; export type MutationDeleteFacetValuesArgs = { force?: InputMaybe<Scalars['Boolean']['input']>; ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteFacetsArgs = { force?: InputMaybe<Scalars['Boolean']['input']>; ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteOrderNoteArgs = { id: Scalars['ID']['input']; }; export type MutationDeletePaymentMethodArgs = { force?: InputMaybe<Scalars['Boolean']['input']>; id: Scalars['ID']['input']; }; export type MutationDeletePaymentMethodsArgs = { force?: InputMaybe<Scalars['Boolean']['input']>; ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteProductArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteProductOptionArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteProductVariantArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteProductVariantsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteProductsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeletePromotionArgs = { id: Scalars['ID']['input']; }; export type MutationDeletePromotionsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteProvinceArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteRoleArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteRolesArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteSellerArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteSellersArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteShippingMethodArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteShippingMethodsArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteStockLocationArgs = { input: DeleteStockLocationInput; }; export type MutationDeleteStockLocationsArgs = { input: Array<DeleteStockLocationInput>; }; export type MutationDeleteTagArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteTaxCategoriesArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteTaxCategoryArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteTaxRateArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteTaxRatesArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDeleteZoneArgs = { id: Scalars['ID']['input']; }; export type MutationDeleteZonesArgs = { ids: Array<Scalars['ID']['input']>; }; export type MutationDuplicateEntityArgs = { input: DuplicateEntityInput; }; export type MutationFlushBufferedJobsArgs = { bufferIds?: InputMaybe<Array<Scalars['String']['input']>>; }; export type MutationImportProductsArgs = { csvFile: Scalars['Upload']['input']; }; export type MutationLoginArgs = { password: Scalars['String']['input']; rememberMe?: InputMaybe<Scalars['Boolean']['input']>; username: Scalars['String']['input']; }; export type MutationModifyOrderArgs = { input: ModifyOrderInput; }; export type MutationMoveCollectionArgs = { input: MoveCollectionInput; }; export type MutationRefundOrderArgs = { input: RefundOrderInput; }; export type MutationRemoveCollectionsFromChannelArgs = { input: RemoveCollectionsFromChannelInput; }; export type MutationRemoveCouponCodeFromDraftOrderArgs = { couponCode: Scalars['String']['input']; orderId: Scalars['ID']['input']; }; export type MutationRemoveCustomersFromGroupArgs = { customerGroupId: Scalars['ID']['input']; customerIds: Array<Scalars['ID']['input']>; }; export type MutationRemoveDraftOrderLineArgs = { orderId: Scalars['ID']['input']; orderLineId: Scalars['ID']['input']; }; export type MutationRemoveFacetsFromChannelArgs = { input: RemoveFacetsFromChannelInput; }; export type MutationRemoveMembersFromZoneArgs = { memberIds: Array<Scalars['ID']['input']>; zoneId: Scalars['ID']['input']; }; export type MutationRemoveOptionGroupFromProductArgs = { force?: InputMaybe<Scalars['Boolean']['input']>; optionGroupId: Scalars['ID']['input']; productId: Scalars['ID']['input']; }; export type MutationRemovePaymentMethodsFromChannelArgs = { input: RemovePaymentMethodsFromChannelInput; }; export type MutationRemoveProductVariantsFromChannelArgs = { input: RemoveProductVariantsFromChannelInput; }; export type MutationRemoveProductsFromChannelArgs = { input: RemoveProductsFromChannelInput; }; export type MutationRemovePromotionsFromChannelArgs = { input: RemovePromotionsFromChannelInput; }; export type MutationRemoveSettledJobsArgs = { olderThan?: InputMaybe<Scalars['DateTime']['input']>; queueNames?: InputMaybe<Array<Scalars['String']['input']>>; }; export type MutationRemoveShippingMethodsFromChannelArgs = { input: RemoveShippingMethodsFromChannelInput; }; export type MutationRemoveStockLocationsFromChannelArgs = { input: RemoveStockLocationsFromChannelInput; }; export type MutationSetCustomerForDraftOrderArgs = { customerId?: InputMaybe<Scalars['ID']['input']>; input?: InputMaybe<CreateCustomerInput>; orderId: Scalars['ID']['input']; }; export type MutationSetDraftOrderBillingAddressArgs = { input: CreateAddressInput; orderId: Scalars['ID']['input']; }; export type MutationSetDraftOrderCustomFieldsArgs = { input: UpdateOrderInput; orderId: Scalars['ID']['input']; }; export type MutationSetDraftOrderShippingAddressArgs = { input: CreateAddressInput; orderId: Scalars['ID']['input']; }; export type MutationSetDraftOrderShippingMethodArgs = { orderId: Scalars['ID']['input']; shippingMethodId: Scalars['ID']['input']; }; export type MutationSetOrderCustomFieldsArgs = { input: UpdateOrderInput; }; export type MutationSetOrderCustomerArgs = { input: SetOrderCustomerInput; }; export type MutationSettlePaymentArgs = { id: Scalars['ID']['input']; }; export type MutationSettleRefundArgs = { input: SettleRefundInput; }; export type MutationTransitionFulfillmentToStateArgs = { id: Scalars['ID']['input']; state: Scalars['String']['input']; }; export type MutationTransitionOrderToStateArgs = { id: Scalars['ID']['input']; state: Scalars['String']['input']; }; export type MutationTransitionPaymentToStateArgs = { id: Scalars['ID']['input']; state: Scalars['String']['input']; }; export type MutationUpdateActiveAdministratorArgs = { input: UpdateActiveAdministratorInput; }; export type MutationUpdateAdministratorArgs = { input: UpdateAdministratorInput; }; export type MutationUpdateAssetArgs = { input: UpdateAssetInput; }; export type MutationUpdateChannelArgs = { input: UpdateChannelInput; }; export type MutationUpdateCollectionArgs = { input: UpdateCollectionInput; }; export type MutationUpdateCountryArgs = { input: UpdateCountryInput; }; export type MutationUpdateCustomerArgs = { input: UpdateCustomerInput; }; export type MutationUpdateCustomerAddressArgs = { input: UpdateAddressInput; }; export type MutationUpdateCustomerGroupArgs = { input: UpdateCustomerGroupInput; }; export type MutationUpdateCustomerNoteArgs = { input: UpdateCustomerNoteInput; }; export type MutationUpdateFacetArgs = { input: UpdateFacetInput; }; export type MutationUpdateFacetValuesArgs = { input: Array<UpdateFacetValueInput>; }; export type MutationUpdateGlobalSettingsArgs = { input: UpdateGlobalSettingsInput; }; export type MutationUpdateOrderNoteArgs = { input: UpdateOrderNoteInput; }; export type MutationUpdatePaymentMethodArgs = { input: UpdatePaymentMethodInput; }; export type MutationUpdateProductArgs = { input: UpdateProductInput; }; export type MutationUpdateProductOptionArgs = { input: UpdateProductOptionInput; }; export type MutationUpdateProductOptionGroupArgs = { input: UpdateProductOptionGroupInput; }; export type MutationUpdateProductVariantsArgs = { input: Array<UpdateProductVariantInput>; }; export type MutationUpdateProductsArgs = { input: Array<UpdateProductInput>; }; export type MutationUpdatePromotionArgs = { input: UpdatePromotionInput; }; export type MutationUpdateProvinceArgs = { input: UpdateProvinceInput; }; export type MutationUpdateRoleArgs = { input: UpdateRoleInput; }; export type MutationUpdateSellerArgs = { input: UpdateSellerInput; }; export type MutationUpdateShippingMethodArgs = { input: UpdateShippingMethodInput; }; export type MutationUpdateStockLocationArgs = { input: UpdateStockLocationInput; }; export type MutationUpdateTagArgs = { input: UpdateTagInput; }; export type MutationUpdateTaxCategoryArgs = { input: UpdateTaxCategoryInput; }; export type MutationUpdateTaxRateArgs = { input: UpdateTaxRateInput; }; export type MutationUpdateZoneArgs = { input: UpdateZoneInput; }; export type NativeAuthInput = { password: Scalars['String']['input']; username: Scalars['String']['input']; }; /** Returned when attempting an operation that relies on the NativeAuthStrategy, if that strategy is not configured. */ export type NativeAuthStrategyError = ErrorResult & { __typename?: 'NativeAuthStrategyError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type NativeAuthenticationResult = CurrentUser | InvalidCredentialsError | NativeAuthStrategyError; /** Returned when attempting to set a negative OrderLine quantity. */ export type NegativeQuantityError = ErrorResult & { __typename?: 'NegativeQuantityError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** * Returned when invoking a mutation which depends on there being an active Order on the * current session. */ export type NoActiveOrderError = ErrorResult & { __typename?: 'NoActiveOrderError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when a call to modifyOrder fails to specify any changes */ export type NoChangesSpecifiedError = ErrorResult & { __typename?: 'NoChangesSpecifiedError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Node = { id: Scalars['ID']['output']; }; /** Returned if an attempting to refund an Order but neither items nor shipping refund was specified */ export type NothingToRefundError = ErrorResult & { __typename?: 'NothingToRefundError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Operators for filtering on a list of Number fields */ export type NumberListOperators = { inList: Scalars['Float']['input']; }; /** Operators for filtering on a Int or Float field */ export type NumberOperators = { between?: InputMaybe<NumberRange>; eq?: InputMaybe<Scalars['Float']['input']>; gt?: InputMaybe<Scalars['Float']['input']>; gte?: InputMaybe<Scalars['Float']['input']>; isNull?: InputMaybe<Scalars['Boolean']['input']>; lt?: InputMaybe<Scalars['Float']['input']>; lte?: InputMaybe<Scalars['Float']['input']>; }; export type NumberRange = { end: Scalars['Float']['input']; start: Scalars['Float']['input']; }; export type Order = Node & { __typename?: 'Order'; /** An order is active as long as the payment process has not been completed */ active: Scalars['Boolean']['output']; aggregateOrder?: Maybe<Order>; aggregateOrderId?: Maybe<Scalars['ID']['output']>; billingAddress?: Maybe<OrderAddress>; channels: Array<Channel>; /** A unique code for the Order */ code: Scalars['String']['output']; /** An array of all coupon codes applied to the Order */ couponCodes: Array<Scalars['String']['output']>; createdAt: Scalars['DateTime']['output']; currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; customer?: Maybe<Customer>; discounts: Array<Discount>; fulfillments?: Maybe<Array<Fulfillment>>; history: HistoryEntryList; id: Scalars['ID']['output']; lines: Array<OrderLine>; modifications: Array<OrderModification>; nextStates: Array<Scalars['String']['output']>; /** * The date & time that the Order was placed, i.e. the Customer * completed the checkout and the Order is no longer "active" */ orderPlacedAt?: Maybe<Scalars['DateTime']['output']>; payments?: Maybe<Array<Payment>>; /** Promotions applied to the order. Only gets populated after the payment process has completed. */ promotions: Array<Promotion>; sellerOrders?: Maybe<Array<Order>>; shipping: Scalars['Money']['output']; shippingAddress?: Maybe<OrderAddress>; shippingLines: Array<ShippingLine>; shippingWithTax: Scalars['Money']['output']; state: Scalars['String']['output']; /** * The subTotal is the total of all OrderLines in the Order. This figure also includes any Order-level * discounts which have been prorated (proportionally distributed) amongst the items of each OrderLine. * To get a total of all OrderLines which does not account for prorated discounts, use the * sum of `OrderLine.discountedLinePrice` values. */ subTotal: Scalars['Money']['output']; /** Same as subTotal, but inclusive of tax */ subTotalWithTax: Scalars['Money']['output']; /** * Surcharges are arbitrary modifications to the Order total which are neither * ProductVariants nor discounts resulting from applied Promotions. For example, * one-off discounts based on customer interaction, or surcharges based on payment * methods. */ surcharges: Array<Surcharge>; /** A summary of the taxes being applied to this Order */ taxSummary: Array<OrderTaxSummary>; /** Equal to subTotal plus shipping */ total: Scalars['Money']['output']; totalQuantity: Scalars['Int']['output']; /** The final payable amount. Equal to subTotalWithTax plus shippingWithTax */ totalWithTax: Scalars['Money']['output']; type: OrderType; updatedAt: Scalars['DateTime']['output']; }; export type OrderHistoryArgs = { options?: InputMaybe<HistoryEntryListOptions>; }; export type OrderAddress = { __typename?: 'OrderAddress'; city?: Maybe<Scalars['String']['output']>; company?: Maybe<Scalars['String']['output']>; country?: Maybe<Scalars['String']['output']>; countryCode?: Maybe<Scalars['String']['output']>; customFields?: Maybe<Scalars['JSON']['output']>; fullName?: Maybe<Scalars['String']['output']>; phoneNumber?: Maybe<Scalars['String']['output']>; postalCode?: Maybe<Scalars['String']['output']>; province?: Maybe<Scalars['String']['output']>; streetLine1?: Maybe<Scalars['String']['output']>; streetLine2?: Maybe<Scalars['String']['output']>; }; export type OrderFilterParameter = { _and?: InputMaybe<Array<OrderFilterParameter>>; _or?: InputMaybe<Array<OrderFilterParameter>>; active?: InputMaybe<BooleanOperators>; aggregateOrderId?: InputMaybe<IdOperators>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; currencyCode?: InputMaybe<StringOperators>; customerLastName?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; orderPlacedAt?: InputMaybe<DateOperators>; shipping?: InputMaybe<NumberOperators>; shippingWithTax?: InputMaybe<NumberOperators>; state?: InputMaybe<StringOperators>; subTotal?: InputMaybe<NumberOperators>; subTotalWithTax?: InputMaybe<NumberOperators>; total?: InputMaybe<NumberOperators>; totalQuantity?: InputMaybe<NumberOperators>; totalWithTax?: InputMaybe<NumberOperators>; transactionId?: InputMaybe<StringOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; /** Returned when the maximum order size limit has been reached. */ export type OrderLimitError = ErrorResult & { __typename?: 'OrderLimitError'; errorCode: ErrorCode; maxItems: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type OrderLine = Node & { __typename?: 'OrderLine'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; /** The price of the line including discounts, excluding tax */ discountedLinePrice: Scalars['Money']['output']; /** The price of the line including discounts and tax */ discountedLinePriceWithTax: Scalars['Money']['output']; /** * The price of a single unit including discounts, excluding tax. * * If Order-level discounts have been applied, this will not be the * actual taxable unit price (see `proratedUnitPrice`), but is generally the * correct price to display to customers to avoid confusion * about the internal handling of distributed Order-level discounts. */ discountedUnitPrice: Scalars['Money']['output']; /** The price of a single unit including discounts and tax */ discountedUnitPriceWithTax: Scalars['Money']['output']; discounts: Array<Discount>; featuredAsset?: Maybe<Asset>; fulfillmentLines?: Maybe<Array<FulfillmentLine>>; id: Scalars['ID']['output']; /** The total price of the line excluding tax and discounts. */ linePrice: Scalars['Money']['output']; /** The total price of the line including tax but excluding discounts. */ linePriceWithTax: Scalars['Money']['output']; /** The total tax on this line */ lineTax: Scalars['Money']['output']; order: Order; /** The quantity at the time the Order was placed */ orderPlacedQuantity: Scalars['Int']['output']; productVariant: ProductVariant; /** * The actual line price, taking into account both item discounts _and_ prorated (proportionally-distributed) * Order-level discounts. This value is the true economic value of the OrderLine, and is used in tax * and refund calculations. */ proratedLinePrice: Scalars['Money']['output']; /** The proratedLinePrice including tax */ proratedLinePriceWithTax: Scalars['Money']['output']; /** * The actual unit price, taking into account both item discounts _and_ prorated (proportionally-distributed) * Order-level discounts. This value is the true economic value of the OrderItem, and is used in tax * and refund calculations. */ proratedUnitPrice: Scalars['Money']['output']; /** The proratedUnitPrice including tax */ proratedUnitPriceWithTax: Scalars['Money']['output']; /** The quantity of items purchased */ quantity: Scalars['Int']['output']; taxLines: Array<TaxLine>; taxRate: Scalars['Float']['output']; /** The price of a single unit, excluding tax and discounts */ unitPrice: Scalars['Money']['output']; /** Non-zero if the unitPrice has changed since it was initially added to Order */ unitPriceChangeSinceAdded: Scalars['Money']['output']; /** The price of a single unit, including tax but excluding discounts */ unitPriceWithTax: Scalars['Money']['output']; /** Non-zero if the unitPriceWithTax has changed since it was initially added to Order */ unitPriceWithTaxChangeSinceAdded: Scalars['Money']['output']; updatedAt: Scalars['DateTime']['output']; }; export type OrderLineInput = { orderLineId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type OrderList = PaginatedList & { __typename?: 'OrderList'; items: Array<Order>; totalItems: Scalars['Int']['output']; }; export type OrderListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<OrderFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<OrderSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type OrderModification = Node & { __typename?: 'OrderModification'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; isSettled: Scalars['Boolean']['output']; lines: Array<OrderModificationLine>; note: Scalars['String']['output']; payment?: Maybe<Payment>; priceChange: Scalars['Money']['output']; refund?: Maybe<Refund>; surcharges?: Maybe<Array<Surcharge>>; updatedAt: Scalars['DateTime']['output']; }; /** Returned when attempting to modify the contents of an Order that is not in the `AddingItems` state. */ export type OrderModificationError = ErrorResult & { __typename?: 'OrderModificationError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type OrderModificationLine = { __typename?: 'OrderModificationLine'; modification: OrderModification; modificationId: Scalars['ID']['output']; orderLine: OrderLine; orderLineId: Scalars['ID']['output']; quantity: Scalars['Int']['output']; }; /** Returned when attempting to modify the contents of an Order that is not in the `Modifying` state. */ export type OrderModificationStateError = ErrorResult & { __typename?: 'OrderModificationStateError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type OrderProcessState = { __typename?: 'OrderProcessState'; name: Scalars['String']['output']; to: Array<Scalars['String']['output']>; }; export type OrderSortParameter = { aggregateOrderId?: InputMaybe<SortOrder>; code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; customerLastName?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; orderPlacedAt?: InputMaybe<SortOrder>; shipping?: InputMaybe<SortOrder>; shippingWithTax?: InputMaybe<SortOrder>; state?: InputMaybe<SortOrder>; subTotal?: InputMaybe<SortOrder>; subTotalWithTax?: InputMaybe<SortOrder>; total?: InputMaybe<SortOrder>; totalQuantity?: InputMaybe<SortOrder>; totalWithTax?: InputMaybe<SortOrder>; transactionId?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; /** Returned if there is an error in transitioning the Order state */ export type OrderStateTransitionError = ErrorResult & { __typename?: 'OrderStateTransitionError'; errorCode: ErrorCode; fromState: Scalars['String']['output']; message: Scalars['String']['output']; toState: Scalars['String']['output']; transitionError: Scalars['String']['output']; }; /** * A summary of the taxes being applied to this order, grouped * by taxRate. */ export type OrderTaxSummary = { __typename?: 'OrderTaxSummary'; /** A description of this tax */ description: Scalars['String']['output']; /** The total net price of OrderLines to which this taxRate applies */ taxBase: Scalars['Money']['output']; /** The taxRate as a percentage */ taxRate: Scalars['Float']['output']; /** The total tax being applied to the Order at this taxRate */ taxTotal: Scalars['Money']['output']; }; export enum OrderType { Aggregate = 'Aggregate', Regular = 'Regular', Seller = 'Seller' } export type PaginatedList = { items: Array<Node>; totalItems: Scalars['Int']['output']; }; export type Payment = Node & { __typename?: 'Payment'; amount: Scalars['Money']['output']; createdAt: Scalars['DateTime']['output']; errorMessage?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; metadata?: Maybe<Scalars['JSON']['output']>; method: Scalars['String']['output']; nextStates: Array<Scalars['String']['output']>; refunds: Array<Refund>; state: Scalars['String']['output']; transactionId?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; export type PaymentMethod = Node & { __typename?: 'PaymentMethod'; checker?: Maybe<ConfigurableOperation>; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; handler: ConfigurableOperation; id: Scalars['ID']['output']; name: Scalars['String']['output']; translations: Array<PaymentMethodTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type PaymentMethodFilterParameter = { _and?: InputMaybe<Array<PaymentMethodFilterParameter>>; _or?: InputMaybe<Array<PaymentMethodFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; enabled?: InputMaybe<BooleanOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type PaymentMethodList = PaginatedList & { __typename?: 'PaymentMethodList'; items: Array<PaymentMethod>; totalItems: Scalars['Int']['output']; }; export type PaymentMethodListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<PaymentMethodFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<PaymentMethodSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; /** * Returned when a call to modifyOrder fails to include a paymentMethod even * though the price has increased as a result of the changes. */ export type PaymentMethodMissingError = ErrorResult & { __typename?: 'PaymentMethodMissingError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type PaymentMethodQuote = { __typename?: 'PaymentMethodQuote'; code: Scalars['String']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; eligibilityMessage?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; isEligible: Scalars['Boolean']['output']; name: Scalars['String']['output']; }; export type PaymentMethodSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type PaymentMethodTranslation = { __typename?: 'PaymentMethodTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type PaymentMethodTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; /** Returned if an attempting to refund a Payment against OrderLines from a different Order */ export type PaymentOrderMismatchError = ErrorResult & { __typename?: 'PaymentOrderMismatchError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when there is an error in transitioning the Payment state */ export type PaymentStateTransitionError = ErrorResult & { __typename?: 'PaymentStateTransitionError'; errorCode: ErrorCode; fromState: Scalars['String']['output']; message: Scalars['String']['output']; toState: Scalars['String']['output']; transitionError: Scalars['String']['output']; }; /** * @description * Permissions for administrators and customers. Used to control access to * GraphQL resolvers via the {@link Allow} decorator. * * ## Understanding Permission.Owner * * `Permission.Owner` is a special permission which is used in some Vendure resolvers to indicate that that resolver should only * be accessible to the "owner" of that resource. * * For example, the Shop API `activeCustomer` query resolver should only return the Customer object for the "owner" of that Customer, i.e. * based on the activeUserId of the current session. As a result, the resolver code looks like this: * * @example * ```TypeScript * \@Query() * \@Allow(Permission.Owner) * async activeCustomer(\@Ctx() ctx: RequestContext): Promise<Customer | undefined> { * const userId = ctx.activeUserId; * if (userId) { * return this.customerService.findOneByUserId(ctx, userId); * } * } * ``` * * Here we can see that the "ownership" must be enforced by custom logic inside the resolver. Since "ownership" cannot be defined generally * nor statically encoded at build-time, any resolvers using `Permission.Owner` **must** include logic to enforce that only the owner * of the resource has access. If not, then it is the equivalent of using `Permission.Public`. * * * @docsCategory common */ export enum Permission { /** Authenticated means simply that the user is logged in */ Authenticated = 'Authenticated', /** Grants permission to create Administrator */ CreateAdministrator = 'CreateAdministrator', /** Grants permission to create Asset */ CreateAsset = 'CreateAsset', /** Grants permission to create Products, Facets, Assets, Collections */ CreateCatalog = 'CreateCatalog', /** Grants permission to create Channel */ CreateChannel = 'CreateChannel', /** Grants permission to create Collection */ CreateCollection = 'CreateCollection', /** Grants permission to create Country */ CreateCountry = 'CreateCountry', /** Grants permission to create Customer */ CreateCustomer = 'CreateCustomer', /** Grants permission to create CustomerGroup */ CreateCustomerGroup = 'CreateCustomerGroup', /** Grants permission to create Facet */ CreateFacet = 'CreateFacet', /** Grants permission to create Order */ CreateOrder = 'CreateOrder', /** Grants permission to create PaymentMethod */ CreatePaymentMethod = 'CreatePaymentMethod', /** Grants permission to create Product */ CreateProduct = 'CreateProduct', /** Grants permission to create Promotion */ CreatePromotion = 'CreatePromotion', /** Grants permission to create Seller */ CreateSeller = 'CreateSeller', /** Grants permission to create PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ CreateSettings = 'CreateSettings', /** Grants permission to create ShippingMethod */ CreateShippingMethod = 'CreateShippingMethod', /** Grants permission to create StockLocation */ CreateStockLocation = 'CreateStockLocation', /** Grants permission to create System */ CreateSystem = 'CreateSystem', /** Grants permission to create Tag */ CreateTag = 'CreateTag', /** Grants permission to create TaxCategory */ CreateTaxCategory = 'CreateTaxCategory', /** Grants permission to create TaxRate */ CreateTaxRate = 'CreateTaxRate', /** Grants permission to create Zone */ CreateZone = 'CreateZone', /** Grants permission to delete Administrator */ DeleteAdministrator = 'DeleteAdministrator', /** Grants permission to delete Asset */ DeleteAsset = 'DeleteAsset', /** Grants permission to delete Products, Facets, Assets, Collections */ DeleteCatalog = 'DeleteCatalog', /** Grants permission to delete Channel */ DeleteChannel = 'DeleteChannel', /** Grants permission to delete Collection */ DeleteCollection = 'DeleteCollection', /** Grants permission to delete Country */ DeleteCountry = 'DeleteCountry', /** Grants permission to delete Customer */ DeleteCustomer = 'DeleteCustomer', /** Grants permission to delete CustomerGroup */ DeleteCustomerGroup = 'DeleteCustomerGroup', /** Grants permission to delete Facet */ DeleteFacet = 'DeleteFacet', /** Grants permission to delete Order */ DeleteOrder = 'DeleteOrder', /** Grants permission to delete PaymentMethod */ DeletePaymentMethod = 'DeletePaymentMethod', /** Grants permission to delete Product */ DeleteProduct = 'DeleteProduct', /** Grants permission to delete Promotion */ DeletePromotion = 'DeletePromotion', /** Grants permission to delete Seller */ DeleteSeller = 'DeleteSeller', /** Grants permission to delete PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ DeleteSettings = 'DeleteSettings', /** Grants permission to delete ShippingMethod */ DeleteShippingMethod = 'DeleteShippingMethod', /** Grants permission to delete StockLocation */ DeleteStockLocation = 'DeleteStockLocation', /** Grants permission to delete System */ DeleteSystem = 'DeleteSystem', /** Grants permission to delete Tag */ DeleteTag = 'DeleteTag', /** Grants permission to delete TaxCategory */ DeleteTaxCategory = 'DeleteTaxCategory', /** Grants permission to delete TaxRate */ DeleteTaxRate = 'DeleteTaxRate', /** Grants permission to delete Zone */ DeleteZone = 'DeleteZone', /** Owner means the user owns this entity, e.g. a Customer's own Order */ Owner = 'Owner', /** Public means any unauthenticated user may perform the operation */ Public = 'Public', /** Grants permission to read Administrator */ ReadAdministrator = 'ReadAdministrator', /** Grants permission to read Asset */ ReadAsset = 'ReadAsset', /** Grants permission to read Products, Facets, Assets, Collections */ ReadCatalog = 'ReadCatalog', /** Grants permission to read Channel */ ReadChannel = 'ReadChannel', /** Grants permission to read Collection */ ReadCollection = 'ReadCollection', /** Grants permission to read Country */ ReadCountry = 'ReadCountry', /** Grants permission to read Customer */ ReadCustomer = 'ReadCustomer', /** Grants permission to read CustomerGroup */ ReadCustomerGroup = 'ReadCustomerGroup', /** Grants permission to read Facet */ ReadFacet = 'ReadFacet', /** Grants permission to read Order */ ReadOrder = 'ReadOrder', /** Grants permission to read PaymentMethod */ ReadPaymentMethod = 'ReadPaymentMethod', /** Grants permission to read Product */ ReadProduct = 'ReadProduct', /** Grants permission to read Promotion */ ReadPromotion = 'ReadPromotion', /** Grants permission to read Seller */ ReadSeller = 'ReadSeller', /** Grants permission to read PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ ReadSettings = 'ReadSettings', /** Grants permission to read ShippingMethod */ ReadShippingMethod = 'ReadShippingMethod', /** Grants permission to read StockLocation */ ReadStockLocation = 'ReadStockLocation', /** Grants permission to read System */ ReadSystem = 'ReadSystem', /** Grants permission to read Tag */ ReadTag = 'ReadTag', /** Grants permission to read TaxCategory */ ReadTaxCategory = 'ReadTaxCategory', /** Grants permission to read TaxRate */ ReadTaxRate = 'ReadTaxRate', /** Grants permission to read Zone */ ReadZone = 'ReadZone', /** SuperAdmin has unrestricted access to all operations */ SuperAdmin = 'SuperAdmin', /** Grants permission to update Administrator */ UpdateAdministrator = 'UpdateAdministrator', /** Grants permission to update Asset */ UpdateAsset = 'UpdateAsset', /** Grants permission to update Products, Facets, Assets, Collections */ UpdateCatalog = 'UpdateCatalog', /** Grants permission to update Channel */ UpdateChannel = 'UpdateChannel', /** Grants permission to update Collection */ UpdateCollection = 'UpdateCollection', /** Grants permission to update Country */ UpdateCountry = 'UpdateCountry', /** Grants permission to update Customer */ UpdateCustomer = 'UpdateCustomer', /** Grants permission to update CustomerGroup */ UpdateCustomerGroup = 'UpdateCustomerGroup', /** Grants permission to update Facet */ UpdateFacet = 'UpdateFacet', /** Grants permission to update GlobalSettings */ UpdateGlobalSettings = 'UpdateGlobalSettings', /** Grants permission to update Order */ UpdateOrder = 'UpdateOrder', /** Grants permission to update PaymentMethod */ UpdatePaymentMethod = 'UpdatePaymentMethod', /** Grants permission to update Product */ UpdateProduct = 'UpdateProduct', /** Grants permission to update Promotion */ UpdatePromotion = 'UpdatePromotion', /** Grants permission to update Seller */ UpdateSeller = 'UpdateSeller', /** Grants permission to update PaymentMethods, ShippingMethods, TaxCategories, TaxRates, Zones, Countries, System & GlobalSettings */ UpdateSettings = 'UpdateSettings', /** Grants permission to update ShippingMethod */ UpdateShippingMethod = 'UpdateShippingMethod', /** Grants permission to update StockLocation */ UpdateStockLocation = 'UpdateStockLocation', /** Grants permission to update System */ UpdateSystem = 'UpdateSystem', /** Grants permission to update Tag */ UpdateTag = 'UpdateTag', /** Grants permission to update TaxCategory */ UpdateTaxCategory = 'UpdateTaxCategory', /** Grants permission to update TaxRate */ UpdateTaxRate = 'UpdateTaxRate', /** Grants permission to update Zone */ UpdateZone = 'UpdateZone' } export type PermissionDefinition = { __typename?: 'PermissionDefinition'; assignable: Scalars['Boolean']['output']; description: Scalars['String']['output']; name: Scalars['String']['output']; }; export type PreviewCollectionVariantsInput = { filters: Array<ConfigurableOperationInput>; inheritFilters: Scalars['Boolean']['input']; parentId?: InputMaybe<Scalars['ID']['input']>; }; /** The price range where the result has more than one price */ export type PriceRange = { __typename?: 'PriceRange'; max: Scalars['Money']['output']; min: Scalars['Money']['output']; }; export type Product = Node & { __typename?: 'Product'; assets: Array<Asset>; channels: Array<Channel>; collections: Array<Collection>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; facetValues: Array<FacetValue>; featuredAsset?: Maybe<Asset>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; optionGroups: Array<ProductOptionGroup>; slug: Scalars['String']['output']; translations: Array<ProductTranslation>; updatedAt: Scalars['DateTime']['output']; /** Returns a paginated, sortable, filterable list of ProductVariants */ variantList: ProductVariantList; /** Returns all ProductVariants */ variants: Array<ProductVariant>; }; export type ProductVariantListArgs = { options?: InputMaybe<ProductVariantListOptions>; }; export type ProductFilterParameter = { _and?: InputMaybe<Array<ProductFilterParameter>>; _or?: InputMaybe<Array<ProductFilterParameter>>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; enabled?: InputMaybe<BooleanOperators>; facetValueId?: InputMaybe<IdOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; sku?: InputMaybe<StringOperators>; slug?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ProductList = PaginatedList & { __typename?: 'ProductList'; items: Array<Product>; totalItems: Scalars['Int']['output']; }; export type ProductListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ProductFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ProductSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ProductOption = Node & { __typename?: 'ProductOption'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; group: ProductOptionGroup; groupId: Scalars['ID']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<ProductOptionTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionGroup = Node & { __typename?: 'ProductOptionGroup'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; options: Array<ProductOption>; translations: Array<ProductOptionGroupTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionGroupTranslation = { __typename?: 'ProductOptionGroupTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionGroupTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; export type ProductOptionInUseError = ErrorResult & { __typename?: 'ProductOptionInUseError'; errorCode: ErrorCode; message: Scalars['String']['output']; optionGroupCode: Scalars['String']['output']; productVariantCount: Scalars['Int']['output']; }; export type ProductOptionTranslation = { __typename?: 'ProductOptionTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductOptionTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; export type ProductSortParameter = { createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; slug?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ProductTranslation = { __typename?: 'ProductTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; slug: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; slug?: InputMaybe<Scalars['String']['input']>; }; export type ProductVariant = Node & { __typename?: 'ProductVariant'; assets: Array<Asset>; channels: Array<Channel>; createdAt: Scalars['DateTime']['output']; currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; enabled: Scalars['Boolean']['output']; facetValues: Array<FacetValue>; featuredAsset?: Maybe<Asset>; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; options: Array<ProductOption>; outOfStockThreshold: Scalars['Int']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; prices: Array<ProductVariantPrice>; product: Product; productId: Scalars['ID']['output']; sku: Scalars['String']['output']; /** @deprecated use stockLevels */ stockAllocated: Scalars['Int']['output']; stockLevel: Scalars['String']['output']; stockLevels: Array<StockLevel>; stockMovements: StockMovementList; /** @deprecated use stockLevels */ stockOnHand: Scalars['Int']['output']; taxCategory: TaxCategory; taxRateApplied: TaxRate; trackInventory: GlobalFlag; translations: Array<ProductVariantTranslation>; updatedAt: Scalars['DateTime']['output']; useGlobalOutOfStockThreshold: Scalars['Boolean']['output']; }; export type ProductVariantStockMovementsArgs = { options?: InputMaybe<StockMovementListOptions>; }; export type ProductVariantFilterParameter = { _and?: InputMaybe<Array<ProductVariantFilterParameter>>; _or?: InputMaybe<Array<ProductVariantFilterParameter>>; createdAt?: InputMaybe<DateOperators>; currencyCode?: InputMaybe<StringOperators>; enabled?: InputMaybe<BooleanOperators>; facetValueId?: InputMaybe<IdOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; outOfStockThreshold?: InputMaybe<NumberOperators>; price?: InputMaybe<NumberOperators>; priceWithTax?: InputMaybe<NumberOperators>; productId?: InputMaybe<IdOperators>; sku?: InputMaybe<StringOperators>; stockAllocated?: InputMaybe<NumberOperators>; stockLevel?: InputMaybe<StringOperators>; stockOnHand?: InputMaybe<NumberOperators>; trackInventory?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; useGlobalOutOfStockThreshold?: InputMaybe<BooleanOperators>; }; export type ProductVariantList = PaginatedList & { __typename?: 'ProductVariantList'; items: Array<ProductVariant>; totalItems: Scalars['Int']['output']; }; export type ProductVariantListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ProductVariantFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ProductVariantSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ProductVariantPrice = { __typename?: 'ProductVariantPrice'; currencyCode: CurrencyCode; customFields?: Maybe<Scalars['JSON']['output']>; price: Scalars['Money']['output']; }; /** * Used to set up update the price of a ProductVariant in a particular Channel. * If the `delete` flag is `true`, the price will be deleted for the given Channel. */ export type ProductVariantPriceInput = { currencyCode: CurrencyCode; delete?: InputMaybe<Scalars['Boolean']['input']>; price: Scalars['Money']['input']; }; export type ProductVariantSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; outOfStockThreshold?: InputMaybe<SortOrder>; price?: InputMaybe<SortOrder>; priceWithTax?: InputMaybe<SortOrder>; productId?: InputMaybe<SortOrder>; sku?: InputMaybe<SortOrder>; stockAllocated?: InputMaybe<SortOrder>; stockLevel?: InputMaybe<SortOrder>; stockOnHand?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ProductVariantTranslation = { __typename?: 'ProductVariantTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProductVariantTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; export type Promotion = Node & { __typename?: 'Promotion'; actions: Array<ConfigurableOperation>; conditions: Array<ConfigurableOperation>; couponCode?: Maybe<Scalars['String']['output']>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; endsAt?: Maybe<Scalars['DateTime']['output']>; id: Scalars['ID']['output']; name: Scalars['String']['output']; perCustomerUsageLimit?: Maybe<Scalars['Int']['output']>; startsAt?: Maybe<Scalars['DateTime']['output']>; translations: Array<PromotionTranslation>; updatedAt: Scalars['DateTime']['output']; usageLimit?: Maybe<Scalars['Int']['output']>; }; export type PromotionFilterParameter = { _and?: InputMaybe<Array<PromotionFilterParameter>>; _or?: InputMaybe<Array<PromotionFilterParameter>>; couponCode?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; enabled?: InputMaybe<BooleanOperators>; endsAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; perCustomerUsageLimit?: InputMaybe<NumberOperators>; startsAt?: InputMaybe<DateOperators>; updatedAt?: InputMaybe<DateOperators>; usageLimit?: InputMaybe<NumberOperators>; }; export type PromotionList = PaginatedList & { __typename?: 'PromotionList'; items: Array<Promotion>; totalItems: Scalars['Int']['output']; }; export type PromotionListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<PromotionFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<PromotionSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type PromotionSortParameter = { couponCode?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; endsAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; perCustomerUsageLimit?: InputMaybe<SortOrder>; startsAt?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; usageLimit?: InputMaybe<SortOrder>; }; export type PromotionTranslation = { __typename?: 'PromotionTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type PromotionTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; export type Province = Node & Region & { __typename?: 'Province'; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; parent?: Maybe<Region>; parentId?: Maybe<Scalars['ID']['output']>; translations: Array<RegionTranslation>; type: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ProvinceFilterParameter = { _and?: InputMaybe<Array<ProvinceFilterParameter>>; _or?: InputMaybe<Array<ProvinceFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; enabled?: InputMaybe<BooleanOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; parentId?: InputMaybe<IdOperators>; type?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ProvinceList = PaginatedList & { __typename?: 'ProvinceList'; items: Array<Province>; totalItems: Scalars['Int']['output']; }; export type ProvinceListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ProvinceFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ProvinceSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ProvinceSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; parentId?: InputMaybe<SortOrder>; type?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ProvinceTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; /** Returned if the specified quantity of an OrderLine is greater than the number of items in that line */ export type QuantityTooGreatError = ErrorResult & { __typename?: 'QuantityTooGreatError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Query = { __typename?: 'Query'; activeAdministrator?: Maybe<Administrator>; activeChannel: Channel; administrator?: Maybe<Administrator>; administrators: AdministratorList; /** Get a single Asset by id */ asset?: Maybe<Asset>; /** Get a list of Assets */ assets: AssetList; channel?: Maybe<Channel>; channels: ChannelList; /** Get a Collection either by id or slug. If neither id nor slug is specified, an error will result. */ collection?: Maybe<Collection>; collectionFilters: Array<ConfigurableOperationDefinition>; collections: CollectionList; countries: CountryList; country?: Maybe<Country>; customer?: Maybe<Customer>; customerGroup?: Maybe<CustomerGroup>; customerGroups: CustomerGroupList; customers: CustomerList; /** Returns a list of eligible shipping methods for the draft Order */ eligibleShippingMethodsForDraftOrder: Array<ShippingMethodQuote>; entityDuplicators: Array<EntityDuplicatorDefinition>; facet?: Maybe<Facet>; facetValues: FacetValueList; facets: FacetList; fulfillmentHandlers: Array<ConfigurableOperationDefinition>; globalSettings: GlobalSettings; job?: Maybe<Job>; jobBufferSize: Array<JobBufferSize>; jobQueues: Array<JobQueue>; jobs: JobList; jobsById: Array<Job>; me?: Maybe<CurrentUser>; /** Get metrics for the given interval and metric types. */ metricSummary: Array<MetricSummary>; order?: Maybe<Order>; orders: OrderList; paymentMethod?: Maybe<PaymentMethod>; paymentMethodEligibilityCheckers: Array<ConfigurableOperationDefinition>; paymentMethodHandlers: Array<ConfigurableOperationDefinition>; paymentMethods: PaymentMethodList; pendingSearchIndexUpdates: Scalars['Int']['output']; /** Used for real-time previews of the contents of a Collection */ previewCollectionVariants: ProductVariantList; /** Get a Product either by id or slug. If neither id nor slug is specified, an error will result. */ product?: Maybe<Product>; productOptionGroup?: Maybe<ProductOptionGroup>; productOptionGroups: Array<ProductOptionGroup>; /** Get a ProductVariant by id */ productVariant?: Maybe<ProductVariant>; /** List ProductVariants either all or for the specific product. */ productVariants: ProductVariantList; /** List Products */ products: ProductList; promotion?: Maybe<Promotion>; promotionActions: Array<ConfigurableOperationDefinition>; promotionConditions: Array<ConfigurableOperationDefinition>; promotions: PromotionList; province?: Maybe<Province>; provinces: ProvinceList; role?: Maybe<Role>; roles: RoleList; search: SearchResponse; seller?: Maybe<Seller>; sellers: SellerList; shippingCalculators: Array<ConfigurableOperationDefinition>; shippingEligibilityCheckers: Array<ConfigurableOperationDefinition>; shippingMethod?: Maybe<ShippingMethod>; shippingMethods: ShippingMethodList; stockLocation?: Maybe<StockLocation>; stockLocations: StockLocationList; tag: Tag; tags: TagList; taxCategories: TaxCategoryList; taxCategory?: Maybe<TaxCategory>; taxRate?: Maybe<TaxRate>; taxRates: TaxRateList; testEligibleShippingMethods: Array<ShippingMethodQuote>; testShippingMethod: TestShippingMethodResult; zone?: Maybe<Zone>; zones: ZoneList; }; export type QueryAdministratorArgs = { id: Scalars['ID']['input']; }; export type QueryAdministratorsArgs = { options?: InputMaybe<AdministratorListOptions>; }; export type QueryAssetArgs = { id: Scalars['ID']['input']; }; export type QueryAssetsArgs = { options?: InputMaybe<AssetListOptions>; }; export type QueryChannelArgs = { id: Scalars['ID']['input']; }; export type QueryChannelsArgs = { options?: InputMaybe<ChannelListOptions>; }; export type QueryCollectionArgs = { id?: InputMaybe<Scalars['ID']['input']>; slug?: InputMaybe<Scalars['String']['input']>; }; export type QueryCollectionsArgs = { options?: InputMaybe<CollectionListOptions>; }; export type QueryCountriesArgs = { options?: InputMaybe<CountryListOptions>; }; export type QueryCountryArgs = { id: Scalars['ID']['input']; }; export type QueryCustomerArgs = { id: Scalars['ID']['input']; }; export type QueryCustomerGroupArgs = { id: Scalars['ID']['input']; }; export type QueryCustomerGroupsArgs = { options?: InputMaybe<CustomerGroupListOptions>; }; export type QueryCustomersArgs = { options?: InputMaybe<CustomerListOptions>; }; export type QueryEligibleShippingMethodsForDraftOrderArgs = { orderId: Scalars['ID']['input']; }; export type QueryFacetArgs = { id: Scalars['ID']['input']; }; export type QueryFacetValuesArgs = { options?: InputMaybe<FacetValueListOptions>; }; export type QueryFacetsArgs = { options?: InputMaybe<FacetListOptions>; }; export type QueryJobArgs = { jobId: Scalars['ID']['input']; }; export type QueryJobBufferSizeArgs = { bufferIds?: InputMaybe<Array<Scalars['String']['input']>>; }; export type QueryJobsArgs = { options?: InputMaybe<JobListOptions>; }; export type QueryJobsByIdArgs = { jobIds: Array<Scalars['ID']['input']>; }; export type QueryMetricSummaryArgs = { input?: InputMaybe<MetricSummaryInput>; }; export type QueryOrderArgs = { id: Scalars['ID']['input']; }; export type QueryOrdersArgs = { options?: InputMaybe<OrderListOptions>; }; export type QueryPaymentMethodArgs = { id: Scalars['ID']['input']; }; export type QueryPaymentMethodsArgs = { options?: InputMaybe<PaymentMethodListOptions>; }; export type QueryPreviewCollectionVariantsArgs = { input: PreviewCollectionVariantsInput; options?: InputMaybe<ProductVariantListOptions>; }; export type QueryProductArgs = { id?: InputMaybe<Scalars['ID']['input']>; slug?: InputMaybe<Scalars['String']['input']>; }; export type QueryProductOptionGroupArgs = { id: Scalars['ID']['input']; }; export type QueryProductOptionGroupsArgs = { filterTerm?: InputMaybe<Scalars['String']['input']>; }; export type QueryProductVariantArgs = { id: Scalars['ID']['input']; }; export type QueryProductVariantsArgs = { options?: InputMaybe<ProductVariantListOptions>; productId?: InputMaybe<Scalars['ID']['input']>; }; export type QueryProductsArgs = { options?: InputMaybe<ProductListOptions>; }; export type QueryPromotionArgs = { id: Scalars['ID']['input']; }; export type QueryPromotionsArgs = { options?: InputMaybe<PromotionListOptions>; }; export type QueryProvinceArgs = { id: Scalars['ID']['input']; }; export type QueryProvincesArgs = { options?: InputMaybe<ProvinceListOptions>; }; export type QueryRoleArgs = { id: Scalars['ID']['input']; }; export type QueryRolesArgs = { options?: InputMaybe<RoleListOptions>; }; export type QuerySearchArgs = { input: SearchInput; }; export type QuerySellerArgs = { id: Scalars['ID']['input']; }; export type QuerySellersArgs = { options?: InputMaybe<SellerListOptions>; }; export type QueryShippingMethodArgs = { id: Scalars['ID']['input']; }; export type QueryShippingMethodsArgs = { options?: InputMaybe<ShippingMethodListOptions>; }; export type QueryStockLocationArgs = { id: Scalars['ID']['input']; }; export type QueryStockLocationsArgs = { options?: InputMaybe<StockLocationListOptions>; }; export type QueryTagArgs = { id: Scalars['ID']['input']; }; export type QueryTagsArgs = { options?: InputMaybe<TagListOptions>; }; export type QueryTaxCategoriesArgs = { options?: InputMaybe<TaxCategoryListOptions>; }; export type QueryTaxCategoryArgs = { id: Scalars['ID']['input']; }; export type QueryTaxRateArgs = { id: Scalars['ID']['input']; }; export type QueryTaxRatesArgs = { options?: InputMaybe<TaxRateListOptions>; }; export type QueryTestEligibleShippingMethodsArgs = { input: TestEligibleShippingMethodsInput; }; export type QueryTestShippingMethodArgs = { input: TestShippingMethodInput; }; export type QueryZoneArgs = { id: Scalars['ID']['input']; }; export type QueryZonesArgs = { options?: InputMaybe<ZoneListOptions>; }; export type Refund = Node & { __typename?: 'Refund'; adjustment: Scalars['Money']['output']; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; items: Scalars['Money']['output']; lines: Array<RefundLine>; metadata?: Maybe<Scalars['JSON']['output']>; method?: Maybe<Scalars['String']['output']>; paymentId: Scalars['ID']['output']; reason?: Maybe<Scalars['String']['output']>; shipping: Scalars['Money']['output']; state: Scalars['String']['output']; total: Scalars['Money']['output']; transactionId?: Maybe<Scalars['String']['output']>; updatedAt: Scalars['DateTime']['output']; }; /** Returned if `amount` is greater than the maximum un-refunded amount of the Payment */ export type RefundAmountError = ErrorResult & { __typename?: 'RefundAmountError'; errorCode: ErrorCode; maximumRefundable: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type RefundLine = { __typename?: 'RefundLine'; orderLine: OrderLine; orderLineId: Scalars['ID']['output']; quantity: Scalars['Int']['output']; refund: Refund; refundId: Scalars['ID']['output']; }; export type RefundOrderInput = { adjustment: Scalars['Money']['input']; /** * If an amount is specified, this value will be used to create a Refund rather than calculating the * amount automatically. This was added in v2.2 and will be the preferred way to specify the refund * amount in the future. The `lines`, `shipping` and `adjustment` fields will likely be removed in a future * version. */ amount?: InputMaybe<Scalars['Money']['input']>; lines: Array<OrderLineInput>; paymentId: Scalars['ID']['input']; reason?: InputMaybe<Scalars['String']['input']>; shipping: Scalars['Money']['input']; }; export type RefundOrderResult = AlreadyRefundedError | MultipleOrderError | NothingToRefundError | OrderStateTransitionError | PaymentOrderMismatchError | QuantityTooGreatError | Refund | RefundAmountError | RefundOrderStateError | RefundStateTransitionError; /** Returned if an attempting to refund an Order which is not in the expected state */ export type RefundOrderStateError = ErrorResult & { __typename?: 'RefundOrderStateError'; errorCode: ErrorCode; message: Scalars['String']['output']; orderState: Scalars['String']['output']; }; /** * Returned when a call to modifyOrder fails to include a refundPaymentId even * though the price has decreased as a result of the changes. */ export type RefundPaymentIdMissingError = ErrorResult & { __typename?: 'RefundPaymentIdMissingError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when there is an error in transitioning the Refund state */ export type RefundStateTransitionError = ErrorResult & { __typename?: 'RefundStateTransitionError'; errorCode: ErrorCode; fromState: Scalars['String']['output']; message: Scalars['String']['output']; toState: Scalars['String']['output']; transitionError: Scalars['String']['output']; }; export type Region = { code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; parent?: Maybe<Region>; parentId?: Maybe<Scalars['ID']['output']>; translations: Array<RegionTranslation>; type: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type RegionTranslation = { __typename?: 'RegionTranslation'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type RelationCustomFieldConfig = CustomField & { __typename?: 'RelationCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; entity: Scalars['String']['output']; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; scalarFields: Array<Scalars['String']['output']>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type Release = Node & StockMovement & { __typename?: 'Release'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type RemoveCollectionsFromChannelInput = { channelId: Scalars['ID']['input']; collectionIds: Array<Scalars['ID']['input']>; }; export type RemoveFacetFromChannelResult = Facet | FacetInUseError; export type RemoveFacetsFromChannelInput = { channelId: Scalars['ID']['input']; facetIds: Array<Scalars['ID']['input']>; force?: InputMaybe<Scalars['Boolean']['input']>; }; export type RemoveOptionGroupFromProductResult = Product | ProductOptionInUseError; export type RemoveOrderItemsResult = Order | OrderModificationError; export type RemovePaymentMethodsFromChannelInput = { channelId: Scalars['ID']['input']; paymentMethodIds: Array<Scalars['ID']['input']>; }; export type RemoveProductVariantsFromChannelInput = { channelId: Scalars['ID']['input']; productVariantIds: Array<Scalars['ID']['input']>; }; export type RemoveProductsFromChannelInput = { channelId: Scalars['ID']['input']; productIds: Array<Scalars['ID']['input']>; }; export type RemovePromotionsFromChannelInput = { channelId: Scalars['ID']['input']; promotionIds: Array<Scalars['ID']['input']>; }; export type RemoveShippingMethodsFromChannelInput = { channelId: Scalars['ID']['input']; shippingMethodIds: Array<Scalars['ID']['input']>; }; export type RemoveStockLocationsFromChannelInput = { channelId: Scalars['ID']['input']; stockLocationIds: Array<Scalars['ID']['input']>; }; export type Return = Node & StockMovement & { __typename?: 'Return'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type Role = Node & { __typename?: 'Role'; channels: Array<Channel>; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; permissions: Array<Permission>; updatedAt: Scalars['DateTime']['output']; }; export type RoleFilterParameter = { _and?: InputMaybe<Array<RoleFilterParameter>>; _or?: InputMaybe<Array<RoleFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type RoleList = PaginatedList & { __typename?: 'RoleList'; items: Array<Role>; totalItems: Scalars['Int']['output']; }; export type RoleListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<RoleFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<RoleSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type RoleSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type Sale = Node & StockMovement & { __typename?: 'Sale'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type SearchInput = { collectionId?: InputMaybe<Scalars['ID']['input']>; collectionSlug?: InputMaybe<Scalars['String']['input']>; facetValueFilters?: InputMaybe<Array<FacetValueFilterInput>>; /** @deprecated Use `facetValueFilters` instead */ facetValueIds?: InputMaybe<Array<Scalars['ID']['input']>>; /** @deprecated Use `facetValueFilters` instead */ facetValueOperator?: InputMaybe<LogicalOperator>; groupByProduct?: InputMaybe<Scalars['Boolean']['input']>; skip?: InputMaybe<Scalars['Int']['input']>; sort?: InputMaybe<SearchResultSortParameter>; take?: InputMaybe<Scalars['Int']['input']>; term?: InputMaybe<Scalars['String']['input']>; }; export type SearchReindexResponse = { __typename?: 'SearchReindexResponse'; success: Scalars['Boolean']['output']; }; export type SearchResponse = { __typename?: 'SearchResponse'; collections: Array<CollectionResult>; facetValues: Array<FacetValueResult>; items: Array<SearchResult>; totalItems: Scalars['Int']['output']; }; export type SearchResult = { __typename?: 'SearchResult'; /** An array of ids of the Channels in which this result appears */ channelIds: Array<Scalars['ID']['output']>; /** An array of ids of the Collections in which this result appears */ collectionIds: Array<Scalars['ID']['output']>; currencyCode: CurrencyCode; description: Scalars['String']['output']; enabled: Scalars['Boolean']['output']; facetIds: Array<Scalars['ID']['output']>; facetValueIds: Array<Scalars['ID']['output']>; price: SearchResultPrice; priceWithTax: SearchResultPrice; productAsset?: Maybe<SearchResultAsset>; productId: Scalars['ID']['output']; productName: Scalars['String']['output']; productVariantAsset?: Maybe<SearchResultAsset>; productVariantId: Scalars['ID']['output']; productVariantName: Scalars['String']['output']; /** A relevance score for the result. Differs between database implementations */ score: Scalars['Float']['output']; sku: Scalars['String']['output']; slug: Scalars['String']['output']; }; export type SearchResultAsset = { __typename?: 'SearchResultAsset'; focalPoint?: Maybe<Coordinate>; id: Scalars['ID']['output']; preview: Scalars['String']['output']; }; /** The price of a search result product, either as a range or as a single price */ export type SearchResultPrice = PriceRange | SinglePrice; export type SearchResultSortParameter = { name?: InputMaybe<SortOrder>; price?: InputMaybe<SortOrder>; }; export type Seller = Node & { __typename?: 'Seller'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type SellerFilterParameter = { _and?: InputMaybe<Array<SellerFilterParameter>>; _or?: InputMaybe<Array<SellerFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type SellerList = PaginatedList & { __typename?: 'SellerList'; items: Array<Seller>; totalItems: Scalars['Int']['output']; }; export type SellerListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<SellerFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<SellerSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type SellerSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ServerConfig = { __typename?: 'ServerConfig'; /** * This field is deprecated in v2.2 in favor of the entityCustomFields field, * which allows custom fields to be defined on user-supplies entities. */ customFieldConfig: CustomFields; entityCustomFields: Array<EntityCustomFields>; moneyStrategyPrecision: Scalars['Int']['output']; orderProcess: Array<OrderProcessState>; permissions: Array<PermissionDefinition>; permittedAssetTypes: Array<Scalars['String']['output']>; }; export type SetCustomerForDraftOrderResult = EmailAddressConflictError | Order; export type SetOrderCustomerInput = { customerId: Scalars['ID']['input']; note?: InputMaybe<Scalars['String']['input']>; orderId: Scalars['ID']['input']; }; export type SetOrderShippingMethodResult = IneligibleShippingMethodError | NoActiveOrderError | Order | OrderModificationError; /** Returned if the Payment settlement fails */ export type SettlePaymentError = ErrorResult & { __typename?: 'SettlePaymentError'; errorCode: ErrorCode; message: Scalars['String']['output']; paymentErrorMessage: Scalars['String']['output']; }; export type SettlePaymentResult = OrderStateTransitionError | Payment | PaymentStateTransitionError | SettlePaymentError; export type SettleRefundInput = { id: Scalars['ID']['input']; transactionId: Scalars['String']['input']; }; export type SettleRefundResult = Refund | RefundStateTransitionError; export type ShippingLine = { __typename?: 'ShippingLine'; discountedPrice: Scalars['Money']['output']; discountedPriceWithTax: Scalars['Money']['output']; discounts: Array<Discount>; id: Scalars['ID']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; shippingMethod: ShippingMethod; }; export type ShippingMethod = Node & { __typename?: 'ShippingMethod'; calculator: ConfigurableOperation; checker: ConfigurableOperation; code: Scalars['String']['output']; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; fulfillmentHandlerCode: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; translations: Array<ShippingMethodTranslation>; updatedAt: Scalars['DateTime']['output']; }; export type ShippingMethodFilterParameter = { _and?: InputMaybe<Array<ShippingMethodFilterParameter>>; _or?: InputMaybe<Array<ShippingMethodFilterParameter>>; code?: InputMaybe<StringOperators>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; fulfillmentHandlerCode?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; languageCode?: InputMaybe<StringOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ShippingMethodList = PaginatedList & { __typename?: 'ShippingMethodList'; items: Array<ShippingMethod>; totalItems: Scalars['Int']['output']; }; export type ShippingMethodListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ShippingMethodFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ShippingMethodSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ShippingMethodQuote = { __typename?: 'ShippingMethodQuote'; code: Scalars['String']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; id: Scalars['ID']['output']; /** Any optional metadata returned by the ShippingCalculator in the ShippingCalculationResult */ metadata?: Maybe<Scalars['JSON']['output']>; name: Scalars['String']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; }; export type ShippingMethodSortParameter = { code?: InputMaybe<SortOrder>; createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; fulfillmentHandlerCode?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type ShippingMethodTranslation = { __typename?: 'ShippingMethodTranslation'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ShippingMethodTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; }; /** The price value where the result has a single price */ export type SinglePrice = { __typename?: 'SinglePrice'; value: Scalars['Money']['output']; }; export enum SortOrder { ASC = 'ASC', DESC = 'DESC' } export type StockAdjustment = Node & StockMovement & { __typename?: 'StockAdjustment'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type StockLevel = Node & { __typename?: 'StockLevel'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; stockAllocated: Scalars['Int']['output']; stockLocation: StockLocation; stockLocationId: Scalars['ID']['output']; stockOnHand: Scalars['Int']['output']; updatedAt: Scalars['DateTime']['output']; }; export type StockLevelInput = { stockLocationId: Scalars['ID']['input']; stockOnHand: Scalars['Int']['input']; }; export type StockLocation = Node & { __typename?: 'StockLocation'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; description: Scalars['String']['output']; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type StockLocationFilterParameter = { _and?: InputMaybe<Array<StockLocationFilterParameter>>; _or?: InputMaybe<Array<StockLocationFilterParameter>>; createdAt?: InputMaybe<DateOperators>; description?: InputMaybe<StringOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type StockLocationList = PaginatedList & { __typename?: 'StockLocationList'; items: Array<StockLocation>; totalItems: Scalars['Int']['output']; }; export type StockLocationListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<StockLocationFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<StockLocationSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type StockLocationSortParameter = { createdAt?: InputMaybe<SortOrder>; description?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type StockMovement = { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type StockMovementItem = Allocation | Cancellation | Release | Return | Sale | StockAdjustment; export type StockMovementList = { __typename?: 'StockMovementList'; items: Array<StockMovementItem>; totalItems: Scalars['Int']['output']; }; export type StockMovementListOptions = { skip?: InputMaybe<Scalars['Int']['input']>; take?: InputMaybe<Scalars['Int']['input']>; type?: InputMaybe<StockMovementType>; }; export enum StockMovementType { ADJUSTMENT = 'ADJUSTMENT', ALLOCATION = 'ALLOCATION', CANCELLATION = 'CANCELLATION', RELEASE = 'RELEASE', RETURN = 'RETURN', SALE = 'SALE' } export type StringCustomFieldConfig = CustomField & { __typename?: 'StringCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; length?: Maybe<Scalars['Int']['output']>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; options?: Maybe<Array<StringFieldOption>>; pattern?: Maybe<Scalars['String']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type StringFieldOption = { __typename?: 'StringFieldOption'; label?: Maybe<Array<LocalizedString>>; value: Scalars['String']['output']; }; /** Operators for filtering on a list of String fields */ export type StringListOperators = { inList: Scalars['String']['input']; }; /** Operators for filtering on a String field */ export type StringOperators = { contains?: InputMaybe<Scalars['String']['input']>; eq?: InputMaybe<Scalars['String']['input']>; in?: InputMaybe<Array<Scalars['String']['input']>>; isNull?: InputMaybe<Scalars['Boolean']['input']>; notContains?: InputMaybe<Scalars['String']['input']>; notEq?: InputMaybe<Scalars['String']['input']>; notIn?: InputMaybe<Array<Scalars['String']['input']>>; regex?: InputMaybe<Scalars['String']['input']>; }; /** Indicates that an operation succeeded, where we do not want to return any more specific information. */ export type Success = { __typename?: 'Success'; success: Scalars['Boolean']['output']; }; export type Surcharge = Node & { __typename?: 'Surcharge'; createdAt: Scalars['DateTime']['output']; description: Scalars['String']['output']; id: Scalars['ID']['output']; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; sku?: Maybe<Scalars['String']['output']>; taxLines: Array<TaxLine>; taxRate: Scalars['Float']['output']; updatedAt: Scalars['DateTime']['output']; }; export type SurchargeInput = { description: Scalars['String']['input']; price: Scalars['Money']['input']; priceIncludesTax: Scalars['Boolean']['input']; sku?: InputMaybe<Scalars['String']['input']>; taxDescription?: InputMaybe<Scalars['String']['input']>; taxRate?: InputMaybe<Scalars['Float']['input']>; }; export type Tag = Node & { __typename?: 'Tag'; createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; updatedAt: Scalars['DateTime']['output']; value: Scalars['String']['output']; }; export type TagFilterParameter = { _and?: InputMaybe<Array<TagFilterParameter>>; _or?: InputMaybe<Array<TagFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; updatedAt?: InputMaybe<DateOperators>; value?: InputMaybe<StringOperators>; }; export type TagList = PaginatedList & { __typename?: 'TagList'; items: Array<Tag>; totalItems: Scalars['Int']['output']; }; export type TagListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<TagFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<TagSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type TagSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; value?: InputMaybe<SortOrder>; }; export type TaxCategory = Node & { __typename?: 'TaxCategory'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; isDefault: Scalars['Boolean']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type TaxCategoryFilterParameter = { _and?: InputMaybe<Array<TaxCategoryFilterParameter>>; _or?: InputMaybe<Array<TaxCategoryFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; isDefault?: InputMaybe<BooleanOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type TaxCategoryList = PaginatedList & { __typename?: 'TaxCategoryList'; items: Array<TaxCategory>; totalItems: Scalars['Int']['output']; }; export type TaxCategoryListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<TaxCategoryFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<TaxCategorySortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type TaxCategorySortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; }; export type TaxLine = { __typename?: 'TaxLine'; description: Scalars['String']['output']; taxRate: Scalars['Float']['output']; }; export type TaxRate = Node & { __typename?: 'TaxRate'; category: TaxCategory; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; customerGroup?: Maybe<CustomerGroup>; enabled: Scalars['Boolean']['output']; id: Scalars['ID']['output']; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; value: Scalars['Float']['output']; zone: Zone; }; export type TaxRateFilterParameter = { _and?: InputMaybe<Array<TaxRateFilterParameter>>; _or?: InputMaybe<Array<TaxRateFilterParameter>>; createdAt?: InputMaybe<DateOperators>; enabled?: InputMaybe<BooleanOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; value?: InputMaybe<NumberOperators>; }; export type TaxRateList = PaginatedList & { __typename?: 'TaxRateList'; items: Array<TaxRate>; totalItems: Scalars['Int']['output']; }; export type TaxRateListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<TaxRateFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<TaxRateSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type TaxRateSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; value?: InputMaybe<SortOrder>; }; export type TestEligibleShippingMethodsInput = { lines: Array<TestShippingMethodOrderLineInput>; shippingAddress: CreateAddressInput; }; export type TestShippingMethodInput = { calculator: ConfigurableOperationInput; checker: ConfigurableOperationInput; lines: Array<TestShippingMethodOrderLineInput>; shippingAddress: CreateAddressInput; }; export type TestShippingMethodOrderLineInput = { productVariantId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }; export type TestShippingMethodQuote = { __typename?: 'TestShippingMethodQuote'; metadata?: Maybe<Scalars['JSON']['output']>; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; }; export type TestShippingMethodResult = { __typename?: 'TestShippingMethodResult'; eligible: Scalars['Boolean']['output']; quote?: Maybe<TestShippingMethodQuote>; }; export type TextCustomFieldConfig = CustomField & { __typename?: 'TextCustomFieldConfig'; description?: Maybe<Array<LocalizedString>>; internal?: Maybe<Scalars['Boolean']['output']>; label?: Maybe<Array<LocalizedString>>; list: Scalars['Boolean']['output']; name: Scalars['String']['output']; nullable?: Maybe<Scalars['Boolean']['output']>; readonly?: Maybe<Scalars['Boolean']['output']>; requiresPermission?: Maybe<Array<Permission>>; type: Scalars['String']['output']; ui?: Maybe<Scalars['JSON']['output']>; }; export type TransitionFulfillmentToStateResult = Fulfillment | FulfillmentStateTransitionError; export type TransitionOrderToStateResult = Order | OrderStateTransitionError; export type TransitionPaymentToStateResult = Payment | PaymentStateTransitionError; export type UpdateActiveAdministratorInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; emailAddress?: InputMaybe<Scalars['String']['input']>; firstName?: InputMaybe<Scalars['String']['input']>; lastName?: InputMaybe<Scalars['String']['input']>; password?: InputMaybe<Scalars['String']['input']>; }; /** * Input used to update an Address. * * The countryCode must correspond to a `code` property of a Country that has been defined in the * Vendure server. The `code` property is typically a 2-character ISO code such as "GB", "US", "DE" etc. * If an invalid code is passed, the mutation will fail. */ export type UpdateAddressInput = { city?: InputMaybe<Scalars['String']['input']>; company?: InputMaybe<Scalars['String']['input']>; countryCode?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; defaultBillingAddress?: InputMaybe<Scalars['Boolean']['input']>; defaultShippingAddress?: InputMaybe<Scalars['Boolean']['input']>; fullName?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; phoneNumber?: InputMaybe<Scalars['String']['input']>; postalCode?: InputMaybe<Scalars['String']['input']>; province?: InputMaybe<Scalars['String']['input']>; streetLine1?: InputMaybe<Scalars['String']['input']>; streetLine2?: InputMaybe<Scalars['String']['input']>; }; export type UpdateAdministratorInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; emailAddress?: InputMaybe<Scalars['String']['input']>; firstName?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; lastName?: InputMaybe<Scalars['String']['input']>; password?: InputMaybe<Scalars['String']['input']>; roleIds?: InputMaybe<Array<Scalars['ID']['input']>>; }; export type UpdateAssetInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; focalPoint?: InputMaybe<CoordinateInput>; id: Scalars['ID']['input']; name?: InputMaybe<Scalars['String']['input']>; tags?: InputMaybe<Array<Scalars['String']['input']>>; }; export type UpdateChannelInput = { availableCurrencyCodes?: InputMaybe<Array<CurrencyCode>>; availableLanguageCodes?: InputMaybe<Array<LanguageCode>>; code?: InputMaybe<Scalars['String']['input']>; /** @deprecated Use defaultCurrencyCode instead */ currencyCode?: InputMaybe<CurrencyCode>; customFields?: InputMaybe<Scalars['JSON']['input']>; defaultCurrencyCode?: InputMaybe<CurrencyCode>; defaultLanguageCode?: InputMaybe<LanguageCode>; defaultShippingZoneId?: InputMaybe<Scalars['ID']['input']>; defaultTaxZoneId?: InputMaybe<Scalars['ID']['input']>; id: Scalars['ID']['input']; outOfStockThreshold?: InputMaybe<Scalars['Int']['input']>; pricesIncludeTax?: InputMaybe<Scalars['Boolean']['input']>; sellerId?: InputMaybe<Scalars['ID']['input']>; token?: InputMaybe<Scalars['String']['input']>; trackInventory?: InputMaybe<Scalars['Boolean']['input']>; }; export type UpdateChannelResult = Channel | LanguageNotAvailableError; export type UpdateCollectionInput = { assetIds?: InputMaybe<Array<Scalars['ID']['input']>>; customFields?: InputMaybe<Scalars['JSON']['input']>; featuredAssetId?: InputMaybe<Scalars['ID']['input']>; filters?: InputMaybe<Array<ConfigurableOperationInput>>; id: Scalars['ID']['input']; inheritFilters?: InputMaybe<Scalars['Boolean']['input']>; isPrivate?: InputMaybe<Scalars['Boolean']['input']>; parentId?: InputMaybe<Scalars['ID']['input']>; translations?: InputMaybe<Array<UpdateCollectionTranslationInput>>; }; export type UpdateCollectionTranslationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; id?: InputMaybe<Scalars['ID']['input']>; languageCode: LanguageCode; name?: InputMaybe<Scalars['String']['input']>; slug?: InputMaybe<Scalars['String']['input']>; }; export type UpdateCountryInput = { code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<CountryTranslationInput>>; }; export type UpdateCustomerGroupInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; name?: InputMaybe<Scalars['String']['input']>; }; export type UpdateCustomerInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; emailAddress?: InputMaybe<Scalars['String']['input']>; firstName?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; lastName?: InputMaybe<Scalars['String']['input']>; phoneNumber?: InputMaybe<Scalars['String']['input']>; title?: InputMaybe<Scalars['String']['input']>; }; export type UpdateCustomerNoteInput = { note: Scalars['String']['input']; noteId: Scalars['ID']['input']; }; export type UpdateCustomerResult = Customer | EmailAddressConflictError; export type UpdateFacetInput = { code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; isPrivate?: InputMaybe<Scalars['Boolean']['input']>; translations?: InputMaybe<Array<FacetTranslationInput>>; }; export type UpdateFacetValueInput = { code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<FacetValueTranslationInput>>; }; export type UpdateGlobalSettingsInput = { availableLanguages?: InputMaybe<Array<LanguageCode>>; customFields?: InputMaybe<Scalars['JSON']['input']>; outOfStockThreshold?: InputMaybe<Scalars['Int']['input']>; trackInventory?: InputMaybe<Scalars['Boolean']['input']>; }; export type UpdateGlobalSettingsResult = ChannelDefaultLanguageError | GlobalSettings; export type UpdateOrderAddressInput = { city?: InputMaybe<Scalars['String']['input']>; company?: InputMaybe<Scalars['String']['input']>; countryCode?: InputMaybe<Scalars['String']['input']>; fullName?: InputMaybe<Scalars['String']['input']>; phoneNumber?: InputMaybe<Scalars['String']['input']>; postalCode?: InputMaybe<Scalars['String']['input']>; province?: InputMaybe<Scalars['String']['input']>; streetLine1?: InputMaybe<Scalars['String']['input']>; streetLine2?: InputMaybe<Scalars['String']['input']>; }; export type UpdateOrderInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; }; export type UpdateOrderItemsResult = InsufficientStockError | NegativeQuantityError | Order | OrderLimitError | OrderModificationError; export type UpdateOrderNoteInput = { isPublic?: InputMaybe<Scalars['Boolean']['input']>; note?: InputMaybe<Scalars['String']['input']>; noteId: Scalars['ID']['input']; }; export type UpdatePaymentMethodInput = { checker?: InputMaybe<ConfigurableOperationInput>; code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; handler?: InputMaybe<ConfigurableOperationInput>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<PaymentMethodTranslationInput>>; }; export type UpdateProductInput = { assetIds?: InputMaybe<Array<Scalars['ID']['input']>>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; facetValueIds?: InputMaybe<Array<Scalars['ID']['input']>>; featuredAssetId?: InputMaybe<Scalars['ID']['input']>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<ProductTranslationInput>>; }; export type UpdateProductOptionGroupInput = { code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<ProductOptionGroupTranslationInput>>; }; export type UpdateProductOptionInput = { code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<ProductOptionGroupTranslationInput>>; }; export type UpdateProductVariantInput = { assetIds?: InputMaybe<Array<Scalars['ID']['input']>>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; facetValueIds?: InputMaybe<Array<Scalars['ID']['input']>>; featuredAssetId?: InputMaybe<Scalars['ID']['input']>; id: Scalars['ID']['input']; optionIds?: InputMaybe<Array<Scalars['ID']['input']>>; outOfStockThreshold?: InputMaybe<Scalars['Int']['input']>; /** Sets the price for the ProductVariant in the Channel's default currency */ price?: InputMaybe<Scalars['Money']['input']>; /** Allows multiple prices to be set for the ProductVariant in different currencies. */ prices?: InputMaybe<Array<ProductVariantPriceInput>>; sku?: InputMaybe<Scalars['String']['input']>; stockLevels?: InputMaybe<Array<StockLevelInput>>; stockOnHand?: InputMaybe<Scalars['Int']['input']>; taxCategoryId?: InputMaybe<Scalars['ID']['input']>; trackInventory?: InputMaybe<GlobalFlag>; translations?: InputMaybe<Array<ProductVariantTranslationInput>>; useGlobalOutOfStockThreshold?: InputMaybe<Scalars['Boolean']['input']>; }; export type UpdatePromotionInput = { actions?: InputMaybe<Array<ConfigurableOperationInput>>; conditions?: InputMaybe<Array<ConfigurableOperationInput>>; couponCode?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; endsAt?: InputMaybe<Scalars['DateTime']['input']>; id: Scalars['ID']['input']; perCustomerUsageLimit?: InputMaybe<Scalars['Int']['input']>; startsAt?: InputMaybe<Scalars['DateTime']['input']>; translations?: InputMaybe<Array<PromotionTranslationInput>>; usageLimit?: InputMaybe<Scalars['Int']['input']>; }; export type UpdatePromotionResult = MissingConditionsError | Promotion; export type UpdateProvinceInput = { code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; id: Scalars['ID']['input']; translations?: InputMaybe<Array<ProvinceTranslationInput>>; }; export type UpdateRoleInput = { channelIds?: InputMaybe<Array<Scalars['ID']['input']>>; code?: InputMaybe<Scalars['String']['input']>; description?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; permissions?: InputMaybe<Array<Permission>>; }; export type UpdateSellerInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; name?: InputMaybe<Scalars['String']['input']>; }; export type UpdateShippingMethodInput = { calculator?: InputMaybe<ConfigurableOperationInput>; checker?: InputMaybe<ConfigurableOperationInput>; code?: InputMaybe<Scalars['String']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; fulfillmentHandler?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; translations: Array<ShippingMethodTranslationInput>; }; export type UpdateStockLocationInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; description?: InputMaybe<Scalars['String']['input']>; id: Scalars['ID']['input']; name?: InputMaybe<Scalars['String']['input']>; }; export type UpdateTagInput = { id: Scalars['ID']['input']; value?: InputMaybe<Scalars['String']['input']>; }; export type UpdateTaxCategoryInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; isDefault?: InputMaybe<Scalars['Boolean']['input']>; name?: InputMaybe<Scalars['String']['input']>; }; export type UpdateTaxRateInput = { categoryId?: InputMaybe<Scalars['ID']['input']>; customFields?: InputMaybe<Scalars['JSON']['input']>; customerGroupId?: InputMaybe<Scalars['ID']['input']>; enabled?: InputMaybe<Scalars['Boolean']['input']>; id: Scalars['ID']['input']; name?: InputMaybe<Scalars['String']['input']>; value?: InputMaybe<Scalars['Float']['input']>; zoneId?: InputMaybe<Scalars['ID']['input']>; }; export type UpdateZoneInput = { customFields?: InputMaybe<Scalars['JSON']['input']>; id: Scalars['ID']['input']; name?: InputMaybe<Scalars['String']['input']>; }; export type User = Node & { __typename?: 'User'; authenticationMethods: Array<AuthenticationMethod>; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; identifier: Scalars['String']['output']; lastLogin?: Maybe<Scalars['DateTime']['output']>; roles: Array<Role>; updatedAt: Scalars['DateTime']['output']; verified: Scalars['Boolean']['output']; }; export type Zone = Node & { __typename?: 'Zone'; createdAt: Scalars['DateTime']['output']; customFields?: Maybe<Scalars['JSON']['output']>; id: Scalars['ID']['output']; members: Array<Region>; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type ZoneFilterParameter = { _and?: InputMaybe<Array<ZoneFilterParameter>>; _or?: InputMaybe<Array<ZoneFilterParameter>>; createdAt?: InputMaybe<DateOperators>; id?: InputMaybe<IdOperators>; name?: InputMaybe<StringOperators>; updatedAt?: InputMaybe<DateOperators>; }; export type ZoneList = PaginatedList & { __typename?: 'ZoneList'; items: Array<Zone>; totalItems: Scalars['Int']['output']; }; export type ZoneListOptions = { /** Allows the results to be filtered */ filter?: InputMaybe<ZoneFilterParameter>; /** Specifies whether multiple top-level "filter" fields should be combined with a logical AND or OR operation. Defaults to AND. */ filterOperator?: InputMaybe<LogicalOperator>; /** Skips the first n results, for use in pagination */ skip?: InputMaybe<Scalars['Int']['input']>; /** Specifies which properties to sort the results by */ sort?: InputMaybe<ZoneSortParameter>; /** Takes n results, for use in pagination */ take?: InputMaybe<Scalars['Int']['input']>; }; export type ZoneSortParameter = { createdAt?: InputMaybe<SortOrder>; id?: InputMaybe<SortOrder>; name?: InputMaybe<SortOrder>; updatedAt?: InputMaybe<SortOrder>; };
import { describe, expect, it } from 'vitest'; import { normalizeString } from './normalize-string'; describe('normalizeString()', () => { it('lowercases the string', () => { expect(normalizeString('FOO')).toBe('foo'); expect(normalizeString('Foo Bar')).toBe('foo bar'); }); it('replaces diacritical marks with plain equivalents', () => { expect(normalizeString('thé')).toBe('the'); expect(normalizeString('curaçao')).toBe('curacao'); expect(normalizeString('dấu hỏi')).toBe('dau hoi'); expect(normalizeString('el niño')).toBe('el nino'); expect(normalizeString('genkō yōshi')).toBe('genko yoshi'); expect(normalizeString('việt nam')).toBe('viet nam'); }); it('replaces spaces with the spaceReplacer', () => { expect(normalizeString('old man', '_')).toBe('old_man'); expect(normalizeString('old man', '_')).toBe('old_man'); }); it('strips non-alphanumeric characters', () => { expect(normalizeString('hi!!!')).toBe('hi'); expect(normalizeString('who? me?')).toBe('who me'); expect(normalizeString('!"£$%^&*()+[]{};:@#~?/,|\\><`¬\'=©®™')).toBe(''); }); it('allows a subset of non-alphanumeric characters to pass through', () => { expect(normalizeString('-_.')).toBe('-_.'); }); // https://github.com/vendure-ecommerce/vendure/issues/679 it('replaces single quotation marks', () => { expect(normalizeString('Capture d’écran')).toBe('capture decran'); expect(normalizeString('Capture d‘écran')).toBe('capture decran'); }); it('replaces eszett with double-s digraph', () => { expect(normalizeString('KONGREẞ im Straßennamen')).toBe('kongress im strassennamen'); }); // works for German language, might not work for e.g. Finnish language it('replaces combining diaeresis with e', () => { expect(normalizeString('Ja quäkt Schwyz Pöbel vor Gmünd')).toBe('ja quaekt schwyz poebel vor gmuend'); }); });
/** * Normalizes a string to replace non-alphanumeric and diacritical marks with * plain equivalents. * Based on https://stackoverflow.com/a/37511463/772859 */ export function normalizeString(input: string, spaceReplacer = ' '): string { return (input || '') .normalize('NFD') .replace(/[\u00df]/g, 'ss') .replace(/[\u1e9e]/g, 'SS') .replace(/[\u0308]/g, 'e') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .replace(/[!"£$%^&*()+[\]{};:@#~?\\/,|><`¬'=‘’©®™]/g, '') .replace(/\s+/g, spaceReplacer); }
import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { omit } from './omit'; declare const File: any; describe('omit()', () => { let patchedFileClass = false; beforeAll(() => { // In Node.js there is no File constructor, so we need to patch // a mock version. if (typeof File === 'undefined') { (global as any).File = class MockFile {}; patchedFileClass = true; } }); afterAll(() => { if (patchedFileClass) { delete (global as any).File; } }); it('returns a new object', () => { const obj = { foo: 1, bar: 2 }; expect(omit(obj, ['bar'])).not.toBe(obj); }); it('works with 1-level-deep objects', () => { expect(omit({ foo: 1, bar: 2 }, ['bar'])).toEqual({ foo: 1 }); expect(omit({ foo: 1, bar: 2 }, ['bar', 'foo'])).toEqual({}); }); it('works with deeply-nested objects', () => { expect( omit( { name: { first: 'joe', last: 'smith', }, address: { number: 12, }, }, ['address'], ), ).toEqual({ name: { first: 'joe', last: 'smith', }, }); }); describe('recursive', () => { it('returns a new object', () => { const obj = { foo: 1, bar: 2 }; expect(omit(obj, ['bar'], true)).not.toBe(obj); }); it('works with 1-level-deep objects', () => { const input = { foo: 1, bar: 2, baz: 3, }; const expected = { foo: 1, baz: 3 }; expect(omit(input, ['bar'], true)).toEqual(expected); }); it('works with 2-level-deep objects', () => { const input = { foo: 1, bar: { bad: true, good: true, }, baz: { bad: true, }, }; const expected = { foo: 1, bar: { good: true, }, baz: {}, }; expect(omit(input, ['bad'], true)).toEqual(expected); }); it('works with array of objects', () => { const input = { foo: 1, bar: [ { bad: true, good: true, }, { bad: true }, ], }; const expected = { foo: 1, bar: [{ good: true }, {}], }; expect(omit(input, ['bad'], true)).toEqual(expected); }); it('works top-level array', () => { const input = [{ foo: 1 }, { bad: true }, { bar: 2 }]; const expected = [{ foo: 1 }, {}, { bar: 2 }]; expect(omit(input, ['bad'], true)).toEqual(expected); }); it('preserves File objects', () => { const file = new File([], 'foo'); const input = [{ foo: 1 }, { bad: true }, { bar: file }]; const expected = [{ foo: 1 }, {}, { bar: file }]; expect(omit(input, ['bad'], true)).toEqual(expected); }); }); });
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; declare const File: any; /** * Type-safe omit function - returns a new object which omits the specified keys. */ export function omit<T extends object, K extends keyof T>(obj: T, keysToOmit: K[]): Omit<T, K>; export function omit<T extends object | any[], K extends keyof T>( obj: T, keysToOmit: string[], recursive: boolean, ): T; export function omit<T, K extends keyof T>(obj: T, keysToOmit: string[], recursive: boolean = false): T { if ((recursive && !isObject(obj)) || isFileObject(obj)) { return obj; } if (recursive && Array.isArray(obj)) { return obj.map((item: any) => omit(item, keysToOmit, true)) as T; } return Object.keys(obj as object).reduce((output: any, key) => { if (keysToOmit.includes(key)) { return output; } if (recursive) { return { ...output, [key]: omit((obj as any)[key], keysToOmit, true) }; } return { ...output, [key]: (obj as any)[key] }; }, {} as Omit<T, K>); } function isObject(input: any): input is object { return typeof input === 'object' && input !== null; } /** * When running in the Node environment, there is no native File object. */ function isFileObject(input: any): boolean { if (typeof File === 'undefined') { return false; } else { return input instanceof File; } }
import { describe, expect, it } from 'vitest'; import { pick } from './pick'; describe('pick()', () => { it('picks specified properties', () => { const input = { foo: 1, bar: 2, baz: [1, 2, 3], }; const result = pick(input, ['foo', 'baz']); expect(result).toEqual({ foo: 1, baz: [1, 2, 3], }); }); it('partially applies the pick when signle argument is array', () => { const input = { foo: 1, bar: 2, baz: [1, 2, 3], }; const result = pick(['foo', 'baz']); expect(typeof result).toBe('function'); expect(result(input)).toEqual({ foo: 1, baz: [1, 2, 3], }); }); });
/** * Returns a new object which is a subset of the input, including only the specified properties. * Can be called with a single argument (array of props to pick), in which case it returns a partially * applied pick function. */ export function pick<T extends string>(props: T[]): <U>(input: U) => Pick<U, Extract<keyof U, T>>; export function pick<U, T extends keyof U>(input: U, props: T[]): { [K in T]: U[K] }; export function pick<U, T extends keyof U>( inputOrProps: U | T[], maybeProps?: T[], ): { [K in T]: U[K] } | ((input: U) => Pick<U, Extract<keyof U, T>>) { if (Array.isArray(inputOrProps)) { return (input: U) => _pick(input, inputOrProps); } else { return _pick(inputOrProps, maybeProps || []); } } function _pick<U, T extends keyof U>(input: U, props: T[]): { [K in T]: U[K] } { const output: any = {}; for (const prop of props) { output[prop] = input[prop]; } return output; }
/* * This file contains constants which are shared between more than one sub-module * e.g. values required by both the server and admin-ui. */ export const API_PORT = 3000; export const ADMIN_API_PATH = 'admin-api'; export const SHOP_API_PATH = 'shop-api'; export const DEFAULT_CHANNEL_CODE = '__default_channel__'; export const SUPER_ADMIN_ROLE_CODE = '__super_admin_role__'; export const SUPER_ADMIN_ROLE_DESCRIPTION = 'SuperAdmin'; export const SUPER_ADMIN_USER_IDENTIFIER = 'superadmin'; export const SUPER_ADMIN_USER_PASSWORD = 'superadmin'; export const CUSTOMER_ROLE_CODE = '__customer_role__'; export const CUSTOMER_ROLE_DESCRIPTION = 'Customer'; export const ROOT_COLLECTION_NAME = '__root_collection__'; export const DEFAULT_AUTH_TOKEN_HEADER_KEY = 'vendure-auth-token'; export const DEFAULT_COOKIE_NAME = 'session'; export const DEFAULT_CHANNEL_TOKEN_KEY = 'vendure-token'; // An environment variable which is set when the @vendure/create // script is run. Can be used to modify normal behaviour // to fit with the initial create task. export type CREATING_VENDURE_APP = 'CREATING_VENDURE_APP'; export const CREATING_VENDURE_APP: CREATING_VENDURE_APP = 'CREATING_VENDURE_APP';
/* eslint-disable no-shadow,@typescript-eslint/no-shadow */ // prettier-ignore import { LanguageCode, LocalizedString } from './generated-types'; /** * A recursive implementation of the Partial<T> type. * Source: https://stackoverflow.com/a/49936686/772859 */ export type DeepPartial<T> = { [P in keyof T]?: | null | (T[P] extends Array<infer U> ? Array<DeepPartial<U>> : T[P] extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : DeepPartial<T[P]>); }; /* eslint-enable no-shadow, @typescript-eslint/no-shadow */ /* eslint-disable @typescript-eslint/ban-types */ /** * A recursive implementation of Required<T>. * Source: https://github.com/microsoft/TypeScript/issues/15012#issuecomment-365453623 */ export type DeepRequired<T, U extends object | undefined = undefined> = T extends object ? { [P in keyof T]-?: NonNullable<T[P]> extends NonNullable<U | Function | Type<any>> ? NonNullable<T[P]> : DeepRequired<NonNullable<T[P]>, U>; } : T; /* eslint-enable @typescript-eslint/ban-types */ /** * A type representing the type rather than instance of a class. */ // eslint-disable-next-line @typescript-eslint/ban-types export interface Type<T> extends Function { // eslint-disable-next-line @typescript-eslint/prefer-function-type new (...args: any[]): T; } export type Json = null | boolean | number | string | Json[] | { [prop: string]: Json }; /** * @description * A type representing JSON-compatible values. * From https://github.com/microsoft/TypeScript/issues/1897#issuecomment-580962081 * * @docsCategory common */ export type JsonCompatible<T> = { [P in keyof T]: T[P] extends Json ? T[P] : Pick<T, P> extends Required<Pick<T, P>> ? never : JsonCompatible<T[P]>; }; /** * @description * A type describing the shape of a paginated list response. In Vendure, almost all list queries * (`products`, `collections`, `orders`, `customers` etc) return an object of this type. * * @docsCategory common */ export type PaginatedList<T> = { items: T[]; totalItems: number; }; /** * @description * An entity ID. Depending on the configured {@link EntityIdStrategy}, it will be either * a `string` or a `number`; * * @docsCategory common */ export type ID = string | number; /** * @description * A data type for a custom field. The CustomFieldType determines the data types used in the generated * database columns and GraphQL fields as follows (key: m = MySQL, p = Postgres, s = SQLite): * * Type | DB type | GraphQL type * ----- |--------- |--------------- * string | varchar | String * localeString | varchar | String * text | longtext(m), text(p,s) | String * localeText | longtext(m), text(p,s) | String * int | int | Int * float | double precision | Float * boolean | tinyint (m), bool (p), boolean (s) | Boolean * datetime | datetime (m,s), timestamp (p) | DateTime * relation | many-to-one / many-to-many relation | As specified in config * * Additionally, the CustomFieldType also dictates which [configuration options](/reference/typescript-api/custom-fields/#configuration-options) * are available for that custom field. * * @docsCategory custom-fields */ export type CustomFieldType = | 'string' | 'localeString' | 'int' | 'float' | 'boolean' | 'datetime' | 'relation' | 'text' | 'localeText'; /** * @description * Certain entities (those which implement {@link ConfigurableOperationDef}) allow arbitrary * configuration arguments to be specified which can then be set in the admin-ui and used in * the business logic of the app. These are the valid data types of such arguments. * The data type influences: * * 1. How the argument form field is rendered in the admin-ui * 2. The JavaScript type into which the value is coerced before being passed to the business logic. * * @docsCategory ConfigurableOperationDef */ export type ConfigArgType = 'string' | 'int' | 'float' | 'boolean' | 'datetime' | 'ID'; /** * @description * The ids of the default form input components that ship with the * Admin UI. * * @docsCategory ConfigurableOperationDef */ export type DefaultFormComponentId = | 'boolean-form-input' | 'currency-form-input' | 'customer-group-form-input' | 'date-form-input' | 'facet-value-form-input' | 'json-editor-form-input' | 'html-editor-form-input' | 'number-form-input' | 'password-form-input' | 'product-selector-form-input' | 'relation-form-input' | 'rich-text-form-input' | 'select-form-input' | 'text-form-input' | 'textarea-form-input' | 'product-multi-form-input' | 'combination-mode-form-input'; /** * @description * Used to define the expected arguments for a given default form input component. * * @docsCategory ConfigurableOperationDef */ type DefaultFormConfigHash = { 'boolean-form-input': Record<string, never>; 'currency-form-input': Record<string, never>; 'customer-group-form-input': Record<string, never>; 'date-form-input': { min?: string; max?: string; yearRange?: number }; 'facet-value-form-input': Record<string, never>; 'json-editor-form-input': { height?: string }; 'html-editor-form-input': { height?: string }; 'number-form-input': { min?: number; max?: number; step?: number; prefix?: string; suffix?: string }; 'password-form-input': Record<string, never>; 'product-selector-form-input': Record<string, never>; 'relation-form-input': Record<string, never>; 'rich-text-form-input': Record<string, never>; 'select-form-input': { options?: Array<{ value: string; label?: Array<Omit<LocalizedString, '__typename'>> }>; }; 'text-form-input': { prefix?: string; suffix?: string }; 'textarea-form-input': { spellcheck?: boolean; }; 'product-multi-form-input': { selectionMode?: 'product' | 'variant'; }; 'combination-mode-form-input': Record<string, never>; }; export type DefaultFormComponentUiConfig<T extends DefaultFormComponentId | string> = T extends DefaultFormComponentId ? DefaultFormConfigHash[T] : any; export type DefaultFormComponentConfig<T extends DefaultFormComponentId | string> = DefaultFormComponentUiConfig<T> & { ui?: DefaultFormComponentUiConfig<T>; }; export type UiComponentConfig<T extends DefaultFormComponentId | string> = T extends DefaultFormComponentId ? { component: T; tab?: string; } & DefaultFormConfigHash[T] : { component: string; tab?: string; [prop: string]: any; }; export type CustomFieldsObject = { [key: string]: any }; /** * @description * This interface describes JSON config file (vendure-ui-config.json) used by the Admin UI. * The values are loaded at run-time by the Admin UI app, and allow core configuration to be * managed without the need to re-build the application. * * @docsCategory common/AdminUi */ export interface AdminUiConfig { /** * @description * The hostname of the Vendure server which the admin UI will be making API calls * to. If set to "auto", the Admin UI app will determine the hostname from the * current location (i.e. `window.location.hostname`). * * @default 'http://localhost' */ apiHost: string | 'auto'; /** * @description * The port of the Vendure server which the admin UI will be making API calls * to. If set to "auto", the Admin UI app will determine the port from the * current location (i.e. `window.location.port`). * * @default 3000 */ apiPort: number | 'auto'; /** * @description * The path to the GraphQL Admin API. * * @default 'admin-api' */ adminApiPath: string; /** * @description * Whether to use cookies or bearer tokens to track sessions. * Should match the setting of in the server's `tokenMethod` config * option. * * @default 'cookie' */ tokenMethod: 'cookie' | 'bearer'; /** * @description * The header used when using the 'bearer' auth method. Should match the * setting of the server's `authOptions.authTokenHeaderKey` config option. * * @default 'vendure-auth-token' */ authTokenHeaderKey: string; /** * @description * The name of the header which contains the channel token. Should match the * setting of the server's `apiOptions.channelTokenKey` config option. * * @default 'vendure-token' */ channelTokenKey: string; /** * @description * The default language for the Admin UI. Must be one of the * items specified in the `availableLanguages` property. * * @default LanguageCode.en */ defaultLanguage: LanguageCode; /** * @description * The default locale for the Admin UI. The locale affects the formatting of * currencies & dates. Must be one of the items specified * in the `availableLocales` property. * * If not set, the browser default locale will be used. * * @since 2.2.0 */ defaultLocale?: string; /** * @description * An array of languages for which translations exist for the Admin UI. */ availableLanguages: LanguageCode[]; /** * @description * An array of locales to be used on Admin UI. * * @since 2.2.0 */ availableLocales: string[]; /** * @description * If you are using an external {@link AuthenticationStrategy} for the Admin API, you can configure * a custom URL for the login page with this option. On logging out or redirecting an unauthenticated * user, the Admin UI app will redirect the user to this URL rather than the default username/password * screen. */ loginUrl?: string; /** * @description * The custom brand name. */ brand?: string; /** * @description * Option to hide vendure branding. * * @default false */ hideVendureBranding?: boolean; /** * @description * Option to hide version. * * @default false */ hideVersion?: boolean; /** * @description * A url of a custom image to be used on the login screen, to override the images provided by Vendure's login image server. * * @since 1.9.0 */ loginImageUrl?: string; /** * @description * Allows you to provide default reasons for a refund or cancellation. This will be used in the * refund/cancel dialog. The values can be literal strings (e.g. "Not in stock") or translation * tokens (see [Adding Admin UI Translations](/guides/extending-the-admin-ui/adding-ui-translations/)). * * @since 1.5.0 * @default ['order.cancel-reason-customer-request', 'order.cancel-reason-not-available'] */ cancellationReasons?: string[]; } /** * @description * Configures the path to a custom-build of the Admin UI app. * * @docsCategory common/AdminUi */ export interface AdminUiAppConfig { /** * @description * The path to the compiled admin UI app files. If not specified, an internal * default build is used. This path should contain the `vendure-ui-config.json` file, * index.html, the compiled js bundles etc. */ path: string; /** * @description * Specifies the url route to the Admin UI app. * * @default 'admin' */ route?: string; /** * @description * The function which will be invoked to start the app compilation process. */ compile?: () => Promise<void>; } /** * @description * Information about the Admin UI app dev server. * * @docsCategory common/AdminUi */ export interface AdminUiAppDevModeConfig { /** * @description * The path to the uncompiled UI app source files. This path should contain the `vendure-ui-config.json` file. */ sourcePath: string; /** * @description * The port on which the dev server is listening. Overrides the value set by `AdminUiOptions.port`. */ port: number; /** * @description * Specifies the url route to the Admin UI app. * * @default 'admin' */ route?: string; /** * @description * The function which will be invoked to start the app compilation process. */ compile: () => Promise<void>; }
import { describe, expect, it } from 'vitest'; import { generateAllCombinations, isClassInstance } from './shared-utils'; describe('generateAllCombinations()', () => { it('works with an empty input array', () => { const result = generateAllCombinations([]); expect(result).toEqual([]); }); it('works with an input of length 1', () => { const result = generateAllCombinations([['red', 'green', 'blue']]); expect(result).toEqual([['red'], ['green'], ['blue']]); }); it('works with an input of length 2', () => { const result = generateAllCombinations([ ['red', 'green', 'blue'], ['small', 'large'], ]); expect(result).toEqual([ ['red', 'small'], ['red', 'large'], ['green', 'small'], ['green', 'large'], ['blue', 'small'], ['blue', 'large'], ]); }); it('works with second array empty', () => { const result = generateAllCombinations([['red', 'green', 'blue'], []]); expect(result).toEqual([['red'], ['green'], ['blue']]); }); }); describe('isClassInstance()', () => { it('returns true for class instances', () => { expect(isClassInstance(new Date())).toBe(true); expect(isClassInstance(new Foo())).toBe(true); // eslint-disable-next-line no-new-wrappers expect(isClassInstance(new Number(1))).toBe(true); }); it('returns false for not class instances', () => { expect(isClassInstance(Date)).toBe(false); expect(isClassInstance(1)).toBe(false); expect(isClassInstance(Number)).toBe(false); expect(isClassInstance({ a: 1 })).toBe(false); expect(isClassInstance([1, 2, 3])).toBe(false); }); class Foo {} });
import { CustomFieldConfig } from './generated-types'; /** * Predicate with type guard, used to filter out null or undefined values * in a filter operation. */ export function notNullOrUndefined<T>(val: T | undefined | null): val is T { return val !== undefined && val !== null; } /** * Used in exhaustiveness checks to assert a codepath should never be reached. */ export function assertNever(value: never): never { throw new Error(`Expected never, got ${typeof value} (${JSON.stringify(value)})`); } /** * Simple object check. * From https://stackoverflow.com/a/34749873/772859 */ export function isObject(item: any): item is object { return item && typeof item === 'object' && !Array.isArray(item); } export function isClassInstance(item: any): boolean { // Even if item is an object, it might not have a constructor as in the // case when it is a null-prototype object, i.e. created using `Object.create(null)`. return isObject(item) && item.constructor && item.constructor.name !== 'Object'; } type NumericPropsOf<T> = { [K in keyof T]: T[K] extends number ? K : never; }[keyof T]; // homomorphic helper type // From https://stackoverflow.com/a/56140392/772859 type NPO<T, KT extends keyof T> = { [K in KT]: T[K] extends string | number | boolean ? T[K] : T[K] extends Array<infer A> ? Array<OnlyNumerics<A>> : OnlyNumerics<T[K]>; }; // quick abort if T is a function or primitive // otherwise pass to a homomorphic helper type type OnlyNumerics<T> = NPO<T, NumericPropsOf<T>>; /** * Adds up all the values of a given numeric property of a list of objects. */ export function summate<T extends OnlyNumerics<T>>( items: T[] | undefined | null, prop: keyof OnlyNumerics<T>, ): number { return (items || []).reduce((sum, i) => sum + (i[prop] as unknown as number), 0); } /** * Given an array of option arrays `[['red, 'blue'], ['small', 'large']]`, this method returns a new array * containing all the combinations of those options: * * @example * ``` * generateAllCombinations([['red, 'blue'], ['small', 'large']]); * // => * // [ * // ['red', 'small'], * // ['red', 'large'], * // ['blue', 'small'], * // ['blue', 'large'], * // ] */ export function generateAllCombinations<T>( optionGroups: T[][], combination: T[] = [], k: number = 0, output: T[][] = [], ): T[][] { if (k === 0) { optionGroups = optionGroups.filter(g => 0 < g.length); } if (k === optionGroups.length) { output.push(combination); return []; } else { /* eslint-disable @typescript-eslint/prefer-for-of */ for (let i = 0; i < optionGroups[k].length; i++) { generateAllCombinations(optionGroups, combination.concat(optionGroups[k][i]), k + 1, output); } /* eslint-enable @typescript-eslint/prefer-for-of */ return output; } } /** * @description * Returns the input field name of a custom field, taking into account that "relation" type custom * field inputs are suffixed with "Id" or "Ids". */ export function getGraphQlInputName(config: { name: string; type: string; list?: boolean }): string { if (config.type === 'relation') { return config.list === true ? `${config.name}Ids` : `${config.name}Id`; } else { return config.name; } }
import { describe, expect, it } from 'vitest'; import { simpleDeepClone } from './simple-deep-clone'; describe('simpleDeepClone()', () => { it('clones a simple flat object', () => { const target = { a: 1, b: 2 }; const result = simpleDeepClone(target); expect(result).toEqual(target); expect(result).not.toBe(target); }); it('clones a simple deep object', () => { const target = { a: 1, b: { c: 3, d: [1, 2, 3] } }; const result = simpleDeepClone(target); expect(result).toEqual(target); expect(result).not.toBe(target); }); it('clones a simple flat array', () => { const target = [1, 2, 3]; const result = simpleDeepClone(target); expect(result).toEqual(target); expect(result).not.toBe(target); }); it('clones a simple deep array', () => { const target = [1, [2, 3], [4, [5, [6]]]]; const result = simpleDeepClone(target); expect(result).toEqual(target); expect(result).not.toBe(target); }); it('passes through primitive types', () => { expect(simpleDeepClone(1)).toBe(1); expect(simpleDeepClone('a')).toBe('a'); expect(simpleDeepClone(true as any)).toBe(true); expect(simpleDeepClone(null as any)).toBe(null); expect(simpleDeepClone(undefined as any)).toBe(undefined); }); it('does not clone class instance', () => { const target = new Foo(); const result = simpleDeepClone(target); expect(result).toBe(target); }); it('does not clone class instance in array', () => { const foo = new Foo(); const target = [foo]; const result = simpleDeepClone(target); expect(result).toEqual(target); expect(result).not.toBe(target); expect(result[0]).toBe(target[0]); }); it('does not clone class instance in object', () => { const foo = new Foo(); const target = { a: foo }; const result = simpleDeepClone(target); expect(result).toEqual(target); expect(result).not.toBe(target); expect(result.a).toBe(target.a); }); it('clone does not share references with original', () => { const original = { user: { name: 'mike' } }; const clone = simpleDeepClone(original); original.user.name = 'pete'; expect(clone.user.name).toEqual('mike'); }); }); class Foo {}
import { isClassInstance } from './shared-utils'; /** * An extremely fast function for deep-cloning an object which only contains simple * values, i.e. primitives, arrays and nested simple objects. */ export function simpleDeepClone<T extends string | number | any[] | object>(input: T): T { // if not array or object or is null return self if (typeof input !== 'object' || input === null) { return input; } let output: any; let i: number | string; // handle case: array if (input instanceof Array) { let l; output = [] as any[]; for (i = 0, l = input.length; i < l; i++) { output[i] = simpleDeepClone(input[i]); } return output; } if (isClassInstance(input)) { return input; } // handle case: object output = {}; for (i in input) { if (input.hasOwnProperty(i)) { output[i] = simpleDeepClone((input as any)[i]); } } return output; }
import { describe, expect, it } from 'vitest'; import { unique } from './unique'; describe('unique()', () => { it('works with primitive values', () => { expect(unique([1, 1, 2, 3, 2, 6, 4, 2])).toEqual([1, 2, 3, 6, 4]); expect(unique(['a', 'f', 'g', 'f', 'y'])).toEqual(['a', 'f', 'g', 'y']); expect(unique([null, null, 1, 'a', 1])).toEqual([null, 1, 'a']); }); it('works with object references', () => { const a = { a: true }; const b = { b: true }; const c = { c: true }; expect(unique([a, b, a, b, c, a])).toEqual([a, b, c]); expect(unique([a, b, a, b, c, a])[0]).toBe(a); expect(unique([a, b, a, b, c, a])[1]).toBe(b); expect(unique([a, b, a, b, c, a])[2]).toBe(c); }); it('works with object key param', () => { const a = { id: 'a', a: true }; const b = { id: 'b', b: true }; const c = { id: 'c', c: true }; const d = { id: 'a', d: true }; expect(unique([a, b, a, b, d, c, a], 'id')).toEqual([a, b, c]); }); it('works an empty array', () => { expect(unique([])).toEqual([]); }); it('perf on primitive array', () => { const bigArray = Array.from({ length: 50000 }).map(() => Math.random().toString().substr(2, 5)); const timeStart = new Date().getTime(); unique(bigArray); const timeEnd = new Date().getTime(); expect(timeEnd - timeStart).toBeLessThan(100); }); it('perf on object array', () => { const bigArray = Array.from({ length: 50000 }) .map(() => Math.random().toString().substr(2, 5)) .map(id => ({ id })); const timeStart = new Date().getTime(); unique(bigArray, 'id'); const timeEnd = new Date().getTime(); expect(timeEnd - timeStart).toBeLessThan(100); }); });
/** * @description * Returns an array with only unique values. Objects are compared by reference, * unless the `byKey` argument is supplied, in which case matching properties will * be used to check duplicates */ export function unique<T>(arr: T[], byKey?: keyof T): T[] { if (byKey == null) { return Array.from(new Set(arr)); } else { // Based on https://stackoverflow.com/a/58429784/772859 return [...new Map(arr.map(item => [item[byKey], item])).values()]; } }
// This file is for any 3rd party JS libs which don't have a corresponding @types/ package. declare module 'opn' { declare const opn: (path: string) => Promise<any>; export default opn; } declare module 'i18next-icu' { // default } declare module 'i18next-fs-backend' { // default }
/* eslint-disable no-console */ import chokidar from 'chokidar'; import fs from 'fs-extra'; import { globSync } from 'glob'; import path from 'path'; const SCHEMAS_GLOB = '**/*.graphql'; const MESSAGES_GLOB = 'i18n/messages/**/*'; const DEST_DIR = path.join(__dirname, '../dist'); function copyFiles(sourceGlob: string, destinationDir: string) { const srcDir = path.join(__dirname, '../src'); const files = globSync(sourceGlob, { cwd: srcDir, }); for (const file of files) { const destFile = path.join(destinationDir, file); try { fs.ensureDirSync(path.dirname(destFile)); fs.copySync(path.join(srcDir, file), destFile); } catch (error: any) { console.error(`Error copying file ${file}:`, error); } } } function copySchemas() { try { copyFiles(SCHEMAS_GLOB, DEST_DIR); console.log('Schemas copied successfully!'); } catch (error) { console.error('Error copying schemas:', error); } } function copyI18nMessages() { try { copyFiles(MESSAGES_GLOB, DEST_DIR); console.log('I18n messages copied successfully!'); } catch (error) { console.error('Error copying i18n messages:', error); } } function build() { copySchemas(); copyI18nMessages(); } function watch() { const watcher1 = chokidar.watch(SCHEMAS_GLOB, { cwd: path.join(__dirname, '../src') }); const watcher2 = chokidar.watch(MESSAGES_GLOB, { cwd: path.join(__dirname, '../src') }); watcher1.on('change', copySchemas); watcher2.on('change', copyI18nMessages); console.log('Watching for changes...'); } function runCommand() { const command = process.argv[2]; if (command === 'build') { build(); } else if (command === 'watch') { watch(); } else { console.error('Invalid command. Please use "build" or "watch".'); } } // Run command specified in the command line argument runCommand();
import { dest, parallel, src, watch as gulpWatch } from 'gulp'; const SCHEMAS_GLOB = ['../src/**/*.graphql']; const MESSAGES_GLOB = ['../src/i18n/messages/**/*']; function copySchemas() { return src(SCHEMAS_GLOB).pipe(dest('../dist')); } function copyI18nMessages() { return src(MESSAGES_GLOB).pipe(dest('../dist/i18n/messages')); } export const build = parallel(copySchemas, copyI18nMessages); export function watch() { const watcher1 = gulpWatch(SCHEMAS_GLOB, copySchemas); const watcher2 = gulpWatch(MESSAGES_GLOB, copyI18nMessages); // eslint-disable-next-line @typescript-eslint/no-empty-function return new Promise(resolve => {}); }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { mergeConfig, orderPercentageDiscount } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { testSuccessfulPaymentMethod } from './fixtures/test-payment-methods'; import { TokenActiveOrderPlugin } from './fixtures/test-plugins/token-active-order-plugin'; import { CreatePromotionMutation, CreatePromotionMutationVariables, GetCustomerListQuery, } from './graphql/generated-e2e-admin-types'; import { AddItemToOrderMutation, AddItemToOrderMutationVariables, GetActiveOrderQuery, } from './graphql/generated-e2e-shop-types'; import { CREATE_PROMOTION, GET_CUSTOMER_LIST } from './graphql/shared-definitions'; import { ADD_ITEM_TO_ORDER, GET_ACTIVE_ORDER } from './graphql/shop-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; describe('custom ActiveOrderStrategy', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [TokenActiveOrderPlugin], paymentOptions: { paymentMethodHandlers: [testSuccessfulPaymentMethod], }, customFields: { Order: [ { name: 'message', type: 'string', nullable: true, }, ], }, }), ); let customers: GetCustomerListQuery['customers']['items']; beforeAll(async () => { await server.init({ initialData: { ...initialData, paymentMethods: [ { name: testSuccessfulPaymentMethod.code, handler: { code: testSuccessfulPaymentMethod.code, arguments: [] }, }, ], }, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 3, }); await adminClient.asSuperAdmin(); const result = await adminClient.query<GetCustomerListQuery>(GET_CUSTOMER_LIST); customers = result.customers.items; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('activeOrder with no createActiveOrder defined returns null', async () => { const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); expect(activeOrder).toBeNull(); }); it( 'addItemToOrder with no createActiveOrder throws', assertThrowsWithMessage(async () => { await shopClient.query<AddItemToOrderMutation, AddItemToOrderMutationVariables>( ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 1, }, ); }, 'No active Order could be determined nor created'), ); it('activeOrder with valid input', async () => { const { createOrder } = await shopClient.query(gql` mutation CreateCustomOrder { createOrder(customerId: "${customers[1].id}") { id orderToken } } `); expect(createOrder).toEqual({ id: 'T_1', orderToken: 'token-2', }); await shopClient.asUserWithCredentials(customers[1].emailAddress, 'test'); const { activeOrder } = await shopClient.query(ACTIVE_ORDER_BY_TOKEN, { input: { orderToken: { token: 'token-2' }, }, }); expect(activeOrder).toEqual({ id: 'T_1', orderToken: 'token-2', }); }); it('activeOrder with invalid input', async () => { await shopClient.asUserWithCredentials(customers[1].emailAddress, 'test'); const { activeOrder } = await shopClient.query(ACTIVE_ORDER_BY_TOKEN, { input: { orderToken: { token: 'invalid' }, }, }); expect(activeOrder).toBeNull(); }); it('activeOrder with invalid condition', async () => { // wrong customer logged in await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { activeOrder } = await shopClient.query(ACTIVE_ORDER_BY_TOKEN, { input: { orderToken: { token: 'token-2' }, }, }); expect(activeOrder).toBeNull(); }); describe('happy path', () => { const activeOrderInput = 'activeOrderInput: { orderToken: { token: "token-2" } }'; const TEST_COUPON_CODE = 'TESTCOUPON'; let firstOrderLineId: string; beforeAll(async () => { await shopClient.asUserWithCredentials(customers[1].emailAddress, 'test'); const result = await adminClient.query<CreatePromotionMutation, CreatePromotionMutationVariables>( CREATE_PROMOTION, { input: { enabled: true, couponCode: TEST_COUPON_CODE, conditions: [], actions: [ { code: orderPercentageDiscount.code, arguments: [{ name: 'discount', value: '100' }], }, ], translations: [{ languageCode: LanguageCode.en, name: 'Free with test coupon' }], }, }, ); }); it('addItemToOrder', async () => { const { addItemToOrder } = await shopClient.query(gql` mutation { addItemToOrder(productVariantId: "T_1", quantity: 1, ${activeOrderInput}) { ...on Order { id orderToken lines { id productVariant { id } } } } } `); expect(addItemToOrder).toEqual({ id: 'T_1', orderToken: 'token-2', lines: [ { id: 'T_1', productVariant: { id: 'T_1' }, }, ], }); firstOrderLineId = addItemToOrder.lines[0].id; }); it('adjustOrderLine', async () => { const { adjustOrderLine } = await shopClient.query(gql` mutation { adjustOrderLine(orderLineId: "${firstOrderLineId}", quantity: 2, ${activeOrderInput}) { ...on Order { id orderToken lines { quantity productVariant { id } } } } } `); expect(adjustOrderLine).toEqual({ id: 'T_1', orderToken: 'token-2', lines: [ { quantity: 2, productVariant: { id: 'T_1' }, }, ], }); }); it('removeOrderLine', async () => { const { removeOrderLine } = await shopClient.query(gql` mutation { removeOrderLine(orderLineId: "${firstOrderLineId}", ${activeOrderInput}) { ...on Order { id orderToken lines { id } } } } `); expect(removeOrderLine).toEqual({ id: 'T_1', orderToken: 'token-2', lines: [], }); }); it('removeAllOrderLines', async () => { const { addItemToOrder } = await shopClient.query(gql` mutation { addItemToOrder(productVariantId: "T_1", quantity: 1, ${activeOrderInput}) { ...on Order { lines { id } } } } `); expect(addItemToOrder.lines.length).toBe(1); const { removeAllOrderLines } = await shopClient.query(gql` mutation { removeAllOrderLines(${activeOrderInput}) { ...on Order { id orderToken lines { id } } } } `); expect(removeAllOrderLines.lines.length).toBe(0); }); it('applyCouponCode', async () => { await shopClient.query(gql` mutation { addItemToOrder(productVariantId: "T_1", quantity: 1, ${activeOrderInput}) { ...on Order { lines { id } } } } `); const { applyCouponCode } = await shopClient.query(gql` mutation { applyCouponCode(couponCode: "${TEST_COUPON_CODE}", ${activeOrderInput}) { ...on Order { id orderToken couponCodes discounts { description } } } } `); expect(applyCouponCode).toEqual({ id: 'T_1', orderToken: 'token-2', couponCodes: [TEST_COUPON_CODE], discounts: [{ description: 'Free with test coupon' }], }); }); it('removeCouponCode', async () => { const { removeCouponCode } = await shopClient.query(gql` mutation { removeCouponCode(couponCode: "${TEST_COUPON_CODE}", ${activeOrderInput}) { ...on Order { id orderToken couponCodes discounts { description } } } } `); expect(removeCouponCode).toEqual({ id: 'T_1', orderToken: 'token-2', couponCodes: [], discounts: [], }); }); it('setOrderShippingAddress', async () => { const { setOrderShippingAddress } = await shopClient.query(gql` mutation { setOrderShippingAddress(input: { streetLine1: "Shipping Street" countryCode: "AT" }, ${activeOrderInput}) { ...on Order { id orderToken shippingAddress { streetLine1 country } } } } `); expect(setOrderShippingAddress).toEqual({ id: 'T_1', orderToken: 'token-2', shippingAddress: { streetLine1: 'Shipping Street', country: 'Austria', }, }); }); it('setOrderBillingAddress', async () => { const { setOrderBillingAddress } = await shopClient.query(gql` mutation { setOrderBillingAddress(input: { streetLine1: "Billing Street" countryCode: "AT" }, ${activeOrderInput}) { ...on Order { id orderToken billingAddress { streetLine1 country } } } } `); expect(setOrderBillingAddress).toEqual({ id: 'T_1', orderToken: 'token-2', billingAddress: { streetLine1: 'Billing Street', country: 'Austria', }, }); }); it('eligibleShippingMethods', async () => { const { eligibleShippingMethods } = await shopClient.query(gql` query { eligibleShippingMethods(${activeOrderInput}) { id name priceWithTax } } `); expect(eligibleShippingMethods).toEqual([ { id: 'T_1', name: 'Standard Shipping', priceWithTax: 500, }, { id: 'T_2', name: 'Express Shipping', priceWithTax: 1000, }, ]); }); it('setOrderShippingMethod', async () => { const { setOrderShippingMethod } = await shopClient.query(gql` mutation { setOrderShippingMethod(shippingMethodId: "T_1", ${activeOrderInput}) { ...on Order { id orderToken shippingLines { price } } } } `); expect(setOrderShippingMethod).toEqual({ id: 'T_1', orderToken: 'token-2', shippingLines: [{ price: 500 }], }); }); it('setOrderCustomFields', async () => { const { setOrderCustomFields } = await shopClient.query(gql` mutation { setOrderCustomFields(input: { customFields: { message: "foo" } }, ${activeOrderInput}) { ...on Order { id orderToken customFields { message } } } } `); expect(setOrderCustomFields).toEqual({ id: 'T_1', orderToken: 'token-2', customFields: { message: 'foo' }, }); }); it('eligiblePaymentMethods', async () => { const { eligiblePaymentMethods } = await shopClient.query(gql` query { eligiblePaymentMethods(${activeOrderInput}) { id name code } } `); expect(eligiblePaymentMethods).toEqual([ { id: 'T_1', name: 'test-payment-method', code: 'test-payment-method', }, ]); }); it('nextOrderStates', async () => { const { nextOrderStates } = await shopClient.query(gql` query { nextOrderStates(${activeOrderInput}) } `); expect(nextOrderStates).toEqual(['ArrangingPayment', 'Cancelled']); }); it('transitionOrderToState', async () => { const { transitionOrderToState } = await shopClient.query(gql` mutation { transitionOrderToState(state: "ArrangingPayment", ${activeOrderInput}) { ...on Order { id orderToken state } } } `); expect(transitionOrderToState).toEqual({ id: 'T_1', orderToken: 'token-2', state: 'ArrangingPayment', }); }); it('addPaymentToOrder', async () => { const { addPaymentToOrder } = await shopClient.query(gql` mutation { addPaymentToOrder(input: { method: "test-payment-method", metadata: {}}, ${activeOrderInput}) { ...on Order { id orderToken state payments { state } } } } `); expect(addPaymentToOrder).toEqual({ id: 'T_1', orderToken: 'token-2', payments: [ { state: 'Settled', }, ], state: 'PaymentSettled', }); }); }); }); export const ACTIVE_ORDER_BY_TOKEN = gql` query ActiveOrderByToken($input: ActiveOrderInput) { activeOrder(activeOrderInput: $input) { id orderToken } } `;
import { SUPER_ADMIN_USER_IDENTIFIER } from '@vendure/common/lib/shared-constants'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import { fail } from 'assert'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config'; import { ADMINISTRATOR_FRAGMENT } from './graphql/fragments'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { AdministratorFragment, AttemptLoginDocument, CurrentUser, DeletionResult, } from './graphql/generated-e2e-admin-types'; import { CREATE_ADMINISTRATOR, UPDATE_ADMINISTRATOR } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; describe('Administrator resolver', () => { const { server, adminClient } = createTestEnvironment(testConfig()); let createdAdmin: AdministratorFragment; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('administrators', async () => { const result = await adminClient.query< Codegen.GetAdministratorsQuery, Codegen.GetAdministratorsQueryVariables >(GET_ADMINISTRATORS); expect(result.administrators.items.length).toBe(1); expect(result.administrators.totalItems).toBe(1); }); it('createAdministrator', async () => { const result = await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { emailAddress: 'test@test.com', firstName: 'First', lastName: 'Last', password: 'password', roleIds: ['1'], }, }); createdAdmin = result.createAdministrator; expect(createdAdmin).toMatchSnapshot(); }); it('administrator', async () => { const result = await adminClient.query< Codegen.GetAdministratorQuery, Codegen.GetAdministratorQueryVariables >(GET_ADMINISTRATOR, { id: createdAdmin.id, }); expect(result.administrator).toEqual(createdAdmin); }); it('updateAdministrator', async () => { const result = await adminClient.query< Codegen.UpdateAdministratorMutation, Codegen.UpdateAdministratorMutationVariables >(UPDATE_ADMINISTRATOR, { input: { id: createdAdmin.id, emailAddress: 'new-email', firstName: 'new first', lastName: 'new last', password: 'new password', roleIds: ['2'], }, }); expect(result.updateAdministrator).toMatchSnapshot(); }); it('updateAdministrator works with partial input', async () => { const result = await adminClient.query< Codegen.UpdateAdministratorMutation, Codegen.UpdateAdministratorMutationVariables >(UPDATE_ADMINISTRATOR, { input: { id: createdAdmin.id, emailAddress: 'newest-email', }, }); expect(result.updateAdministrator.emailAddress).toBe('newest-email'); expect(result.updateAdministrator.firstName).toBe('new first'); expect(result.updateAdministrator.lastName).toBe('new last'); }); it( 'updateAdministrator throws with invalid roleId', assertThrowsWithMessage( () => adminClient.query< Codegen.UpdateAdministratorMutation, Codegen.UpdateAdministratorMutationVariables >(UPDATE_ADMINISTRATOR, { input: { id: createdAdmin.id, emailAddress: 'new-email', firstName: 'new first', lastName: 'new last', password: 'new password', roleIds: ['999'], }, }), 'No Role with the id "999" could be found', ), ); it('deleteAdministrator', async () => { const { administrators: before } = await adminClient.query< Codegen.GetAdministratorsQuery, Codegen.GetAdministratorsQueryVariables >(GET_ADMINISTRATORS); expect(before.totalItems).toBe(2); const { deleteAdministrator } = await adminClient.query< Codegen.DeleteAdministratorMutation, Codegen.DeleteAdministratorMutationVariables >(DELETE_ADMINISTRATOR, { id: createdAdmin.id, }); expect(deleteAdministrator.result).toBe(DeletionResult.DELETED); const { administrators: after } = await adminClient.query< Codegen.GetAdministratorsQuery, Codegen.GetAdministratorsQueryVariables >(GET_ADMINISTRATORS); expect(after.totalItems).toBe(1); }); it('cannot delete sole SuperAdmin', async () => { const { administrators: before } = await adminClient.query< Codegen.GetAdministratorsQuery, Codegen.GetAdministratorsQueryVariables >(GET_ADMINISTRATORS); expect(before.totalItems).toBe(1); expect(before.items[0].emailAddress).toBe('superadmin'); try { const { deleteAdministrator } = await adminClient.query< Codegen.DeleteAdministratorMutation, Codegen.DeleteAdministratorMutationVariables >(DELETE_ADMINISTRATOR, { id: before.items[0].id, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toBe('The sole SuperAdmin cannot be deleted'); } const { administrators: after } = await adminClient.query< Codegen.GetAdministratorsQuery, Codegen.GetAdministratorsQueryVariables >(GET_ADMINISTRATORS); expect(after.totalItems).toBe(1); }); it( 'cannot remove SuperAdmin role from sole SuperAdmin', assertThrowsWithMessage(async () => { const result = await adminClient.query< Codegen.UpdateAdministratorMutation, Codegen.UpdateAdministratorMutationVariables >(UPDATE_ADMINISTRATOR, { input: { id: 'T_1', roleIds: [], }, }); }, 'Cannot remove the SuperAdmin role from the sole SuperAdmin'), ); it('cannot query a deleted Administrator', async () => { const { administrator } = await adminClient.query< Codegen.GetAdministratorQuery, Codegen.GetAdministratorQueryVariables >(GET_ADMINISTRATOR, { id: createdAdmin.id, }); expect(administrator).toBeNull(); }); it('activeAdministrator', async () => { await adminClient.asAnonymousUser(); const { activeAdministrator: result1 } = await adminClient.query<Codegen.ActiveAdministratorQuery>( GET_ACTIVE_ADMINISTRATOR, ); expect(result1).toBeNull(); await adminClient.asSuperAdmin(); const { activeAdministrator: result2 } = await adminClient.query<Codegen.ActiveAdministratorQuery>( GET_ACTIVE_ADMINISTRATOR, ); expect(result2?.emailAddress).toBe(SUPER_ADMIN_USER_IDENTIFIER); }); it('updateActiveAdministrator', async () => { const { updateActiveAdministrator } = await adminClient.query< Codegen.UpdateActiveAdministratorMutation, Codegen.UpdateActiveAdministratorMutationVariables >(UPDATE_ACTIVE_ADMINISTRATOR, { input: { firstName: 'Thomas', lastName: 'Anderson', emailAddress: 'neo@metacortex.com', }, }); expect(updateActiveAdministrator.firstName).toBe('Thomas'); expect(updateActiveAdministrator.lastName).toBe('Anderson'); const { activeAdministrator } = await adminClient.query<Codegen.ActiveAdministratorQuery>( GET_ACTIVE_ADMINISTRATOR, ); expect(activeAdministrator?.firstName).toBe('Thomas'); expect(activeAdministrator?.user.identifier).toBe('neo@metacortex.com'); }); it('supports case-sensitive admin identifiers', async () => { const loginResultGuard: ErrorResultGuard<CurrentUser> = createErrorResultGuard( input => !!input.identifier, ); const { createAdministrator } = await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { emailAddress: 'NewAdmin', firstName: 'New', lastName: 'Admin', password: 'password', roleIds: ['1'], }, }); const { login } = await adminClient.query(AttemptLoginDocument, { username: 'NewAdmin', password: 'password', }); loginResultGuard.assertSuccess(login); expect(login.identifier).toBe('NewAdmin'); }); }); export const GET_ADMINISTRATORS = gql` query GetAdministrators($options: AdministratorListOptions) { administrators(options: $options) { items { ...Administrator } totalItems } } ${ADMINISTRATOR_FRAGMENT} `; export const GET_ADMINISTRATOR = gql` query GetAdministrator($id: ID!) { administrator(id: $id) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const GET_ACTIVE_ADMINISTRATOR = gql` query ActiveAdministrator { activeAdministrator { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const UPDATE_ACTIVE_ADMINISTRATOR = gql` mutation UpdateActiveAdministrator($input: UpdateActiveAdministratorInput!) { updateActiveAdministrator(input: $input) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const DELETE_ADMINISTRATOR = gql` mutation DeleteAdministrator($id: ID!) { deleteAdministrator(id: $id) { message result } } `;
import { ApolloServerPlugin, GraphQLRequestListener, GraphQLServerContext } from '@apollo/server'; import { mergeConfig } from '@vendure/core'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { createTestEnvironment } from '../../testing/lib/create-test-environment'; class MyApolloServerPlugin implements ApolloServerPlugin { static serverWillStartFn = vi.fn(); static requestDidStartFn = vi.fn(); static willSendResponseFn = vi.fn(); static reset() { this.serverWillStartFn = vi.fn(); this.requestDidStartFn = vi.fn(); this.willSendResponseFn = vi.fn(); } async serverWillStart(service: GraphQLServerContext): Promise<void> { MyApolloServerPlugin.serverWillStartFn(service); } async requestDidStart(): Promise<GraphQLRequestListener<any>> { MyApolloServerPlugin.requestDidStartFn(); return { async willSendResponse(requestContext): Promise<void> { const { body } = requestContext.response; if (body.kind === 'single') { MyApolloServerPlugin.willSendResponseFn(body.singleResult.data); } }, }; } } describe('custom apolloServerPlugins', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { apiOptions: { apolloServerPlugins: [new MyApolloServerPlugin()], }, }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('calls serverWillStart()', () => { expect(MyApolloServerPlugin.serverWillStartFn).toHaveBeenCalled(); }); it('runs plugin on shop api query', async () => { MyApolloServerPlugin.reset(); await shopClient.query(gql` query Q1 { product(id: "T_1") { id name } } `); expect(MyApolloServerPlugin.requestDidStartFn).toHaveBeenCalledTimes(1); expect(MyApolloServerPlugin.willSendResponseFn).toHaveBeenCalledTimes(1); expect(MyApolloServerPlugin.willSendResponseFn.mock.calls[0][0]).toEqual({ product: { id: 'T_1', name: 'Laptop', }, }); }); it('runs plugin on admin api query', async () => { MyApolloServerPlugin.reset(); await adminClient.query(gql` query Q2 { product(id: "T_1") { id name } } `); expect(MyApolloServerPlugin.requestDidStartFn).toHaveBeenCalledTimes(1); expect(MyApolloServerPlugin.willSendResponseFn).toHaveBeenCalledTimes(1); expect(MyApolloServerPlugin.willSendResponseFn.mock.calls[0][0]).toEqual({ product: { id: 'T_1', name: 'Laptop', }, }); }); });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { DefaultLogger, LogLevel } from '../src/config'; import { ASSET_FRAGMENT } from './graphql/fragments'; import { CurrencyCode, LanguageCode } from './graphql/generated-e2e-admin-types'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { DeletionResult } from './graphql/generated-e2e-shop-types'; import { ASSIGN_COLLECTIONS_TO_CHANNEL, ASSIGN_PRODUCT_TO_CHANNEL, CREATE_ASSETS, CREATE_CHANNEL, DELETE_ASSET, GET_ASSET, GET_PRODUCT_WITH_VARIANTS, UPDATE_COLLECTION, UPDATE_PRODUCT, } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; const { server, adminClient } = createTestEnvironment(testConfig()); const SECOND_CHANNEL_TOKEN = 'second_channel_token'; let createdAssetId: string; let channel2Id: string; let featuredAssetId: string; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); const { createChannel } = await adminClient.query< Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables >(CREATE_CHANNEL, { input: { code: 'second-channel', token: SECOND_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, currencyCode: CurrencyCode.GBP, pricesIncludeTax: true, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', }, }); channel2Id = createChannel.id; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); describe('ChannelAware Assets', () => { it('Create asset in default channel', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/pps2.jpg')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets.length).toBe(1); createdAssetId = createAssets[0].id; expect(createdAssetId).toBeDefined(); }); it('Get asset from default channel', async () => { const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: createdAssetId, }, ); expect(asset?.id).toEqual(createdAssetId); }); it('Asset is not in channel2', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: createdAssetId, }, ); expect(asset).toBe(null); }); it('Add asset to channel2', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignAssetsToChannel: assets } = await adminClient.query< Codegen.AssignAssetsToChannelMutation, Codegen.AssignAssetsToChannelMutationVariables >(ASSIGN_ASSET_TO_CHANNEL, { input: { assetIds: [createdAssetId], channelId: channel2Id, }, }); expect(assets[0].id).toBe(createdAssetId); }); it('Get asset from channel2', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: createdAssetId, }, ); expect(asset?.id).toBe(createdAssetId); }); it('Delete asset from channel2', async () => { const { deleteAsset } = await adminClient.query< Codegen.DeleteAssetMutation, Codegen.DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: createdAssetId, }, }); expect(deleteAsset.result).toBe(DeletionResult.DELETED); }); it('Asset is available in default channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: createdAssetId, }, ); expect(asset?.id).toEqual(createdAssetId); }); it('Add asset to channel2', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignAssetsToChannel: assets } = await adminClient.query< Codegen.AssignAssetsToChannelMutation, Codegen.AssignAssetsToChannelMutationVariables >(ASSIGN_ASSET_TO_CHANNEL, { input: { assetIds: [createdAssetId], channelId: channel2Id, }, }); expect(assets[0].id).toBe(createdAssetId); }); it( 'Delete asset from all channels with insufficient permission', assertThrowsWithMessage(async () => { await adminClient.asAnonymousUser(); const { deleteAsset } = await adminClient.query< Codegen.DeleteAssetMutation, Codegen.DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: createdAssetId, deleteFromAllChannels: true, }, }); }, 'You are not currently authorized to perform this action'), ); it('Delete asset from all channels as superadmin', async () => { await adminClient.asSuperAdmin(); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { deleteAsset } = await adminClient.query< Codegen.DeleteAssetMutation, Codegen.DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: createdAssetId, deleteFromAllChannels: true, }, }); expect(deleteAsset.result).toEqual(DeletionResult.DELETED); }); it('Asset is also deleted in default channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: createdAssetId, }, ); expect(asset?.id).toBeUndefined(); }); }); describe('Product related assets', () => { it('Featured asset is available in default channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: 'T_1', }); featuredAssetId = product!.featuredAsset!.id; expect(featuredAssetId).toBeDefined(); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: featuredAssetId, }, ); expect(asset?.id).toEqual(featuredAssetId); }); it('Featured asset is not available in channel2', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: featuredAssetId, }, ); expect(asset?.id).toBeUndefined(); }); it('Add Product to channel2', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignProductsToChannel } = await adminClient.query< Codegen.AssignProductsToChannelMutation, Codegen.AssignProductsToChannelMutationVariables >(ASSIGN_PRODUCT_TO_CHANNEL, { input: { channelId: channel2Id, productIds: ['T_1'], }, }); expect(assignProductsToChannel[0].id).toEqual('T_1'); expect(assignProductsToChannel[0].channels.map(c => c.id)).toContain(channel2Id); }); it('Get featured asset from channel2', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: featuredAssetId, }, ); expect(asset?.id).toEqual(featuredAssetId); }); it('Add Product 2 to channel2', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignProductsToChannel } = await adminClient.query< Codegen.AssignProductsToChannelMutation, Codegen.AssignProductsToChannelMutationVariables >(ASSIGN_PRODUCT_TO_CHANNEL, { input: { channelId: channel2Id, productIds: ['T_2'], }, }); expect(assignProductsToChannel[0].id).toEqual('T_2'); expect(assignProductsToChannel[0].channels.map(c => c.id)).toContain(channel2Id); }); it('Add asset A to Product 2 in default channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { updateProduct } = await adminClient.query< Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables >(UPDATE_PRODUCT, { input: { id: 'T_2', assetIds: ['T_3'], }, }); expect(updateProduct.assets.map(a => a.id)).toContain('T_3'); }); it('Channel2 does not have asset A', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: 'T_2', }); expect(product!.assets.find(a => a.id === 'T_3')).toBeUndefined(); }); }); describe('Collection related assets', () => { let collectionFeaturedAssetId: string; it('Featured asset is available in default channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query<Codegen.UpdateCollectionMutation, Codegen.UpdateCollectionMutationVariables>( UPDATE_COLLECTION, { input: { id: 'T_2', featuredAssetId: 'T_3', assetIds: ['T_3'], }, }, ); const { collection } = await adminClient.query< Codegen.GetCollectionWithAssetsQuery, Codegen.GetCollectionWithAssetsQueryVariables >(GET_COLLECTION_WITH_ASSETS, { id: 'T_2', }); collectionFeaturedAssetId = collection!.featuredAsset!.id; expect(collectionFeaturedAssetId).toBeDefined(); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: collectionFeaturedAssetId, }, ); expect(asset?.id).toEqual(collectionFeaturedAssetId); }); it('Featured asset is not available in channel2', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: collectionFeaturedAssetId, }, ); expect(asset?.id).toBeUndefined(); }); it('Add Collection to channel2', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignCollectionsToChannel } = await adminClient.query< Codegen.AssignCollectionsToChannelMutation, Codegen.AssignCollectionsToChannelMutationVariables >(ASSIGN_COLLECTIONS_TO_CHANNEL, { input: { channelId: channel2Id, collectionIds: ['T_2'], }, }); expect(assignCollectionsToChannel[0].id).toEqual('T_2'); }); it('Get featured asset from channel2', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: collectionFeaturedAssetId, }, ); expect(asset?.id).toEqual(collectionFeaturedAssetId); }); }); const GET_COLLECTION_WITH_ASSETS = gql` query GetCollectionWithAssets($id: ID!) { collection(id: $id) { id name featuredAsset { ...Asset } assets { ...Asset } } } ${ASSET_FRAGMENT} `; export const ASSIGN_ASSET_TO_CHANNEL = gql` mutation assignAssetsToChannel($input: AssignAssetsToChannelInput!) { assignAssetsToChannel(input: $input) { ...Asset } } ${ASSET_FRAGMENT} `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { omit } from '@vendure/common/lib/omit'; import { pick } from '@vendure/common/lib/pick'; import { mergeConfig } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import fs from 'fs-extra'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { AssetFragment, AssetWithTagsAndFocalPointFragment, CreateAssetsMutation, DeletionResult, GetProductWithVariantsQuery, LogicalOperator, SortOrder, } from './graphql/generated-e2e-admin-types'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { CREATE_ASSETS, DELETE_ASSET, GET_ASSET, GET_ASSET_FRAGMENT_FIRST, GET_ASSET_LIST, GET_PRODUCT_WITH_VARIANTS, UPDATE_ASSET, } from './graphql/shared-definitions'; describe('Asset resolver', () => { const { server, adminClient } = createTestEnvironment( mergeConfig(testConfig(), { assetOptions: { permittedFileTypes: ['image/*', '.pdf', '.zip'], }, }), ); let firstAssetId: string; let createdAssetId: string; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('assets', async () => { const { assets } = await adminClient.query< Codegen.GetAssetListQuery, Codegen.GetAssetListQueryVariables >(GET_ASSET_LIST, { options: { sort: { name: SortOrder.ASC, }, }, }); expect(assets.totalItems).toBe(4); expect(assets.items.map(a => omit(a, ['id']))).toEqual([ { fileSize: 1680, mimeType: 'image/jpeg', name: 'alexandru-acea-686569-unsplash.jpg', preview: 'test-url/test-assets/alexandru-acea-686569-unsplash__preview.jpg', source: 'test-url/test-assets/alexandru-acea-686569-unsplash.jpg', type: 'IMAGE', }, { fileSize: 1680, mimeType: 'image/jpeg', name: 'derick-david-409858-unsplash.jpg', preview: 'test-url/test-assets/derick-david-409858-unsplash__preview.jpg', source: 'test-url/test-assets/derick-david-409858-unsplash.jpg', type: 'IMAGE', }, { fileSize: 1680, mimeType: 'image/jpeg', name: 'florian-olivo-1166419-unsplash.jpg', preview: 'test-url/test-assets/florian-olivo-1166419-unsplash__preview.jpg', source: 'test-url/test-assets/florian-olivo-1166419-unsplash.jpg', type: 'IMAGE', }, { fileSize: 1680, mimeType: 'image/jpeg', name: 'vincent-botta-736919-unsplash.jpg', preview: 'test-url/test-assets/vincent-botta-736919-unsplash__preview.jpg', source: 'test-url/test-assets/vincent-botta-736919-unsplash.jpg', type: 'IMAGE', }, ]); firstAssetId = assets.items[0].id; }); it('asset', async () => { const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: firstAssetId, }, ); expect(asset).toEqual({ fileSize: 1680, height: 48, id: firstAssetId, mimeType: 'image/jpeg', name: 'alexandru-acea-686569-unsplash.jpg', preview: 'test-url/test-assets/alexandru-acea-686569-unsplash__preview.jpg', source: 'test-url/test-assets/alexandru-acea-686569-unsplash.jpg', type: 'IMAGE', width: 48, }); }); /** * https://github.com/vendure-ecommerce/vendure/issues/459 */ it('transforms URL when fragment defined before query (GH issue #459)', async () => { const { asset } = await adminClient.query< Codegen.GetAssetFragmentFirstQuery, Codegen.GetAssetFragmentFirstQueryVariables >(GET_ASSET_FRAGMENT_FIRST, { id: firstAssetId, }); expect(asset?.preview).toBe('test-url/test-assets/alexandru-acea-686569-unsplash__preview.jpg'); }); describe('createAssets', () => { function isAsset( input: CreateAssetsMutation['createAssets'][number], ): input is AssetWithTagsAndFocalPointFragment { return input.hasOwnProperty('name'); } it('permitted types by mime type', async () => { const filesToUpload = [ path.join(__dirname, 'fixtures/assets/pps1.jpg'), path.join(__dirname, 'fixtures/assets/pps2.jpg'), ]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets.length).toBe(2); const results = createAssets.filter(isAsset); expect(results.map(a => omit(a, ['id'])).sort((a, b) => (a.name < b.name ? -1 : 1))).toEqual([ { fileSize: 1680, focalPoint: null, mimeType: 'image/jpeg', name: 'pps1.jpg', preview: 'test-url/test-assets/pps1__preview.jpg', source: 'test-url/test-assets/pps1.jpg', tags: [], type: 'IMAGE', }, { fileSize: 1680, focalPoint: null, mimeType: 'image/jpeg', name: 'pps2.jpg', preview: 'test-url/test-assets/pps2__preview.jpg', source: 'test-url/test-assets/pps2.jpg', tags: [], type: 'IMAGE', }, ]); createdAssetId = results[0].id; }); it('permitted type by file extension', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/dummy.pdf')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets.length).toBe(1); const results = createAssets.filter(isAsset); expect(results.map(a => omit(a, ['id']))).toEqual([ { fileSize: 1680, focalPoint: null, mimeType: 'application/pdf', name: 'dummy.pdf', preview: 'test-url/test-assets/dummy__preview.pdf.png', source: 'test-url/test-assets/dummy.pdf', tags: [], type: 'BINARY', }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/727 it('file extension with shared type', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/dummy.zip')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets.length).toBe(1); expect(isAsset(createAssets[0])).toBe(true); const results = createAssets.filter(isAsset); expect(results.map(a => omit(a, ['id']))).toEqual([ { fileSize: 1680, focalPoint: null, mimeType: 'application/zip', name: 'dummy.zip', preview: 'test-url/test-assets/dummy__preview.zip.png', source: 'test-url/test-assets/dummy.zip', tags: [], type: 'BINARY', }, ]); }); it('not permitted type', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/dummy.txt')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets.length).toBe(1); expect(createAssets[0]).toEqual({ message: 'The MIME type "text/plain" is not permitted.', mimeType: 'text/plain', fileName: 'dummy.txt', }); }); it('create with new tags', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/pps1.jpg')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null, tags: ['foo', 'bar'] })), }), }); const results = createAssets.filter(isAsset); expect(results.map(a => pick(a, ['id', 'name', 'tags']))).toEqual([ { id: 'T_9', name: 'pps1.jpg', tags: [ { id: 'T_1', value: 'foo' }, { id: 'T_2', value: 'bar' }, ], }, ]); }); it('create with existing tags', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/pps1.jpg')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null, tags: ['foo', 'bar'] })), }), }); const results = createAssets.filter(isAsset); expect(results.map(a => pick(a, ['id', 'name', 'tags']))).toEqual([ { id: 'T_10', name: 'pps1.jpg', tags: [ { id: 'T_1', value: 'foo' }, { id: 'T_2', value: 'bar' }, ], }, ]); }); it('create with new and existing tags', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/pps1.jpg')]; const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null, tags: ['quux', 'bar'] })), }), }); const results = createAssets.filter(isAsset); expect(results.map(a => pick(a, ['id', 'name', 'tags']))).toEqual([ { id: 'T_11', name: 'pps1.jpg', tags: [ { id: 'T_3', value: 'quux' }, { id: 'T_2', value: 'bar' }, ], }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/990 it('errors if the filesize is too large', async () => { /** * Based on https://stackoverflow.com/a/49433633/772859 */ function createEmptyFileOfSize(fileName: string, sizeInBytes: number) { return new Promise((resolve, reject) => { const fh = fs.openSync(fileName, 'w'); fs.writeSync(fh, 'ok', Math.max(0, sizeInBytes - 2)); fs.closeSync(fh); resolve(true); }); } const twentyOneMib = 22020096; const filename = path.join(__dirname, 'fixtures/assets/temp_large_file.pdf'); await createEmptyFileOfSize(filename, twentyOneMib); try { const { createAssets }: Codegen.CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: [filename], mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toContain('File truncated as it exceeds the 20971520 byte size limit'); } finally { fs.rmSync(filename); } }); }); describe('filter by tags', () => { it('and', async () => { const { assets } = await adminClient.query< Codegen.GetAssetListQuery, Codegen.GetAssetListQueryVariables >(GET_ASSET_LIST, { options: { tags: ['foo', 'bar'], tagsOperator: LogicalOperator.AND, }, }); expect(assets.items.map(i => i.id).sort()).toEqual(['T_10', 'T_9']); }); it('or', async () => { const { assets } = await adminClient.query< Codegen.GetAssetListQuery, Codegen.GetAssetListQueryVariables >(GET_ASSET_LIST, { options: { tags: ['foo', 'bar'], tagsOperator: LogicalOperator.OR, }, }); expect(assets.items.map(i => i.id).sort()).toEqual(['T_10', 'T_11', 'T_9']); }); it('empty array', async () => { const { assets } = await adminClient.query< Codegen.GetAssetListQuery, Codegen.GetAssetListQueryVariables >(GET_ASSET_LIST, { options: { tags: [], }, }); expect(assets.totalItems).toBe(11); }); }); describe('updateAsset', () => { it('update name', async () => { const { updateAsset } = await adminClient.query< Codegen.UpdateAssetMutation, Codegen.UpdateAssetMutationVariables >(UPDATE_ASSET, { input: { id: firstAssetId, name: 'new name', }, }); expect(updateAsset.name).toEqual('new name'); }); it('update focalPoint', async () => { const { updateAsset } = await adminClient.query< Codegen.UpdateAssetMutation, Codegen.UpdateAssetMutationVariables >(UPDATE_ASSET, { input: { id: firstAssetId, focalPoint: { x: 0.3, y: 0.9, }, }, }); expect(updateAsset.focalPoint).toEqual({ x: 0.3, y: 0.9, }); }); it('unset focalPoint', async () => { const { updateAsset } = await adminClient.query< Codegen.UpdateAssetMutation, Codegen.UpdateAssetMutationVariables >(UPDATE_ASSET, { input: { id: firstAssetId, focalPoint: null, }, }); expect(updateAsset.focalPoint).toEqual(null); }); it('update tags', async () => { const { updateAsset } = await adminClient.query< Codegen.UpdateAssetMutation, Codegen.UpdateAssetMutationVariables >(UPDATE_ASSET, { input: { id: firstAssetId, tags: ['foo', 'quux'], }, }); expect(updateAsset.tags).toEqual([ { id: 'T_1', value: 'foo' }, { id: 'T_3', value: 'quux' }, ]); }); it('remove tags', async () => { const { updateAsset } = await adminClient.query< Codegen.UpdateAssetMutation, Codegen.UpdateAssetMutationVariables >(UPDATE_ASSET, { input: { id: firstAssetId, tags: [], }, }); expect(updateAsset.tags).toEqual([]); }); }); describe('deleteAsset', () => { let firstProduct: NonNullable<GetProductWithVariantsQuery['product']>; beforeAll(async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: 'T_1', }); firstProduct = product!; }); it('non-featured asset', async () => { const { deleteAsset } = await adminClient.query< Codegen.DeleteAssetMutation, Codegen.DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: createdAssetId, }, }); expect(deleteAsset.result).toBe(DeletionResult.DELETED); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: createdAssetId, }, ); expect(asset).toBeNull(); }); it('featured asset not deleted', async () => { const { deleteAsset } = await adminClient.query< Codegen.DeleteAssetMutation, Codegen.DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: firstProduct.featuredAsset!.id, }, }); expect(deleteAsset.result).toBe(DeletionResult.NOT_DELETED); expect(deleteAsset.message).toContain('The selected Asset is featured by 1 Product'); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: firstAssetId, }, ); expect(asset).not.toBeNull(); }); it('featured asset force deleted', async () => { const { product: p1 } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: firstProduct.id, }); expect(p1!.assets.length).toEqual(1); const { deleteAsset } = await adminClient.query< Codegen.DeleteAssetMutation, Codegen.DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: firstProduct.featuredAsset!.id, force: true, }, }); expect(deleteAsset.result).toBe(DeletionResult.DELETED); const { asset } = await adminClient.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>( GET_ASSET, { id: firstAssetId, }, ); expect(asset).not.toBeNull(); const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: firstProduct.id, }); expect(product!.featuredAsset).toBeNull(); expect(product!.assets.length).toEqual(0); }); }); });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '@vendure/common/lib/shared-constants'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import { DocumentNode } from 'graphql'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { ProtectedFieldsPlugin, transactions } from './fixtures/test-plugins/with-protected-field-resolver'; import { ErrorCode, Permission } from './graphql/generated-e2e-admin-types'; import * as Codegen from './graphql/generated-e2e-admin-types'; import * as CodegenShop from './graphql/generated-e2e-shop-types'; import { ATTEMPT_LOGIN, CREATE_ADMINISTRATOR, CREATE_CUSTOMER, CREATE_CUSTOMER_GROUP, CREATE_PRODUCT, CREATE_ROLE, GET_CUSTOMER_LIST, GET_PRODUCT_LIST, GET_TAX_RATES_LIST, ME, UPDATE_PRODUCT, UPDATE_TAX_RATE, } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; describe('Authorization & permissions', () => { const { server, adminClient, shopClient } = createTestEnvironment({ ...testConfig(), plugins: [ProtectedFieldsPlugin], }); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 5, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); describe('admin permissions', () => { describe('Anonymous user', () => { beforeAll(async () => { await adminClient.asAnonymousUser(); }); it( 'me is not permitted', assertThrowsWithMessage(async () => { await adminClient.query<Codegen.MeQuery>(ME); }, 'You are not currently authorized to perform this action'), ); it('can attempt login', async () => { await assertRequestAllowed<Codegen.MutationLoginArgs>(ATTEMPT_LOGIN, { username: SUPER_ADMIN_USER_IDENTIFIER, password: SUPER_ADMIN_USER_PASSWORD, rememberMe: false, }); }); }); describe('Customer user', () => { let customerEmailAddress: string; beforeAll(async () => { await adminClient.asSuperAdmin(); const { customers } = await adminClient.query<Codegen.GetCustomerListQuery>( GET_CUSTOMER_LIST, ); customerEmailAddress = customers.items[0].emailAddress; }); it('cannot login', async () => { const result = await adminClient.asUserWithCredentials(customerEmailAddress, 'test'); expect(result.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR); }); }); describe('ReadCatalog permission', () => { beforeAll(async () => { await adminClient.asSuperAdmin(); const { identifier, password } = await createAdministratorWithPermissions('ReadCatalog', [ Permission.ReadCatalog, ]); await adminClient.asUserWithCredentials(identifier, password); }); it('me returns correct permissions', async () => { const { me } = await adminClient.query<Codegen.MeQuery>(ME); expect(me!.channels[0].permissions).toEqual([ Permission.Authenticated, Permission.ReadCatalog, ]); }); it('can read', async () => { await assertRequestAllowed(GET_PRODUCT_LIST); }); it('cannot update', async () => { await assertRequestForbidden<Codegen.MutationUpdateProductArgs>(UPDATE_PRODUCT, { input: { id: '1', translations: [], }, }); }); it('cannot create', async () => { await assertRequestForbidden<Codegen.MutationCreateProductArgs>(CREATE_PRODUCT, { input: { translations: [], }, }); }); }); describe('CRUD on Customers permissions', () => { beforeAll(async () => { await adminClient.asSuperAdmin(); const { identifier, password } = await createAdministratorWithPermissions('CRUDCustomer', [ Permission.CreateCustomer, Permission.ReadCustomer, Permission.UpdateCustomer, Permission.DeleteCustomer, ]); await adminClient.asUserWithCredentials(identifier, password); }); it('me returns correct permissions', async () => { const { me } = await adminClient.query<Codegen.MeQuery>(ME); expect(me!.channels[0].permissions).toEqual([ Permission.Authenticated, Permission.CreateCustomer, Permission.ReadCustomer, Permission.UpdateCustomer, Permission.DeleteCustomer, ]); }); it('can create', async () => { await assertRequestAllowed( gql(`mutation CanCreateCustomer($input: CreateCustomerInput!) { createCustomer(input: $input) { ... on Customer { id } } } `), { input: { emailAddress: '', firstName: '', lastName: '' } }, ); }); it('can read', async () => { await assertRequestAllowed(gql` query GetCustomerCount { customers { totalItems } } `); }); }); }); describe('administrator and customer users with the same email address', () => { const emailAddress = 'same-email@test.com'; const adminPassword = 'admin-password'; const customerPassword = 'customer-password'; const loginErrorGuard: ErrorResultGuard<Codegen.CurrentUserFragment> = createErrorResultGuard( input => !!input.identifier, ); beforeAll(async () => { await adminClient.asSuperAdmin(); await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { emailAddress, firstName: 'First', lastName: 'Last', password: adminPassword, roleIds: ['1'], }, }); await adminClient.query<Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables>( CREATE_CUSTOMER, { input: { emailAddress, firstName: 'First', lastName: 'Last', }, password: customerPassword, }, ); }); beforeEach(async () => { await adminClient.asAnonymousUser(); await shopClient.asAnonymousUser(); }); it('can log in as an administrator', async () => { const loginResult = await adminClient.query< CodegenShop.AttemptLoginMutation, CodegenShop.AttemptLoginMutationVariables >(ATTEMPT_LOGIN, { username: emailAddress, password: adminPassword, }); loginErrorGuard.assertSuccess(loginResult.login); expect(loginResult.login.identifier).toEqual(emailAddress); }); it('can log in as a customer', async () => { const loginResult = await shopClient.query< CodegenShop.AttemptLoginMutation, CodegenShop.AttemptLoginMutationVariables >(ATTEMPT_LOGIN, { username: emailAddress, password: customerPassword, }); loginErrorGuard.assertSuccess(loginResult.login); expect(loginResult.login.identifier).toEqual(emailAddress); }); it('cannot log in as an administrator using a customer password', async () => { const loginResult = await adminClient.query< CodegenShop.AttemptLoginMutation, CodegenShop.AttemptLoginMutationVariables >(ATTEMPT_LOGIN, { username: emailAddress, password: customerPassword, }); loginErrorGuard.assertErrorResult(loginResult.login); expect(loginResult.login.errorCode).toEqual(ErrorCode.INVALID_CREDENTIALS_ERROR); }); it('cannot log in as a customer using an administrator password', async () => { const loginResult = await shopClient.query< CodegenShop.AttemptLoginMutation, CodegenShop.AttemptLoginMutationVariables >(ATTEMPT_LOGIN, { username: emailAddress, password: adminPassword, }); loginErrorGuard.assertErrorResult(loginResult.login); expect(loginResult.login.errorCode).toEqual(ErrorCode.INVALID_CREDENTIALS_ERROR); }); }); describe('protected field resolvers', () => { let readCatalogAdmin: { identifier: string; password: string }; let transactionsAdmin: { identifier: string; password: string }; const GET_PRODUCT_WITH_TRANSACTIONS = ` query GetProductWithTransactions($id: ID!) { product(id: $id) { id transactions { id amount description } } } `; beforeAll(async () => { await adminClient.asSuperAdmin(); transactionsAdmin = await createAdministratorWithPermissions('Transactions', [ Permission.ReadCatalog, transactions.Permission, ]); readCatalogAdmin = await createAdministratorWithPermissions('ReadCatalog', [ Permission.ReadCatalog, ]); }); it('protected field not resolved without permissions', async () => { await adminClient.asUserWithCredentials(readCatalogAdmin.identifier, readCatalogAdmin.password); try { const status = await adminClient.query(gql(GET_PRODUCT_WITH_TRANSACTIONS), { id: 'T_1' }); fail('Should have thrown'); } catch (e: any) { expect(getErrorCode(e)).toBe('FORBIDDEN'); } }); it('protected field is resolved with permissions', async () => { await adminClient.asUserWithCredentials(transactionsAdmin.identifier, transactionsAdmin.password); const { product } = await adminClient.query(gql(GET_PRODUCT_WITH_TRANSACTIONS), { id: 'T_1' }); expect(product.id).toBe('T_1'); expect(product.transactions).toEqual([ { id: 'T_1', amount: 100, description: 'credit' }, { id: 'T_2', amount: -50, description: 'debit' }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/730 it('protects against deep query data leakage', async () => { await adminClient.asSuperAdmin(); const { createCustomerGroup } = await adminClient.query< Codegen.CreateCustomerGroupMutation, Codegen.CreateCustomerGroupMutationVariables >(CREATE_CUSTOMER_GROUP, { input: { name: 'Test group', customerIds: ['T_1', 'T_2', 'T_3', 'T_4'], }, }); const taxRateName = `Standard Tax ${initialData.defaultZone}`; const { taxRates } = await adminClient.query< Codegen.GetTaxRatesQuery, Codegen.GetTaxRatesQueryVariables >(GET_TAX_RATES_LIST, { options: { filter: { name: { eq: taxRateName }, }, }, }); const standardTax = taxRates.items[0]; expect(standardTax.name).toBe(taxRateName); await adminClient.query<Codegen.UpdateTaxRateMutation, Codegen.UpdateTaxRateMutationVariables>( UPDATE_TAX_RATE, { input: { id: standardTax.id, customerGroupId: createCustomerGroup.id, }, }, ); try { const status = await shopClient.query( gql(` query DeepFieldResolutionTestQuery{ product(id: "T_1") { variants { taxRateApplied { customerGroup { customers { items { id emailAddress } } } } } } }`), { id: 'T_1' }, ); fail('Should have thrown'); } catch (e: any) { expect(getErrorCode(e)).toBe('FORBIDDEN'); } }); }); async function assertRequestAllowed<V>(operation: DocumentNode, variables?: V) { try { const status = await adminClient.queryStatus(operation, variables); expect(status).toBe(200); } catch (e: any) { const errorCode = getErrorCode(e); if (!errorCode) { fail(`Unexpected failure: ${JSON.stringify(e)}`); } else { fail(`Operation should be allowed, got status ${getErrorCode(e)}`); } } } async function assertRequestForbidden<V>(operation: DocumentNode, variables: V) { try { const status = await adminClient.query(operation, variables); fail('Should have thrown'); } catch (e: any) { expect(getErrorCode(e)).toBe('FORBIDDEN'); } } function getErrorCode(err: any): string { return err.response.errors[0].extensions.code; } async function createAdministratorWithPermissions( code: string, permissions: Permission[], ): Promise<{ identifier: string; password: string }> { const roleResult = await adminClient.query< Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables >(CREATE_ROLE, { input: { code, description: '', permissions, }, }); const role = roleResult.createRole; const identifier = `${code}@${Math.random().toString(16).substr(2, 8)}`; const password = 'test'; const adminResult = await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { emailAddress: identifier, firstName: code, lastName: 'Admin', password, roleIds: [role.id], }, }); const admin = adminResult.createAdministrator; return { identifier, password, }; } });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { ErrorCode } from '@vendure/common/lib/generated-shop-types'; import { pick } from '@vendure/common/lib/pick'; import { mergeConfig, NativeAuthenticationStrategy } from '@vendure/core'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { TestAuthenticationStrategy, TestAuthenticationStrategy2, TestSSOStrategyAdmin, TestSSOStrategyShop, VALID_AUTH_TOKEN, } from './fixtures/test-authentication-strategies'; import { CURRENT_USER_FRAGMENT } from './graphql/fragments'; import { AttemptLoginDocument, CurrentUserFragment, CustomerFragment, HistoryEntryType, } from './graphql/generated-e2e-admin-types'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { RegisterMutation, RegisterMutationVariables } from './graphql/generated-e2e-shop-types'; import { CREATE_CUSTOMER, DELETE_CUSTOMER, GET_CUSTOMER_HISTORY, ME } from './graphql/shared-definitions'; import { REGISTER_ACCOUNT } from './graphql/shop-definitions'; const currentUserGuard: ErrorResultGuard<CurrentUserFragment> = createErrorResultGuard( input => input.identifier != null, ); const customerGuard: ErrorResultGuard<CustomerFragment> = createErrorResultGuard( input => input.emailAddress != null, ); describe('AuthenticationStrategy', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { authOptions: { shopAuthenticationStrategy: [ new NativeAuthenticationStrategy(), new TestAuthenticationStrategy(), new TestAuthenticationStrategy2(), new TestSSOStrategyShop(), ], adminAuthenticationStrategy: [new NativeAuthenticationStrategy(), new TestSSOStrategyAdmin()], }, }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); describe('external auth', () => { const userData = { email: 'test@email.com', firstName: 'Cixin', lastName: 'Liu', }; let newCustomerId: string; it('fails with a bad token', async () => { const { authenticate } = await shopClient.query(AUTHENTICATE, { input: { test_strategy: { token: 'bad-token', }, }, }); expect(authenticate.message).toBe('The provided credentials are invalid'); expect(authenticate.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR); expect(authenticate.authenticationError).toBe(''); }); it('fails with an expired token', async () => { const { authenticate } = await shopClient.query(AUTHENTICATE, { input: { test_strategy: { token: 'expired-token', }, }, }); expect(authenticate.message).toBe('The provided credentials are invalid'); expect(authenticate.errorCode).toBe(ErrorCode.INVALID_CREDENTIALS_ERROR); expect(authenticate.authenticationError).toBe('Expired token'); }); it('creates a new Customer with valid token', async () => { const { customers: before } = await adminClient.query<Codegen.GetCustomersQuery>(GET_CUSTOMERS); expect(before.totalItems).toBe(1); const { authenticate } = await shopClient.query<Codegen.AuthenticateMutation>(AUTHENTICATE, { input: { test_strategy: { token: VALID_AUTH_TOKEN, userData, }, }, }); currentUserGuard.assertSuccess(authenticate); expect(authenticate.identifier).toEqual(userData.email); const { customers: after } = await adminClient.query<Codegen.GetCustomersQuery>(GET_CUSTOMERS); expect(after.totalItems).toBe(2); expect(after.items.map(i => i.emailAddress)).toEqual([ 'hayden.zieme12@hotmail.com', userData.email, ]); newCustomerId = after.items[1].id; }); it('creates customer history entry', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: newCustomerId, }); expect( customer?.history.items.sort((a, b) => (a.id > b.id ? 1 : -1)).map(pick(['type', 'data'])), ).toEqual([ { type: HistoryEntryType.CUSTOMER_REGISTERED, data: { strategy: 'test_strategy', }, }, { type: HistoryEntryType.CUSTOMER_VERIFIED, data: { strategy: 'test_strategy', }, }, ]); }); it('user authenticationMethod populated', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerUserAuthQuery, Codegen.GetCustomerUserAuthQueryVariables >(GET_CUSTOMER_USER_AUTH, { id: newCustomerId, }); expect(customer?.user?.authenticationMethods.length).toBe(1); expect(customer?.user?.authenticationMethods[0].strategy).toBe('test_strategy'); }); it('creates authenticated session', async () => { const { me } = await shopClient.query<Codegen.MeQuery>(ME); expect(me?.identifier).toBe(userData.email); }); it('log out', async () => { await shopClient.asAnonymousUser(); }); it('logging in again re-uses created User & Customer', async () => { const { authenticate } = await shopClient.query<Codegen.AuthenticateMutation>(AUTHENTICATE, { input: { test_strategy: { token: VALID_AUTH_TOKEN, userData, }, }, }); currentUserGuard.assertSuccess(authenticate); expect(authenticate.identifier).toEqual(userData.email); const { customers: after } = await adminClient.query<Codegen.GetCustomersQuery>(GET_CUSTOMERS); expect(after.totalItems).toBe(2); expect(after.items.map(i => i.emailAddress)).toEqual([ 'hayden.zieme12@hotmail.com', userData.email, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/695 it('multiple external auth strategies to not interfere with one another', async () => { const EXPECTED_CUSTOMERS = [ { emailAddress: 'hayden.zieme12@hotmail.com', id: 'T_1', }, { emailAddress: 'test@email.com', id: 'T_2', }, ]; const { customers: customers1 } = await adminClient.query<Codegen.GetCustomersQuery>( GET_CUSTOMERS, ); expect(customers1.items).toEqual(EXPECTED_CUSTOMERS); const { authenticate: auth1 } = await shopClient.query<Codegen.AuthenticateMutation>( AUTHENTICATE, { input: { test_strategy2: { token: VALID_AUTH_TOKEN, email: userData.email, }, }, }, ); currentUserGuard.assertSuccess(auth1); expect(auth1.identifier).toBe(userData.email); const { customers: customers2 } = await adminClient.query<Codegen.GetCustomersQuery>( GET_CUSTOMERS, ); expect(customers2.items).toEqual(EXPECTED_CUSTOMERS); await shopClient.asAnonymousUser(); const { authenticate: auth2 } = await shopClient.query<Codegen.AuthenticateMutation>( AUTHENTICATE, { input: { test_strategy: { token: VALID_AUTH_TOKEN, userData, }, }, }, ); currentUserGuard.assertSuccess(auth2); expect(auth2.identifier).toBe(userData.email); const { customers: customers3 } = await adminClient.query<Codegen.GetCustomersQuery>( GET_CUSTOMERS, ); expect(customers3.items).toEqual(EXPECTED_CUSTOMERS); }); it('registerCustomerAccount with external email', async () => { const successErrorGuard: ErrorResultGuard<{ success: boolean }> = createErrorResultGuard( input => input.success != null, ); const { registerCustomerAccount } = await shopClient.query< RegisterMutation, RegisterMutationVariables >(REGISTER_ACCOUNT, { input: { emailAddress: userData.email, }, }); successErrorGuard.assertSuccess(registerCustomerAccount); expect(registerCustomerAccount.success).toBe(true); const { customer } = await adminClient.query< Codegen.GetCustomerUserAuthQuery, Codegen.GetCustomerUserAuthQueryVariables >(GET_CUSTOMER_USER_AUTH, { id: newCustomerId, }); expect(customer?.user?.authenticationMethods.length).toBe(3); expect(customer?.user?.authenticationMethods.map(m => m.strategy)).toEqual([ 'test_strategy', 'test_strategy2', 'native', ]); const { customer: customer2 } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: newCustomerId, options: { skip: 4, }, }); expect(customer2?.history.items.map(pick(['type', 'data']))).toEqual([ { type: HistoryEntryType.CUSTOMER_REGISTERED, data: { strategy: 'native', }, }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/926 it('Customer and Admin external auth does not reuse same User for different strategies', async () => { const emailAddress = 'hello@test-domain.com'; await adminClient.asAnonymousUser(); const { authenticate: adminAuth } = await adminClient.query<Codegen.AuthenticateMutation>( AUTHENTICATE, { input: { test_sso_strategy_admin: { email: emailAddress, }, }, }, ); currentUserGuard.assertSuccess(adminAuth); const { authenticate: shopAuth } = await shopClient.query<Codegen.AuthenticateMutation>( AUTHENTICATE, { input: { test_sso_strategy_shop: { email: emailAddress, }, }, }, ); currentUserGuard.assertSuccess(shopAuth); expect(adminAuth.id).not.toBe(shopAuth.id); }); }); describe('native auth', () => { const testEmailAddress = 'test-person@testdomain.com'; // https://github.com/vendure-ecommerce/vendure/issues/486#issuecomment-704991768 it('allows login for an email address which is shared by a previously-deleted Customer', async () => { const { createCustomer: result1 } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { firstName: 'Test', lastName: 'Person', emailAddress: testEmailAddress, }, password: 'password1', }); customerGuard.assertSuccess(result1); await adminClient.query<Codegen.DeleteCustomerMutation, Codegen.DeleteCustomerMutationVariables>( DELETE_CUSTOMER, { id: result1.id, }, ); const { createCustomer: result2 } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { firstName: 'Test', lastName: 'Person', emailAddress: testEmailAddress, }, password: 'password2', }); customerGuard.assertSuccess(result2); const { authenticate } = await shopClient.query(AUTHENTICATE, { input: { native: { username: testEmailAddress, password: 'password2', }, }, }); currentUserGuard.assertSuccess(authenticate); expect(pick(authenticate, ['id', 'identifier'])).toEqual({ id: result2.user!.id, identifier: result2.emailAddress, }); }); }); }); describe('No NativeAuthStrategy on Shop API', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { authOptions: { shopAuthenticationStrategy: [new TestAuthenticationStrategy()], }, }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); // https://github.com/vendure-ecommerce/vendure/issues/2282 it('can log in to Admin API', async () => { const { login } = await adminClient.query(AttemptLoginDocument, { username: 'superadmin', password: 'superadmin', }); currentUserGuard.assertSuccess(login); expect(login.identifier).toBe('superadmin'); }); }); const AUTHENTICATE = gql` mutation Authenticate($input: AuthenticationInput!) { authenticate(input: $input) { ...CurrentUser ... on InvalidCredentialsError { authenticationError errorCode message } } } ${CURRENT_USER_FRAGMENT} `; const GET_CUSTOMERS = gql` query GetCustomers { customers { totalItems items { id emailAddress } } } `; const GET_CUSTOMER_USER_AUTH = gql` query GetCustomerUserAuth($id: ID!) { customer(id: $id) { id user { id verified authenticationMethods { id strategy } } } } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { createErrorResultGuard, createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN, ErrorResultGuard, } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { CurrencyCode, DeletionResult, ErrorCode, LanguageCode, Permission, } from './graphql/generated-e2e-admin-types'; import { ASSIGN_PRODUCT_TO_CHANNEL, CREATE_ADMINISTRATOR, CREATE_CHANNEL, CREATE_ROLE, GET_CHANNELS, GET_CUSTOMER_LIST, GET_PRODUCT_LIST, GET_PRODUCT_WITH_VARIANTS, ME, UPDATE_CHANNEL, } from './graphql/shared-definitions'; import { GET_ACTIVE_ORDER } from './graphql/shop-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; describe('Channels', () => { const { server, adminClient, shopClient } = createTestEnvironment(testConfig()); const SECOND_CHANNEL_TOKEN = 'second_channel_token'; let secondChannelAdminRole: Codegen.CreateRoleMutation['createRole']; let customerUser: Codegen.GetCustomerListQuery['customers']['items'][number]; const channelGuard: ErrorResultGuard<Codegen.ChannelFragment> = createErrorResultGuard<Codegen.ChannelFragment>(input => !!input.defaultLanguageCode); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST, { options: { take: 1 }, }); customerUser = customers.items[0]; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('createChannel returns error result defaultLanguageCode not available', async () => { const { createChannel } = await adminClient.query< Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables >(CREATE_CHANNEL, { input: { code: 'second-channel', token: SECOND_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.zh, currencyCode: CurrencyCode.GBP, pricesIncludeTax: true, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', }, }); channelGuard.assertErrorResult(createChannel); expect(createChannel.message).toBe( 'Language "zh" is not available. First enable it via GlobalSettings and try again', ); expect(createChannel.errorCode).toBe(ErrorCode.LANGUAGE_NOT_AVAILABLE_ERROR); expect(createChannel.languageCode).toBe('zh'); }); it('create a new Channel', async () => { const { createChannel } = await adminClient.query< Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables >(CREATE_CHANNEL, { input: { code: 'second-channel', token: SECOND_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, currencyCode: CurrencyCode.GBP, pricesIncludeTax: true, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', }, }); channelGuard.assertSuccess(createChannel); expect(createChannel).toEqual({ id: 'T_2', code: 'second-channel', token: SECOND_CHANNEL_TOKEN, availableCurrencyCodes: ['GBP'], currencyCode: 'GBP', defaultCurrencyCode: 'GBP', defaultLanguageCode: 'en', defaultShippingZone: { id: 'T_1', }, defaultTaxZone: { id: 'T_1', }, pricesIncludeTax: true, }); }); // it('update currencyCode', async () => { // const { updateChannel } = await adminClient.query< // Codegen.UpdateChannelMutation, // Codegen.UpdateChannelMutationVariables // >(UPDATE_CHANNEL, { // input: { // id: 'T_1', // currencyCode: CurrencyCode.MYR, // }, // }); // channelGuard.assertSuccess(updateChannel); // expect(updateChannel.currencyCode).toBe('MYR'); // }); it('superadmin has all permissions on new channel', async () => { const { me } = await adminClient.query<Codegen.MeQuery>(ME); expect(me!.channels.length).toBe(2); const secondChannelData = me!.channels.find(c => c.token === SECOND_CHANNEL_TOKEN); const nonOwnerPermissions = Object.values(Permission).filter( p => p !== Permission.Owner && p !== Permission.Public, ); expect(secondChannelData!.permissions.sort()).toEqual(nonOwnerPermissions); }); it('customer has Authenticated permission on new channel', async () => { await shopClient.asUserWithCredentials(customerUser.emailAddress, 'test'); const { me } = await shopClient.query<Codegen.MeQuery>(ME); expect(me!.channels.length).toBe(2); const secondChannelData = me!.channels.find(c => c.token === SECOND_CHANNEL_TOKEN); expect(me!.channels).toEqual([ { code: DEFAULT_CHANNEL_CODE, permissions: ['Authenticated'], token: E2E_DEFAULT_CHANNEL_TOKEN, }, { code: 'second-channel', permissions: ['Authenticated'], token: SECOND_CHANNEL_TOKEN, }, ]); }); it('createRole on second Channel', async () => { const { createRole } = await adminClient.query< Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables >(CREATE_ROLE, { input: { description: 'second channel admin', code: 'second-channel-admin', channelIds: ['T_2'], permissions: [ Permission.ReadCatalog, Permission.ReadSettings, Permission.ReadAdministrator, Permission.CreateAdministrator, Permission.UpdateAdministrator, ], }, }); expect(createRole.channels).toEqual([ { id: 'T_2', code: 'second-channel', token: SECOND_CHANNEL_TOKEN, }, ]); secondChannelAdminRole = createRole; }); it('createAdministrator with second-channel-admin role', async () => { const { createAdministrator } = await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { firstName: 'Admin', lastName: 'Two', emailAddress: 'admin2@test.com', password: 'test', roleIds: [secondChannelAdminRole.id], }, }); expect(createAdministrator.user.roles.map(r => r.description)).toEqual(['second channel admin']); }); it( 'cannot create role on channel for which admin does not have CreateAdministrator permission', assertThrowsWithMessage(async () => { await adminClient.asUserWithCredentials('admin2@test.com', 'test'); await adminClient.query<Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables>( CREATE_ROLE, { input: { description: 'read default channel catalog', code: 'read default channel catalog', channelIds: ['T_1'], permissions: [Permission.ReadCatalog], }, }, ); }, 'You are not currently authorized to perform this action'), ); it('can create role on channel for which admin has CreateAdministrator permission', async () => { const { createRole } = await adminClient.query< Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables >(CREATE_ROLE, { input: { description: 'read second channel catalog', code: 'read-second-channel-catalog', channelIds: ['T_2'], permissions: [Permission.ReadCatalog], }, }); expect(createRole.channels).toEqual([ { id: 'T_2', code: 'second-channel', token: SECOND_CHANNEL_TOKEN, }, ]); }); it('createRole with no channelId implicitly uses active channel', async () => { await adminClient.asSuperAdmin(); const { createRole } = await adminClient.query< Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables >(CREATE_ROLE, { input: { description: 'update second channel catalog', code: 'update-second-channel-catalog', permissions: [Permission.UpdateCatalog], }, }); expect(createRole.channels).toEqual([ { id: 'T_2', code: 'second-channel', token: SECOND_CHANNEL_TOKEN, }, ]); }); describe('setting defaultLanguage', () => { it('returns error result if languageCode not in availableLanguages', async () => { await adminClient.asSuperAdmin(); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { updateChannel } = await adminClient.query< Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables >(UPDATE_CHANNEL, { input: { id: 'T_1', defaultLanguageCode: LanguageCode.zh, }, }); channelGuard.assertErrorResult(updateChannel); expect(updateChannel.message).toBe( 'Language "zh" is not available. First enable it via GlobalSettings and try again', ); expect(updateChannel.errorCode).toBe(ErrorCode.LANGUAGE_NOT_AVAILABLE_ERROR); expect(updateChannel.languageCode).toBe('zh'); }); it('allows setting to an available language', async () => { await adminClient.asSuperAdmin(); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query< Codegen.UpdateGlobalLanguagesMutation, Codegen.UpdateGlobalLanguagesMutationVariables >(UPDATE_GLOBAL_LANGUAGES, { input: { availableLanguages: [LanguageCode.en, LanguageCode.zh], }, }); const { updateChannel } = await adminClient.query< Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables >(UPDATE_CHANNEL, { input: { id: 'T_1', defaultLanguageCode: LanguageCode.zh, }, }); channelGuard.assertSuccess(updateChannel); expect(updateChannel.defaultLanguageCode).toBe(LanguageCode.zh); }); }); it('deleteChannel', async () => { const PROD_ID = 'T_1'; await adminClient.asSuperAdmin(); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignProductsToChannel } = await adminClient.query< Codegen.AssignProductsToChannelMutation, Codegen.AssignProductsToChannelMutationVariables >(ASSIGN_PRODUCT_TO_CHANNEL, { input: { channelId: 'T_2', productIds: [PROD_ID], }, }); expect(assignProductsToChannel[0].channels.map(c => c.id).sort()).toEqual(['T_1', 'T_2']); // create a Session on the Channel to be deleted to ensure it gets cleaned up shopClient.setChannelToken(SECOND_CHANNEL_TOKEN); await shopClient.query(GET_ACTIVE_ORDER); const { deleteChannel } = await adminClient.query< Codegen.DeleteChannelMutation, Codegen.DeleteChannelMutationVariables >(DELETE_CHANNEL, { id: 'T_2', }); expect(deleteChannel.result).toBe(DeletionResult.DELETED); const { channels } = await adminClient.query<Codegen.GetChannelsQuery>(GET_CHANNELS); expect(channels.items.map(c => c.id).sort()).toEqual(['T_1']); const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: PROD_ID, }); expect(product!.channels.map(c => c.id)).toEqual(['T_1']); }); describe('currencyCode support', () => { beforeAll(async () => { await adminClient.asSuperAdmin(); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); }); it('initial currencyCode values', async () => { const { channel } = await adminClient.query< Codegen.GetChannelQuery, Codegen.GetChannelQueryVariables >(GET_CHANNEL, { id: 'T_1', }); expect(channel?.defaultCurrencyCode).toBe('USD'); expect(channel?.availableCurrencyCodes).toEqual(['USD']); }); it('setting defaultCurrencyCode adds it to availableCurrencyCodes', async () => { const { updateChannel } = await adminClient.query< Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables >(UPDATE_CHANNEL, { input: { id: 'T_1', defaultCurrencyCode: CurrencyCode.MYR, }, }); channelGuard.assertSuccess(updateChannel); expect(updateChannel.defaultCurrencyCode).toBe('MYR'); expect(updateChannel.currencyCode).toBe('MYR'); expect(updateChannel.availableCurrencyCodes).toEqual(['USD', 'MYR']); }); it('setting defaultCurrencyCode adds it to availableCurrencyCodes 2', async () => { // As above, but this time we set the availableCurrencyCodes explicitly // to exclude the defaultCurrencyCode const { updateChannel } = await adminClient.query< Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables >(UPDATE_CHANNEL, { input: { id: 'T_1', defaultCurrencyCode: CurrencyCode.AUD, availableCurrencyCodes: [CurrencyCode.GBP], }, }); channelGuard.assertSuccess(updateChannel); expect(updateChannel.defaultCurrencyCode).toBe('AUD'); expect(updateChannel.currencyCode).toBe('AUD'); expect(updateChannel.availableCurrencyCodes).toEqual(['GBP', 'AUD']); }); it( 'cannot remove the defaultCurrencyCode from availableCurrencyCodes', assertThrowsWithMessage(async () => { await adminClient.query< Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables >(UPDATE_CHANNEL, { input: { id: 'T_1', availableCurrencyCodes: [CurrencyCode.GBP], }, }); }, 'availableCurrencyCodes must include the defaultCurrencyCode (AUD)'), ); it( 'specifying an unsupported currencyCode throws', assertThrowsWithMessage(async () => { await adminClient.query<Codegen.GetProductListQuery, Codegen.GetProductListQueryVariables>( GET_PRODUCT_LIST, { options: { take: 1, }, }, { currencyCode: 'JPY' }, ); }, 'The currency "JPY" is not available in the current Channel'), ); }); }); const DELETE_CHANNEL = gql` mutation DeleteChannel($id: ID!) { deleteChannel(id: $id) { message result } } `; const GET_CHANNEL = gql` query GetChannel($id: ID!) { channel(id: $id) { id code token defaultCurrencyCode availableCurrencyCodes defaultLanguageCode availableLanguageCodes outOfStockThreshold pricesIncludeTax } } `; const UPDATE_GLOBAL_LANGUAGES = gql` mutation UpdateGlobalLanguages($input: UpdateGlobalSettingsInput!) { updateGlobalSettings(input: $input) { ... on GlobalSettings { id availableLanguages } } } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { ROOT_COLLECTION_NAME } from '@vendure/common/lib/shared-constants'; import { DefaultJobQueuePlugin, facetValueCollectionFilter, productIdCollectionFilter, variantIdCollectionFilter, variantNameCollectionFilter, } from '@vendure/core'; import { createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config'; import { pick } from '../../common/lib/pick'; import { COLLECTION_FRAGMENT, FACET_VALUE_FRAGMENT } from './graphql/fragments'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { ChannelFragment, CollectionFragment, CurrencyCode, DeletionResult, FacetValueFragment, LanguageCode, SortOrder, } from './graphql/generated-e2e-admin-types'; import { ASSIGN_COLLECTIONS_TO_CHANNEL, CREATE_CHANNEL, CREATE_COLLECTION, DELETE_PRODUCT, DELETE_PRODUCT_VARIANT, GET_ASSET_LIST, GET_COLLECTION, GET_COLLECTIONS, UPDATE_COLLECTION, UPDATE_PRODUCT, UPDATE_PRODUCT_VARIANTS, } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; import { awaitRunningJobs } from './utils/await-running-jobs'; import { sortById } from './utils/test-order-utils'; describe('Collection resolver', () => { const { server, adminClient, shopClient } = createTestEnvironment({ ...testConfig(), plugins: [DefaultJobQueuePlugin], }); let assets: Codegen.GetAssetListQuery['assets']['items']; let facetValues: FacetValueFragment[]; let electronicsCollection: CollectionFragment; let computersCollection: CollectionFragment; let pearCollection: CollectionFragment; let electronicsBreadcrumbsCollection: CollectionFragment; let computersBreadcrumbsCollection: CollectionFragment; let pearBreadcrumbsCollection: CollectionFragment; const SECOND_CHANNEL_TOKEN = 'second_channel_token'; let secondChannel: ChannelFragment; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-collections.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); const assetsResult = await adminClient.query< Codegen.GetAssetListQuery, Codegen.GetAssetListQueryVariables >(GET_ASSET_LIST, { options: { sort: { name: SortOrder.ASC, }, }, }); assets = assetsResult.assets.items; const facetValuesResult = await adminClient.query<Codegen.GetFacetValuesQuery>(GET_FACET_VALUES); facetValues = facetValuesResult.facets.items.reduce( (values, facet) => [...values, ...facet.values], [] as FacetValueFragment[], ); const { createChannel } = await adminClient.query< Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables >(CREATE_CHANNEL, { input: { code: 'second-channel', token: SECOND_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, currencyCode: CurrencyCode.USD, pricesIncludeTax: true, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', }, }); secondChannel = createChannel; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); /** * Test case for https://github.com/vendure-ecommerce/vendure/issues/97 */ it('collection breadcrumbs works after bootstrap', async () => { const result = await adminClient.query<Codegen.GetCollectionBreadcrumbsQuery>( GET_COLLECTION_BREADCRUMBS, { id: 'T_1', }, ); expect(result.collection!.breadcrumbs[0].name).toBe(ROOT_COLLECTION_NAME); }); describe('createCollection', () => { it('creates a root collection', async () => { const result = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { assetIds: [assets[0].id, assets[1].id], featuredAssetId: assets[1].id, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('electronics')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], translations: [ { languageCode: LanguageCode.en, name: 'Electronics', description: '', slug: 'electronics', }, ], }, }); electronicsCollection = result.createCollection; expect(electronicsCollection).toMatchSnapshot(); expect(electronicsCollection.parent!.name).toBe(ROOT_COLLECTION_NAME); }); it('creates a nested collection', async () => { const result = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { parentId: electronicsCollection.id, translations: [ { languageCode: LanguageCode.en, name: 'Computers', description: '', slug: 'computers', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('computers')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], }, }); computersCollection = result.createCollection; expect(computersCollection.parent!.name).toBe(electronicsCollection.name); }); it('creates a 2nd level nested collection', async () => { const result = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { parentId: computersCollection.id, translations: [ { languageCode: LanguageCode.en, name: 'Pear', description: '', slug: 'pear' }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('pear')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], }, }); pearCollection = result.createCollection; expect(pearCollection.parent!.name).toBe(computersCollection.name); }); it('slug is normalized to be url-safe', async () => { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Accessories', description: '', slug: 'Accessories!', }, { languageCode: LanguageCode.de, name: 'Zubehör', description: '', slug: 'Zubehör!', }, ], filters: [], }, }); expect(createCollection.slug).toBe('accessories'); expect(createCollection.translations.find(t => t.languageCode === LanguageCode.en)?.slug).toBe( 'accessories', ); expect(createCollection.translations.find(t => t.languageCode === LanguageCode.de)?.slug).toBe( 'zubehoer', ); }); it('create with duplicate slug is renamed to be unique', async () => { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Accessories', description: '', slug: 'Accessories', }, { languageCode: LanguageCode.de, name: 'Zubehör', description: '', slug: 'Zubehör', }, ], filters: [], }, }); expect(createCollection.translations.find(t => t.languageCode === LanguageCode.en)?.slug).toBe( 'accessories-2', ); expect(createCollection.translations.find(t => t.languageCode === LanguageCode.de)?.slug).toBe( 'zubehoer-2', ); }); it('creates the duplicate slug without suffix in another channel', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Accessories', description: '', slug: 'Accessories', }, { languageCode: LanguageCode.de, name: 'Zubehör', description: '', slug: 'Zubehör', }, ], filters: [], }, }); expect(createCollection.translations.find(t => t.languageCode === LanguageCode.en)?.slug).toBe( 'accessories', ); expect(createCollection.translations.find(t => t.languageCode === LanguageCode.de)?.slug).toBe( 'zubehoer', ); }); it('creates a root collection to become a 1st level collection later #779', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const result = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { assetIds: [assets[0].id, assets[1].id], featuredAssetId: assets[1].id, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('computers')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], translations: [ { languageCode: LanguageCode.en, name: 'Computers Breadcrumbs', description: '', slug: 'computers_breadcrumbs', }, ], }, }); computersBreadcrumbsCollection = result.createCollection; expect(computersBreadcrumbsCollection.parent!.name).toBe(ROOT_COLLECTION_NAME); }); it('creates a root collection to be a parent collection for 1st level collection with id greater than child collection #779', async () => { const result = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { assetIds: [assets[0].id, assets[1].id], featuredAssetId: assets[1].id, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('electronics')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], translations: [ { languageCode: LanguageCode.en, name: 'Electronics Breadcrumbs', description: '', slug: 'electronics_breadcrumbs', }, ], }, }); electronicsBreadcrumbsCollection = result.createCollection; expect(electronicsBreadcrumbsCollection.parent!.name).toBe(ROOT_COLLECTION_NAME); }); it('creates a 2nd level nested collection #779', async () => { const result = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { parentId: computersBreadcrumbsCollection.id, translations: [ { languageCode: LanguageCode.en, name: 'Pear Breadcrumbs', description: '', slug: 'pear_breadcrumbs', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('pear')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], }, }); pearBreadcrumbsCollection = result.createCollection; expect(pearBreadcrumbsCollection.parent!.name).toBe(computersBreadcrumbsCollection.name); }); }); describe('updateCollection', () => { it('updates with assets', async () => { const { updateCollection } = await adminClient.query< Codegen.UpdateCollectionMutation, Codegen.UpdateCollectionMutationVariables >(UPDATE_COLLECTION, { input: { id: pearCollection.id, assetIds: [assets[1].id, assets[2].id], featuredAssetId: assets[1].id, translations: [ { languageCode: LanguageCode.en, description: 'Apple stuff ', slug: 'apple-stuff' }, ], }, }); await awaitRunningJobs(adminClient, 5000); expect(updateCollection).toMatchSnapshot(); pearCollection = updateCollection; }); it('updating existing assets', async () => { const { updateCollection } = await adminClient.query< Codegen.UpdateCollectionMutation, Codegen.UpdateCollectionMutationVariables >(UPDATE_COLLECTION, { input: { id: pearCollection.id, assetIds: [assets[3].id, assets[0].id], featuredAssetId: assets[3].id, }, }); await awaitRunningJobs(adminClient, 5000); expect(updateCollection.assets.map(a => a.id)).toEqual([assets[3].id, assets[0].id]); }); it('removes all assets', async () => { const { updateCollection } = await adminClient.query< Codegen.UpdateCollectionMutation, Codegen.UpdateCollectionMutationVariables >(UPDATE_COLLECTION, { input: { id: pearCollection.id, assetIds: [], }, }); await awaitRunningJobs(adminClient, 5000); expect(updateCollection.assets).toEqual([]); expect(updateCollection.featuredAsset).toBeNull(); }); }); describe('querying', () => { it('collection by id', async () => { const result = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: computersCollection.id, }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.id).toBe(computersCollection.id); }); it('collection by slug', async () => { const result = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { slug: computersCollection.slug, }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.id).toBe(computersCollection.id); }); // https://github.com/vendure-ecommerce/vendure/issues/538 it('falls back to default language slug', async () => { const result = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >( GET_COLLECTION, { slug: computersCollection.slug, }, { languageCode: LanguageCode.de }, ); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.id).toBe(computersCollection.id); }); it( 'throws if neither id nor slug provided', assertThrowsWithMessage(async () => { await adminClient.query<Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables>( GET_COLLECTION, {}, ); }, 'Either the Collection id or slug must be provided'), ); it( 'throws if id and slug do not refer to the same Product', assertThrowsWithMessage(async () => { await adminClient.query<Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables>( GET_COLLECTION, { id: computersCollection.id, slug: pearCollection.slug, }, ); }, 'The provided id and slug refer to different Collections'), ); it('parent field', async () => { const result = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: computersCollection.id, }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.parent!.name).toBe('Electronics'); }); // Tests fix for https://github.com/vendure-ecommerce/vendure/issues/361 it('parent field resolved by CollectionEntityResolver', async () => { const { product } = await adminClient.query< Codegen.GetProductCollectionsWithParentQuery, Codegen.GetProductCollectionsWithParentQueryVariables >(GET_PRODUCT_COLLECTIONS_WITH_PARENT, { id: 'T_1', }); expect(product?.collections.length).toBe(6); expect(product?.collections.sort(sortById)).toEqual([ { id: 'T_10', name: 'Electronics Breadcrumbs', parent: { id: 'T_1', name: '__root_collection__', }, }, { id: 'T_11', name: 'Pear Breadcrumbs', parent: { id: 'T_9', name: 'Computers Breadcrumbs', }, }, { id: 'T_3', name: 'Electronics', parent: { id: 'T_1', name: '__root_collection__', }, }, { id: 'T_4', name: 'Computers', parent: { id: 'T_3', name: 'Electronics', }, }, { id: 'T_5', name: 'Pear', parent: { id: 'T_4', name: 'Computers', }, }, { id: 'T_9', name: 'Computers Breadcrumbs', parent: { id: 'T_1', name: '__root_collection__', }, }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/981 it('nested parent field in shop API', async () => { const { collections } = await shopClient.query<Codegen.GetCollectionNestedParentsQuery>( GET_COLLECTION_NESTED_PARENTS, ); expect(collections.items[0].parent?.name).toBe(ROOT_COLLECTION_NAME); }); it('children field', async () => { const result = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: electronicsCollection.id, }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.children!.length).toBe(1); expect(result.collection.children![0].name).toBe('Computers'); }); it('breadcrumbs', async () => { const result = await adminClient.query< Codegen.GetCollectionBreadcrumbsQuery, Codegen.GetCollectionBreadcrumbsQueryVariables >(GET_COLLECTION_BREADCRUMBS, { id: pearCollection.id, }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.breadcrumbs).toEqual([ { id: 'T_1', name: ROOT_COLLECTION_NAME, slug: ROOT_COLLECTION_NAME }, { id: electronicsCollection.id, name: electronicsCollection.name, slug: electronicsCollection.slug, }, { id: computersCollection.id, name: computersCollection.name, slug: computersCollection.slug, }, { id: pearCollection.id, name: pearCollection.name, slug: pearCollection.slug }, ]); }); it('breadcrumbs for root collection', async () => { const result = await adminClient.query< Codegen.GetCollectionBreadcrumbsQuery, Codegen.GetCollectionBreadcrumbsQueryVariables >(GET_COLLECTION_BREADCRUMBS, { id: 'T_1', }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.breadcrumbs).toEqual([ { id: 'T_1', name: ROOT_COLLECTION_NAME, slug: ROOT_COLLECTION_NAME }, ]); }); it('collections.assets', async () => { const { collections } = await adminClient.query<Codegen.GetCollectionsWithAssetsQuery>(gql` query GetCollectionsWithAssets { collections { items { assets { name } } } } `); expect(collections.items[0].assets).toBeDefined(); }); // https://github.com/vendure-ecommerce/vendure/issues/642 it('sorting on Collection.productVariants.price', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: computersCollection.id, variantListOptions: { sort: { price: SortOrder.ASC, }, }, }); expect(collection!.productVariants.items.map(i => i.price)).toEqual([ 3799, 5374, 6900, 7489, 7896, 9299, 13435, 14374, 16994, 93120, 94920, 108720, 109995, 129900, 139900, 219900, 229900, ]); }); }); describe('moveCollection', () => { it('moves a collection to a new parent', async () => { const result = await adminClient.query< Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables >(MOVE_COLLECTION, { input: { collectionId: pearCollection.id, parentId: electronicsCollection.id, index: 0, }, }); expect(result.moveCollection.parent!.id).toBe(electronicsCollection.id); const positions = await getChildrenOf(electronicsCollection.id); expect(positions.map(i => i.id)).toEqual([pearCollection.id, computersCollection.id]); }); it('re-evaluates Collection contents on move', async () => { await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Instant Camera', ]); }); it('moves a 1st level collection to a new parent to check breadcrumbs', async () => { const result = await adminClient.query< Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables >(MOVE_COLLECTION, { input: { collectionId: computersBreadcrumbsCollection.id, parentId: electronicsBreadcrumbsCollection.id, index: 0, }, }); expect(result.moveCollection.parent!.id).toBe(electronicsBreadcrumbsCollection.id); const positions = await getChildrenOf(electronicsBreadcrumbsCollection.id); expect(positions.map(i => i.id)).toEqual([computersBreadcrumbsCollection.id]); }); it('breadcrumbs for collection with ids out of order', async () => { const result = await adminClient.query< Codegen.GetCollectionBreadcrumbsQuery, Codegen.GetCollectionBreadcrumbsQueryVariables >(GET_COLLECTION_BREADCRUMBS, { id: pearBreadcrumbsCollection.id, }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.breadcrumbs).toEqual([ { id: 'T_1', name: ROOT_COLLECTION_NAME, slug: ROOT_COLLECTION_NAME }, { id: electronicsBreadcrumbsCollection.id, name: electronicsBreadcrumbsCollection.name, slug: electronicsBreadcrumbsCollection.slug, }, { id: computersBreadcrumbsCollection.id, name: computersBreadcrumbsCollection.name, slug: computersBreadcrumbsCollection.slug, }, { id: pearBreadcrumbsCollection.id, name: pearBreadcrumbsCollection.name, slug: pearBreadcrumbsCollection.slug, }, ]); }); it('alters the position in the current parent 1', async () => { await adminClient.query<Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables>( MOVE_COLLECTION, { input: { collectionId: computersCollection.id, parentId: electronicsCollection.id, index: 0, }, }, ); const afterResult = await getChildrenOf(electronicsCollection.id); expect(afterResult.map(i => i.id)).toEqual([computersCollection.id, pearCollection.id]); }); it('alters the position in the current parent 2', async () => { await adminClient.query<Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables>( MOVE_COLLECTION, { input: { collectionId: pearCollection.id, parentId: electronicsCollection.id, index: 0, }, }, ); const afterResult = await getChildrenOf(electronicsCollection.id); expect(afterResult.map(i => i.id)).toEqual([pearCollection.id, computersCollection.id]); }); it('corrects an out-of-bounds negative index value', async () => { await adminClient.query<Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables>( MOVE_COLLECTION, { input: { collectionId: pearCollection.id, parentId: electronicsCollection.id, index: -3, }, }, ); const afterResult = await getChildrenOf(electronicsCollection.id); expect(afterResult.map(i => i.id)).toEqual([pearCollection.id, computersCollection.id]); }); it('corrects an out-of-bounds positive index value', async () => { await adminClient.query<Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables>( MOVE_COLLECTION, { input: { collectionId: pearCollection.id, parentId: electronicsCollection.id, index: 10, }, }, ); const afterResult = await getChildrenOf(electronicsCollection.id); expect(afterResult.map(i => i.id)).toEqual([computersCollection.id, pearCollection.id]); }); it( 'throws if attempting to move into self', assertThrowsWithMessage( () => adminClient.query< Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables >(MOVE_COLLECTION, { input: { collectionId: pearCollection.id, parentId: pearCollection.id, index: 0, }, }), 'Cannot move a Collection into itself', ), ); it( 'throws if attempting to move into a descendant of self', assertThrowsWithMessage( () => adminClient.query< Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables >(MOVE_COLLECTION, { input: { collectionId: pearCollection.id, parentId: pearCollection.id, index: 0, }, }), 'Cannot move a Collection into itself', ), ); // https://github.com/vendure-ecommerce/vendure/issues/1595 it('children correctly ordered', async () => { await adminClient.query<Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables>( MOVE_COLLECTION, { input: { collectionId: computersCollection.id, parentId: 'T_1', index: 4, }, }, ); const result = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: 'T_1', }); if (!result.collection) { fail('did not return the collection'); return; } expect(result.collection.children?.map(c => (c as any).position)).toEqual([0, 1, 2, 3, 4, 5, 6]); }); async function getChildrenOf(parentId: string): Promise<Array<{ name: string; id: string }>> { const result = await adminClient.query<Codegen.GetCollectionsQuery>(GET_COLLECTIONS); return result.collections.items.filter(i => i.parent!.id === parentId); } }); describe('deleteCollection', () => { let collectionToDeleteParent: Codegen.CreateCollectionMutation['createCollection']; let collectionToDeleteChild: Codegen.CreateCollectionMutation['createCollection']; let laptopProductId: string; beforeAll(async () => { const result1 = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { filters: [ { code: variantNameCollectionFilter.code, arguments: [ { name: 'operator', value: 'contains', }, { name: 'term', value: 'laptop', }, ], }, ], translations: [ { languageCode: LanguageCode.en, name: 'Delete Me Parent', description: '', slug: 'delete-me-parent', }, ], assetIds: ['T_1'], }, }); collectionToDeleteParent = result1.createCollection; const result2 = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { filters: [], translations: [ { languageCode: LanguageCode.en, name: 'Delete Me Child', description: '', slug: 'delete-me-child', }, ], parentId: collectionToDeleteParent.id, assetIds: ['T_2'], }, }); collectionToDeleteChild = result2.createCollection; await awaitRunningJobs(adminClient, 5000); }); it( 'throws for invalid collection id', assertThrowsWithMessage(async () => { await adminClient.query< Codegen.DeleteCollectionMutation, Codegen.DeleteCollectionMutationVariables >(DELETE_COLLECTION, { id: 'T_999', }); }, 'No Collection with the id "999" could be found'), ); it('collection and product related prior to deletion', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: collectionToDeleteParent.id, }); expect(collection!.productVariants.items.map(pick(['name']))).toEqual([ { name: 'Laptop 13 inch 8GB' }, { name: 'Laptop 15 inch 8GB' }, { name: 'Laptop 13 inch 16GB' }, { name: 'Laptop 15 inch 16GB' }, ]); laptopProductId = collection!.productVariants.items[0].productId; const { product } = await adminClient.query< Codegen.GetProductCollectionsQuery, Codegen.GetProductCollectionsQueryVariables >(GET_PRODUCT_COLLECTIONS, { id: laptopProductId, }); expect(product!.collections).toEqual([ { id: 'T_3', name: 'Electronics', }, { id: 'T_4', name: 'Computers', }, { id: 'T_5', name: 'Pear', }, { id: 'T_9', name: 'Computers Breadcrumbs', }, { id: 'T_10', name: 'Electronics Breadcrumbs', }, { id: 'T_11', name: 'Pear Breadcrumbs', }, { id: 'T_12', name: 'Delete Me Parent', }, { id: 'T_13', name: 'Delete Me Child', }, ]); }); it('deleteCollection works', async () => { const { deleteCollection } = await adminClient.query< Codegen.DeleteCollectionMutation, Codegen.DeleteCollectionMutationVariables >(DELETE_COLLECTION, { id: collectionToDeleteParent.id, }); expect(deleteCollection.result).toBe(DeletionResult.DELETED); }); it('deleted parent collection is null', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: collectionToDeleteParent.id, }); expect(collection).toBeNull(); }); it('deleted child collection is null', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: collectionToDeleteChild.id, }); expect(collection).toBeNull(); }); it('product no longer lists collection', async () => { const { product } = await adminClient.query< Codegen.GetProductCollectionsQuery, Codegen.GetProductCollectionsQueryVariables >(GET_PRODUCT_COLLECTIONS, { id: laptopProductId, }); expect(product!.collections).toEqual([ { id: 'T_3', name: 'Electronics' }, { id: 'T_4', name: 'Computers' }, { id: 'T_5', name: 'Pear' }, { id: 'T_9', name: 'Computers Breadcrumbs', }, { id: 'T_10', name: 'Electronics Breadcrumbs', }, { id: 'T_11', name: 'Pear Breadcrumbs', }, ]); }); }); describe('filters', () => { it('Collection with no filters has no productVariants', async () => { const result = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Empty', description: '', slug: 'empty' }, ], filters: [], } as Codegen.CreateCollectionInput, }); expect(result.createCollection.productVariants.totalItems).toBe(0); }); describe('facetValue filter', () => { it('electronics', async () => { const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: electronicsCollection.id, }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Gaming PC R7-2700 240GB SSD', 'Gaming PC i7-8700 120GB SSD', 'Gaming PC R7-2700 120GB SSD', 'Hard Drive 1TB', 'Hard Drive 2TB', 'Hard Drive 3TB', 'Hard Drive 4TB', 'Hard Drive 6TB', 'Clacky Keyboard', 'USB Cable', 'Instant Camera', 'Camera Lens', 'Tripod', 'SLR Camera', ]); }); it('computers', async () => { const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: computersCollection.id, }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Gaming PC R7-2700 240GB SSD', 'Gaming PC i7-8700 120GB SSD', 'Gaming PC R7-2700 120GB SSD', 'Hard Drive 1TB', 'Hard Drive 2TB', 'Hard Drive 3TB', 'Hard Drive 4TB', 'Hard Drive 6TB', 'Clacky Keyboard', 'USB Cable', ]); }); it('photo AND pear', async () => { const result = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Photo AND Pear', description: '', slug: 'photo-and-pear', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('pear')}", "${getFacetValueId( 'photo', )}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], } as Codegen.CreateCollectionInput, }); await awaitRunningJobs(adminClient, 5000); const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: result.createCollection.id, }); expect(collection!.productVariants.items.map(i => i.name)).toEqual(['Instant Camera']); }); it('photo OR pear', async () => { const result = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Photo OR Pear', description: '', slug: 'photo-or-pear', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('pear')}", "${getFacetValueId( 'photo', )}"]`, }, { name: 'containsAny', value: 'true', }, ], }, ], } as Codegen.CreateCollectionInput, }); await awaitRunningJobs(adminClient, 5000); const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: result.createCollection.id, }); expect(collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Instant Camera', 'Camera Lens', 'Tripod', 'SLR Camera', 'Hat', ]); }); it('bell OR pear in computers', async () => { const result = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { parentId: computersCollection.id, translations: [ { languageCode: LanguageCode.en, name: 'Bell OR Pear Computers', description: '', slug: 'bell-or-pear', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('pear')}", "${getFacetValueId('bell')}"]`, }, { name: 'containsAny', value: 'true', }, ], }, ], } as Codegen.CreateCollectionInput, }); await awaitRunningJobs(adminClient, 5000); const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: result.createCollection.id, }); expect(collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', ]); }); }); describe('variantName filter', () => { async function createVariantNameFilteredCollection( operator: string, term: string, parentId?: string, ): Promise<CollectionFragment> { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { parentId, translations: [ { languageCode: LanguageCode.en, name: `${operator} ${term}`, description: '', slug: `${operator} ${term}`, }, ], filters: [ { code: variantNameCollectionFilter.code, arguments: [ { name: 'operator', value: operator, }, { name: 'term', value: term, }, ], }, ], }, }); await awaitRunningJobs(adminClient, 5000); return createCollection; } it('contains operator', async () => { const collection = await createVariantNameFilteredCollection('contains', 'camera'); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: collection.id, }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Instant Camera', 'Camera Lens', 'SLR Camera', ]); }); it('startsWith operator', async () => { const collection = await createVariantNameFilteredCollection('startsWith', 'camera'); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: collection.id, }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual(['Camera Lens']); }); it('endsWith operator', async () => { const collection = await createVariantNameFilteredCollection('endsWith', 'camera'); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: collection.id, }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Instant Camera', 'SLR Camera', ]); }); it('doesNotContain operator', async () => { const collection = await createVariantNameFilteredCollection('doesNotContain', 'camera'); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: collection.id, }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Gaming PC R7-2700 240GB SSD', 'Gaming PC i7-8700 120GB SSD', 'Gaming PC R7-2700 120GB SSD', 'Hard Drive 1TB', 'Hard Drive 2TB', 'Hard Drive 3TB', 'Hard Drive 4TB', 'Hard Drive 6TB', 'Clacky Keyboard', 'USB Cable', 'Tripod', 'Hat', 'Boots', ]); }); // https://github.com/vendure-ecommerce/vendure/issues/927 it('nested variantName filter', async () => { const parent = await createVariantNameFilteredCollection('contains', 'lap'); const parentResult = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: parent.id, }); expect(parentResult.collection?.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', ]); const child = await createVariantNameFilteredCollection('contains', 'GB', parent.id); const childResult = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: child.id, }); expect(childResult.collection?.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', ]); }); }); describe('variantId filter', () => { it('contains expects variants', async () => { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name: 'variantId filter test', description: '', slug: 'variantId-filter-test', }, ], filters: [ { code: variantIdCollectionFilter.code, arguments: [ { name: 'variantIds', value: '["T_1", "T_4"]', }, ], }, ], }, }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: createCollection.id, }); expect(result.collection!.productVariants.items.map(i => i.id).sort()).toEqual([ 'T_1', 'T_4', ]); }); }); describe('productId filter', () => { it('contains expects variants', async () => { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name: 'productId filter test', description: '', slug: 'productId-filter-test', }, ], filters: [ { code: productIdCollectionFilter.code, arguments: [ { name: 'productIds', value: '["T_2"]', }, ], }, ], }, }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: createCollection.id, }); expect(result.collection!.productVariants.items.map(i => i.id).sort()).toEqual([ 'T_5', 'T_6', ]); }); }); describe('re-evaluation of contents on changes', () => { let products: Codegen.GetProductsWithVariantIdsQuery['products']['items']; beforeAll(async () => { const result = await adminClient.query<Codegen.GetProductsWithVariantIdsQuery>(gql` query GetProductsWithVariantIds { products(options: { sort: { id: ASC } }) { items { id name variants { id name } } } } `); products = result.products.items; }); it('updates contents when Product is updated', async () => { await adminClient.query< Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables >(UPDATE_PRODUCT, { input: { id: products[1].id, facetValueIds: [ getFacetValueId('electronics'), getFacetValueId('computers'), getFacetValueId('pear'), ], }, }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Instant Camera', ]); }); it('updates contents when ProductVariant is updated', async () => { const gamingPc240GB = products .find(p => p.name === 'Gaming PC')! .variants.find(v => v.name.includes('240GB'))!; await adminClient.query< Codegen.UpdateProductVariantsMutation, Codegen.UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [ { id: gamingPc240GB.id, facetValueIds: [getFacetValueId('pear')], }, ], }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Instant Camera', ]); }); it('correctly filters when ProductVariant and Product both have matching FacetValue', async () => { const gamingPc240GB = products .find(p => p.name === 'Gaming PC')! .variants.find(v => v.name.includes('240GB'))!; await adminClient.query< Codegen.UpdateProductVariantsMutation, Codegen.UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [ { id: gamingPc240GB.id, facetValueIds: [getFacetValueId('electronics'), getFacetValueId('pear')], }, ], }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Instant Camera', ]); }); }); describe('filter inheritance', () => { let clothesCollectionId: string; it('filter inheritance of nested collections (issue #158)', async () => { const { createCollection: pearElectronics } = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { parentId: electronicsCollection.id, translations: [ { languageCode: LanguageCode.en, name: 'pear electronics', description: '', slug: 'pear-electronics', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('pear')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], } as Codegen.CreateCollectionInput, }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearElectronics.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Instant Camera', // no "Hat" ]); }); it('child collection with no inheritance', async () => { const { createCollection: clothesCollection } = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { parentId: electronicsCollection.id, translations: [ { languageCode: LanguageCode.en, name: 'clothes', description: '', slug: 'clothes', }, ], inheritFilters: false, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('clothing')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], } as Codegen.CreateCollectionInput, }); await awaitRunningJobs(adminClient, 5000); clothesCollectionId = clothesCollection.id; const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: clothesCollection.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual(['Hat', 'Boots']); }); it('grandchild collection with inheritance (root -> no inherit -> inherit', async () => { const { createCollection: footwearCollection } = await adminClient.query< Codegen.CreateCollectionSelectVariantsMutation, Codegen.CreateCollectionSelectVariantsMutationVariables >(CREATE_COLLECTION_SELECT_VARIANTS, { input: { parentId: clothesCollectionId, translations: [ { languageCode: LanguageCode.en, name: 'footwear', description: '', slug: 'footwear', }, ], inheritFilters: true, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('footwear')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], } as Codegen.CreateCollectionInput, }); await awaitRunningJobs(adminClient, 5000); const result = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: footwearCollection.id }); expect(result.collection!.productVariants.items.map(i => i.name)).toEqual(['Boots']); }); }); describe('previewCollectionVariants', () => { it('returns correct contents', async () => { const { previewCollectionVariants } = await adminClient.query< Codegen.PreviewCollectionVariantsQuery, Codegen.PreviewCollectionVariantsQueryVariables >(PREVIEW_COLLECTION_VARIANTS, { input: { parentId: electronicsCollection.parent?.id, inheritFilters: true, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('electronics')}","${getFacetValueId( 'pear', )}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], }, }); expect(previewCollectionVariants.items.map(i => i.name).sort()).toEqual([ 'Curvy Monitor 24 inch', 'Curvy Monitor 27 inch', 'Gaming PC i7-8700 240GB SSD', 'Instant Camera', 'Laptop 13 inch 16GB', 'Laptop 13 inch 8GB', 'Laptop 15 inch 16GB', 'Laptop 15 inch 8GB', ]); }); it('works with list options', async () => { const { previewCollectionVariants } = await adminClient.query< Codegen.PreviewCollectionVariantsQuery, Codegen.PreviewCollectionVariantsQueryVariables >(PREVIEW_COLLECTION_VARIANTS, { input: { parentId: electronicsCollection.parent?.id, inheritFilters: true, filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('electronics')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], }, options: { sort: { name: SortOrder.ASC, }, filter: { name: { contains: 'mon', }, }, take: 5, }, }); expect(previewCollectionVariants.items).toEqual([ { id: 'T_5', name: 'Curvy Monitor 24 inch' }, { id: 'T_6', name: 'Curvy Monitor 27 inch' }, ]); }); it('takes parent filters into account', async () => { const { previewCollectionVariants } = await adminClient.query< Codegen.PreviewCollectionVariantsQuery, Codegen.PreviewCollectionVariantsQueryVariables >(PREVIEW_COLLECTION_VARIANTS, { input: { parentId: electronicsCollection.id, inheritFilters: true, filters: [ { code: variantNameCollectionFilter.code, arguments: [ { name: 'operator', value: 'startsWith', }, { name: 'term', value: 'h', }, ], }, ], }, }); expect(previewCollectionVariants.items.map(i => i.name).sort()).toEqual([ 'Hard Drive 1TB', 'Hard Drive 2TB', 'Hard Drive 3TB', 'Hard Drive 4TB', 'Hard Drive 6TB', ]); }); it('ignores parent filters id inheritFilters set to false', async () => { const { previewCollectionVariants } = await adminClient.query< Codegen.PreviewCollectionVariantsQuery, Codegen.PreviewCollectionVariantsQueryVariables >(PREVIEW_COLLECTION_VARIANTS, { input: { parentId: electronicsCollection.id, inheritFilters: false, filters: [ { code: variantNameCollectionFilter.code, arguments: [ { name: 'operator', value: 'startsWith', }, { name: 'term', value: 'h', }, ], }, ], }, }); expect(previewCollectionVariants.items.map(i => i.name).sort()).toEqual([ 'Hard Drive 1TB', 'Hard Drive 2TB', 'Hard Drive 3TB', 'Hard Drive 4TB', 'Hard Drive 6TB', 'Hat', ]); }); it('with no parentId, operates at the root level', async () => { const { previewCollectionVariants } = await adminClient.query< Codegen.PreviewCollectionVariantsQuery, Codegen.PreviewCollectionVariantsQueryVariables >(PREVIEW_COLLECTION_VARIANTS, { input: { inheritFilters: true, filters: [ { code: variantNameCollectionFilter.code, arguments: [ { name: 'operator', value: 'startsWith', }, { name: 'term', value: 'h', }, ], }, ], }, }); expect(previewCollectionVariants.items.map(i => i.name).sort()).toEqual([ 'Hard Drive 1TB', 'Hard Drive 2TB', 'Hard Drive 3TB', 'Hard Drive 4TB', 'Hard Drive 6TB', 'Hat', ]); }); }); }); describe('Product collections property', () => { it('returns all collections to which the Product belongs', async () => { const result = await adminClient.query< Codegen.GetCollectionsForProductsQuery, Codegen.GetCollectionsForProductsQueryVariables >(GET_COLLECTIONS_FOR_PRODUCTS, { term: 'camera' }); expect(result.products.items[0].collections).toEqual([ { id: 'T_3', name: 'Electronics', }, { id: 'T_5', name: 'Pear', }, { id: 'T_10', name: 'Electronics Breadcrumbs', }, { id: 'T_15', name: 'Photo AND Pear', }, { id: 'T_16', name: 'Photo OR Pear', }, { id: 'T_18', name: 'contains camera', }, { id: 'T_20', name: 'endsWith camera', }, { id: 'T_26', name: 'pear electronics', }, ]); }); }); describe('productVariants list', () => { it('does not list variants from deleted products', async () => { await adminClient.query<Codegen.DeleteProductMutation, Codegen.DeleteProductMutationVariables>( DELETE_PRODUCT, { id: 'T_2', // curvy monitor }, ); await awaitRunningJobs(adminClient, 5000); const { collection } = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id, }); expect(collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Gaming PC i7-8700 240GB SSD', 'Instant Camera', ]); }); // https://github.com/vendure-ecommerce/vendure/issues/1213 it('does not list deleted variants', async () => { await adminClient.query< Codegen.DeleteProductVariantMutation, Codegen.DeleteProductVariantMutationVariables >(DELETE_PRODUCT_VARIANT, { id: 'T_18', // Instant Camera }); await awaitRunningJobs(adminClient, 5000); const { collection } = await adminClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id, }); expect(collection!.productVariants.items.map(i => i.name)).toEqual([ 'Laptop 13 inch 8GB', 'Laptop 15 inch 8GB', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Gaming PC i7-8700 240GB SSD', // 'Instant Camera', ]); }); it('does not list disabled variants in Shop API', async () => { await adminClient.query< Codegen.UpdateProductVariantsMutation, Codegen.UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [{ id: 'T_1', enabled: false }], }); await awaitRunningJobs(adminClient, 5000); const { collection } = await shopClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id, }); expect(collection!.productVariants.items.map(i => i.id).includes('T_1')).toBe(false); }); it('does not list variants of disabled products in Shop API', async () => { await adminClient.query<Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_1', enabled: false }, }, ); await awaitRunningJobs(adminClient, 5000); const { collection } = await shopClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >(GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id, }); expect(collection!.productVariants.items.map(i => i.id).includes('T_1')).toBe(false); expect(collection!.productVariants.items.map(i => i.id).includes('T_2')).toBe(false); expect(collection!.productVariants.items.map(i => i.id).includes('T_3')).toBe(false); expect(collection!.productVariants.items.map(i => i.id).includes('T_4')).toBe(false); }); it('handles other languages', async () => { await adminClient.query<Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_1', enabled: true }, }, ); await adminClient.query< Codegen.UpdateProductVariantsMutation, Codegen.UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [ { id: 'T_2', translations: [{ languageCode: LanguageCode.de, name: 'Taschenrechner 15 Zoll' }], }, ], }); const { collection } = await shopClient.query< Codegen.GetCollectionProductsQuery, Codegen.GetCollectionProductsQueryVariables >( GET_COLLECTION_PRODUCT_VARIANTS, { id: pearCollection.id, }, { languageCode: LanguageCode.de }, ); expect(collection!.productVariants.items.map(i => i.name)).toEqual([ 'Taschenrechner 15 Zoll', 'Laptop 13 inch 16GB', 'Laptop 15 inch 16GB', 'Gaming PC i7-8700 240GB SSD', ]); }); }); describe('channel assignment & removal', () => { let testCollection: CollectionFragment; beforeAll(async () => { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: `["${getFacetValueId('electronics')}"]`, }, { name: 'containsAny', value: 'false', }, ], }, ], translations: [ { languageCode: LanguageCode.en, name: 'Channels Test Collection', description: '', slug: 'channels-test-collection', }, ], }, }); testCollection = createCollection; }); it('assign to channel', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { collections: before } = await adminClient.query< Codegen.GetCollectionListAdminQuery, Codegen.GetCollectionListAdminQueryVariables >(GET_COLLECTION_LIST); expect(before.items.length).toBe(1); expect(before.items.map(i => i.id).includes(testCollection.id)).toBe(false); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { assignCollectionsToChannel } = await adminClient.query< Codegen.AssignCollectionsToChannelMutation, Codegen.AssignCollectionsToChannelMutationVariables >(ASSIGN_COLLECTIONS_TO_CHANNEL, { input: { channelId: secondChannel.id, collectionIds: [testCollection.id], }, }); expect(assignCollectionsToChannel.map(c => c.id)).toEqual([testCollection.id]); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { collections: after } = await adminClient.query< Codegen.GetCollectionListAdminQuery, Codegen.GetCollectionListAdminQueryVariables >(GET_COLLECTION_LIST); expect(after.items.length).toBe(2); expect(after.items.map(i => i.id).includes(testCollection.id)).toBe(true); }); it('remove from channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { removeCollectionsFromChannel } = await adminClient.query< Codegen.RemoveCollectionsFromChannelMutation, Codegen.RemoveCollectionsFromChannelMutationVariables >(REMOVE_COLLECTIONS_FROM_CHANNEL, { input: { channelId: secondChannel.id, collectionIds: [testCollection.id], }, }); expect(removeCollectionsFromChannel.map(c => c.id)).toEqual([testCollection.id]); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { collections: after } = await adminClient.query< Codegen.GetCollectionListAdminQuery, Codegen.GetCollectionListAdminQueryVariables >(GET_COLLECTION_LIST); expect(after.items.length).toBe(1); expect(after.items.map(i => i.id).includes(testCollection.id)).toBe(false); }); }); describe('deleteCollections (multiple)', () => { let top: CollectionFragment; let child: CollectionFragment; let grandchild: CollectionFragment; beforeAll(async () => { async function createNewCollection(name: string, parentId?: string) { const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name, description: '', slug: name, }, ], filters: [], }, }); return createCollection; } top = await createNewCollection('top'); child = await createNewCollection('child', top.id); grandchild = await createNewCollection('grandchild', child.id); }); it('deletes all selected collections', async () => { const { collections: before } = await adminClient.query< Codegen.GetCollectionListQuery, Codegen.GetCollectionListQueryVariables >(GET_COLLECTION_LIST); expect(before.items.sort(sortById).map(pick(['name']))).toEqual([ { name: 'top' }, { name: 'child' }, { name: 'grandchild' }, { name: 'Accessories' }, ]); const { deleteCollections } = await adminClient.query< Codegen.DeleteCollectionsBulkMutation, Codegen.DeleteCollectionsBulkMutationVariables >(DELETE_COLLECTIONS_BULK, { ids: [top.id, child.id, grandchild.id], }); expect(deleteCollections).toEqual([ { result: DeletionResult.DELETED, message: null }, { result: DeletionResult.DELETED, message: null }, { result: DeletionResult.DELETED, message: null }, ]); const { collections: after } = await adminClient.query< Codegen.GetCollectionListQuery, Codegen.GetCollectionListQueryVariables >(GET_COLLECTION_LIST); expect(after.items.map(pick(['id', 'name'])).sort(sortById)).toEqual([ { id: 'T_8', name: 'Accessories' }, ]); }); }); function getFacetValueId(code: string): string { const match = facetValues.find(fv => fv.code === code); if (!match) { throw new Error(`Could not find a FacetValue with the code "${code}"`); } return match.id; } }); export const GET_COLLECTION_LIST = gql` query GetCollectionListAdmin($options: CollectionListOptions) { collections(options: $options) { items { ...Collection } totalItems } } ${COLLECTION_FRAGMENT} `; export const MOVE_COLLECTION = gql` mutation MoveCollection($input: MoveCollectionInput!) { moveCollection(input: $input) { ...Collection } } ${COLLECTION_FRAGMENT} `; const GET_FACET_VALUES = gql` query GetFacetValues { facets { items { values { ...FacetValue } } } } ${FACET_VALUE_FRAGMENT} `; const GET_COLLECTION_PRODUCT_VARIANTS = gql` query GetCollectionProducts($id: ID!) { collection(id: $id) { productVariants(options: { sort: { id: ASC } }) { items { id name facetValues { code } productId } } } } `; const CREATE_COLLECTION_SELECT_VARIANTS = gql` mutation CreateCollectionSelectVariants($input: CreateCollectionInput!) { createCollection(input: $input) { id productVariants { items { name } totalItems } } } `; const GET_COLLECTION_BREADCRUMBS = gql` query GetCollectionBreadcrumbs($id: ID!) { collection(id: $id) { breadcrumbs { id name slug } } } `; const GET_COLLECTIONS_FOR_PRODUCTS = gql` query GetCollectionsForProducts($term: String!) { products(options: { filter: { name: { contains: $term } } }) { items { id name collections { id name } } } } `; const DELETE_COLLECTION = gql` mutation DeleteCollection($id: ID!) { deleteCollection(id: $id) { result message } } `; const GET_PRODUCT_COLLECTIONS = gql` query GetProductCollections($id: ID!) { product(id: $id) { id collections { id name } } } `; const GET_PRODUCT_COLLECTIONS_WITH_PARENT = gql` query GetProductCollectionsWithParent($id: ID!) { product(id: $id) { id collections { id name parent { id name } } } } `; const GET_COLLECTION_NESTED_PARENTS = gql` query GetCollectionNestedParents { collections { items { id name parent { name parent { name parent { name } } } } } } `; const PREVIEW_COLLECTION_VARIANTS = gql` query PreviewCollectionVariants( $input: PreviewCollectionVariantsInput! $options: ProductVariantListOptions ) { previewCollectionVariants(input: $input, options: $options) { items { id name } totalItems } } `; const REMOVE_COLLECTIONS_FROM_CHANNEL = gql` mutation RemoveCollectionsFromChannel($input: RemoveCollectionsFromChannelInput!) { removeCollectionsFromChannel(input: $input) { ...Collection } } ${COLLECTION_FRAGMENT} `; const DELETE_COLLECTIONS_BULK = gql` mutation DeleteCollectionsBulk($ids: [ID!]!) { deleteCollections(ids: $ids) { message result } } `;
import { pick } from '@vendure/common/lib/pick'; import { defaultShippingEligibilityChecker, LanguageCode, mergeConfig, ShippingEligibilityChecker, } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { UpdateShippingMethodMutationVariables } from './graphql/generated-e2e-admin-types'; import { GetCheckersQuery, UpdateShippingMethodMutation } from './graphql/generated-e2e-admin-types'; import { UPDATE_SHIPPING_METHOD } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; const testShippingEligibilityChecker = new ShippingEligibilityChecker({ code: 'test-checker', description: [{ languageCode: LanguageCode.en, value: 'test checker' }], args: { optional: { label: [ { languageCode: LanguageCode.en, value: 'Optional argument' }, { languageCode: LanguageCode.de, value: 'Optional eingabe' }, ], description: [ { languageCode: LanguageCode.en, value: 'This is an optional argument' }, { languageCode: LanguageCode.de, value: 'Das ist eine optionale eingabe' }, ], required: false, type: 'string', }, required: { required: true, type: 'string', defaultValue: 'hello', }, }, check: ctx => true, }); describe('Configurable operations', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { shippingOptions: { shippingEligibilityCheckers: [ defaultShippingEligibilityChecker, testShippingEligibilityChecker, ], }, }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); describe('required args', () => { it('allows empty optional arg', async () => { const { updateShippingMethod } = await adminClient.query< UpdateShippingMethodMutation, UpdateShippingMethodMutationVariables >(UPDATE_SHIPPING_METHOD, { input: { id: 'T_1', checker: { code: testShippingEligibilityChecker.code, arguments: [ { name: 'optional', value: '' }, { name: 'required', value: 'foo' }, ], }, translations: [], }, }); expect(updateShippingMethod.checker.args).toEqual([ { name: 'optional', value: '', }, { name: 'required', value: 'foo', }, ]); }); it( 'throws if a required arg is null', assertThrowsWithMessage(async () => { await adminClient.query<UpdateShippingMethodMutation, UpdateShippingMethodMutationVariables>( UPDATE_SHIPPING_METHOD, { input: { id: 'T_1', checker: { code: testShippingEligibilityChecker.code, arguments: [ { name: 'optional', value: 'null' }, { name: 'required', value: '' }, ], }, translations: [], }, }, ); }, 'The argument "required" is required'), ); }); it('defaultValue', async () => { const { shippingEligibilityCheckers } = await adminClient.query<GetCheckersQuery>(GET_CHECKERS); expect(shippingEligibilityCheckers[1].args.map(pick(['name', 'defaultValue']))).toEqual([ { name: 'optional', defaultValue: null }, { name: 'required', defaultValue: 'hello' }, ]); }); }); export const GET_CHECKERS = gql` query GetCheckers { shippingEligibilityCheckers { code args { defaultValue description label list name required type } } } `;
import { createTestEnvironment } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { COUNTRY_FRAGMENT } from './graphql/fragments'; import { DeletionResult, GetCountryListQuery, LanguageCode } from './graphql/generated-e2e-admin-types'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { GET_COUNTRY_LIST, UPDATE_COUNTRY } from './graphql/shared-definitions'; /* eslint-disable @typescript-eslint/no-non-null-assertion */ describe('Country resolver', () => { const { server, adminClient } = createTestEnvironment(testConfig()); let countries: GetCountryList.Items[]; let GB: GetCountryListQuery['countries']['items'][number]; let AT: GetCountryListQuery['countries']['items'][number]; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('countries', async () => { const result = await adminClient.query<Codegen.GetCountryListQuery>(GET_COUNTRY_LIST, {}); expect(result.countries.totalItems).toBe(7); countries = result.countries.items; GB = countries.find(c => c.code === 'GB')!; AT = countries.find(c => c.code === 'AT')!; }); it('country', async () => { const result = await adminClient.query<Codegen.GetCountryQuery, Codegen.GetCountryQueryVariables>( GET_COUNTRY, { id: GB.id, }, ); expect(result.country!.name).toBe(GB.name); }); it('updateCountry', async () => { const result = await adminClient.query< Codegen.UpdateCountryMutation, Codegen.UpdateCountryMutationVariables >(UPDATE_COUNTRY, { input: { id: AT.id, enabled: false, }, }); expect(result.updateCountry.enabled).toBe(false); }); it('createCountry', async () => { const result = await adminClient.query< Codegen.CreateCountryMutation, Codegen.CreateCountryMutationVariables >(CREATE_COUNTRY, { input: { code: 'GL', enabled: true, translations: [{ languageCode: LanguageCode.en, name: 'Gondwanaland' }], }, }); expect(result.createCountry.name).toBe('Gondwanaland'); }); describe('deletion', () => { it('deletes Country not used in any address', async () => { const result1 = await adminClient.query< Codegen.DeleteCountryMutation, Codegen.DeleteCountryMutationVariables >(DELETE_COUNTRY, { id: AT.id }); expect(result1.deleteCountry).toEqual({ result: DeletionResult.DELETED, message: '', }); const result2 = await adminClient.query<Codegen.GetCountryListQuery>(GET_COUNTRY_LIST, {}); expect(result2.countries.items.find(c => c.id === AT.id)).toBeUndefined(); }); it('does not delete Country that is used in one or more addresses', async () => { const result1 = await adminClient.query< Codegen.DeleteCountryMutation, Codegen.DeleteCountryMutationVariables >(DELETE_COUNTRY, { id: GB.id }); expect(result1.deleteCountry).toEqual({ result: DeletionResult.NOT_DELETED, message: 'The selected Country cannot be deleted as it is used in 1 Address', }); const result2 = await adminClient.query<Codegen.GetCountryListQuery>(GET_COUNTRY_LIST, {}); expect(result2.countries.items.find(c => c.id === GB.id)).not.toBeUndefined(); }); }); }); export const DELETE_COUNTRY = gql` mutation DeleteCountry($id: ID!) { deleteCountry(id: $id) { result message } } `; export const GET_COUNTRY = gql` query GetCountry($id: ID!) { country(id: $id) { ...Country } } ${COUNTRY_FRAGMENT} `; export const CREATE_COUNTRY = gql` mutation CreateCountry($input: CreateCountryInput!) { createCountry(input: $input) { ...Country } } ${COUNTRY_FRAGMENT} `;
import { mergeConfig } from '@vendure/core'; import { createTestEnvironment, SimpleGraphQLClient } from '@vendure/testing'; import { fail } from 'assert'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { Permission } from './graphql/generated-e2e-shop-types'; import { CREATE_ADMINISTRATOR, CREATE_ROLE, UPDATE_PRODUCT } from './graphql/shared-definitions'; describe('Custom field permissions', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { customFields: { Product: [ { name: 'publicField', type: 'string', defaultValue: 'publicField Value', }, { name: 'authenticatedField', type: 'string', defaultValue: 'authenticatedField Value', requiresPermission: Permission.Authenticated, }, { name: 'updateProductField', type: 'string', defaultValue: 'updateProductField Value', requiresPermission: Permission.UpdateProduct, }, { name: 'updateProductOrCustomerField', type: 'string', defaultValue: 'updateProductOrCustomerField Value', requiresPermission: [Permission.UpdateProduct, Permission.UpdateCustomer], }, { name: 'superadminField', type: 'string', defaultValue: 'superadminField Value', requiresPermission: Permission.SuperAdmin, }, ], }, }), ); let readProductUpdateProductAdmin: Codegen.CreateAdministratorMutation['createAdministrator']; let readProductUpdateCustomerAdmin: Codegen.CreateAdministratorMutation['createAdministrator']; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 3, }); await adminClient.asSuperAdmin(); readProductUpdateProductAdmin = await createAdminWithPermissions({ adminClient, name: 'ReadProductUpdateProduct', permissions: [Permission.ReadProduct, Permission.UpdateProduct], }); readProductUpdateCustomerAdmin = await createAdminWithPermissions({ adminClient, name: 'ReadProductUpdateCustomer', permissions: [Permission.ReadProduct, Permission.UpdateCustomer], }); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); const GET_PRODUCT_WITH_CUSTOM_FIELDS = gql(` query { product(id: "T_1") { id customFields { publicField authenticatedField updateProductField updateProductOrCustomerField superadminField } } } `); it('anonymous user can only read public custom field', async () => { await shopClient.asAnonymousUser(); const { product } = await shopClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields).toEqual({ publicField: 'publicField Value', authenticatedField: null, updateProductField: null, updateProductOrCustomerField: null, superadminField: null, }); }); it('authenticated user can read public and authenticated custom fields', async () => { await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test'); const { product } = await shopClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields).toEqual({ publicField: 'publicField Value', authenticatedField: 'authenticatedField Value', updateProductField: null, updateProductOrCustomerField: null, superadminField: null, }); }); it('readProductUpdateProductAdmin can read public and updateProduct custom fields', async () => { await adminClient.asUserWithCredentials(readProductUpdateProductAdmin.emailAddress, 'test'); const { product } = await adminClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields).toEqual({ publicField: 'publicField Value', authenticatedField: 'authenticatedField Value', updateProductField: 'updateProductField Value', updateProductOrCustomerField: 'updateProductOrCustomerField Value', superadminField: null, }); }); it('readProductUpdateCustomerAdmin can read public and updateCustomer custom fields', async () => { await adminClient.asUserWithCredentials(readProductUpdateCustomerAdmin.emailAddress, 'test'); const { product } = await adminClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields).toEqual({ publicField: 'publicField Value', authenticatedField: 'authenticatedField Value', updateProductField: null, updateProductOrCustomerField: 'updateProductOrCustomerField Value', superadminField: null, }); }); it('superadmin can read all custom fields', async () => { await adminClient.asSuperAdmin(); const { product } = await adminClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields).toEqual({ publicField: 'publicField Value', authenticatedField: 'authenticatedField Value', updateProductField: 'updateProductField Value', updateProductOrCustomerField: 'updateProductOrCustomerField Value', superadminField: 'superadminField Value', }); }); it('superadmin can update all custom fields', async () => { await adminClient.asSuperAdmin(); await adminClient.query<Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_1', customFields: { publicField: 'new publicField Value', authenticatedField: 'new authenticatedField Value', updateProductField: 'new updateProductField Value', updateProductOrCustomerField: 'new updateProductOrCustomerField Value', superadminField: 'new superadminField Value', }, }, }, ); const { product } = await adminClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields).toEqual({ publicField: 'new publicField Value', authenticatedField: 'new authenticatedField Value', updateProductField: 'new updateProductField Value', updateProductOrCustomerField: 'new updateProductOrCustomerField Value', superadminField: 'new superadminField Value', }); }); it('readProductUpdateProductAdmin can update updateProduct custom field', async () => { await adminClient.asUserWithCredentials(readProductUpdateProductAdmin.emailAddress, 'test'); await adminClient.query<Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_1', customFields: { updateProductField: 'new updateProductField Value 2', }, }, }, ); const { product } = await adminClient.query(GET_PRODUCT_WITH_CUSTOM_FIELDS, { id: 'T_1', }); expect(product.customFields.updateProductField).toBe('new updateProductField Value 2'); }); it('readProductUpdateProductAdmin cannot update superadminField', async () => { await adminClient.asUserWithCredentials(readProductUpdateProductAdmin.emailAddress, 'test'); try { const result = await adminClient.query< Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables >(UPDATE_PRODUCT, { input: { id: 'T_1', customFields: { superadminField: 'new superadminField Value 2', }, }, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toBe( 'You do not have the required permissions to update the "superadminField" field', ); } }); // This will throw anyway because the user does not have permission to even // update the Product at all. it('readProductUpdateCustomerAdmin cannot update updateProductField', async () => { await adminClient.asUserWithCredentials(readProductUpdateCustomerAdmin.emailAddress, 'test'); try { const result = await adminClient.query< Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables >(UPDATE_PRODUCT, { input: { id: 'T_1', customFields: { updateProductField: 'new updateProductField Value 2', }, }, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toBe('You are not currently authorized to perform this action'); } }); }); async function createAdminWithPermissions(input: { adminClient: SimpleGraphQLClient; name: string; permissions: Permission[]; }) { const { adminClient, name, permissions } = input; const { createRole } = await adminClient.query< Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables >(CREATE_ROLE, { input: { code: name, description: name, permissions, }, }); const { createAdministrator } = await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { firstName: name, lastName: 'LastName', emailAddress: `${name}@test.com`, roleIds: [createRole.id], password: 'test', }, }); return createAdministrator; }
import { assertFound, Asset, Collection, Country, CustomFields, DefaultLogger, defaultShippingCalculator, defaultShippingEligibilityChecker, Facet, FacetValue, LogLevel, manualFulfillmentHandler, mergeConfig, PluginCommonModule, Product, ProductOption, ProductOptionGroup, ProductVariant, RequestContext, ShippingMethod, TransactionalConnection, VendureEntity, VendurePlugin, } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { Repository } from 'typeorm'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { testSuccessfulPaymentMethod } from './fixtures/test-payment-methods'; import { TestPlugin1636_1664 } from './fixtures/test-plugins/issue-1636-1664/issue-1636-1664-plugin'; import { PluginIssue2453 } from './fixtures/test-plugins/issue-2453/plugin-issue2453'; import { TestCustomEntity, WithCustomEntity } from './fixtures/test-plugins/with-custom-entity'; import { AddItemToOrderMutationVariables } from './graphql/generated-e2e-shop-types'; import { ADD_ITEM_TO_ORDER } from './graphql/shop-definitions'; import { sortById } from './utils/test-order-utils'; // From https://github.com/microsoft/TypeScript/issues/13298#issuecomment-654906323 // to ensure that we _always_ test all entities which support custom fields type ValueOf<T> = T[keyof T]; type NonEmptyArray<T> = [T, ...T[]]; type MustInclude<T, U extends T[]> = [T] extends [ValueOf<U>] ? U : never; const enumerate = <T>() => <U extends NonEmptyArray<T>>(...elements: MustInclude<T, U>) => elements; const entitiesWithCustomFields = enumerate<keyof CustomFields>()( 'Address', 'Administrator', 'Asset', 'Channel', 'Collection', 'Customer', 'CustomerGroup', 'Facet', 'FacetValue', 'Fulfillment', 'GlobalSettings', 'Order', 'OrderLine', 'PaymentMethod', 'Product', 'ProductOption', 'ProductOptionGroup', 'ProductVariant', 'Promotion', 'Region', 'Seller', 'ShippingMethod', 'TaxCategory', 'TaxRate', 'User', 'Zone', ); const customFieldConfig: CustomFields = {}; for (const entity of entitiesWithCustomFields) { customFieldConfig[entity] = [ { name: 'single', type: 'relation', entity: Asset, graphQLType: 'Asset', list: false }, { name: 'multi', type: 'relation', entity: Asset, graphQLType: 'Asset', list: true }, ]; } customFieldConfig.Product?.push( { name: 'cfCollection', type: 'relation', entity: Collection, list: false }, { name: 'cfCountry', type: 'relation', entity: Country, list: false }, { name: 'cfFacetValue', type: 'relation', entity: FacetValue, list: false }, { name: 'cfFacet', type: 'relation', entity: Facet, list: false }, { name: 'cfProductOptionGroup', type: 'relation', entity: ProductOptionGroup, list: false }, { name: 'cfProductOption', type: 'relation', entity: ProductOption, list: false }, { name: 'cfProductVariant', type: 'relation', entity: ProductVariant, list: false }, { name: 'cfProduct', type: 'relation', entity: Product, list: false }, { name: 'cfShippingMethod', type: 'relation', entity: ShippingMethod, list: false }, { name: 'cfInternalAsset', type: 'relation', entity: Asset, list: false, internal: true }, ); customFieldConfig.ProductVariant?.push({ name: 'cfRelatedProducts', type: 'relation', entity: Product, list: true, internal: false, public: true, }); const customConfig = mergeConfig(testConfig(), { paymentOptions: { paymentMethodHandlers: [testSuccessfulPaymentMethod], }, // logger: new DefaultLogger({ level: LogLevel.Debug }), dbConnectionOptions: { timezone: 'Z', }, customFields: customFieldConfig, plugins: [TestPlugin1636_1664, WithCustomEntity, PluginIssue2453], }); describe('Custom field relations', () => { const { server, adminClient, shopClient } = createTestEnvironment(customConfig); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 3, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('customFieldConfig query returns entity and scalar fields', async () => { const { globalSettings } = await adminClient.query(gql` query { globalSettings { serverConfig { customFieldConfig { Customer { ... on RelationCustomFieldConfig { name entity scalarFields } } } } } } `); const single = globalSettings.serverConfig.customFieldConfig.Customer[0]; expect(single.entity).toBe('Asset'); expect(single.scalarFields).toEqual([ 'id', 'createdAt', 'updatedAt', 'name', 'type', 'fileSize', 'mimeType', 'width', 'height', 'source', 'preview', ]); }); describe('special data resolution', () => { let productId: string; const productCustomFieldRelationsSelection = ` id customFields { cfCollection { languageCode name } cfCountry { languageCode name } cfFacetValue { languageCode name } cfFacet { languageCode name } cfProductOptionGroup { languageCode name } cfProductOption { languageCode name } cfProductVariant { languageCode name } cfProduct { languageCode name } cfShippingMethod { languageCode name } }`; function assertTranslatableCustomFieldValues(product: { customFields: any }) { expect(product.customFields.cfCollection).toEqual({ languageCode: 'en', name: '__root_collection__', }); expect(product.customFields.cfCountry).toEqual({ languageCode: 'en', name: 'Australia' }); expect(product.customFields.cfFacetValue).toEqual({ languageCode: 'en', name: 'electronics', }); expect(product.customFields.cfFacet).toEqual({ languageCode: 'en', name: 'category' }); expect(product.customFields.cfProductOptionGroup).toEqual({ languageCode: 'en', name: 'screen size', }); expect(product.customFields.cfProductOption).toEqual({ languageCode: 'en', name: '13 inch', }); expect(product.customFields.cfProductVariant).toEqual({ languageCode: 'en', name: 'Laptop 13 inch 8GB', }); expect(product.customFields.cfProduct).toEqual({ languageCode: 'en', name: 'Laptop' }); expect(product.customFields.cfShippingMethod).toEqual({ languageCode: 'en', name: 'Standard Shipping', }); } it('translatable entities get translated', async () => { const { createProduct } = await adminClient.query(gql` mutation { createProduct( input: { translations: [ { languageCode: en name: "Test product" description: "" slug: "test-product" } ] customFields: { cfCollectionId: "T_1" cfCountryId: "T_1" cfFacetValueId: "T_1" cfFacetId: "T_1" cfProductOptionGroupId: "T_1" cfProductOptionId: "T_1" cfProductVariantId: "T_1" cfProductId: "T_1" cfShippingMethodId: "T_1" } } ) { ${productCustomFieldRelationsSelection} } } `); productId = createProduct.id; assertTranslatableCustomFieldValues(createProduct); }); it('translatable entities get translated on findOneInChannel', async () => { const { product } = await adminClient.query(gql` query { product(id: "${productId}") { ${productCustomFieldRelationsSelection} } } `); assertTranslatableCustomFieldValues(product); }); // https://github.com/vendure-ecommerce/vendure/issues/2453 it('translatable eager-loaded relation works (issue 2453)', async () => { const { collections } = await adminClient.query(gql` query { collections(options: { sort: { name: DESC } }) { totalItems items { id name customFields { campaign { name languageCode } } } } } `); expect(collections.totalItems).toBe(3); expect(collections.items.find((c: any) => c.id === 'T_3')).toEqual({ customFields: { campaign: { languageCode: 'en', name: 'Clearance Up to 70% Off frames', }, }, id: 'T_3', name: 'children collection', }); }); it('ProductVariant prices get resolved', async () => { const { product } = await adminClient.query(gql` query { product(id: "${productId}") { id customFields { cfProductVariant { price currencyCode priceWithTax } } } }`); expect(product.customFields.cfProductVariant).toEqual({ price: 129900, currencyCode: 'USD', priceWithTax: 155880, }); }); }); it('ProductVariant without a specified property value returns null', async () => { const { createProduct } = await adminClient.query(gql` mutation { createProduct( input: { translations: [ { languageCode: en name: "Product with empty custom fields" description: "" slug: "product-with-empty-custom-fields" } ] } ) { id } } `); const { product } = await adminClient.query(gql` query { product(id: "${createProduct.id}") { id customFields { cfProductVariant{ price currencyCode priceWithTax } } } }`); expect(product.customFields.cfProductVariant).toEqual(null); }); describe('entity-specific implementation', () => { function assertCustomFieldIds(customFields: any, single: string, multi: string[]) { expect(customFields.single).toEqual({ id: single }); expect(customFields.multi.sort(sortById)).toEqual(multi.map(id => ({ id }))); } const customFieldsSelection = ` customFields { single { id } multi { id } }`; describe('Address entity', () => { it('admin createCustomerAddress', async () => { const { createCustomerAddress } = await adminClient.query(gql` mutation { createCustomerAddress( customerId: "T_1" input: { countryCode: "GB" streetLine1: "Test Street" customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createCustomerAddress.customFields, 'T_1', ['T_1', 'T_2']); }); it('shop createCustomerAddress', async () => { await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test'); const { createCustomerAddress } = await shopClient.query(gql` mutation { createCustomerAddress( input: { countryCode: "GB" streetLine1: "Test Street" customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createCustomerAddress.customFields, 'T_1', ['T_1', 'T_2']); }); it('admin updateCustomerAddress', async () => { const { updateCustomerAddress } = await adminClient.query(gql` mutation { updateCustomerAddress( input: { id: "T_1", customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateCustomerAddress.customFields, 'T_2', ['T_3', 'T_4']); }); it('shop updateCustomerAddress', async () => { const { updateCustomerAddress } = await shopClient.query(gql` mutation { updateCustomerAddress( input: { id: "T_1", customFields: { singleId: "T_3", multiIds: ["T_4", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateCustomerAddress.customFields, 'T_3', ['T_2', 'T_4']); }); }); describe('Collection entity', () => { let collectionId: string; it('admin createCollection', async () => { const { createCollection } = await adminClient.query(gql` mutation { createCollection( input: { translations: [ { languageCode: en, name: "Test", description: "test", slug: "test" } ] filters: [] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createCollection.customFields, 'T_1', ['T_1', 'T_2']); collectionId = createCollection.id; }); it('admin updateCollection', async () => { const { updateCollection } = await adminClient.query(gql` mutation { updateCollection( input: { id: "${collectionId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateCollection.customFields, 'T_2', ['T_3', 'T_4']); }); }); describe('Customer entity', () => { let customerId: string; it('admin createCustomer', async () => { const { createCustomer } = await adminClient.query(gql` mutation { createCustomer( input: { emailAddress: "test@test.com" firstName: "Test" lastName: "Person" customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { ... on Customer { id ${customFieldsSelection} } } } `); assertCustomFieldIds(createCustomer.customFields, 'T_1', ['T_1', 'T_2']); customerId = createCustomer.id; }); it('admin updateCustomer', async () => { const { updateCustomer } = await adminClient.query(gql` mutation { updateCustomer( input: { id: "${customerId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { ...on Customer { id ${customFieldsSelection} } } } `); assertCustomFieldIds(updateCustomer.customFields, 'T_2', ['T_3', 'T_4']); }); it('shop updateCustomer', async () => { const { updateCustomer } = await shopClient.query(gql` mutation { updateCustomer(input: { customFields: { singleId: "T_4", multiIds: ["T_2", "T_4"] } }) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateCustomer.customFields, 'T_4', ['T_2', 'T_4']); }); }); describe('Facet entity', () => { let facetId: string; it('admin createFacet', async () => { const { createFacet } = await adminClient.query(gql` mutation { createFacet( input: { code: "test" isPrivate: false translations: [{ languageCode: en, name: "test" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createFacet.customFields, 'T_1', ['T_1', 'T_2']); facetId = createFacet.id; }); it('admin updateFacet', async () => { const { updateFacet } = await adminClient.query(gql` mutation { updateFacet( input: { id: "${facetId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateFacet.customFields, 'T_2', ['T_3', 'T_4']); }); }); describe('FacetValue entity', () => { let facetValueId: string; it('admin createFacetValues', async () => { const { createFacetValues } = await adminClient.query(gql` mutation { createFacetValues( input: { code: "test" facetId: "T_1" translations: [{ languageCode: en, name: "test" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createFacetValues[0].customFields, 'T_1', ['T_1', 'T_2']); facetValueId = createFacetValues[0].id; }); it('admin updateFacetValues', async () => { const { updateFacetValues } = await adminClient.query(gql` mutation { updateFacetValues( input: { id: "${facetValueId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateFacetValues[0].customFields, 'T_2', ['T_3', 'T_4']); }); }); // describe('Fulfillment entity', () => { // // Currently no GraphQL API to set customFields on fulfillments // }); describe('GlobalSettings entity', () => { it('admin updateGlobalSettings', async () => { const { updateGlobalSettings } = await adminClient.query(gql` mutation { updateGlobalSettings( input: { customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { ... on GlobalSettings { id ${customFieldsSelection} } } } `); assertCustomFieldIds(updateGlobalSettings.customFields, 'T_2', ['T_3', 'T_4']); }); }); describe('Order entity', () => { let orderId: string; beforeAll(async () => { const { addItemToOrder } = await shopClient.query<any, AddItemToOrderMutationVariables>( ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 1, }, ); orderId = addItemToOrder.id; }); it('shop setOrderCustomFields', async () => { const { setOrderCustomFields } = await shopClient.query(gql` mutation { setOrderCustomFields( input: { customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { ... on Order { id ${customFieldsSelection} } } } `); assertCustomFieldIds(setOrderCustomFields.customFields, 'T_2', ['T_3', 'T_4']); }); it('admin setOrderCustomFields', async () => { const { setOrderCustomFields } = await adminClient.query(gql` mutation { setOrderCustomFields( input: { id: "${orderId}" customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { ... on Order { id ${customFieldsSelection} } } } `); assertCustomFieldIds(setOrderCustomFields.customFields, 'T_1', ['T_1', 'T_2']); }); // https://github.com/vendure-ecommerce/vendure/issues/1664#issuecomment-1320872627 it('admin order query with eager-loaded custom field relation', async () => { const { order } = await adminClient.query(gql` query { order(id: 1) { id customFields { productOwner { id } } } } `); // we're just making sure it does not throw here. expect(order).toEqual({ customFields: { productOwner: null, }, id: 'T_1', }); }); }); describe('OrderLine entity', () => { it('shop addItemToOrder', async () => { const { addItemToOrder } = await shopClient.query( gql`mutation { addItemToOrder(productVariantId: "T_1", quantity: 1, customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] }) { ... on Order { id ${customFieldsSelection} } } }`, ); assertCustomFieldIds(addItemToOrder.customFields, 'T_1', ['T_1', 'T_2']); }); }); describe('Product, ProductVariant entity', () => { let productId: string; it('admin createProduct', async () => { const { createProduct } = await adminClient.query(gql` mutation { createProduct( input: { translations: [{ languageCode: en, name: "test" slug: "test" description: "test" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createProduct.customFields, 'T_1', ['T_1', 'T_2']); productId = createProduct.id; }); it('admin updateProduct', async () => { const { updateProduct } = await adminClient.query(gql` mutation { updateProduct( input: { id: "${productId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateProduct.customFields, 'T_2', ['T_3', 'T_4']); }); let productVariantId: string; it('admin createProductVariant', async () => { const { createProductVariants } = await adminClient.query(gql` mutation { createProductVariants( input: [{ sku: "TEST01" productId: "${productId}" translations: [{ languageCode: en, name: "test" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } }] ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createProductVariants[0].customFields, 'T_1', ['T_1', 'T_2']); productVariantId = createProductVariants[0].id; }); it('admin updateProductVariant', async () => { const { updateProductVariants } = await adminClient.query(gql` mutation { updateProductVariants( input: [{ id: "${productVariantId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } }] ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateProductVariants[0].customFields, 'T_2', ['T_3', 'T_4']); }); describe('issue 1664', () => { // https://github.com/vendure-ecommerce/vendure/issues/1664 it('successfully gets product by id with eager-loading custom field relation', async () => { const { product } = await shopClient.query(gql` query { product(id: "T_1") { id customFields { cfVendor { featuredProduct { id } } } } } `); expect(product).toBeDefined(); }); // https://github.com/vendure-ecommerce/vendure/issues/1664 it('successfully gets product by id with nested eager-loading custom field relation', async () => { const { customer } = await adminClient.query(gql` query { customer(id: "T_1") { id firstName lastName emailAddress phoneNumber user { customFields { cfVendor { id } } } } } `); expect(customer).toBeDefined(); }); // https://github.com/vendure-ecommerce/vendure/issues/1664 it('successfully gets product.variants with nested custom field relation', async () => { await adminClient.query(gql` mutation { updateProductVariants( input: [{ id: "T_1", customFields: { cfRelatedProductsIds: ["T_2"] } }] ) { id } } `); const { product } = await adminClient.query(gql` query { product(id: "T_1") { variants { id customFields { cfRelatedProducts { featuredAsset { id } } } } } } `); expect(product).toBeDefined(); expect(product.variants[0].customFields.cfRelatedProducts).toEqual([ { featuredAsset: { id: 'T_2' }, }, ]); }); it('successfully gets product by slug with eager-loading custom field relation', async () => { const { product } = await shopClient.query(gql` query { product(slug: "laptop") { id customFields { cfVendor { featuredProduct { id } } } } } `); expect(product).toBeDefined(); }); it('does not error on custom field relation with eager custom field relation', async () => { const { product } = await adminClient.query(gql` query { product(slug: "laptop") { name customFields { owner { id code customFields { profile { id name } } } } } } `); expect(product).toBeDefined(); }); }); }); describe('ProductOptionGroup, ProductOption entity', () => { let productOptionGroupId: string; it('admin createProductOptionGroup', async () => { const { createProductOptionGroup } = await adminClient.query(gql` mutation { createProductOptionGroup( input: { code: "test" options: [] translations: [{ languageCode: en, name: "test" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createProductOptionGroup.customFields, 'T_1', ['T_1', 'T_2']); productOptionGroupId = createProductOptionGroup.id; }); it('admin updateProductOptionGroup', async () => { const { updateProductOptionGroup } = await adminClient.query(gql` mutation { updateProductOptionGroup( input: { id: "${productOptionGroupId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateProductOptionGroup.customFields, 'T_2', ['T_3', 'T_4']); }); let productOptionId: string; it('admin createProductOption', async () => { const { createProductOption } = await adminClient.query(gql` mutation { createProductOption( input: { productOptionGroupId: "${productOptionGroupId}" code: "test-option" translations: [{ languageCode: en, name: "test-option" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createProductOption.customFields, 'T_1', ['T_1', 'T_2']); productOptionId = createProductOption.id; }); it('admin updateProductOption', async () => { const { updateProductOption } = await adminClient.query(gql` mutation { updateProductOption( input: { id: "${productOptionId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateProductOption.customFields, 'T_2', ['T_3', 'T_4']); }); }); // describe('User entity', () => { // // Currently no GraphQL API to set User custom fields // }); describe('ShippingMethod entity', () => { let shippingMethodId: string; it('admin createShippingMethod', async () => { const { createShippingMethod } = await adminClient.query(gql` mutation { createShippingMethod( input: { code: "test" calculator: { code: "${defaultShippingCalculator.code}" arguments: [ { name: "rate" value: "10"}, { name: "includesTax" value: "true"}, { name: "taxRate" value: "10"}, ] } checker: { code: "${defaultShippingEligibilityChecker.code}" arguments: [ { name: "orderMinimum" value: "0"}, ] } fulfillmentHandler: "${manualFulfillmentHandler.code}" translations: [{ languageCode: en, name: "test" description: "test" }] customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createShippingMethod.customFields, 'T_1', ['T_1', 'T_2']); shippingMethodId = createShippingMethod.id; }); it('admin updateShippingMethod', async () => { const { updateShippingMethod } = await adminClient.query(gql` mutation { updateShippingMethod( input: { id: "${shippingMethodId}" translations: [] customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateShippingMethod.customFields, 'T_2', ['T_3', 'T_4']); }); it('shop eligibleShippingMethods (ShippingMethodQuote)', async () => { const { eligibleShippingMethods } = await shopClient.query(gql` query { eligibleShippingMethods { id name code description ${customFieldsSelection} } } `); const testShippingMethodQuote = eligibleShippingMethods.find( (quote: any) => quote.code === 'test', ); assertCustomFieldIds(testShippingMethodQuote.customFields, 'T_2', ['T_3', 'T_4']); }); }); describe('PaymentMethod entity', () => { let paymentMethodId: string; it('admin createShippingMethod', async () => { const { createPaymentMethod } = await adminClient.query(gql` mutation { createPaymentMethod( input: { code: "test" enabled: true handler: { code: "${testSuccessfulPaymentMethod.code}" arguments: [] } customFields: { singleId: "T_1", multiIds: ["T_1", "T_2"] }, translations: [{ languageCode: en, name: "test" }] } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(createPaymentMethod.customFields, 'T_1', ['T_1', 'T_2']); paymentMethodId = createPaymentMethod.id; }); it('admin updatePaymentMethod', async () => { const { updatePaymentMethod } = await adminClient.query(gql` mutation { updatePaymentMethod( input: { id: "${paymentMethodId}" customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] }, } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updatePaymentMethod.customFields, 'T_2', ['T_3', 'T_4']); }); it('shop eligiblePaymentMethods (PaymentMethodQuote)', async () => { const { eligiblePaymentMethods } = await shopClient.query(gql` query { eligiblePaymentMethods { id name description ${customFieldsSelection} } } `); assertCustomFieldIds(eligiblePaymentMethods[0].customFields, 'T_2', ['T_3', 'T_4']); }); }); describe('Asset entity', () => { it('set custom field relations on Asset', async () => { const { updateAsset } = await adminClient.query(gql` mutation { updateAsset( input: { id: "T_1", customFields: { singleId: "T_2", multiIds: ["T_3", "T_4"] } } ) { id ${customFieldsSelection} } } `); assertCustomFieldIds(updateAsset.customFields, 'T_2', ['T_3', 'T_4']); }); it('findOne on Asset', async () => { const { asset } = await adminClient.query(gql` query { asset(id: "T_1") { id ${customFieldsSelection} } } `); expect(asset.customFields.single.id).toBe('T_2'); expect(asset.customFields.multi.length).toEqual(2); }); // https://github.com/vendure-ecommerce/vendure/issues/1636 it('calling TransactionalConnection.findOneInChannel() returns custom field relations', async () => { TestPlugin1636_1664.testResolverSpy.mockReset(); await shopClient.query(gql` query { getAssetTest(id: "T_1") } `); const args = TestPlugin1636_1664.testResolverSpy.mock.calls[0]; expect(args[0].customFields.single.id).toEqual(2); expect(args[0].customFields.multi.length).toEqual(2); }); }); }); it('null values', async () => { const { updateCustomerAddress } = await adminClient.query(gql` mutation { updateCustomerAddress( input: { id: "T_1", customFields: { singleId: null, multiIds: ["T_1", "null"] } } ) { id customFields { single { id } multi { id } } } } `); expect(updateCustomerAddress.customFields.single).toEqual(null); expect(updateCustomerAddress.customFields.multi).toEqual([{ id: 'T_1' }]); }); describe('bi-direction relations', () => { let customEntityRepository: Repository<TestCustomEntity>; let customEntity: TestCustomEntity; let collectionIdInternal: number; beforeAll(async () => { customEntityRepository = server.app .get(TransactionalConnection) .getRepository(RequestContext.empty(), TestCustomEntity); const customEntityId = (await customEntityRepository.save({})).id; const { createCollection } = await adminClient.query(gql` mutation { createCollection( input: { translations: [ { languageCode: en, name: "Test", description: "test", slug: "test" } ] filters: [] customFields: { customEntityListIds: [${customEntityId}] customEntityId: ${customEntityId} } } ) { id } } `); collectionIdInternal = parseInt(createCollection.id.replace('T_', ''), 10); customEntity = await assertFound( customEntityRepository.findOne({ where: { id: customEntityId }, relations: { customEntityInverse: true, customEntityListInverse: true, }, }), ); }); it('can create inverse relation for list=false', () => { expect(customEntity.customEntityInverse).toEqual([ expect.objectContaining({ id: collectionIdInternal }), ]); }); it('can create inverse relation for list=true', () => { expect(customEntity.customEntityListInverse).toEqual([ expect.objectContaining({ id: collectionIdInternal }), ]); }); }); });
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { Asset, CustomFields, mergeConfig, TransactionalConnection } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import { fail } from 'assert'; import gql from 'graphql-tag'; import path from 'path'; import { vi } from 'vitest'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; import { fixPostgresTimezone } from './utils/fix-pg-timezone'; fixPostgresTimezone(); /* eslint-disable @typescript-eslint/no-non-null-assertion */ const validateInjectorSpy = vi.fn(); const customConfig = mergeConfig(testConfig(), { dbConnectionOptions: { timezone: 'Z', }, customFields: { Product: [ { name: 'nullable', type: 'string' }, { name: 'notNullable', type: 'string', nullable: false, defaultValue: '' }, { name: 'stringWithDefault', type: 'string', defaultValue: 'hello' }, { name: 'localeStringWithDefault', type: 'localeString', defaultValue: 'hola' }, { name: 'intWithDefault', type: 'int', defaultValue: 5 }, { name: 'floatWithDefault', type: 'float', defaultValue: 5.5678 }, { name: 'booleanWithDefault', type: 'boolean', defaultValue: true }, { name: 'dateTimeWithDefault', type: 'datetime', defaultValue: new Date('2019-04-30T12:59:16.4158386Z'), }, { name: 'validateString', type: 'string', pattern: '^[0-9][a-z]+$' }, { name: 'validateLocaleString', type: 'localeString', pattern: '^[0-9][a-z]+$' }, { name: 'validateInt', type: 'int', min: 0, max: 10 }, { name: 'validateFloat', type: 'float', min: 0.5, max: 10.5 }, { name: 'validateDateTime', type: 'datetime', min: '2019-01-01T08:30', max: '2019-06-01T08:30', }, { name: 'validateFn1', type: 'string', validate: value => { if (value !== 'valid') { return `The value ['${value as string}'] is not valid`; } }, }, { name: 'validateFn2', type: 'string', validate: value => { if (value !== 'valid') { return [ { languageCode: LanguageCode.en, value: `The value ['${value as string}'] is not valid`, }, ]; } }, }, { name: 'validateFn3', type: 'string', validate: (value, injector) => { const connection = injector.get(TransactionalConnection); validateInjectorSpy(connection); }, }, { name: 'validateFn4', type: 'string', validate: async (value, injector) => { await new Promise(resolve => setTimeout(resolve, 1)); return 'async error'; }, }, { name: 'validateRelation', type: 'relation', entity: Asset, validate: async value => { await new Promise(resolve => setTimeout(resolve, 1)); return 'relation error'; }, }, { name: 'stringWithOptions', type: 'string', options: [{ value: 'small' }, { value: 'medium' }, { value: 'large' }], }, { name: 'nullableStringWithOptions', type: 'string', nullable: true, options: [{ value: 'small' }, { value: 'medium' }, { value: 'large' }], }, { name: 'nonPublic', type: 'string', defaultValue: 'hi!', public: false, }, { name: 'public', type: 'string', defaultValue: 'ho!', public: true, }, { name: 'longString', type: 'string', length: 10000, }, { name: 'longLocaleString', type: 'localeString', length: 10000, }, { name: 'readonlyString', type: 'string', readonly: true, }, { name: 'internalString', type: 'string', internal: true, }, { name: 'stringList', type: 'string', list: true, }, { name: 'localeStringList', type: 'localeString', list: true, }, { name: 'stringListWithDefault', type: 'string', list: true, defaultValue: ['cat'], }, { name: 'intListWithValidation', type: 'int', list: true, validate: value => { if (!value.includes(42)) { return 'Must include the number 42!'; } }, }, { name: 'uniqueString', type: 'string', unique: true, }, ], Facet: [ { name: 'translated', type: 'localeString', }, ], Customer: [ { name: 'score', type: 'int', readonly: true, }, ], OrderLine: [{ name: 'validateInt', type: 'int', min: 0, max: 10 }], } as CustomFields, }); describe('Custom fields', () => { const { server, adminClient, shopClient } = createTestEnvironment(customConfig); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('globalSettings.serverConfig.customFieldConfig', async () => { const { globalSettings } = await adminClient.query(gql` query { globalSettings { serverConfig { customFieldConfig { Product { ... on CustomField { name type list } ... on RelationCustomFieldConfig { scalarFields } } } } } } `); expect(globalSettings.serverConfig.customFieldConfig).toEqual({ Product: [ { name: 'nullable', type: 'string', list: false }, { name: 'notNullable', type: 'string', list: false }, { name: 'stringWithDefault', type: 'string', list: false }, { name: 'localeStringWithDefault', type: 'localeString', list: false }, { name: 'intWithDefault', type: 'int', list: false }, { name: 'floatWithDefault', type: 'float', list: false }, { name: 'booleanWithDefault', type: 'boolean', list: false }, { name: 'dateTimeWithDefault', type: 'datetime', list: false }, { name: 'validateString', type: 'string', list: false }, { name: 'validateLocaleString', type: 'localeString', list: false }, { name: 'validateInt', type: 'int', list: false }, { name: 'validateFloat', type: 'float', list: false }, { name: 'validateDateTime', type: 'datetime', list: false }, { name: 'validateFn1', type: 'string', list: false }, { name: 'validateFn2', type: 'string', list: false }, { name: 'validateFn3', type: 'string', list: false }, { name: 'validateFn4', type: 'string', list: false }, { name: 'validateRelation', type: 'relation', list: false, scalarFields: [ 'id', 'createdAt', 'updatedAt', 'name', 'type', 'fileSize', 'mimeType', 'width', 'height', 'source', 'preview', 'customFields', ], }, { name: 'stringWithOptions', type: 'string', list: false }, { name: 'nullableStringWithOptions', type: 'string', list: false }, { name: 'nonPublic', type: 'string', list: false }, { name: 'public', type: 'string', list: false }, { name: 'longString', type: 'string', list: false }, { name: 'longLocaleString', type: 'localeString', list: false }, { name: 'readonlyString', type: 'string', list: false }, { name: 'stringList', type: 'string', list: true }, { name: 'localeStringList', type: 'localeString', list: true }, { name: 'stringListWithDefault', type: 'string', list: true }, { name: 'intListWithValidation', type: 'int', list: true }, { name: 'uniqueString', type: 'string', list: false }, // The internal type should not be exposed at all // { name: 'internalString', type: 'string' }, ], }); }); it('globalSettings.serverConfig.entityCustomFields', async () => { const { globalSettings } = await adminClient.query(gql` query { globalSettings { serverConfig { entityCustomFields { entityName customFields { ... on CustomField { name type list } ... on RelationCustomFieldConfig { scalarFields } } } } } } `); const productCustomFields = globalSettings.serverConfig.entityCustomFields.find( e => e.entityName === 'Product', ); expect(productCustomFields).toEqual({ entityName: 'Product', customFields: [ { name: 'nullable', type: 'string', list: false }, { name: 'notNullable', type: 'string', list: false }, { name: 'stringWithDefault', type: 'string', list: false }, { name: 'localeStringWithDefault', type: 'localeString', list: false }, { name: 'intWithDefault', type: 'int', list: false }, { name: 'floatWithDefault', type: 'float', list: false }, { name: 'booleanWithDefault', type: 'boolean', list: false }, { name: 'dateTimeWithDefault', type: 'datetime', list: false }, { name: 'validateString', type: 'string', list: false }, { name: 'validateLocaleString', type: 'localeString', list: false }, { name: 'validateInt', type: 'int', list: false }, { name: 'validateFloat', type: 'float', list: false }, { name: 'validateDateTime', type: 'datetime', list: false }, { name: 'validateFn1', type: 'string', list: false }, { name: 'validateFn2', type: 'string', list: false }, { name: 'validateFn3', type: 'string', list: false }, { name: 'validateFn4', type: 'string', list: false }, { name: 'validateRelation', type: 'relation', list: false, scalarFields: [ 'id', 'createdAt', 'updatedAt', 'name', 'type', 'fileSize', 'mimeType', 'width', 'height', 'source', 'preview', 'customFields', ], }, { name: 'stringWithOptions', type: 'string', list: false }, { name: 'nullableStringWithOptions', type: 'string', list: false }, { name: 'nonPublic', type: 'string', list: false }, { name: 'public', type: 'string', list: false }, { name: 'longString', type: 'string', list: false }, { name: 'longLocaleString', type: 'localeString', list: false }, { name: 'readonlyString', type: 'string', list: false }, { name: 'stringList', type: 'string', list: true }, { name: 'localeStringList', type: 'localeString', list: true }, { name: 'stringListWithDefault', type: 'string', list: true }, { name: 'intListWithValidation', type: 'int', list: true }, { name: 'uniqueString', type: 'string', list: false }, // The internal type should not be exposed at all // { name: 'internalString', type: 'string' }, ], }); }); it('get nullable with no default', async () => { const { product } = await adminClient.query(gql` query { product(id: "T_1") { id name customFields { nullable } } } `); expect(product).toEqual({ id: 'T_1', name: 'Laptop', customFields: { nullable: null, }, }); }); it('get entity with localeString only', async () => { const { facet } = await adminClient.query(gql` query { facet(id: "T_1") { id name customFields { translated } } } `); expect(facet).toEqual({ id: 'T_1', name: 'category', customFields: { translated: null, }, }); }); it('get fields with default values', async () => { const { product } = await adminClient.query(gql` query { product(id: "T_1") { id name customFields { stringWithDefault localeStringWithDefault intWithDefault floatWithDefault booleanWithDefault dateTimeWithDefault stringListWithDefault } } } `); const customFields = { stringWithDefault: 'hello', localeStringWithDefault: 'hola', intWithDefault: 5, floatWithDefault: 5.5678, booleanWithDefault: true, dateTimeWithDefault: '2019-04-30T12:59:16.415Z', // MySQL does not support defaults on TEXT fields, which is what "simple-json" uses // internally. See https://stackoverflow.com/q/3466872/772859 stringListWithDefault: customConfig.dbConnectionOptions.type === 'mysql' ? null : ['cat'], }; expect(product).toEqual({ id: 'T_1', name: 'Laptop', customFields, }); }); it( 'update non-nullable field', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { notNullable: null } }) { id } } `); }, 'The custom field "notNullable" value cannot be set to null'), ); it( 'throws on attempt to update readonly field', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { readonlyString: "hello" } }) { id } } `); }, 'Field "readonlyString" is not defined by type "UpdateProductCustomFieldsInput"'), ); it( 'throws on attempt to update readonly field when no other custom fields defined', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateCustomer(input: { id: "T_1", customFields: { score: 5 } }) { ... on Customer { id } } } `); }, 'The custom field "score" is readonly'), ); it( 'throws on attempt to create readonly field', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { createProduct( input: { translations: [{ languageCode: en, name: "test" }] customFields: { readonlyString: "hello" } } ) { id } } `); }, 'Field "readonlyString" is not defined by type "CreateProductCustomFieldsInput"'), ); it('string length allows long strings', async () => { const longString = Array.from({ length: 500 }, v => 'hello there!').join(' '); const result = await adminClient.query( gql` mutation ($stringValue: String!) { updateProduct(input: { id: "T_1", customFields: { longString: $stringValue } }) { id customFields { longString } } } `, { stringValue: longString }, ); expect(result.updateProduct.customFields.longString).toBe(longString); }); it('string length allows long localeStrings', async () => { const longString = Array.from({ length: 500 }, v => 'hello there!').join(' '); const result = await adminClient.query( gql` mutation ($stringValue: String!) { updateProduct( input: { id: "T_1" translations: [ { languageCode: en, customFields: { longLocaleString: $stringValue } } ] } ) { id customFields { longLocaleString } } } `, { stringValue: longString }, ); expect(result.updateProduct.customFields.longLocaleString).toBe(longString); }); describe('validation', () => { it( 'invalid string', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateString: "hello" } }) { id } } `); }, 'The custom field "validateString" value ["hello"] does not match the pattern [^[0-9][a-z]+$]'), ); it( 'invalid string option', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { stringWithOptions: "tiny" } }) { id } } `); }, "The custom field \"stringWithOptions\" value [\"tiny\"] is invalid. Valid options are ['small', 'medium', 'large']"), ); it('valid string option', async () => { const { updateProduct } = await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { stringWithOptions: "medium" } }) { id customFields { stringWithOptions } } } `); expect(updateProduct.customFields.stringWithOptions).toBe('medium'); }); it('nullable string option with null', async () => { const { updateProduct } = await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { nullableStringWithOptions: null } }) { id customFields { nullableStringWithOptions } } } `); expect(updateProduct.customFields.nullableStringWithOptions).toBeNull(); }); it( 'invalid localeString', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct( input: { id: "T_1" translations: [ { id: "T_1" languageCode: en customFields: { validateLocaleString: "servus" } } ] } ) { id } } `); }, 'The custom field "validateLocaleString" value ["servus"] does not match the pattern [^[0-9][a-z]+$]'), ); it( 'invalid int', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateInt: 12 } }) { id } } `); }, 'The custom field "validateInt" value [12] is greater than the maximum [10]'), ); it( 'invalid float', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateFloat: 10.6 } }) { id } } `); }, 'The custom field "validateFloat" value [10.6] is greater than the maximum [10.5]'), ); it( 'invalid datetime', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct( input: { id: "T_1" customFields: { validateDateTime: "2019-01-01T05:25:00.000Z" } } ) { id } } `); }, 'The custom field "validateDateTime" value [2019-01-01T05:25:00.000Z] is less than the minimum [2019-01-01T08:30]'), ); it( 'invalid validate function with string', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateFn1: "invalid" } }) { id } } `); }, "The value ['invalid'] is not valid"), ); it( 'invalid validate function with localized string', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateFn2: "invalid" } }) { id } } `); }, "The value ['invalid'] is not valid"), ); it( 'invalid list field', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct( input: { id: "T_1", customFields: { intListWithValidation: [1, 2, 3] } } ) { id } } `); }, 'Must include the number 42!'), ); it('valid list field', async () => { const { updateProduct } = await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { intListWithValidation: [1, 42, 3] } }) { id customFields { intListWithValidation } } } `); expect(updateProduct.customFields.intListWithValidation).toEqual([1, 42, 3]); }); it('can inject providers into validation fn', async () => { const { updateProduct } = await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateFn3: "some value" } }) { id customFields { validateFn3 } } } `); expect(updateProduct.customFields.validateFn3).toBe('some value'); expect(validateInjectorSpy).toHaveBeenCalledTimes(1); expect(validateInjectorSpy.mock.calls[0][0] instanceof TransactionalConnection).toBe(true); }); it( 'supports async validation fn', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateFn4: "some value" } }) { id customFields { validateFn4 } } } `); }, 'async error'), ); // https://github.com/vendure-ecommerce/vendure/issues/1000 it( 'supports validation of relation types', assertThrowsWithMessage(async () => { await adminClient.query(gql` mutation { updateProduct(input: { id: "T_1", customFields: { validateRelationId: "T_1" } }) { id customFields { validateFn4 } } } `); }, 'relation error'), ); // https://github.com/vendure-ecommerce/vendure/issues/1091 it('handles well graphql internal fields', async () => { // throws "Cannot read property 'args' of undefined" if broken await adminClient.query(gql` mutation { __typename updateProduct(input: { id: "T_1", customFields: { nullable: "some value" } }) { __typename id customFields { __typename nullable } } } `); }); // https://github.com/vendure-ecommerce/vendure/issues/1953 describe('validation of OrderLine custom fields', () => { it('addItemToOrder', async () => { try { const { addItemToOrder } = await shopClient.query(gql` mutation { addItemToOrder( productVariantId: 1 quantity: 1 customFields: { validateInt: 11 } ) { ... on Order { id } } } `); fail('Should have thrown'); } catch (e) { expect(e.message).toContain( 'The custom field "validateInt" value [11] is greater than the maximum [10]', ); } const { addItemToOrder: result } = await shopClient.query(gql` mutation { addItemToOrder(productVariantId: 1, quantity: 1, customFields: { validateInt: 9 }) { ... on Order { id lines { customFields { validateInt } } } } } `); expect(result.lines[0].customFields).toEqual({ validateInt: 9 }); }); it('adjustOrderLine', async () => { try { const { adjustOrderLine } = await shopClient.query(gql` mutation { adjustOrderLine( orderLineId: "T_1" quantity: 1 customFields: { validateInt: 11 } ) { ... on Order { id } } } `); fail('Should have thrown'); } catch (e) { expect(e.message).toContain( 'The custom field "validateInt" value [11] is greater than the maximum [10]', ); } const { adjustOrderLine: result } = await shopClient.query(gql` mutation { adjustOrderLine(orderLineId: "T_1", quantity: 1, customFields: { validateInt: 2 }) { ... on Order { id lines { customFields { validateInt } } } } } `); expect(result.lines[0].customFields).toEqual({ validateInt: 2 }); }); }); }); describe('public access', () => { it( 'non-public throws for Shop API', assertThrowsWithMessage(async () => { await shopClient.query(gql` query { product(id: "T_1") { id customFields { nonPublic } } } `); }, 'Cannot query field "nonPublic" on type "ProductCustomFields"'), ); it('publicly accessible via Shop API', async () => { const { product } = await shopClient.query(gql` query { product(id: "T_1") { id customFields { public } } } `); expect(product.customFields.public).toBe('ho!'); }); it( 'internal throws for Shop API', assertThrowsWithMessage(async () => { await shopClient.query(gql` query { product(id: "T_1") { id customFields { internalString } } } `); }, 'Cannot query field "internalString" on type "ProductCustomFields"'), ); it( 'internal throws for Admin API', assertThrowsWithMessage(async () => { await adminClient.query(gql` query { product(id: "T_1") { id customFields { internalString } } } `); }, 'Cannot query field "internalString" on type "ProductCustomFields"'), ); }); describe('sort & filter', () => { it('can sort by custom fields', async () => { const { products } = await adminClient.query(gql` query { products(options: { sort: { nullable: ASC } }) { totalItems } } `); expect(products.totalItems).toBe(1); }); // https://github.com/vendure-ecommerce/vendure/issues/1581 it('can sort by localeString custom fields', async () => { const { products } = await adminClient.query(gql` query { products(options: { sort: { localeStringWithDefault: ASC } }) { totalItems } } `); expect(products.totalItems).toBe(1); }); it('can filter by custom fields', async () => { const { products } = await adminClient.query(gql` query { products(options: { filter: { stringWithDefault: { contains: "hello" } } }) { totalItems } } `); expect(products.totalItems).toBe(1); }); it('can filter by localeString custom fields', async () => { const { products } = await adminClient.query(gql` query { products(options: { filter: { localeStringWithDefault: { contains: "hola" } } }) { totalItems } } `); expect(products.totalItems).toBe(1); }); it('can filter by custom list fields', async () => { const { products: result1 } = await adminClient.query(gql` query { products(options: { filter: { intListWithValidation: { inList: 42 } } }) { totalItems } } `); expect(result1.totalItems).toBe(1); const { products: result2 } = await adminClient.query(gql` query { products(options: { filter: { intListWithValidation: { inList: 43 } } }) { totalItems } } `); expect(result2.totalItems).toBe(0); }); it( 'cannot sort by custom list fields', assertThrowsWithMessage(async () => { await adminClient.query(gql` query { products(options: { sort: { intListWithValidation: ASC } }) { totalItems } } `); }, 'Field "intListWithValidation" is not defined by type "ProductSortParameter".'), ); it( 'cannot filter by internal field in Admin API', assertThrowsWithMessage(async () => { await adminClient.query(gql` query { products(options: { filter: { internalString: { contains: "hello" } } }) { totalItems } } `); }, 'Field "internalString" is not defined by type "ProductFilterParameter"'), ); it( 'cannot filter by internal field in Shop API', assertThrowsWithMessage(async () => { await shopClient.query(gql` query { products(options: { filter: { internalString: { contains: "hello" } } }) { totalItems } } `); }, 'Field "internalString" is not defined by type "ProductFilterParameter"'), ); }); describe('product on productVariant entity', () => { it('is translated', async () => { const { productVariants } = await adminClient.query(gql` query { productVariants(productId: "T_1") { items { product { name id customFields { localeStringWithDefault stringWithDefault } } } } } `); expect(productVariants.items[0].product).toEqual({ id: 'T_1', name: 'Laptop', customFields: { localeStringWithDefault: 'hola', stringWithDefault: 'hello', }, }); }); }); describe('unique constraint', () => { it('setting unique value works', async () => { const result = await adminClient.query( gql` mutation { updateProduct(input: { id: "T_1", customFields: { uniqueString: "foo" } }) { id customFields { uniqueString } } } `, ); expect(result.updateProduct.customFields.uniqueString).toBe('foo'); }); it('setting conflicting value fails', async () => { try { await adminClient.query(gql` mutation { createProduct( input: { translations: [ { languageCode: en, name: "test 2", slug: "test-2", description: "" } ] customFields: { uniqueString: "foo" } } ) { id } } `); fail('Should have thrown'); } catch (e: any) { let duplicateKeyErrMessage = 'unassigned'; switch (customConfig.dbConnectionOptions.type) { case 'mariadb': case 'mysql': duplicateKeyErrMessage = "ER_DUP_ENTRY: Duplicate entry 'foo' for key"; break; case 'postgres': duplicateKeyErrMessage = 'duplicate key value violates unique constraint'; break; case 'sqlite': case 'sqljs': duplicateKeyErrMessage = 'UNIQUE constraint failed: product.customFieldsUniquestring'; break; } expect(e.message).toContain(duplicateKeyErrMessage); } }); }); });
import { mergeConfig } from '@vendure/core'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { createTestEnvironment } from '../../testing/lib/create-test-environment'; import { sync, TestPluginWithCustomPermissions, wishlist, } from './fixtures/test-plugins/with-custom-permissions'; import { AdministratorFragment, CreateAdministratorMutation, CreateAdministratorMutationVariables, CreateRoleMutation, CreateRoleMutationVariables, RoleFragment, UpdateRoleMutation, UpdateRoleMutationVariables, } from './graphql/generated-e2e-admin-types'; import { CREATE_ADMINISTRATOR, CREATE_ROLE, UPDATE_ROLE } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; describe('Custom permissions', () => { const { server, adminClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [TestPluginWithCustomPermissions], }), ); let testRole: RoleFragment; let testAdmin: AdministratorFragment; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); // create a new role and Admin and sign in as that Admin const { createRole } = await adminClient.query<CreateRoleMutation, CreateRoleMutationVariables>( CREATE_ROLE, { input: { channelIds: ['T_1'], code: 'test-role', description: 'Testing custom permissions', permissions: [], }, }, ); testRole = createRole; const { createAdministrator } = await adminClient.query< CreateAdministratorMutation, CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { firstName: 'Test', lastName: 'Admin', emailAddress: 'test@admin.com', password: 'test', roleIds: [testRole.id], }, }); testAdmin = createAdministrator; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); describe('superadmin has custom permissions automatically', () => { beforeAll(async () => { await adminClient.asSuperAdmin(); }); it('single permission', async () => { const { syncWishlist } = await adminClient.query(SYNC); expect(syncWishlist).toBe(true); }); it('CRUD create permission', async () => { const { createWishlist } = await adminClient.query(CRUD_CREATE); expect(createWishlist).toBe(true); }); it('CRUD read permission', async () => { // eslint-disable-next-line no-shadow,@typescript-eslint/no-shadow const { wishlist } = await adminClient.query(CRUD_READ); expect(wishlist).toBe(true); }); it('CRUD update permission', async () => { const { updateWishlist } = await adminClient.query(CRUD_UPDATE); expect(updateWishlist).toBe(true); }); it('CRUD delete permission', async () => { const { deleteWishlist } = await adminClient.query(CRUD_DELETE); expect(deleteWishlist).toBe(true); }); }); describe('custom permissions prevent unauthorized access', () => { beforeAll(async () => { await adminClient.asUserWithCredentials(testAdmin.emailAddress, 'test'); }); it( 'single permission', assertThrowsWithMessage(async () => { await adminClient.query(SYNC); }, 'You are not currently authorized to perform this action'), ); it( 'CRUD create permission', assertThrowsWithMessage(async () => { await adminClient.query(CRUD_CREATE); }, 'You are not currently authorized to perform this action'), ); it( 'CRUD read permission', assertThrowsWithMessage(async () => { await adminClient.query(CRUD_READ); }, 'You are not currently authorized to perform this action'), ); it( 'CRUD update permission', assertThrowsWithMessage(async () => { await adminClient.query(CRUD_UPDATE); }, 'You are not currently authorized to perform this action'), ); it( 'CRUD delete permission', assertThrowsWithMessage(async () => { await adminClient.query(CRUD_DELETE); }, 'You are not currently authorized to perform this action'), ); }); describe('adding permissions enables access', () => { beforeAll(async () => { await adminClient.asSuperAdmin(); await adminClient.query<UpdateRoleMutation, UpdateRoleMutationVariables>(UPDATE_ROLE, { input: { id: testRole.id, permissions: [ sync.Permission, wishlist.Create, wishlist.Read, wishlist.Update, wishlist.Delete, ], }, }); await adminClient.asUserWithCredentials(testAdmin.emailAddress, 'test'); }); it('single permission', async () => { const { syncWishlist } = await adminClient.query(SYNC); expect(syncWishlist).toBe(true); }); it('CRUD create permission', async () => { const { createWishlist } = await adminClient.query(CRUD_CREATE); expect(createWishlist).toBe(true); }); it('CRUD read permission', async () => { // eslint-disable-next-line no-shadow,@typescript-eslint/no-shadow const { wishlist } = await adminClient.query(CRUD_READ); expect(wishlist).toBe(true); }); it('CRUD update permission', async () => { const { updateWishlist } = await adminClient.query(CRUD_UPDATE); expect(updateWishlist).toBe(true); }); it('CRUD delete permission', async () => { const { deleteWishlist } = await adminClient.query(CRUD_DELETE); expect(deleteWishlist).toBe(true); }); }); }); const SYNC = gql` mutation Sync { syncWishlist } `; const CRUD_READ = gql` query CrudRead { wishlist } `; const CRUD_CREATE = gql` mutation CrudCreate { createWishlist } `; const CRUD_UPDATE = gql` mutation CrudUpdate { updateWishlist } `; const CRUD_DELETE = gql` mutation CrudDelete { deleteWishlist } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN } from '@vendure/testing'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { CurrencyCode, LanguageCode } from './graphql/generated-e2e-admin-types'; import { RegisterMutation, RegisterMutationVariables } from './graphql/generated-e2e-shop-types'; import { ADD_CUSTOMERS_TO_GROUP, CREATE_ADDRESS, CREATE_CHANNEL, CREATE_CUSTOMER, CREATE_CUSTOMER_GROUP, DELETE_CUSTOMER, GET_CUSTOMER_GROUP, GET_CUSTOMER_LIST, ME, REMOVE_CUSTOMERS_FROM_GROUP, UPDATE_ADDRESS, UPDATE_CUSTOMER, } from './graphql/shared-definitions'; import { DELETE_ADDRESS, REGISTER_ACCOUNT } from './graphql/shop-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; type CustomerListItem = Codegen.GetCustomerListQuery['customers']['items'][number]; describe('ChannelAware Customers', () => { const { server, adminClient, shopClient } = createTestEnvironment(testConfig()); const SECOND_CHANNEL_TOKEN = 'second_channel_token'; let firstCustomer: CustomerListItem; let secondCustomer: CustomerListItem; let thirdCustomer: CustomerListItem; const numberOfCustomers = 3; let customerGroupId: string; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: numberOfCustomers, }); await adminClient.asSuperAdmin(); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST, { options: { take: numberOfCustomers }, }); firstCustomer = customers.items[0]; secondCustomer = customers.items[1]; thirdCustomer = customers.items[2]; await adminClient.query<Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables>( CREATE_CHANNEL, { input: { code: 'second-channel', token: SECOND_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, currencyCode: CurrencyCode.GBP, pricesIncludeTax: true, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', }, }, ); const { createCustomerGroup } = await adminClient.query< Codegen.CreateCustomerGroupMutation, Codegen.CreateCustomerGroupMutationVariables >(CREATE_CUSTOMER_GROUP, { input: { name: 'TestGroup', }, }); customerGroupId = createCustomerGroup.id; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); describe('Address manipulation', () => { it( 'throws when updating address from customer from other channel', assertThrowsWithMessage(async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.UpdateAddressMutation, Codegen.UpdateAddressMutationVariables >(UPDATE_ADDRESS, { input: { id: 'T_1', streetLine1: 'Dummy street', }, }); }, 'No Address with the id "1" could be found'), ); it( 'throws when creating address for customer from other channel', assertThrowsWithMessage(async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.CreateAddressMutation, Codegen.CreateAddressMutationVariables >(CREATE_ADDRESS, { id: firstCustomer.id, input: { streetLine1: 'Dummy street', countryCode: 'BE', }, }); }, 'No Customer with the id "1" could be found'), ); it( 'throws when deleting address from customer from other channel', assertThrowsWithMessage(async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.DeleteCustomerAddressMutation, Codegen.DeleteCustomerAddressMutationVariables >(DELETE_ADDRESS, { id: 'T_1', }); }, 'No Address with the id "1" could be found'), ); }); describe('Customer manipulation', () => { it( 'throws when deleting customer from other channel', assertThrowsWithMessage(async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.DeleteCustomerMutation, Codegen.DeleteCustomerMutationVariables >(DELETE_CUSTOMER, { id: firstCustomer.id, }); }, 'No Customer with the id "1" could be found'), ); it( 'throws when updating customer from other channel', assertThrowsWithMessage(async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.UpdateCustomerMutation, Codegen.UpdateCustomerMutationVariables >(UPDATE_CUSTOMER, { input: { id: firstCustomer.id, firstName: 'John', lastName: 'Doe', }, }); }, 'No Customer with the id "1" could be found'), ); it('creates customers on current and default channel', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query<Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables>( CREATE_CUSTOMER, { input: { firstName: 'John', lastName: 'Doe', emailAddress: 'john.doe@test.com', }, }, ); const customersSecondChannel = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const customersDefaultChannel = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customersSecondChannel.customers.totalItems).toBe(1); expect(customersDefaultChannel.customers.totalItems).toBe(numberOfCustomers + 1); }); it('only shows customers from current channel', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customers.totalItems).toBe(1); }); it('shows all customers on default channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customers.totalItems).toBe(numberOfCustomers + 1); }); it('brings customer to current channel when creating with existing emailAddress', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); let customersDefaultChannel = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); let customersSecondChannel = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customersDefaultChannel.customers.items.map(customer => customer.emailAddress)).toContain( firstCustomer.emailAddress, ); expect( customersSecondChannel.customers.items.map(customer => customer.emailAddress), ).not.toContain(firstCustomer.emailAddress); await adminClient.query<Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables>( CREATE_CUSTOMER, { input: { firstName: firstCustomer.firstName + '_new', lastName: firstCustomer.lastName + '_new', emailAddress: firstCustomer.emailAddress, }, }, ); customersSecondChannel = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); customersDefaultChannel = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); const firstCustomerOnNewChannel = customersSecondChannel.customers.items.find( customer => customer.emailAddress === firstCustomer.emailAddress, ); const firstCustomerOnDefaultChannel = customersDefaultChannel.customers.items.find( customer => customer.emailAddress === firstCustomer.emailAddress, ); expect(firstCustomerOnNewChannel).not.toBeNull(); expect(firstCustomerOnNewChannel?.emailAddress).toBe(firstCustomer.emailAddress); expect(firstCustomerOnNewChannel?.firstName).toBe(firstCustomer.firstName + '_new'); expect(firstCustomerOnNewChannel?.lastName).toBe(firstCustomer.lastName + '_new'); expect(firstCustomerOnDefaultChannel).not.toBeNull(); expect(firstCustomerOnDefaultChannel?.emailAddress).toBe(firstCustomer.emailAddress); expect(firstCustomerOnDefaultChannel?.firstName).toBe(firstCustomer.firstName + '_new'); expect(firstCustomerOnDefaultChannel?.lastName).toBe(firstCustomer.lastName + '_new'); }); }); describe('Shop API', () => { it('assigns authenticated customers to the channels they visit', async () => { shopClient.setChannelToken(SECOND_CHANNEL_TOKEN); await shopClient.asUserWithCredentials(secondCustomer.emailAddress, 'test'); await shopClient.query<Codegen.MeQuery>(ME); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customers.totalItems).toBe(3); expect(customers.items.map(customer => customer.emailAddress)).toContain( secondCustomer.emailAddress, ); }); it('assigns newly registered customers to channel', async () => { shopClient.setChannelToken(SECOND_CHANNEL_TOKEN); await shopClient.asAnonymousUser(); await shopClient.query<RegisterMutation, RegisterMutationVariables>(REGISTER_ACCOUNT, { input: { emailAddress: 'john.doe.2@test.com', }, }); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customers.totalItems).toBe(4); expect(customers.items.map(customer => customer.emailAddress)).toContain('john.doe.2@test.com'); }); // https://github.com/vendure-ecommerce/vendure/issues/834 it('handles concurrent assignments to a new channel', async () => { const THIRD_CHANNEL_TOKEN = 'third_channel_token'; await adminClient.query<Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables>( CREATE_CHANNEL, { input: { code: 'third-channel', token: THIRD_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, currencyCode: CurrencyCode.GBP, pricesIncludeTax: true, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', }, }, ); await shopClient.asUserWithCredentials(secondCustomer.emailAddress, 'test'); shopClient.setChannelToken(THIRD_CHANNEL_TOKEN); try { await Promise.all([ shopClient.query<Codegen.MeQuery>(ME), shopClient.query<Codegen.MeQuery>(ME), ]); } catch (e: any) { fail('Threw: ' + (e.message as string)); } adminClient.setChannelToken(THIRD_CHANNEL_TOKEN); const { customers } = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(customers.totalItems).toBe(1); expect(customers.items.map(customer => customer.emailAddress)).toContain( secondCustomer.emailAddress, ); }); }); describe('Customergroup manipulation', () => { it('does not add a customer from another channel to customerGroup', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.AddCustomersToGroupMutation, Codegen.AddCustomersToGroupMutationVariables >(ADD_CUSTOMERS_TO_GROUP, { groupId: customerGroupId, customerIds: [thirdCustomer.id], }); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { customerGroup } = await adminClient.query< Codegen.GetCustomerGroupQuery, Codegen.GetCustomerGroupQueryVariables >(GET_CUSTOMER_GROUP, { id: customerGroupId, }); expect(customerGroup!.customers.totalItems).toBe(0); }); it('only shows customers from current channel in customerGroup', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query< Codegen.AddCustomersToGroupMutation, Codegen.AddCustomersToGroupMutationVariables >(ADD_CUSTOMERS_TO_GROUP, { groupId: customerGroupId, customerIds: [secondCustomer.id, thirdCustomer.id], }); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { customerGroup } = await adminClient.query< Codegen.GetCustomerGroupQuery, Codegen.GetCustomerGroupQueryVariables >(GET_CUSTOMER_GROUP, { id: customerGroupId, }); expect(customerGroup!.customers.totalItems).toBe(1); expect(customerGroup!.customers.items.map(customer => customer.id)).toContain(secondCustomer.id); }); it('throws when deleting customer from other channel from customerGroup', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); await adminClient.query< Codegen.RemoveCustomersFromGroupMutation, Codegen.RemoveCustomersFromGroupMutationVariables >(REMOVE_CUSTOMERS_FROM_GROUP, { groupId: customerGroupId, customerIds: [thirdCustomer.id], }); }); }); });
import { pick } from '@vendure/common/lib/pick'; import { createTestEnvironment } from '@vendure/testing'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { HistoryEntryType } from './graphql/generated-e2e-admin-types'; import { DeletionResult } from './graphql/generated-e2e-shop-types'; import { ADD_CUSTOMERS_TO_GROUP, CREATE_CUSTOMER_GROUP, DELETE_CUSTOMER, DELETE_CUSTOMER_GROUP, GET_CUSTOMER_GROUP, GET_CUSTOMER_GROUPS, GET_CUSTOMER_HISTORY, GET_CUSTOMER_LIST, GET_CUSTOMER_WITH_GROUPS, REMOVE_CUSTOMERS_FROM_GROUP, UPDATE_CUSTOMER_GROUP, } from './graphql/shared-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; import { sortById } from './utils/test-order-utils'; describe('CustomerGroup resolver', () => { const { server, adminClient, shopClient } = createTestEnvironment(testConfig()); let customers: Codegen.GetCustomerListQuery['customers']['items']; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 5, }); await adminClient.asSuperAdmin(); const result = await adminClient.query<Codegen.GetCustomerListQuery>(GET_CUSTOMER_LIST); customers = result.customers.items; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('create', async () => { const { createCustomerGroup } = await adminClient.query< Codegen.CreateCustomerGroupMutation, Codegen.CreateCustomerGroupMutationVariables >(CREATE_CUSTOMER_GROUP, { input: { name: 'group 1', customerIds: [customers[0].id, customers[1].id], }, }); expect(createCustomerGroup.name).toBe('group 1'); expect(createCustomerGroup.customers.items.sort(sortById)).toEqual([ { id: customers[0].id }, { id: customers[1].id }, ]); }); it('history entry for CUSTOMER_ADDED_TO_GROUP after group created', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: customers[0].id, options: { skip: 3, }, }); expect(customer?.history.items.map(pick(['type', 'data']))).toEqual([ { type: HistoryEntryType.CUSTOMER_ADDED_TO_GROUP, data: { groupName: 'group 1', }, }, ]); }); it('customerGroups', async () => { const { customerGroups } = await adminClient.query< Codegen.GetCustomerGroupsQuery, Codegen.GetCustomerGroupsQueryVariables >(GET_CUSTOMER_GROUPS, { options: {}, }); expect(customerGroups.totalItems).toBe(1); expect(customerGroups.items[0].name).toBe('group 1'); }); it('customerGroup with customer list options', async () => { const { customerGroup } = await adminClient.query< Codegen.GetCustomerGroupQuery, Codegen.GetCustomerGroupQueryVariables >(GET_CUSTOMER_GROUP, { id: 'T_1', options: { take: 1, }, }); expect(customerGroup?.id).toBe('T_1'); expect(customerGroup?.name).toBe('group 1'); expect(customerGroup?.customers.items.length).toBe(1); expect(customerGroup?.customers.totalItems).toBe(2); }); it('update', async () => { const { updateCustomerGroup } = await adminClient.query< Codegen.UpdateCustomerGroupMutation, Codegen.UpdateCustomerGroupMutationVariables >(UPDATE_CUSTOMER_GROUP, { input: { id: 'T_1', name: 'group 1 updated', }, }); expect(updateCustomerGroup.name).toBe('group 1 updated'); }); it('addCustomersToGroup with existing customer', async () => { const { addCustomersToGroup } = await adminClient.query< Codegen.AddCustomersToGroupMutation, Codegen.AddCustomersToGroupMutationVariables >(ADD_CUSTOMERS_TO_GROUP, { groupId: 'T_1', customerIds: [customers[0].id], }); expect(addCustomersToGroup.customers.items.sort(sortById)).toEqual([ { id: customers[0].id }, { id: customers[1].id }, ]); }); it('addCustomersToGroup with new customers', async () => { const { addCustomersToGroup } = await adminClient.query< Codegen.AddCustomersToGroupMutation, Codegen.AddCustomersToGroupMutationVariables >(ADD_CUSTOMERS_TO_GROUP, { groupId: 'T_1', customerIds: [customers[2].id, customers[3].id], }); expect(addCustomersToGroup.customers.items.sort(sortById)).toEqual([ { id: customers[0].id }, { id: customers[1].id }, { id: customers[2].id }, { id: customers[3].id }, ]); }); it('history entry for CUSTOMER_ADDED_TO_GROUP not duplicated', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: customers[0].id, options: { filter: { type: { eq: HistoryEntryType.CUSTOMER_ADDED_TO_GROUP }, }, }, }); expect(customer?.history.items.map(pick(['type', 'data']))).toEqual([ { type: HistoryEntryType.CUSTOMER_ADDED_TO_GROUP, data: { groupName: 'group 1', }, }, ]); }); it('history entry for CUSTOMER_ADDED_TO_GROUP after customer added', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: customers[2].id, options: { skip: 3, }, }); expect(customer?.history.items.map(pick(['type', 'data']))).toEqual([ { type: HistoryEntryType.CUSTOMER_ADDED_TO_GROUP, data: { groupName: 'group 1 updated', }, }, ]); }); it('customer.groups field resolver', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerWithGroupsQuery, Codegen.GetCustomerWithGroupsQueryVariables >(GET_CUSTOMER_WITH_GROUPS, { id: customers[0].id, }); expect(customer?.groups).toEqual([{ id: 'T_1', name: 'group 1 updated' }]); }); it( 'removeCustomersFromGroup with invalid customerId', assertThrowsWithMessage(async () => { await adminClient.query< Codegen.RemoveCustomersFromGroupMutation, Codegen.RemoveCustomersFromGroupMutationVariables >(REMOVE_CUSTOMERS_FROM_GROUP, { groupId: 'T_1', customerIds: [customers[4].id], }); }, 'Customer does not belong to this CustomerGroup'), ); it('removeCustomersFromGroup with valid customerIds', async () => { const { removeCustomersFromGroup } = await adminClient.query< Codegen.RemoveCustomersFromGroupMutation, Codegen.RemoveCustomersFromGroupMutationVariables >(REMOVE_CUSTOMERS_FROM_GROUP, { groupId: 'T_1', customerIds: [customers[1].id, customers[3].id], }); expect(removeCustomersFromGroup.customers.items.sort(sortById)).toEqual([ { id: customers[0].id }, { id: customers[2].id }, ]); }); it('history entry for CUSTOMER_REMOVED_FROM_GROUP', async () => { const { customer } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: customers[1].id, options: { skip: 4, }, }); expect(customer?.history.items.map(pick(['type', 'data']))).toEqual([ { type: HistoryEntryType.CUSTOMER_REMOVED_FROM_GROUP, data: { groupName: 'group 1 updated', }, }, ]); }); it('deleteCustomerGroup', async () => { const { deleteCustomerGroup } = await adminClient.query< Codegen.DeleteCustomerGroupMutation, Codegen.DeleteCustomerGroupMutationVariables >(DELETE_CUSTOMER_GROUP, { id: 'T_1', }); expect(deleteCustomerGroup.message).toBeNull(); expect(deleteCustomerGroup.result).toBe(DeletionResult.DELETED); const { customerGroups } = await adminClient.query<Codegen.GetCustomerGroupsQuery>( GET_CUSTOMER_GROUPS, ); expect(customerGroups.totalItems).toBe(0); }); // https://github.com/vendure-ecommerce/vendure/issues/1785 it('removes customer from group when customer is deleted', async () => { const customer5Id = customers[4].id; const { createCustomerGroup } = await adminClient.query< Codegen.CreateCustomerGroupMutation, Codegen.CreateCustomerGroupMutationVariables >(CREATE_CUSTOMER_GROUP, { input: { name: 'group-1785', customerIds: [customer5Id], }, }); expect(createCustomerGroup.customers.items).toEqual([{ id: customer5Id }]); await adminClient.query<Codegen.DeleteCustomerMutation, Codegen.DeleteCustomerMutationVariables>( DELETE_CUSTOMER, { id: customer5Id, }, ); const { customerGroup } = await adminClient.query< Codegen.GetCustomerGroupQuery, Codegen.GetCustomerGroupQueryVariables >(GET_CUSTOMER_GROUP, { id: createCustomerGroup.id, }); expect(customerGroup?.customers.items).toEqual([]); }); });
import { OnModuleInit } from '@nestjs/common'; import { HistoryEntryType } from '@vendure/common/lib/generated-types'; import { omit } from '@vendure/common/lib/omit'; import { pick } from '@vendure/common/lib/pick'; import { AccountRegistrationEvent, EventBus, EventBusModule, mergeConfig, VendurePlugin, } from '@vendure/core'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { vi } from 'vitest'; import { afterAll, beforeAll, describe, expect, it, Mock } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { CUSTOMER_FRAGMENT } from './graphql/fragments'; import { DeletionResult, ErrorCode } from './graphql/generated-e2e-admin-types'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { ActiveOrderCustomerFragment, AddItemToOrderMutation, AddItemToOrderMutationVariables, SetCustomerForOrderMutation, SetCustomerForOrderMutationVariables, UpdatedOrderFragment, } from './graphql/generated-e2e-shop-types'; import { CREATE_ADDRESS, CREATE_ADMINISTRATOR, CREATE_CUSTOMER, DELETE_CUSTOMER, DELETE_CUSTOMER_NOTE, GET_CUSTOMER, GET_CUSTOMER_HISTORY, GET_CUSTOMER_LIST, ME, UPDATE_ADDRESS, UPDATE_CUSTOMER, UPDATE_CUSTOMER_NOTE, } from './graphql/shared-definitions'; import { ADD_ITEM_TO_ORDER, SET_CUSTOMER } from './graphql/shop-definitions'; import { assertThrowsWithMessage } from './utils/assert-throws-with-message'; /* eslint-disable @typescript-eslint/no-non-null-assertion */ let sendEmailFn: Mock; /** * This mock plugin simulates an EmailPlugin which would send emails * on the registration & password reset events. */ @VendurePlugin({ imports: [EventBusModule], }) class TestEmailPlugin implements OnModuleInit { constructor(private eventBus: EventBus) {} onModuleInit() { this.eventBus.ofType(AccountRegistrationEvent).subscribe(event => { sendEmailFn?.(event); }); } } type CustomerListItem = Codegen.GetCustomerListQuery['customers']['items'][number]; describe('Customer resolver', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [TestEmailPlugin] }), ); let firstCustomer: CustomerListItem; let secondCustomer: CustomerListItem; let thirdCustomer: CustomerListItem; const customerErrorGuard: ErrorResultGuard<Codegen.CustomerFragment> = createErrorResultGuard( input => !!input.emailAddress, ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 5, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('customers list', async () => { const result = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(result.customers.items.length).toBe(5); expect(result.customers.totalItems).toBe(5); firstCustomer = result.customers.items[0]; secondCustomer = result.customers.items[1]; thirdCustomer = result.customers.items[2]; }); it('customers list filter by postalCode', async () => { const result = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST, { options: { filter: { postalCode: { eq: 'NU9 0PW', }, }, }, }); expect(result.customers.items.length).toBe(1); expect(result.customers.items[0].emailAddress).toBe('eliezer56@yahoo.com'); }); it('customer resolver resolves User', async () => { const emailAddress = 'same-email@test.com'; // Create an administrator with the same email first in order to ensure the right user is resolved. // This test also validates that a customer can be created with the same identifier // of an existing administrator const { createAdministrator } = await adminClient.query< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { emailAddress, firstName: 'First', lastName: 'Last', password: '123', roleIds: ['1'], }, }); expect(createAdministrator.emailAddress).toEqual(emailAddress); const { createCustomer } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { emailAddress, firstName: 'New', lastName: 'Customer', }, password: 'test', }); customerErrorGuard.assertSuccess(createCustomer); expect(createCustomer.emailAddress).toEqual(emailAddress); const { customer } = await adminClient.query< Codegen.GetCustomerWithUserQuery, Codegen.GetCustomerWithUserQueryVariables >(GET_CUSTOMER_WITH_USER, { id: createCustomer.id, }); expect(customer!.user).toEqual({ id: createCustomer.user?.id, identifier: emailAddress, verified: true, }); }); describe('addresses', () => { let firstCustomerAddressIds: string[] = []; let firstCustomerThirdAddressId: string; it( 'createCustomerAddress throws on invalid countryCode', assertThrowsWithMessage( () => adminClient.query<Codegen.CreateAddressMutation, Codegen.CreateAddressMutationVariables>( CREATE_ADDRESS, { id: firstCustomer.id, input: { streetLine1: 'streetLine1', countryCode: 'INVALID', }, }, ), 'The countryCode "INVALID" was not recognized', ), ); it('createCustomerAddress creates a new address', async () => { const result = await adminClient.query< Codegen.CreateAddressMutation, Codegen.CreateAddressMutationVariables >(CREATE_ADDRESS, { id: firstCustomer.id, input: { fullName: 'fullName', company: 'company', streetLine1: 'streetLine1', streetLine2: 'streetLine2', city: 'city', province: 'province', postalCode: 'postalCode', countryCode: 'GB', phoneNumber: 'phoneNumber', defaultShippingAddress: false, defaultBillingAddress: false, }, }); expect(omit(result.createCustomerAddress, ['id'])).toEqual({ fullName: 'fullName', company: 'company', streetLine1: 'streetLine1', streetLine2: 'streetLine2', city: 'city', province: 'province', postalCode: 'postalCode', country: { code: 'GB', name: 'United Kingdom', }, phoneNumber: 'phoneNumber', defaultShippingAddress: false, defaultBillingAddress: false, }); }); it('customer query returns addresses', async () => { const result = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: firstCustomer.id, }); expect(result.customer!.addresses!.length).toBe(2); firstCustomerAddressIds = result.customer!.addresses!.map(a => a.id).sort(); }); it('updateCustomerAddress updates the country', async () => { const result = await adminClient.query< Codegen.UpdateAddressMutation, Codegen.UpdateAddressMutationVariables >(UPDATE_ADDRESS, { input: { id: firstCustomerAddressIds[0], countryCode: 'AT', }, }); expect(result.updateCustomerAddress.country).toEqual({ code: 'AT', name: 'Austria', }); }); it('updateCustomerAddress allows only a single default address', async () => { // set the first customer's second address to be default const result1 = await adminClient.query< Codegen.UpdateAddressMutation, Codegen.UpdateAddressMutationVariables >(UPDATE_ADDRESS, { input: { id: firstCustomerAddressIds[1], defaultShippingAddress: true, defaultBillingAddress: true, }, }); expect(result1.updateCustomerAddress.defaultShippingAddress).toBe(true); expect(result1.updateCustomerAddress.defaultBillingAddress).toBe(true); // assert the first customer's other address is not default const result2 = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: firstCustomer.id, }); const otherAddress = result2.customer!.addresses!.filter( a => a.id !== firstCustomerAddressIds[1], )[0]!; expect(otherAddress.defaultShippingAddress).toBe(false); expect(otherAddress.defaultBillingAddress).toBe(false); // set the first customer's first address to be default const result3 = await adminClient.query< Codegen.UpdateAddressMutation, Codegen.UpdateAddressMutationVariables >(UPDATE_ADDRESS, { input: { id: firstCustomerAddressIds[0], defaultShippingAddress: true, defaultBillingAddress: true, }, }); expect(result3.updateCustomerAddress.defaultShippingAddress).toBe(true); expect(result3.updateCustomerAddress.defaultBillingAddress).toBe(true); // assert the first customer's second address is not default const result4 = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: firstCustomer.id, }); const otherAddress2 = result4.customer!.addresses!.filter( a => a.id !== firstCustomerAddressIds[0], )[0]!; expect(otherAddress2.defaultShippingAddress).toBe(false); expect(otherAddress2.defaultBillingAddress).toBe(false); // get the second customer's address id const result5 = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: secondCustomer.id, }); const secondCustomerAddressId = result5.customer!.addresses![0].id; // set the second customer's address to be default const result6 = await adminClient.query< Codegen.UpdateAddressMutation, Codegen.UpdateAddressMutationVariables >(UPDATE_ADDRESS, { input: { id: secondCustomerAddressId, defaultShippingAddress: true, defaultBillingAddress: true, }, }); expect(result6.updateCustomerAddress.defaultShippingAddress).toBe(true); expect(result6.updateCustomerAddress.defaultBillingAddress).toBe(true); // assets the first customer's address defaults are unchanged const result7 = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: firstCustomer.id, }); const firstCustomerFirstAddress = result7.customer!.addresses!.find( a => a.id === firstCustomerAddressIds[0], )!; const firstCustomerSecondAddress = result7.customer!.addresses!.find( a => a.id === firstCustomerAddressIds[1], )!; expect(firstCustomerFirstAddress.defaultShippingAddress).toBe(true); expect(firstCustomerFirstAddress.defaultBillingAddress).toBe(true); expect(firstCustomerSecondAddress.defaultShippingAddress).toBe(false); expect(firstCustomerSecondAddress.defaultBillingAddress).toBe(false); }); it('createCustomerAddress with true defaults unsets existing defaults', async () => { const { createCustomerAddress } = await adminClient.query< Codegen.CreateAddressMutation, Codegen.CreateAddressMutationVariables >(CREATE_ADDRESS, { id: firstCustomer.id, input: { streetLine1: 'new default streetline', countryCode: 'GB', defaultShippingAddress: true, defaultBillingAddress: true, }, }); expect(omit(createCustomerAddress, ['id'])).toEqual({ fullName: '', company: '', streetLine1: 'new default streetline', streetLine2: '', city: '', province: '', postalCode: '', country: { code: 'GB', name: 'United Kingdom', }, phoneNumber: '', defaultShippingAddress: true, defaultBillingAddress: true, }); const { customer } = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: firstCustomer.id, }); for (const address of customer!.addresses!) { const shouldBeDefault = address.id === createCustomerAddress.id; expect(address.defaultShippingAddress).toEqual(shouldBeDefault); expect(address.defaultBillingAddress).toEqual(shouldBeDefault); } firstCustomerThirdAddressId = createCustomerAddress.id; }); it('deleteCustomerAddress on default address resets defaults', async () => { const { deleteCustomerAddress } = await adminClient.query< Codegen.DeleteCustomerAddressMutation, Codegen.DeleteCustomerAddressMutationVariables >( gql` mutation DeleteCustomerAddress($id: ID!) { deleteCustomerAddress(id: $id) { success } } `, { id: firstCustomerThirdAddressId }, ); expect(deleteCustomerAddress.success).toBe(true); const { customer } = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: firstCustomer.id, }); expect(customer!.addresses!.length).toBe(2); const defaultAddress = customer!.addresses!.filter( a => a.defaultBillingAddress && a.defaultShippingAddress, ); const otherAddress = customer!.addresses!.filter( a => !a.defaultBillingAddress && !a.defaultShippingAddress, ); expect(defaultAddress.length).toBe(1); expect(otherAddress.length).toBe(1); }); }); describe('orders', () => { const orderResultGuard: ErrorResultGuard<UpdatedOrderFragment> = createErrorResultGuard( input => !!input.lines, ); it("lists that user's orders", async () => { // log in as first customer await shopClient.asUserWithCredentials(firstCustomer.emailAddress, 'test'); // add an item to the order to create an order const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 1, }); orderResultGuard.assertSuccess(addItemToOrder); const { customer } = await adminClient.query< Codegen.GetCustomerOrdersQuery, Codegen.GetCustomerOrdersQueryVariables >(GET_CUSTOMER_ORDERS, { id: firstCustomer.id }); expect(customer!.orders.totalItems).toBe(1); expect(customer!.orders.items[0].id).toBe(addItemToOrder.id); }); }); describe('creation', () => { it('triggers verification event if no password supplied', async () => { sendEmailFn = vi.fn(); const { createCustomer } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { emailAddress: 'test1@test.com', firstName: 'New', lastName: 'Customer', }, }); customerErrorGuard.assertSuccess(createCustomer); expect(createCustomer.user!.verified).toBe(false); expect(sendEmailFn).toHaveBeenCalledTimes(1); expect(sendEmailFn.mock.calls[0][0] instanceof AccountRegistrationEvent).toBe(true); expect(sendEmailFn.mock.calls[0][0].user.identifier).toBe('test1@test.com'); }); it('creates a verified Customer', async () => { sendEmailFn = vi.fn(); const { createCustomer } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { emailAddress: 'test2@test.com', firstName: 'New', lastName: 'Customer', }, password: 'test', }); customerErrorGuard.assertSuccess(createCustomer); expect(createCustomer.user!.verified).toBe(true); expect(sendEmailFn).toHaveBeenCalledTimes(1); }); it('return error result when using an existing, non-deleted emailAddress', async () => { const { createCustomer } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { emailAddress: 'test2@test.com', firstName: 'New', lastName: 'Customer', }, password: 'test', }); customerErrorGuard.assertErrorResult(createCustomer); expect(createCustomer.message).toBe('The email address is not available.'); expect(createCustomer.errorCode).toBe(ErrorCode.EMAIL_ADDRESS_CONFLICT_ERROR); }); it('normalizes email address on creation', async () => { const { createCustomer } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { emailAddress: ' JoeSmith@test.com ', firstName: 'Joe', lastName: 'Smith', }, password: 'test', }); customerErrorGuard.assertSuccess(createCustomer); expect(createCustomer.emailAddress).toBe('joesmith@test.com'); }); }); describe('update', () => { it('returns error result when emailAddress not available', async () => { const { updateCustomer } = await adminClient.query< Codegen.UpdateCustomerMutation, Codegen.UpdateCustomerMutationVariables >(UPDATE_CUSTOMER, { input: { id: thirdCustomer.id, emailAddress: firstCustomer.emailAddress, }, }); customerErrorGuard.assertErrorResult(updateCustomer); expect(updateCustomer.message).toBe('The email address is not available.'); expect(updateCustomer.errorCode).toBe(ErrorCode.EMAIL_ADDRESS_CONFLICT_ERROR); }); it('succeeds when emailAddress is available', async () => { const { updateCustomer } = await adminClient.query< Codegen.UpdateCustomerMutation, Codegen.UpdateCustomerMutationVariables >(UPDATE_CUSTOMER, { input: { id: thirdCustomer.id, emailAddress: 'unique-email@test.com', }, }); customerErrorGuard.assertSuccess(updateCustomer); expect(updateCustomer.emailAddress).toBe('unique-email@test.com'); }); // https://github.com/vendure-ecommerce/vendure/issues/1071 it('updates the associated User email address', async () => { await shopClient.asUserWithCredentials('unique-email@test.com', 'test'); const { me } = await shopClient.query<Codegen.MeQuery>(ME); expect(me?.identifier).toBe('unique-email@test.com'); }); // https://github.com/vendure-ecommerce/vendure/issues/2449 it('normalizes email address on update', async () => { const { updateCustomer } = await adminClient.query< Codegen.UpdateCustomerMutation, Codegen.UpdateCustomerMutationVariables >(UPDATE_CUSTOMER, { input: { id: thirdCustomer.id, emailAddress: ' Another-Address@test.com ', }, }); customerErrorGuard.assertSuccess(updateCustomer); expect(updateCustomer.emailAddress).toBe('another-address@test.com'); await shopClient.asUserWithCredentials('another-address@test.com', 'test'); const { me } = await shopClient.query<Codegen.MeQuery>(ME); expect(me?.identifier).toBe('another-address@test.com'); }); }); describe('deletion', () => { it('deletes a customer', async () => { const result = await adminClient.query< Codegen.DeleteCustomerMutation, Codegen.DeleteCustomerMutationVariables >(DELETE_CUSTOMER, { id: thirdCustomer.id }); expect(result.deleteCustomer).toEqual({ result: DeletionResult.DELETED }); }); it('cannot get a deleted customer', async () => { const result = await adminClient.query< Codegen.GetCustomerQuery, Codegen.GetCustomerQueryVariables >(GET_CUSTOMER, { id: thirdCustomer.id, }); expect(result.customer).toBe(null); }); it('deleted customer omitted from list', async () => { const result = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST); expect(result.customers.items.map(c => c.id).includes(thirdCustomer.id)).toBe(false); }); it( 'updateCustomer throws for deleted customer', assertThrowsWithMessage( () => adminClient.query< Codegen.UpdateCustomerMutation, Codegen.UpdateCustomerMutationVariables >(UPDATE_CUSTOMER, { input: { id: thirdCustomer.id, firstName: 'updated', }, }), 'No Customer with the id "3" could be found', ), ); it( 'createCustomerAddress throws for deleted customer', assertThrowsWithMessage( () => adminClient.query<Codegen.CreateAddressMutation, Codegen.CreateAddressMutationVariables>( CREATE_ADDRESS, { id: thirdCustomer.id, input: { streetLine1: 'test', countryCode: 'GB', }, }, ), 'No Customer with the id "3" could be found', ), ); it('new Customer can be created with same emailAddress as a deleted Customer', async () => { const { createCustomer } = await adminClient.query< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input: { emailAddress: thirdCustomer.emailAddress, firstName: 'Reusing Email', lastName: 'Customer', }, }); customerErrorGuard.assertSuccess(createCustomer); expect(createCustomer.emailAddress).toBe(thirdCustomer.emailAddress); expect(createCustomer.firstName).toBe('Reusing Email'); expect(createCustomer.user?.identifier).toBe(thirdCustomer.emailAddress); }); // https://github.com/vendure-ecommerce/vendure/issues/1960 it('delete a guest Customer', async () => { const orderErrorGuard: ErrorResultGuard<ActiveOrderCustomerFragment> = createErrorResultGuard( input => !!input.lines, ); await shopClient.asAnonymousUser(); await shopClient.query<AddItemToOrderMutation, AddItemToOrderMutationVariables>( ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 1, }, ); const { setCustomerForOrder } = await shopClient.query< SetCustomerForOrderMutation, SetCustomerForOrderMutationVariables >(SET_CUSTOMER, { input: { firstName: 'Guest', lastName: 'Customer', emailAddress: 'guest@test.com', }, }); orderErrorGuard.assertSuccess(setCustomerForOrder); const result = await adminClient.query< Codegen.DeleteCustomerMutation, Codegen.DeleteCustomerMutationVariables >(DELETE_CUSTOMER, { id: setCustomerForOrder.customer!.id }); expect(result.deleteCustomer).toEqual({ result: DeletionResult.DELETED }); }); }); describe('customer notes', () => { let noteId: string; it('addNoteToCustomer', async () => { const { addNoteToCustomer } = await adminClient.query< Codegen.AddNoteToCustomerMutation, Codegen.AddNoteToCustomerMutationVariables >(ADD_NOTE_TO_CUSTOMER, { input: { id: firstCustomer.id, isPublic: false, note: 'Test note', }, }); const { customer } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: firstCustomer.id, options: { filter: { type: { eq: HistoryEntryType.CUSTOMER_NOTE, }, }, }, }); expect(customer?.history.items.map(pick(['type', 'data']))).toEqual([ { type: HistoryEntryType.CUSTOMER_NOTE, data: { note: 'Test note', }, }, ]); noteId = customer!.history.items[0].id!; }); it('update note', async () => { const { updateCustomerNote } = await adminClient.query< Codegen.UpdateCustomerNoteMutation, Codegen.UpdateCustomerNoteMutationVariables >(UPDATE_CUSTOMER_NOTE, { input: { noteId, note: 'An updated note', }, }); expect(updateCustomerNote.data).toEqual({ note: 'An updated note', }); }); it('delete note', async () => { const { customer: before } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: firstCustomer.id }); const historyCount = before!.history.totalItems; const { deleteCustomerNote } = await adminClient.query< Codegen.DeleteCustomerNoteMutation, Codegen.DeleteCustomerNoteMutationVariables >(DELETE_CUSTOMER_NOTE, { id: noteId, }); expect(deleteCustomerNote.result).toBe(DeletionResult.DELETED); const { customer: after } = await adminClient.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id: firstCustomer.id }); expect(after?.history.totalItems).toBe(historyCount - 1); }); }); }); const GET_CUSTOMER_WITH_USER = gql` query GetCustomerWithUser($id: ID!) { customer(id: $id) { id user { id identifier verified } } } `; const GET_CUSTOMER_ORDERS = gql` query GetCustomerOrders($id: ID!) { customer(id: $id) { orders { items { id } totalItems } } } `; const ADD_NOTE_TO_CUSTOMER = gql` mutation AddNoteToCustomer($input: AddNoteToCustomerInput!) { addNoteToCustomer(input: $input) { ...Customer } } ${CUSTOMER_FRAGMENT} `;
import { mergeConfig } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import { fail } from 'assert'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config'; import { TransactionTestPlugin, TRIGGER_ATTEMPTED_READ_EMAIL, TRIGGER_ATTEMPTED_UPDATE_EMAIL, TRIGGER_NO_OPERATION, } from './fixtures/test-plugins/transaction-test-plugin'; type DBType = 'mysql' | 'postgres' | 'sqlite' | 'sqljs'; const itIfDb = (dbs: DBType[]) => { return dbs.includes((process.env.DB as DBType) || 'sqljs') ? it : it.skip; }; describe('Transaction infrastructure', () => { const { server, adminClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [TransactionTestPlugin], }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 0, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('non-failing mutation', async () => { const { createTestAdministrator } = await adminClient.query(CREATE_ADMIN, { emailAddress: 'test1', fail: false, }); expect(createTestAdministrator.emailAddress).toBe('test1'); expect(createTestAdministrator.user.identifier).toBe('test1'); const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(2); expect(!!verify.admins.find((a: any) => a.emailAddress === 'test1')).toBe(true); expect(!!verify.users.find((u: any) => u.identifier === 'test1')).toBe(true); }); it('failing mutation', async () => { try { await adminClient.query(CREATE_ADMIN, { emailAddress: 'test2', fail: true, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toContain('Failed!'); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(2); expect(!!verify.admins.find((a: any) => a.emailAddress === 'test2')).toBe(false); expect(!!verify.users.find((u: any) => u.identifier === 'test2')).toBe(false); }); it('failing mutation with promise concurrent execution', async () => { try { await adminClient.query(CREATE_N_ADMINS, { emailAddress: 'testN-', failFactor: 0.4, n: 10, }); fail('Should have thrown'); } catch (e) { expect(e.message).toContain('Failed!'); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(2); expect(!!verify.admins.find((a: any) => a.emailAddress.includes('testN'))).toBe(false); expect(!!verify.users.find((u: any) => u.identifier.includes('testN'))).toBe(false); }); it('failing manual mutation', async () => { try { await adminClient.query(CREATE_ADMIN2, { emailAddress: 'test3', fail: true, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toContain('Failed!'); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(2); expect(!!verify.admins.find((a: any) => a.emailAddress === 'test3')).toBe(false); expect(!!verify.users.find((u: any) => u.identifier === 'test3')).toBe(false); }); it('failing manual mutation without transaction', async () => { try { await adminClient.query(CREATE_ADMIN3, { emailAddress: 'test4', fail: true, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toContain('Failed!'); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(3); expect(!!verify.admins.find((a: any) => a.emailAddress === 'test4')).toBe(false); expect(!!verify.users.find((u: any) => u.identifier === 'test4')).toBe(true); }); it('failing mutation inside connection.withTransaction() wrapper with request context', async () => { try { await adminClient.query(CREATE_ADMIN5, { emailAddress: 'test5', fail: true, noContext: false, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toContain('Failed!'); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(3); expect(!!verify.admins.find((a: any) => a.emailAddress === 'test5')).toBe(false); expect(!!verify.users.find((u: any) => u.identifier === 'test5')).toBe(false); }); itIfDb(['postgres', 'mysql'])( 'failing mutation inside connection.withTransaction() wrapper with context and promise concurrent execution', async () => { try { await adminClient.query(CREATE_N_ADMINS2, { emailAddress: 'testN-', failFactor: 0.4, n: 10, }); fail('Should have thrown'); } catch (e) { expect(e.message).toMatch( /^Failed!|Query runner already released. Cannot run queries anymore.$/, ); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(3); expect(!!verify.admins.find((a: any) => a.emailAddress.includes('testN'))).toBe(false); expect(!!verify.users.find((u: any) => u.identifier.includes('testN'))).toBe(false); }, ); it('failing mutation inside connection.withTransaction() wrapper without request context', async () => { try { await adminClient.query(CREATE_ADMIN5, { emailAddress: 'test5', fail: true, noContext: true, }); fail('Should have thrown'); } catch (e: any) { expect(e.message).toContain('Failed!'); } const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(2); expect(verify.users.length).toBe(3); expect(!!verify.admins.find((a: any) => a.emailAddress === 'test5')).toBe(false); expect(!!verify.users.find((u: any) => u.identifier === 'test5')).toBe(false); }); it('non-failing mutation inside connection.withTransaction() wrapper with failing nested transactions and request context', async () => { await adminClient.query(CREATE_N_ADMINS3, { emailAddress: 'testNestedTransactionsN-', failFactor: 0.5, n: 2, }); const { verify } = await adminClient.query(VERIFY_TEST); expect(verify.admins.length).toBe(3); expect(verify.users.length).toBe(4); expect( verify.admins.filter((a: any) => a.emailAddress.includes('testNestedTransactionsN')), ).toHaveLength(1); expect( verify.users.filter((u: any) => u.identifier.includes('testNestedTransactionsN')), ).toHaveLength(1); }); it('event do not publish after transaction rollback', async () => { TransactionTestPlugin.reset(); try { await adminClient.query(CREATE_N_ADMINS, { emailAddress: TRIGGER_NO_OPERATION, failFactor: 0.5, n: 2, }); fail('Should have thrown'); } catch (e) { expect(e.message).toContain('Failed!'); } // Wait a bit to see an events in handler await new Promise(resolve => setTimeout(resolve, 100)); expect(TransactionTestPlugin.callHandler).not.toHaveBeenCalled(); expect(TransactionTestPlugin.errorHandler).not.toHaveBeenCalled(); }); // Testing https://github.com/vendure-ecommerce/vendure/issues/520 it('passing transaction via EventBus', async () => { TransactionTestPlugin.reset(); const { createTestAdministrator } = await adminClient.query(CREATE_ADMIN, { emailAddress: TRIGGER_ATTEMPTED_UPDATE_EMAIL, fail: false, }); await TransactionTestPlugin.eventHandlerComplete$.toPromise(); expect(createTestAdministrator.emailAddress).toBe(TRIGGER_ATTEMPTED_UPDATE_EMAIL); expect(TransactionTestPlugin.errorHandler).not.toHaveBeenCalled(); }); // Testing https://github.com/vendure-ecommerce/vendure/issues/1107 it('passing transaction via EventBus with delay in committing transaction', async () => { TransactionTestPlugin.reset(); const { createTestAdministrator4 } = await adminClient.query(CREATE_ADMIN4, { emailAddress: TRIGGER_ATTEMPTED_READ_EMAIL, fail: false, }); await TransactionTestPlugin.eventHandlerComplete$.toPromise(); expect(createTestAdministrator4.emailAddress).toBe(TRIGGER_ATTEMPTED_READ_EMAIL); expect(TransactionTestPlugin.errorHandler).not.toHaveBeenCalled(); }); }); const ADMIN_FRAGMENT = gql` fragment CreatedAdmin on Administrator { id emailAddress user { id identifier } } `; const CREATE_ADMIN = gql` mutation CreateTestAdmin($emailAddress: String!, $fail: Boolean!) { createTestAdministrator(emailAddress: $emailAddress, fail: $fail) { ...CreatedAdmin } } ${ADMIN_FRAGMENT} `; const CREATE_ADMIN2 = gql` mutation CreateTestAdmin2($emailAddress: String!, $fail: Boolean!) { createTestAdministrator2(emailAddress: $emailAddress, fail: $fail) { ...CreatedAdmin } } ${ADMIN_FRAGMENT} `; const CREATE_ADMIN3 = gql` mutation CreateTestAdmin3($emailAddress: String!, $fail: Boolean!) { createTestAdministrator3(emailAddress: $emailAddress, fail: $fail) { ...CreatedAdmin } } ${ADMIN_FRAGMENT} `; const CREATE_ADMIN4 = gql` mutation CreateTestAdmin4($emailAddress: String!, $fail: Boolean!) { createTestAdministrator4(emailAddress: $emailAddress, fail: $fail) { ...CreatedAdmin } } ${ADMIN_FRAGMENT} `; const CREATE_ADMIN5 = gql` mutation CreateTestAdmin5($emailAddress: String!, $fail: Boolean!, $noContext: Boolean!) { createTestAdministrator5(emailAddress: $emailAddress, fail: $fail, noContext: $noContext) { ...CreatedAdmin } } ${ADMIN_FRAGMENT} `; const CREATE_N_ADMINS = gql` mutation CreateNTestAdmins($emailAddress: String!, $failFactor: Float!, $n: Int!) { createNTestAdministrators(emailAddress: $emailAddress, failFactor: $failFactor, n: $n) } `; const CREATE_N_ADMINS2 = gql` mutation CreateNTestAdmins2($emailAddress: String!, $failFactor: Float!, $n: Int!) { createNTestAdministrators2(emailAddress: $emailAddress, failFactor: $failFactor, n: $n) } `; const CREATE_N_ADMINS3 = gql` mutation CreateNTestAdmins3($emailAddress: String!, $failFactor: Float!, $n: Int!) { createNTestAdministrators3(emailAddress: $emailAddress, failFactor: $failFactor, n: $n) } `; const VERIFY_TEST = gql` query VerifyTest { verify { admins { id emailAddress } users { id identifier } } } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { DefaultJobQueuePlugin, DefaultSearchPlugin, mergeConfig, UuidIdStrategy } from '@vendure/core'; import { createTestEnvironment, registerInitializer, SqljsInitializer } from '@vendure/testing'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { FacetValueFragment, GetFacetListQuery, GetFacetListQueryVariables, } from './graphql/generated-e2e-admin-types'; import { SearchProductsShopQuery, SearchProductsShopQueryVariables, SortOrder, } from './graphql/generated-e2e-shop-types'; import { GET_FACET_LIST } from './graphql/shared-definitions'; import { SEARCH_PRODUCTS_SHOP } from './graphql/shop-definitions'; import { awaitRunningJobs } from './utils/await-running-jobs'; registerInitializer('sqljs', new SqljsInitializer(path.join(__dirname, '__data__'), 1000)); describe('Default search plugin with UUIDs', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [DefaultSearchPlugin.init({ indexStockStatus: true }), DefaultJobQueuePlugin], entityOptions: { entityIdStrategy: new UuidIdStrategy(), }, }), ); let plantsFacetValue: FacetValueFragment; let furnitureFacetValue: FacetValueFragment; let photoFacetValue: FacetValueFragment; let electronicsFacetValue: FacetValueFragment; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-default-search.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); // A precaution against a race condition in which the index // rebuild is not completed in time for the first test. await new Promise(resolve => setTimeout(resolve, 5000)); const { facets } = await adminClient.query<GetFacetListQuery, GetFacetListQueryVariables>( GET_FACET_LIST, { options: { sort: { name: SortOrder.ASC, }, }, }, ); plantsFacetValue = facets.items[0].values.find(v => v.code === 'plants')!; furnitureFacetValue = facets.items[0].values.find(v => v.code === 'furniture')!; photoFacetValue = facets.items[0].values.find(v => v.code === 'photo')!; electronicsFacetValue = facets.items[0].values.find(v => v.code === 'electronics')!; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await awaitRunningJobs(adminClient); await server.destroy(); }); it('can filter by facetValueIds', async () => { const result = await shopClient.query<SearchProductsShopQuery, SearchProductsShopQueryVariables>( SEARCH_PRODUCTS_SHOP, { input: { facetValueIds: [plantsFacetValue.id], groupByProduct: true, sort: { name: SortOrder.ASC }, }, }, ); expect(result.search.items.map(i => i.productName)).toEqual([ 'Bonsai Tree', 'Orchid', 'Spiky Cactus', ]); }); it('can filter by facetValueFilters', async () => { const { facets } = await adminClient.query<GetFacetListQuery, GetFacetListQueryVariables>( GET_FACET_LIST, ); const result = await shopClient.query<SearchProductsShopQuery, SearchProductsShopQueryVariables>( SEARCH_PRODUCTS_SHOP, { input: { facetValueFilters: [ { and: electronicsFacetValue.id }, { or: [plantsFacetValue.id, photoFacetValue.id] }, ], sort: { name: SortOrder.ASC }, groupByProduct: true, }, }, ); expect(result.search.items.map(i => i.productName)).toEqual([ 'Camera Lens', 'Instant Camera', 'Slr Camera', 'Tripod', ]); }); });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { DefaultJobQueuePlugin, DefaultSearchPlugin, mergeConfig } from '@vendure/core'; import { createTestEnvironment, registerInitializer, SqljsInitializer } from '@vendure/testing'; import path from 'path'; import { Bench } from 'tinybench'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { SearchProductsShopQuery, SearchProductsShopQueryVariables, } from './graphql/generated-e2e-shop-types'; import { SEARCH_PRODUCTS_SHOP } from './graphql/shop-definitions'; import { awaitRunningJobs } from './utils/await-running-jobs'; registerInitializer('sqljs', new SqljsInitializer(path.join(__dirname, '__data__'), 1000)); interface SearchProductsShopQueryVariablesExt extends SearchProductsShopQueryVariables { input: SearchProductsShopQueryVariables['input'] & { // This input field is dynamically added only when the `indexStockStatus` init option // is set to `true`, and therefore not included in the generated type. Therefore // we need to manually patch it here. inStock?: boolean; }; } const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [DefaultSearchPlugin.init({ indexStockStatus: true }), DefaultJobQueuePlugin], }), ); let marginFactor = 1; // Defaults to 1, will be adjusted during test let cpuFactor = 1; // Defaults to 1, will be adjusted during test const fibonacci = (i: number): number => { if (i <= 1) return i; return fibonacci(i - 1) + fibonacci(i - 2); }; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-default-search.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); await awaitRunningJobs(adminClient); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); const isDevelopment = process.env.NODE_ENV === 'development'; describe.skipIf(isDevelopment)('Default search plugin - benchmark', () => { it('defines benchmark cpu and margin factor', async () => { const bench = new Bench({ warmupTime: 0, warmupIterations: 1, time: 0, iterations: 10, }); bench.add('measure time to calcualate fibonacci', () => { fibonacci(41); // If this task would take 1000 ms the cpuFactor would be 1. }); const tasks = await bench.run(); // console.table(bench.table()); tasks.forEach(task => { expect(task.result?.rme).toBeDefined(); expect(task.result?.mean).toBeDefined(); if (task.result?.rme && task.result?.mean) { marginFactor = 1 + task.result.rme / 100; cpuFactor = 1000 / task.result.mean; } }); }); it('performs when grouped by product', async () => { const bench = new Bench({ warmupTime: 0, warmupIterations: 3, time: 0, iterations: 1000, }); bench.add('group by product', async () => { await shopClient.query<SearchProductsShopQuery, SearchProductsShopQueryVariablesExt>( SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: true, }, }, ); }); const tasks = await bench.run(); // console.table(bench.table()); tasks.forEach(task => { expect(task.result?.mean).toBeDefined(); if (task.result?.mean) { expect(task.result.mean * cpuFactor).toBeLessThan(6.835 * marginFactor); } }); }); });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { pick } from '@vendure/common/lib/pick'; import { DefaultJobQueuePlugin, DefaultSearchPlugin, facetValueCollectionFilter, mergeConfig, } from '@vendure/core'; import { createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN, registerInitializer, SimpleGraphQLClient, SqljsInitializer, } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { SEARCH_PRODUCTS_ADMIN } from './graphql/admin-definitions'; import { ChannelFragment, CurrencyCode, LanguageCode, SearchInput, SearchResultSortParameter, SortOrder, SearchProductsAdminQuery, SearchProductsAdminQueryVariables, SearchFacetValuesQuery, SearchFacetValuesQueryVariables, UpdateProductMutation, UpdateProductMutationVariables, SearchCollectionsQuery, SearchCollectionsQueryVariables, SearchGetPricesQuery, SearchGetPricesQueryVariables, CreateFacetMutation, CreateFacetMutationVariables, UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables, DeleteProductVariantMutation, DeleteProductVariantMutationVariables, DeleteProductMutation, DeleteProductMutationVariables, UpdateCollectionMutation, UpdateCollectionMutationVariables, CreateCollectionMutation, CreateCollectionMutationVariables, UpdateTaxRateMutation, UpdateTaxRateMutationVariables, SearchGetAssetsQuery, SearchGetAssetsQueryVariables, UpdateAssetMutation, UpdateAssetMutationVariables, DeleteAssetMutation, DeleteAssetMutationVariables, ReindexMutation, CreateProductMutation, CreateProductMutationVariables, CreateProductVariantsMutation, CreateProductVariantsMutationVariables, CreateChannelMutation, CreateChannelMutationVariables, AssignProductsToChannelMutation, AssignProductsToChannelMutationVariables, RemoveProductsFromChannelMutation, RemoveProductsFromChannelMutationVariables, AssignProductVariantsToChannelMutation, AssignProductVariantsToChannelMutationVariables, RemoveProductVariantsFromChannelMutation, RemoveProductVariantsFromChannelMutationVariables, } from './graphql/generated-e2e-admin-types'; import { LogicalOperator, SearchProductsShopQuery, SearchProductsShopQueryVariables, } from './graphql/generated-e2e-shop-types'; import { ASSIGN_PRODUCTVARIANT_TO_CHANNEL, ASSIGN_PRODUCT_TO_CHANNEL, CREATE_CHANNEL, CREATE_COLLECTION, CREATE_FACET, CREATE_PRODUCT, CREATE_PRODUCT_VARIANTS, DELETE_ASSET, DELETE_PRODUCT, DELETE_PRODUCT_VARIANT, REMOVE_PRODUCTVARIANT_FROM_CHANNEL, REMOVE_PRODUCT_FROM_CHANNEL, UPDATE_ASSET, UPDATE_COLLECTION, UPDATE_PRODUCT, UPDATE_PRODUCT_VARIANTS, UPDATE_TAX_RATE, } from './graphql/shared-definitions'; import { SEARCH_PRODUCTS_SHOP } from './graphql/shop-definitions'; import { awaitRunningJobs } from './utils/await-running-jobs'; registerInitializer('sqljs', new SqljsInitializer(path.join(__dirname, '__data__'), 1000)); interface SearchProductsShopQueryVariablesExt extends SearchProductsShopQueryVariables { input: SearchProductsShopQueryVariables['input'] & { // This input field is dynamically added only when the `indexStockStatus` init option // is set to `true`, and therefore not included in the generated type. Therefore // we need to manually patch it here. inStock?: boolean; }; } describe('Default search plugin', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [DefaultSearchPlugin.init({ indexStockStatus: true }), DefaultJobQueuePlugin], }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-default-search.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); await awaitRunningJobs(adminClient); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await awaitRunningJobs(adminClient); await server.destroy(); }); function testProductsShop(input: SearchProductsShopQueryVariablesExt['input']) { return shopClient.query<SearchProductsShopQuery, SearchProductsShopQueryVariablesExt>( SEARCH_PRODUCTS_SHOP, { input }, ); } function testProductsAdmin(input: SearchInput) { return adminClient.query<SearchProductsAdminQuery, SearchProductsAdminQueryVariables>( SEARCH_PRODUCTS_ADMIN, { input }, ); } type TestProducts = (input: SearchInput) => Promise<SearchProductsShopQuery | SearchProductsAdminQuery>; async function testGroupByProduct(testProducts: TestProducts) { const result = await testProducts({ groupByProduct: true, }); expect(result.search.totalItems).toBe(20); } async function testNoGrouping(testProducts: TestProducts) { const result = await testProducts({ groupByProduct: false, }); expect(result.search.totalItems).toBe(34); } async function testSortingWithGrouping( testProducts: TestProducts, sortBy: keyof SearchResultSortParameter, ) { const result = await testProducts({ groupByProduct: true, sort: { [sortBy]: SortOrder.ASC, }, take: 3, }); const expected = sortBy === 'name' ? ['Bonsai Tree', 'Boxing Gloves', 'Camera Lens'] : ['Skipping Rope', 'Tripod', 'Spiky Cactus']; expect(result.search.items.map(i => i.productName)).toEqual(expected); } async function testSortingNoGrouping( testProducts: TestProducts, sortBy: keyof SearchResultSortParameter, ) { const result = await testProducts({ groupByProduct: false, sort: { [sortBy]: SortOrder.DESC, }, take: 3, }); const expected = sortBy === 'name' ? ['USB Cable', 'Tripod', 'Tent'] : ['Road Bike', 'Laptop 15 inch 16GB', 'Laptop 13 inch 16GB']; expect(result.search.items.map(i => i.productVariantName)).toEqual(expected); } async function testMatchSearchTerm(testProducts: TestProducts) { const result = await testProducts({ term: 'camera', groupByProduct: true, sort: { name: SortOrder.ASC, }, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Camera Lens', 'Instant Camera', 'Slr Camera', ]); } async function testMatchPartialSearchTerm(testProducts: TestProducts) { const result = await testProducts({ term: 'lap', groupByProduct: true, sort: { name: SortOrder.ASC, }, }); expect(result.search.items.map(i => i.productName)).toEqual(['Laptop']); } async function testMatchFacetIdsAnd(testProducts: TestProducts) { const result = await testProducts({ facetValueIds: ['T_1', 'T_2'], facetValueOperator: LogicalOperator.AND, groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Laptop', 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', ]); } async function testMatchFacetIdsOr(testProducts: TestProducts) { const result = await testProducts({ facetValueIds: ['T_1', 'T_5'], facetValueOperator: LogicalOperator.OR, groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Laptop', 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', 'Instant Camera', 'Camera Lens', 'Tripod', 'Slr Camera', 'Spiky Cactus', 'Orchid', 'Bonsai Tree', ]); } async function testMatchFacetValueFiltersAnd(testProducts: TestProducts) { const result = await testProducts({ groupByProduct: true, facetValueFilters: [{ and: 'T_1' }, { and: 'T_2' }], }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Laptop', 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', ]); } async function testMatchFacetValueFiltersOr(testProducts: TestProducts) { const result = await testProducts({ groupByProduct: true, facetValueFilters: [{ or: ['T_1', 'T_5'] }], }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Laptop', 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', 'Instant Camera', 'Camera Lens', 'Tripod', 'Slr Camera', 'Spiky Cactus', 'Orchid', 'Bonsai Tree', ]); } async function testMatchFacetValueFiltersOrWithAnd(testProducts: TestProducts) { const result = await testProducts({ groupByProduct: true, facetValueFilters: [{ and: 'T_1' }, { or: ['T_2', 'T_3'] }], }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Laptop', 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', 'Instant Camera', 'Camera Lens', 'Tripod', 'Slr Camera', ]); } async function testMatchFacetValueFiltersWithFacetIdsOr(testProducts: TestProducts) { const result = await testProducts({ facetValueIds: ['T_2', 'T_3'], facetValueOperator: LogicalOperator.OR, facetValueFilters: [{ and: 'T_1' }], groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Laptop', 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', 'Instant Camera', 'Camera Lens', 'Tripod', 'Slr Camera', ]); } async function testMatchFacetValueFiltersWithFacetIdsAnd(testProducts: TestProducts) { const result = await testProducts({ facetValueIds: ['T_1'], facetValueFilters: [{ and: 'T_3' }], facetValueOperator: LogicalOperator.AND, groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Instant Camera', 'Camera Lens', 'Tripod', 'Slr Camera', ]); } async function testMatchCollectionId(testProducts: TestProducts) { const result = await testProducts({ collectionId: 'T_2', groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Spiky Cactus', 'Orchid', 'Bonsai Tree', ]); } async function testMatchCollectionSlug(testProducts: TestProducts) { const result = await testProducts({ collectionSlug: 'plants', groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Spiky Cactus', 'Orchid', 'Bonsai Tree', ]); } async function testSinglePrices(client: SimpleGraphQLClient) { const result = await client.query<SearchGetPricesQuery, SearchGetPricesQueryVariables>( SEARCH_GET_PRICES, { input: { groupByProduct: false, take: 3, }, }, ); expect(result.search.items).toEqual([ { price: { value: 129900 }, priceWithTax: { value: 155880 }, }, { price: { value: 139900 }, priceWithTax: { value: 167880 }, }, { price: { value: 219900 }, priceWithTax: { value: 263880 }, }, ]); } async function testPriceRanges(client: SimpleGraphQLClient) { const result = await client.query<SearchGetPricesQuery, SearchGetPricesQueryVariables>( SEARCH_GET_PRICES, { input: { groupByProduct: true, take: 3, }, }, ); expect(result.search.items).toEqual([ { price: { min: 129900, max: 229900 }, priceWithTax: { min: 155880, max: 275880 }, }, { price: { min: 14374, max: 16994 }, priceWithTax: { min: 17249, max: 20393 }, }, { price: { min: 93120, max: 109995 }, priceWithTax: { min: 111744, max: 131994 }, }, ]); } describe('shop api', () => { it('group by product', () => testGroupByProduct(testProductsShop)); it('no grouping', () => testNoGrouping(testProductsShop)); it('matches search term', () => testMatchSearchTerm(testProductsShop)); it('matches partial search term', () => testMatchPartialSearchTerm(testProductsShop)); it('matches by facetId with AND operator', () => testMatchFacetIdsAnd(testProductsShop)); it('matches by facetId with OR operator', () => testMatchFacetIdsOr(testProductsShop)); it('matches by FacetValueFilters AND', () => testMatchFacetValueFiltersAnd(testProductsShop)); it('matches by FacetValueFilters OR', () => testMatchFacetValueFiltersOr(testProductsShop)); it('matches by FacetValueFilters OR and AND', () => testMatchFacetValueFiltersOrWithAnd(testProductsShop)); it('matches by FacetValueFilters with facetId OR operator', () => testMatchFacetValueFiltersWithFacetIdsOr(testProductsShop)); it('matches by FacetValueFilters with facetId AND operator', () => testMatchFacetValueFiltersWithFacetIdsAnd(testProductsShop)); it('matches by collectionId', () => testMatchCollectionId(testProductsShop)); it('matches by collectionSlug', () => testMatchCollectionSlug(testProductsShop)); it('single prices', () => testSinglePrices(shopClient)); it('price ranges', () => testPriceRanges(shopClient)); it('returns correct facetValues when not grouped by product', async () => { const result = await shopClient.query<SearchFacetValuesQuery, SearchFacetValuesQueryVariables>( SEARCH_GET_FACET_VALUES, { input: { groupByProduct: false, }, }, ); expect(result.search.facetValues).toEqual([ { count: 21, facetValue: { id: 'T_1', name: 'electronics' } }, { count: 17, facetValue: { id: 'T_2', name: 'computers' } }, { count: 4, facetValue: { id: 'T_3', name: 'photo' } }, { count: 10, facetValue: { id: 'T_4', name: 'sports equipment' } }, { count: 3, facetValue: { id: 'T_5', name: 'home & garden' } }, { count: 3, facetValue: { id: 'T_6', name: 'plants' } }, ]); }); it('returns correct facetValues when grouped by product', async () => { const result = await shopClient.query<SearchFacetValuesQuery, SearchFacetValuesQueryVariables>( SEARCH_GET_FACET_VALUES, { input: { groupByProduct: true, }, }, ); expect(result.search.facetValues).toEqual([ { count: 10, facetValue: { id: 'T_1', name: 'electronics' } }, { count: 6, facetValue: { id: 'T_2', name: 'computers' } }, { count: 4, facetValue: { id: 'T_3', name: 'photo' } }, { count: 7, facetValue: { id: 'T_4', name: 'sports equipment' } }, { count: 3, facetValue: { id: 'T_5', name: 'home & garden' } }, { count: 3, facetValue: { id: 'T_6', name: 'plants' } }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/1236 it('returns correct facetValues when not grouped by product, with search term', async () => { const result = await shopClient.query<SearchFacetValuesQuery, SearchFacetValuesQueryVariables>( SEARCH_GET_FACET_VALUES, { input: { groupByProduct: false, term: 'laptop', }, }, ); expect(result.search.facetValues).toEqual([ { count: 4, facetValue: { id: 'T_1', name: 'electronics' } }, { count: 4, facetValue: { id: 'T_2', name: 'computers' } }, ]); }); it('omits facetValues of private facets', async () => { const { createFacet } = await adminClient.query< CreateFacetMutation, CreateFacetMutationVariables >(CREATE_FACET, { input: { code: 'profit-margin', isPrivate: true, translations: [{ languageCode: LanguageCode.en, name: 'Profit Margin' }], values: [ { code: 'massive', translations: [{ languageCode: LanguageCode.en, name: 'massive' }], }, ], }, }); await adminClient.query<UpdateProductMutation, UpdateProductMutationVariables>(UPDATE_PRODUCT, { input: { id: 'T_2', // T_1 & T_2 are the existing facetValues (electronics & photo) facetValueIds: ['T_1', 'T_2', createFacet.values[0].id], }, }); await awaitRunningJobs(adminClient); const result = await shopClient.query<SearchFacetValuesQuery, SearchFacetValuesQueryVariables>( SEARCH_GET_FACET_VALUES, { input: { groupByProduct: true, }, }, ); expect(result.search.facetValues).toEqual([ { count: 10, facetValue: { id: 'T_1', name: 'electronics' } }, { count: 6, facetValue: { id: 'T_2', name: 'computers' } }, { count: 4, facetValue: { id: 'T_3', name: 'photo' } }, { count: 7, facetValue: { id: 'T_4', name: 'sports equipment' } }, { count: 3, facetValue: { id: 'T_5', name: 'home & garden' } }, { count: 3, facetValue: { id: 'T_6', name: 'plants' } }, ]); }); it('returns correct collections when not grouped by product', async () => { const result = await shopClient.query<SearchCollectionsQuery, SearchCollectionsQueryVariables>( SEARCH_GET_COLLECTIONS, { input: { groupByProduct: false, }, }, ); expect(result.search.collections).toEqual([ { collection: { id: 'T_2', name: 'Plants' }, count: 3 }, ]); }); it('returns correct collections when grouped by product', async () => { const result = await shopClient.query<SearchCollectionsQuery, SearchCollectionsQueryVariables>( SEARCH_GET_COLLECTIONS, { input: { groupByProduct: true, }, }, ); expect(result.search.collections).toEqual([ { collection: { id: 'T_2', name: 'Plants' }, count: 3 }, ]); }); it('encodes the productId and productVariantId', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: false, take: 1, }, }); expect(pick(result.search.items[0], ['productId', 'productVariantId'])).toEqual({ productId: 'T_1', productVariantId: 'T_1', }); }); it('sort name with grouping', () => testSortingWithGrouping(testProductsShop, 'name')); it('sort price with grouping', () => testSortingWithGrouping(testProductsShop, 'price')); it('sort name without grouping', () => testSortingNoGrouping(testProductsShop, 'name')); it('sort price without grouping', () => testSortingNoGrouping(testProductsShop, 'price')); it('omits results for disabled ProductVariants', async () => { await adminClient.query<UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables>( UPDATE_PRODUCT_VARIANTS, { input: [{ id: 'T_3', enabled: false }], }, ); await awaitRunningJobs(adminClient); const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: false, take: 3, }, }); expect(result.search.items.map(i => i.productVariantId)).toEqual(['T_1', 'T_2', 'T_4']); }); it('encodes collectionIds', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: false, term: 'cactus', take: 1, }, }); expect(result.search.items[0].collectionIds).toEqual(['T_2']); }); it('inStock is false and not grouped by product', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: false, inStock: false, }, }); expect(result.search.totalItems).toBe(2); }); it('inStock is false and grouped by product', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: true, inStock: false, }, }); expect(result.search.totalItems).toBe(1); }); it('inStock is true and not grouped by product', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: false, inStock: true, }, }); expect(result.search.totalItems).toBe(31); }); it('inStock is true and grouped by product', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: true, inStock: true, }, }); expect(result.search.totalItems).toBe(19); }); it('inStock is undefined and not grouped by product', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: false, inStock: undefined, }, }); expect(result.search.totalItems).toBe(33); }); it('inStock is undefined and grouped by product', async () => { const result = await shopClient.query< SearchProductsShopQuery, SearchProductsShopQueryVariablesExt >(SEARCH_PRODUCTS_SHOP, { input: { groupByProduct: true, inStock: undefined, }, }); expect(result.search.totalItems).toBe(20); }); }); describe('admin api', () => { it('group by product', () => testGroupByProduct(testProductsAdmin)); it('no grouping', () => testNoGrouping(testProductsAdmin)); it('matches search term', () => testMatchSearchTerm(testProductsAdmin)); it('matches partial search term', () => testMatchPartialSearchTerm(testProductsAdmin)); it('matches by facetId with AND operator', () => testMatchFacetIdsAnd(testProductsAdmin)); it('matches by facetId with OR operator', () => testMatchFacetIdsOr(testProductsAdmin)); it('matches by FacetValueFilters AND', () => testMatchFacetValueFiltersAnd(testProductsAdmin)); it('matches by FacetValueFilters OR', () => testMatchFacetValueFiltersOr(testProductsAdmin)); it('matches by FacetValueFilters OR and AND', () => testMatchFacetValueFiltersOrWithAnd(testProductsAdmin)); it('matches by FacetValueFilters with facetId OR operator', () => testMatchFacetValueFiltersWithFacetIdsOr(testProductsAdmin)); it('matches by FacetValueFilters with facetId AND operator', () => testMatchFacetValueFiltersWithFacetIdsAnd(testProductsAdmin)); it('matches by collectionId', () => testMatchCollectionId(testProductsAdmin)); it('matches by collectionSlug', () => testMatchCollectionSlug(testProductsAdmin)); it('single prices', () => testSinglePrices(adminClient)); it('price ranges', () => testPriceRanges(adminClient)); it('sort name with grouping', () => testSortingWithGrouping(testProductsAdmin, 'name')); it('sort price with grouping', () => testSortingWithGrouping(testProductsAdmin, 'price')); it('sort name without grouping', () => testSortingNoGrouping(testProductsAdmin, 'name')); it('sort price without grouping', () => testSortingNoGrouping(testProductsAdmin, 'price')); describe('updating the index', () => { it('updates index when ProductVariants are changed', async () => { await awaitRunningJobs(adminClient); const { search } = await testProductsAdmin({ term: 'drive', groupByProduct: false }); expect(search.items.map(i => i.sku)).toEqual([ 'IHD455T1', 'IHD455T2', 'IHD455T3', 'IHD455T4', 'IHD455T6', ]); await adminClient.query< UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: search.items.map(i => ({ id: i.productVariantId, sku: i.sku + '_updated', })), }); await awaitRunningJobs(adminClient); const { search: search2 } = await testProductsAdmin({ term: 'drive', groupByProduct: false, }); expect(search2.items.map(i => i.sku)).toEqual([ 'IHD455T1_updated', 'IHD455T2_updated', 'IHD455T3_updated', 'IHD455T4_updated', 'IHD455T6_updated', ]); }); it('updates index when ProductVariants are deleted', async () => { await awaitRunningJobs(adminClient); const { search } = await testProductsAdmin({ term: 'drive', groupByProduct: false }); const variantToDelete = search.items[0]; expect(variantToDelete.sku).toBe('IHD455T1_updated'); await adminClient.query<DeleteProductVariantMutation, DeleteProductVariantMutationVariables>( DELETE_PRODUCT_VARIANT, { id: variantToDelete.productVariantId, }, ); await awaitRunningJobs(adminClient); const { search: search2 } = await testProductsAdmin({ term: 'drive', groupByProduct: false, }); expect(search2.items.map(i => i.sku)).toEqual([ 'IHD455T2_updated', 'IHD455T3_updated', 'IHD455T4_updated', 'IHD455T6_updated', ]); }); it('updates index when a Product is changed', async () => { await adminClient.query<UpdateProductMutation, UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_1', facetValueIds: [], }, }, ); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ facetValueIds: ['T_2'], groupByProduct: true }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Curvy Monitor', 'Gaming PC', 'Hard Drive', 'Clacky Keyboard', 'USB Cable', ]); }); it('updates index when a Product is deleted', async () => { const { search } = await testProductsAdmin({ facetValueIds: ['T_2'], groupByProduct: true }); expect(search.items.map(i => i.productId)).toEqual(['T_2', 'T_3', 'T_4', 'T_5', 'T_6']); await adminClient.query<DeleteProductMutation, DeleteProductMutationVariables>( DELETE_PRODUCT, { id: 'T_5', }, ); await awaitRunningJobs(adminClient); const { search: search2 } = await testProductsAdmin({ facetValueIds: ['T_2'], groupByProduct: true, }); expect(search2.items.map(i => i.productId)).toEqual(['T_2', 'T_3', 'T_4', 'T_6']); }); it('updates index when a Collection is changed', async () => { await adminClient.query<UpdateCollectionMutation, UpdateCollectionMutationVariables>( UPDATE_COLLECTION, { input: { id: 'T_2', filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: '["T_4"]', }, { name: 'containsAny', value: 'false', }, ], }, ], }, }, ); await awaitRunningJobs(adminClient); // add an additional check for the collection filters to update await awaitRunningJobs(adminClient); const result1 = await testProductsAdmin({ collectionId: 'T_2', groupByProduct: true }); expect(result1.search.items.map(i => i.productName)).toEqual([ 'Road Bike', 'Skipping Rope', 'Boxing Gloves', 'Tent', 'Cruiser Skateboard', 'Football', 'Running Shoe', ]); const result2 = await testProductsAdmin({ collectionSlug: 'plants', groupByProduct: true }); expect(result2.search.items.map(i => i.productName)).toEqual([ 'Road Bike', 'Skipping Rope', 'Boxing Gloves', 'Tent', 'Cruiser Skateboard', 'Football', 'Running Shoe', ]); }, 10000); it('updates index when a Collection created', async () => { const { createCollection } = await adminClient.query< CreateCollectionMutation, CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Photo', description: '', slug: 'photo', }, ], filters: [ { code: facetValueCollectionFilter.code, arguments: [ { name: 'facetValueIds', value: '["T_3"]', }, { name: 'containsAny', value: 'false', }, ], }, ], }, }); await awaitRunningJobs(adminClient); // add an additional check for the collection filters to update await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ collectionId: createCollection.id, groupByProduct: true, }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Instant Camera', 'Camera Lens', 'Tripod', 'Slr Camera', ]); }); it('updates index when a taxRate is changed', async () => { await adminClient.query<UpdateTaxRateMutation, UpdateTaxRateMutationVariables>( UPDATE_TAX_RATE, { input: { // Default Channel's defaultTaxZone is Europe (id 2) and the id of the standard TaxRate // to Europe is 2. id: 'T_2', value: 50, }, }, ); await awaitRunningJobs(adminClient); const result = await adminClient.query<SearchGetPricesQuery, SearchGetPricesQueryVariables>( SEARCH_GET_PRICES, { input: { groupByProduct: true, term: 'laptop', } as SearchInput, }, ); expect(result.search.items).toEqual([ { price: { min: 129900, max: 229900 }, priceWithTax: { min: 194850, max: 344850 }, }, ]); }); describe('asset changes', () => { function searchForLaptop() { return adminClient.query<SearchGetAssetsQuery, SearchGetAssetsQueryVariables>( SEARCH_GET_ASSETS, { input: { term: 'laptop', take: 1, }, }, ); } it('updates index when asset focalPoint is changed', async () => { const { search: search1 } = await searchForLaptop(); expect(search1.items[0].productAsset!.id).toBe('T_1'); expect(search1.items[0].productAsset!.focalPoint).toBeNull(); await adminClient.query<UpdateAssetMutation, UpdateAssetMutationVariables>(UPDATE_ASSET, { input: { id: 'T_1', focalPoint: { x: 0.42, y: 0.42, }, }, }); await awaitRunningJobs(adminClient); const { search: search2 } = await searchForLaptop(); expect(search2.items[0].productAsset!.id).toBe('T_1'); expect(search2.items[0].productAsset!.focalPoint).toEqual({ x: 0.42, y: 0.42 }); }); it('updates index when asset deleted', async () => { const { search: search1 } = await searchForLaptop(); const assetId = search1.items[0].productAsset?.id; expect(assetId).toBeTruthy(); await adminClient.query<DeleteAssetMutation, DeleteAssetMutationVariables>(DELETE_ASSET, { input: { assetId: assetId!, force: true, }, }); await awaitRunningJobs(adminClient); const { search: search2 } = await searchForLaptop(); expect(search2.items[0].productAsset).toBeNull(); }); }); it('does not include deleted ProductVariants in index', async () => { const { search: s1 } = await testProductsAdmin({ term: 'hard drive', groupByProduct: false, }); const { deleteProductVariant } = await adminClient.query< DeleteProductVariantMutation, DeleteProductVariantMutationVariables >(DELETE_PRODUCT_VARIANT, { id: s1.items[0].productVariantId }); await awaitRunningJobs(adminClient); const { search } = await adminClient.query< SearchGetPricesQuery, SearchGetPricesQueryVariables >(SEARCH_GET_PRICES, { input: { term: 'hard drive', groupByProduct: true } }); expect(search.items[0].price).toEqual({ min: 7896, max: 13435, }); }); it('returns enabled field when not grouped', async () => { const result = await testProductsAdmin({ groupByProduct: false, take: 3 }); expect(result.search.items.map(pick(['productVariantId', 'enabled']))).toEqual([ { productVariantId: 'T_1', enabled: true }, { productVariantId: 'T_2', enabled: true }, { productVariantId: 'T_3', enabled: false }, ]); }); it('when grouped, enabled is true if at least one variant is enabled', async () => { await adminClient.query< UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [ { id: 'T_1', enabled: false }, { id: 'T_2', enabled: false }, ], }); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ groupByProduct: true, take: 3 }); expect(result.search.items.map(pick(['productId', 'enabled']))).toEqual([ { productId: 'T_1', enabled: true }, { productId: 'T_2', enabled: true }, { productId: 'T_3', enabled: true }, ]); }); it('when grouped, enabled is false if all variants are disabled', async () => { await adminClient.query< UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [{ id: 'T_4', enabled: false }], }); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ groupByProduct: true, take: 3 }); expect(result.search.items.map(pick(['productId', 'enabled']))).toEqual([ { productId: 'T_1', enabled: false }, { productId: 'T_2', enabled: true }, { productId: 'T_3', enabled: true }, ]); }); it('when grouped, enabled is false if product is disabled', async () => { await adminClient.query<UpdateProductMutation, UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_3', enabled: false, }, }, ); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ groupByProduct: true, take: 3 }); expect(result.search.items.map(pick(['productId', 'enabled']))).toEqual([ { productId: 'T_1', enabled: false }, { productId: 'T_2', enabled: true }, { productId: 'T_3', enabled: false }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/295 it('enabled status survives reindex', async () => { await adminClient.query<ReindexMutation>(REINDEX); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ groupByProduct: true, take: 3 }); expect(result.search.items.map(pick(['productId', 'enabled']))).toEqual([ { productId: 'T_1', enabled: false }, { productId: 'T_2', enabled: true }, { productId: 'T_3', enabled: false }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/1482 it('price range omits disabled variant', async () => { const result1 = await shopClient.query<SearchGetPricesQuery, SearchGetPricesQueryVariables>( SEARCH_GET_PRICES, { input: { groupByProduct: true, term: 'monitor', take: 3, } as SearchInput, }, ); expect(result1.search.items).toEqual([ { price: { min: 14374, max: 16994 }, priceWithTax: { min: 21561, max: 25491 }, }, ]); await adminClient.query< UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [{ id: 'T_5', enabled: false }], }); await awaitRunningJobs(adminClient); const result2 = await shopClient.query<SearchGetPricesQuery, SearchGetPricesQueryVariables>( SEARCH_GET_PRICES, { input: { groupByProduct: true, term: 'monitor', take: 3, } as SearchInput, }, ); expect(result2.search.items).toEqual([ { price: { min: 16994, max: 16994 }, priceWithTax: { min: 25491, max: 25491 }, }, ]); }); // https://github.com/vendure-ecommerce/vendure/issues/745 it('very long Product descriptions no not cause indexing to fail', async () => { // We generate this long string out of random chars because Postgres uses compression // when storing the string value, so e.g. a long series of a single character will not // reproduce the error. const description = Array.from({ length: 220 }) .map(() => Math.random().toString(36)) .join(' '); const { createProduct } = await adminClient.query< CreateProductMutation, CreateProductMutationVariables >(CREATE_PRODUCT, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Very long description aabbccdd', slug: 'very-long-description', description, }, ], }, }); await adminClient.query< CreateProductVariantsMutation, CreateProductVariantsMutationVariables >(CREATE_PRODUCT_VARIANTS, { input: [ { productId: createProduct.id, sku: 'VLD01', price: 100, translations: [ { languageCode: LanguageCode.en, name: 'Very long description variant' }, ], }, ], }); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ term: 'aabbccdd' }); expect(result.search.items.map(i => i.productName)).toEqual([ 'Very long description aabbccdd', ]); await adminClient.query<DeleteProductMutation, DeleteProductMutationVariables>( DELETE_PRODUCT, { id: createProduct.id, }, ); }); }); // https://github.com/vendure-ecommerce/vendure/issues/609 describe('Synthetic index items', () => { let createdProductId: string; it('creates synthetic index item for Product with no variants', async () => { const { createProduct } = await adminClient.query< CreateProductMutation, CreateProductMutationVariables >(CREATE_PRODUCT, { input: { facetValueIds: ['T_1'], translations: [ { languageCode: LanguageCode.en, name: 'Strawberry cheesecake', slug: 'strawberry-cheesecake', description: 'A yummy dessert', }, ], }, }); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ groupByProduct: true, term: 'strawberry' }); expect( result.search.items.map( pick([ 'productId', 'enabled', 'productName', 'productVariantName', 'slug', 'description', ]), ), ).toEqual([ { productId: createProduct.id, enabled: false, productName: 'Strawberry cheesecake', productVariantName: 'Strawberry cheesecake', slug: 'strawberry-cheesecake', description: 'A yummy dessert', }, ]); createdProductId = createProduct.id; }); it('removes synthetic index item once a variant is created', async () => { const { createProductVariants } = await adminClient.query< CreateProductVariantsMutation, CreateProductVariantsMutationVariables >(CREATE_PRODUCT_VARIANTS, { input: [ { productId: createdProductId, sku: 'SC01', price: 1399, translations: [ { languageCode: LanguageCode.en, name: 'Strawberry Cheesecake Pie' }, ], }, ], }); await awaitRunningJobs(adminClient); const result = await testProductsAdmin({ groupByProduct: false, term: 'strawberry' }); expect(result.search.items.map(pick(['productVariantName']))).toEqual([ { productVariantName: 'Strawberry Cheesecake Pie' }, ]); }); }); describe('channel handling', () => { const SECOND_CHANNEL_TOKEN = 'second-channel-token'; let secondChannel: ChannelFragment; beforeAll(async () => { const { createChannel } = await adminClient.query< CreateChannelMutation, CreateChannelMutationVariables >(CREATE_CHANNEL, { input: { code: 'second-channel', token: SECOND_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, currencyCode: CurrencyCode.GBP, pricesIncludeTax: true, defaultTaxZoneId: 'T_1', defaultShippingZoneId: 'T_1', }, }); secondChannel = createChannel as ChannelFragment; }); it('assign product to channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query< AssignProductsToChannelMutation, AssignProductsToChannelMutationVariables >(ASSIGN_PRODUCT_TO_CHANNEL, { input: { channelId: secondChannel.id, productIds: ['T_1', 'T_2'] }, }); await awaitRunningJobs(adminClient); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { search } = await testProductsAdmin({ groupByProduct: true }); expect(search.items.map(i => i.productId)).toEqual(['T_1', 'T_2']); }, 10000); it('removing product from channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { removeProductsFromChannel } = await adminClient.query< RemoveProductsFromChannelMutation, RemoveProductsFromChannelMutationVariables >(REMOVE_PRODUCT_FROM_CHANNEL, { input: { productIds: ['T_2'], channelId: secondChannel.id, }, }); await awaitRunningJobs(adminClient); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { search } = await testProductsAdmin({ groupByProduct: true }); expect(search.items.map(i => i.productId)).toEqual(['T_1']); }, 10000); it('assign product variant to channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query< AssignProductVariantsToChannelMutation, AssignProductVariantsToChannelMutationVariables >(ASSIGN_PRODUCTVARIANT_TO_CHANNEL, { input: { channelId: secondChannel.id, productVariantIds: ['T_10', 'T_15'] }, }); await awaitRunningJobs(adminClient); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { search: searchGrouped } = await testProductsAdmin({ groupByProduct: true }); expect(searchGrouped.items.map(i => i.productId)).toEqual(['T_1', 'T_3', 'T_4']); const { search: searchUngrouped } = await testProductsAdmin({ groupByProduct: false }); expect(searchUngrouped.items.map(i => i.productVariantId)).toEqual([ 'T_1', 'T_2', 'T_3', 'T_4', 'T_10', 'T_15', ]); }, 10000); it('removing product variant from channel', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query< RemoveProductVariantsFromChannelMutation, RemoveProductVariantsFromChannelMutationVariables >(REMOVE_PRODUCTVARIANT_FROM_CHANNEL, { input: { channelId: secondChannel.id, productVariantIds: ['T_1', 'T_15'] }, }); await awaitRunningJobs(adminClient); adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { search: searchGrouped } = await testProductsAdmin({ groupByProduct: true }); expect(searchGrouped.items.map(i => i.productId)).toEqual(['T_1', 'T_3']); const { search: searchUngrouped } = await testProductsAdmin({ groupByProduct: false }); expect(searchUngrouped.items.map(i => i.productVariantId)).toEqual([ 'T_2', 'T_3', 'T_4', 'T_10', ]); }, 10000); it('updating product affects current channel', async () => { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { updateProduct } = await adminClient.query< UpdateProductMutation, UpdateProductMutationVariables >(UPDATE_PRODUCT, { input: { id: 'T_3', enabled: true, translations: [{ languageCode: LanguageCode.en, name: 'xyz' }], }, }); await awaitRunningJobs(adminClient); const { search: searchGrouped } = await testProductsAdmin({ groupByProduct: true, term: 'xyz', }); expect(searchGrouped.items.map(i => i.productName)).toEqual(['xyz']); }); it('updating product affects other channels', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { search: searchGrouped } = await testProductsAdmin({ groupByProduct: true, term: 'xyz', }); expect(searchGrouped.items.map(i => i.productName)).toEqual(['xyz']); }); // https://github.com/vendure-ecommerce/vendure/issues/896 it('removing from channel with multiple languages', async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); await adminClient.query<UpdateProductMutation, UpdateProductMutationVariables>( UPDATE_PRODUCT, { input: { id: 'T_4', translations: [ { languageCode: LanguageCode.en, name: 'product en', slug: 'product-en', description: 'en', }, { languageCode: LanguageCode.de, name: 'product de', slug: 'product-de', description: 'de', }, ], }, }, ); await adminClient.query< AssignProductsToChannelMutation, AssignProductsToChannelMutationVariables >(ASSIGN_PRODUCT_TO_CHANNEL, { input: { channelId: secondChannel.id, productIds: ['T_4'] }, }); await awaitRunningJobs(adminClient); async function searchSecondChannelForDEProduct() { adminClient.setChannelToken(SECOND_CHANNEL_TOKEN); const { search } = await adminClient.query< SearchProductsAdminQuery, SearchProductsAdminQueryVariables >( SEARCH_PRODUCTS_ADMIN, { input: { term: 'product', groupByProduct: true }, }, { languageCode: LanguageCode.de }, ); return search; } const search1 = await searchSecondChannelForDEProduct(); expect(search1.items.map(i => i.productName)).toEqual(['product de']); adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { removeProductsFromChannel } = await adminClient.query< RemoveProductsFromChannelMutation, RemoveProductsFromChannelMutationVariables >(REMOVE_PRODUCT_FROM_CHANNEL, { input: { productIds: ['T_4'], channelId: secondChannel.id, }, }); await awaitRunningJobs(adminClient); const search2 = await searchSecondChannelForDEProduct(); expect(search2.items.map(i => i.productName)).toEqual([]); }); }); describe('multiple language handling', () => { beforeAll(async () => { adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN); const { updateProduct } = await adminClient.query< UpdateProductMutation, UpdateProductMutationVariables >(UPDATE_PRODUCT, { input: { id: 'T_1', translations: [ { languageCode: LanguageCode.en, name: 'Laptop en', slug: 'laptop-slug-en', description: 'Laptop description en', }, { languageCode: LanguageCode.de, name: 'Laptop de', slug: 'laptop-slug-de', description: 'Laptop description de', }, { languageCode: LanguageCode.zh, name: 'Laptop zh', slug: 'laptop-slug-zh', description: 'Laptop description zh', }, ], }, }); expect(updateProduct.variants.length).toEqual(4); await adminClient.query< UpdateProductVariantsMutation, UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [ { id: updateProduct.variants[0].id, translations: [ { languageCode: LanguageCode.en, name: 'Laptop variant T_1 en', }, { languageCode: LanguageCode.de, name: 'Laptop variant T_1 de', }, { languageCode: LanguageCode.zh, name: 'Laptop variant T_1 zh', }, ], }, { id: updateProduct.variants[1].id, translations: [ { languageCode: LanguageCode.en, name: 'Laptop variant T_2 en', }, { languageCode: LanguageCode.de, name: 'Laptop variant T_2 de', }, ], }, { id: updateProduct.variants[2].id, translations: [ { languageCode: LanguageCode.en, name: 'Laptop variant T_3 en', }, { languageCode: LanguageCode.zh, name: 'Laptop variant T_3 zh', }, ], }, { id: updateProduct.variants[3].id, translations: [ { languageCode: LanguageCode.en, name: 'Laptop variant T_4 en', }, ], }, ], }); await awaitRunningJobs(adminClient); }); describe('search products', () => { function searchInLanguage(languageCode: LanguageCode) { return adminClient.query<SearchProductsAdminQuery, SearchProductsAdminQueryVariables>( SEARCH_PRODUCTS_ADMIN, { input: { take: 100, }, }, { languageCode, }, ); } it('fallbacks to default language en', async () => { const { search } = await searchInLanguage(LanguageCode.af); const laptopVariants = search.items.filter(i => i.productId === 'T_1'); expect(laptopVariants.length).toEqual(4); const laptopVariantT1 = laptopVariants.find(i => i.productVariantId === 'T_1'); expect(laptopVariantT1?.productVariantName).toEqual('Laptop variant T_1 en'); expect(laptopVariantT1?.productName).toEqual('Laptop en'); expect(laptopVariantT1?.slug).toEqual('laptop-slug-en'); expect(laptopVariantT1?.description).toEqual('Laptop description en'); const laptopVariantT2 = laptopVariants.find(i => i.productVariantId === 'T_2'); expect(laptopVariantT2?.productVariantName).toEqual('Laptop variant T_2 en'); expect(laptopVariantT2?.productName).toEqual('Laptop en'); expect(laptopVariantT2?.slug).toEqual('laptop-slug-en'); expect(laptopVariantT2?.description).toEqual('Laptop description en'); const laptopVariantT3 = laptopVariants.find(i => i.productVariantId === 'T_3'); expect(laptopVariantT3?.productVariantName).toEqual('Laptop variant T_3 en'); expect(laptopVariantT3?.productName).toEqual('Laptop en'); expect(laptopVariantT3?.slug).toEqual('laptop-slug-en'); expect(laptopVariantT3?.description).toEqual('Laptop description en'); const laptopVariantT4 = laptopVariants.find(i => i.productVariantId === 'T_4'); expect(laptopVariantT4?.productVariantName).toEqual('Laptop variant T_4 en'); expect(laptopVariantT4?.productName).toEqual('Laptop en'); expect(laptopVariantT4?.slug).toEqual('laptop-slug-en'); expect(laptopVariantT4?.description).toEqual('Laptop description en'); }); it('indexes non-default language de', async () => { const { search } = await searchInLanguage(LanguageCode.de); const laptopVariants = search.items.filter(i => i.productId === 'T_1'); expect(laptopVariants.length).toEqual(4); const laptopVariantT1 = laptopVariants.find(i => i.productVariantId === 'T_1'); expect(laptopVariantT1?.productVariantName).toEqual('Laptop variant T_1 de'); expect(laptopVariantT1?.productName).toEqual('Laptop de'); expect(laptopVariantT1?.slug).toEqual('laptop-slug-de'); expect(laptopVariantT1?.description).toEqual('Laptop description de'); const laptopVariantT2 = laptopVariants.find(i => i.productVariantId === 'T_2'); expect(laptopVariantT2?.productVariantName).toEqual('Laptop variant T_2 de'); expect(laptopVariantT2?.productName).toEqual('Laptop de'); expect(laptopVariantT2?.slug).toEqual('laptop-slug-de'); expect(laptopVariantT2?.description).toEqual('Laptop description de'); const laptopVariantT3 = laptopVariants.find(i => i.productVariantId === 'T_3'); expect(laptopVariantT3?.productVariantName).toEqual('Laptop variant T_3 en'); expect(laptopVariantT3?.productName).toEqual('Laptop de'); expect(laptopVariantT3?.slug).toEqual('laptop-slug-de'); expect(laptopVariantT3?.description).toEqual('Laptop description de'); const laptopVariantT4 = laptopVariants.find(i => i.productVariantId === 'T_4'); expect(laptopVariantT4?.productVariantName).toEqual('Laptop variant T_4 en'); expect(laptopVariantT4?.productName).toEqual('Laptop de'); expect(laptopVariantT4?.slug).toEqual('laptop-slug-de'); expect(laptopVariantT4?.description).toEqual('Laptop description de'); }); it('indexes non-default language zh', async () => { const { search } = await searchInLanguage(LanguageCode.zh); const laptopVariants = search.items.filter(i => i.productId === 'T_1'); expect(laptopVariants.length).toEqual(4); const laptopVariantT1 = laptopVariants.find(i => i.productVariantId === 'T_1'); expect(laptopVariantT1?.productVariantName).toEqual('Laptop variant T_1 zh'); expect(laptopVariantT1?.productName).toEqual('Laptop zh'); expect(laptopVariantT1?.slug).toEqual('laptop-slug-zh'); expect(laptopVariantT1?.description).toEqual('Laptop description zh'); const laptopVariantT2 = laptopVariants.find(i => i.productVariantId === 'T_2'); expect(laptopVariantT2?.productVariantName).toEqual('Laptop variant T_2 en'); expect(laptopVariantT2?.productName).toEqual('Laptop zh'); expect(laptopVariantT2?.slug).toEqual('laptop-slug-zh'); expect(laptopVariantT2?.description).toEqual('Laptop description zh'); const laptopVariantT3 = laptopVariants.find(i => i.productVariantId === 'T_3'); expect(laptopVariantT3?.productVariantName).toEqual('Laptop variant T_3 zh'); expect(laptopVariantT3?.productName).toEqual('Laptop zh'); expect(laptopVariantT3?.slug).toEqual('laptop-slug-zh'); expect(laptopVariantT3?.description).toEqual('Laptop description zh'); const laptopVariantT4 = laptopVariants.find(i => i.productVariantId === 'T_4'); expect(laptopVariantT4?.productVariantName).toEqual('Laptop variant T_4 en'); expect(laptopVariantT4?.productName).toEqual('Laptop zh'); expect(laptopVariantT4?.slug).toEqual('laptop-slug-zh'); expect(laptopVariantT4?.description).toEqual('Laptop description zh'); }); }); describe('search products grouped by product and sorted by name ASC', () => { function searchInLanguage(languageCode: LanguageCode) { return adminClient.query<SearchProductsAdminQuery, SearchProductsAdminQueryVariables>( SEARCH_PRODUCTS_ADMIN, { input: { groupByProduct: true, take: 100, sort: { name: SortOrder.ASC, }, }, }, { languageCode, }, ); } // https://github.com/vendure-ecommerce/vendure/issues/1752 // https://github.com/vendure-ecommerce/vendure/issues/1746 it('fallbacks to default language en', async () => { const { search } = await searchInLanguage(LanguageCode.af); const productNames = [ 'Bonsai Tree', 'Boxing Gloves', 'Camera Lens', 'Cruiser Skateboard', 'Curvy Monitor', 'Football', 'Gaming PC', 'Instant Camera', 'Laptop en', // fallback language en 'Orchid', 'product en', // fallback language en 'Road Bike', 'Running Shoe', 'Skipping Rope', 'Slr Camera', 'Spiky Cactus', 'Strawberry cheesecake', 'Tent', 'Tripod', 'USB Cable', ]; expect(search.items.map(i => i.productName)).toEqual(productNames); }); it('indexes non-default language de', async () => { const { search } = await searchInLanguage(LanguageCode.de); const productNames = [ 'Bonsai Tree', 'Boxing Gloves', 'Camera Lens', 'Cruiser Skateboard', 'Curvy Monitor', 'Football', 'Gaming PC', 'Instant Camera', 'Laptop de', // language de 'Orchid', 'product de', // language de 'Road Bike', 'Running Shoe', 'Skipping Rope', 'Slr Camera', 'Spiky Cactus', 'Strawberry cheesecake', 'Tent', 'Tripod', 'USB Cable', ]; expect(search.items.map(i => i.productName)).toEqual(productNames); }); it('indexes non-default language zh', async () => { const { search } = await searchInLanguage(LanguageCode.zh); const productNames = [ 'Bonsai Tree', 'Boxing Gloves', 'Camera Lens', 'Cruiser Skateboard', 'Curvy Monitor', 'Football', 'Gaming PC', 'Instant Camera', 'Laptop zh', // language zh 'Orchid', 'product en', // fallback language en 'Road Bike', 'Running Shoe', 'Skipping Rope', 'Slr Camera', 'Spiky Cactus', 'Strawberry cheesecake', 'Tent', 'Tripod', 'USB Cable', ]; expect(search.items.map(i => i.productName)).toEqual(productNames); }); }); }); // https://github.com/vendure-ecommerce/vendure/issues/1789 describe('input escaping', () => { function search(term: string) { return adminClient.query<SearchProductsAdminQuery, SearchProductsAdminQueryVariables>( SEARCH_PRODUCTS_ADMIN, { input: { take: 10, term }, }, { languageCode: LanguageCode.en, }, ); } it('correctly escapes "a & b"', async () => { const result = await search('laptop & camera'); expect(result.search.items).toBeDefined(); }); it('correctly escapes other special chars', async () => { const result = await search('a : b ? * (c) ! "foo"'); expect(result.search.items).toBeDefined(); }); it('correctly escapes mysql binary mode chars', async () => { expect((await search('foo+')).search.items).toBeDefined(); expect((await search('foo-')).search.items).toBeDefined(); expect((await search('foo<')).search.items).toBeDefined(); expect((await search('foo>')).search.items).toBeDefined(); expect((await search('foo*')).search.items).toBeDefined(); expect((await search('foo~')).search.items).toBeDefined(); expect((await search('foo@bar')).search.items).toBeDefined(); expect((await search('foo + - *')).search.items).toBeDefined(); expect((await search('foo + - bar')).search.items).toBeDefined(); }); }); }); }); export const REINDEX = gql` mutation Reindex { reindex { id } } `; export const SEARCH_GET_FACET_VALUES = gql` query SearchFacetValues($input: SearchInput!) { search(input: $input) { totalItems facetValues { count facetValue { id name } } } } `; export const SEARCH_GET_COLLECTIONS = gql` query SearchCollections($input: SearchInput!) { search(input: $input) { totalItems collections { count collection { id name } } } } `; export const SEARCH_GET_ASSETS = gql` query SearchGetAssets($input: SearchInput!) { search(input: $input) { totalItems items { productId productName productVariantName productAsset { id preview focalPoint { x y } } productVariantAsset { id preview focalPoint { x y } } } } } `; export const SEARCH_GET_PRICES = gql` query SearchGetPrices($input: SearchInput!) { search(input: $input) { items { price { ... on PriceRange { min max } ... on SinglePrice { value } } priceWithTax { ... on PriceRange { min max } ... on SinglePrice { value } } } } } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { LanguageCode } from '@vendure/common/lib/generated-types'; import { DefaultLogger, DefaultOrderPlacedStrategy, mergeConfig, Order, orderPercentageDiscount, OrderState, RequestContext, } from '@vendure/core'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { singleStageRefundablePaymentMethod } from './fixtures/test-payment-methods'; import { ORDER_WITH_LINES_FRAGMENT } from './graphql/fragments'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { AddManualPaymentDocument, AdminTransitionDocument, CanceledOrderFragment, GetOrderDocument, GetOrderPlacedAtDocument, OrderWithLinesFragment, } from './graphql/generated-e2e-admin-types'; import { GetActiveCustomerOrdersQuery, TestOrderFragmentFragment, TransitionToStateDocument, UpdatedOrderFragment, } from './graphql/generated-e2e-shop-types'; import { CREATE_PROMOTION, GET_CUSTOMER_LIST } from './graphql/shared-definitions'; import { GET_ACTIVE_CUSTOMER_ORDERS } from './graphql/shop-definitions'; class TestOrderPlacedStrategy extends DefaultOrderPlacedStrategy { static spy = vi.fn(); shouldSetAsPlaced( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean { TestOrderPlacedStrategy.spy(order); return super.shouldSetAsPlaced(ctx, fromState, toState, order); } } describe('Draft Orders resolver', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { logger: new DefaultLogger(), paymentOptions: { paymentMethodHandlers: [singleStageRefundablePaymentMethod], }, orderOptions: { orderPlacedStrategy: new TestOrderPlacedStrategy(), }, dbConnectionOptions: { logging: true, }, }), ); let customers: Codegen.GetCustomerListQuery['customers']['items']; let draftOrder: OrderWithLinesFragment; const freeOrderCouponCode = 'FREE'; const orderGuard: ErrorResultGuard< TestOrderFragmentFragment | CanceledOrderFragment | UpdatedOrderFragment > = createErrorResultGuard(input => !!input.lines || !!input.state); beforeAll(async () => { await server.init({ initialData: { ...initialData, paymentMethods: [ { name: singleStageRefundablePaymentMethod.code, handler: { code: singleStageRefundablePaymentMethod.code, arguments: [] }, }, ], }, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 3, }); await adminClient.asSuperAdmin(); // Create a couple of orders to be queried const result = await adminClient.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST, { options: { take: 3, }, }); customers = result.customers.items; // Create a coupon code promotion const { createPromotion } = await adminClient.query< Codegen.CreatePromotionMutation, Codegen.CreatePromotionMutationVariables >(CREATE_PROMOTION, { input: { enabled: true, conditions: [], couponCode: freeOrderCouponCode, actions: [ { code: orderPercentageDiscount.code, arguments: [{ name: 'discount', value: '100' }], }, ], translations: [{ languageCode: LanguageCode.en, name: 'Free Order' }], }, }); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('create draft order', async () => { const { createDraftOrder } = await adminClient.query<Codegen.CreateDraftOrderMutation>( CREATE_DRAFT_ORDER, ); expect(createDraftOrder.state).toBe('Draft'); expect(createDraftOrder.active).toBe(false); draftOrder = createDraftOrder; }); it('addItemToDraftOrder', async () => { const { addItemToDraftOrder } = await adminClient.query< Codegen.AddItemToDraftOrderMutation, Codegen.AddItemToDraftOrderMutationVariables >(ADD_ITEM_TO_DRAFT_ORDER, { orderId: draftOrder.id, input: { productVariantId: 'T_5', quantity: 2, }, }); orderGuard.assertSuccess(addItemToDraftOrder); expect(addItemToDraftOrder.lines.length).toBe(1); draftOrder = addItemToDraftOrder; }); it('adjustDraftOrderLine up', async () => { const { adjustDraftOrderLine } = await adminClient.query< Codegen.AdjustDraftOrderLineMutation, Codegen.AdjustDraftOrderLineMutationVariables >(ADJUST_DRAFT_ORDER_LINE, { orderId: draftOrder.id, input: { orderLineId: draftOrder.lines[0]!.id, quantity: 5, }, }); orderGuard.assertSuccess(adjustDraftOrderLine); expect(adjustDraftOrderLine.lines[0].quantity).toBe(5); }); it('adjustDraftOrderLine down', async () => { const { adjustDraftOrderLine } = await adminClient.query< Codegen.AdjustDraftOrderLineMutation, Codegen.AdjustDraftOrderLineMutationVariables >(ADJUST_DRAFT_ORDER_LINE, { orderId: draftOrder.id, input: { orderLineId: draftOrder.lines[0]!.id, quantity: 2, }, }); orderGuard.assertSuccess(adjustDraftOrderLine); expect(adjustDraftOrderLine.lines[0].quantity).toBe(2); }); it('removeDraftOrderLine', async () => { const { removeDraftOrderLine } = await adminClient.query< Codegen.RemoveDraftOrderLineMutation, Codegen.RemoveDraftOrderLineMutationVariables >(REMOVE_DRAFT_ORDER_LINE, { orderId: draftOrder.id, orderLineId: draftOrder.lines[0]!.id, }); orderGuard.assertSuccess(removeDraftOrderLine); expect(removeDraftOrderLine.lines.length).toBe(0); }); it('setCustomerForDraftOrder', async () => { const { setCustomerForDraftOrder } = await adminClient.query< Codegen.SetCustomerForDraftOrderMutation, Codegen.SetCustomerForDraftOrderMutationVariables >(SET_CUSTOMER_FOR_DRAFT_ORDER, { orderId: draftOrder.id, customerId: customers[0].id, }); orderGuard.assertSuccess(setCustomerForDraftOrder); expect(setCustomerForDraftOrder.customer?.id).toBe(customers[0].id); }); it('custom does not see draft orders in history', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { activeCustomer } = await shopClient.query<GetActiveCustomerOrdersQuery>( GET_ACTIVE_CUSTOMER_ORDERS, ); expect(activeCustomer?.orders.totalItems).toBe(0); expect(activeCustomer?.orders.items.length).toBe(0); }); it('setDraftOrderShippingAddress', async () => { const { setDraftOrderShippingAddress } = await adminClient.query< Codegen.SetDraftOrderShippingAddressMutation, Codegen.SetDraftOrderShippingAddressMutationVariables >(SET_SHIPPING_ADDRESS_FOR_DRAFT_ORDER, { orderId: draftOrder.id, input: { streetLine1: 'Shipping Street', city: 'Wigan', province: 'Greater Manchester', postalCode: 'WN1 2DD', countryCode: 'GB', }, }); expect(setDraftOrderShippingAddress.shippingAddress).toEqual({ company: null, fullName: null, phoneNumber: null, streetLine2: null, province: 'Greater Manchester', city: 'Wigan', country: 'United Kingdom', postalCode: 'WN1 2DD', streetLine1: 'Shipping Street', }); }); it('setDraftOrderBillingAddress', async () => { const { setDraftOrderBillingAddress } = await adminClient.query< Codegen.SetDraftOrderBillingAddressMutation, Codegen.SetDraftOrderBillingAddressMutationVariables >(SET_BILLING_ADDRESS_FOR_DRAFT_ORDER, { orderId: draftOrder.id, input: { streetLine1: 'Billing Street', city: 'Skelmerdale', province: 'Lancashire', postalCode: 'WN8 3QW', countryCode: 'GB', }, }); expect(setDraftOrderBillingAddress.billingAddress).toEqual({ company: null, fullName: null, phoneNumber: null, streetLine2: null, province: 'Lancashire', city: 'Skelmerdale', country: 'United Kingdom', postalCode: 'WN8 3QW', streetLine1: 'Billing Street', }); }); it('applyCouponCodeToDraftOrder', async () => { const { addItemToDraftOrder } = await adminClient.query< Codegen.AddItemToDraftOrderMutation, Codegen.AddItemToDraftOrderMutationVariables >(ADD_ITEM_TO_DRAFT_ORDER, { orderId: draftOrder.id, input: { productVariantId: 'T_1', quantity: 1, }, }); orderGuard.assertSuccess(addItemToDraftOrder); expect(addItemToDraftOrder.totalWithTax).toBe(155880); const { applyCouponCodeToDraftOrder } = await adminClient.query< Codegen.ApplyCouponCodeToDraftOrderMutation, Codegen.ApplyCouponCodeToDraftOrderMutationVariables >(APPLY_COUPON_CODE_TO_DRAFT_ORDER, { orderId: draftOrder.id, couponCode: freeOrderCouponCode, }); orderGuard.assertSuccess(applyCouponCodeToDraftOrder); expect(applyCouponCodeToDraftOrder.couponCodes).toEqual([freeOrderCouponCode]); expect(applyCouponCodeToDraftOrder.totalWithTax).toBe(0); }); it('removeCouponCodeFromDraftOrder', async () => { const { removeCouponCodeFromDraftOrder } = await adminClient.query< Codegen.RemoveCouponCodeFromDraftOrderMutation, Codegen.RemoveCouponCodeFromDraftOrderMutationVariables >(REMOVE_COUPON_CODE_FROM_DRAFT_ORDER, { orderId: draftOrder.id, couponCode: freeOrderCouponCode, }); expect(removeCouponCodeFromDraftOrder!.couponCodes).toEqual([]); expect(removeCouponCodeFromDraftOrder!.totalWithTax).toBe(155880); }); it('eligibleShippingMethodsForDraftOrder', async () => { const { eligibleShippingMethodsForDraftOrder } = await adminClient.query< Codegen.DraftOrderEligibleShippingMethodsQuery, Codegen.DraftOrderEligibleShippingMethodsQueryVariables >(DRAFT_ORDER_ELIGIBLE_SHIPPING_METHODS, { orderId: draftOrder.id, }); expect(eligibleShippingMethodsForDraftOrder).toEqual([ { code: 'standard-shipping', description: '', id: 'T_1', metadata: null, name: 'Standard Shipping', price: 500, priceWithTax: 500, }, { code: 'express-shipping', description: '', id: 'T_2', metadata: null, name: 'Express Shipping', price: 1000, priceWithTax: 1000, }, ]); }); it('setDraftOrderShippingMethod', async () => { const { setDraftOrderShippingMethod } = await adminClient.query< Codegen.SetDraftOrderShippingMethodMutation, Codegen.SetDraftOrderShippingMethodMutationVariables >(SET_DRAFT_ORDER_SHIPPING_METHOD, { orderId: draftOrder.id, shippingMethodId: 'T_2', }); orderGuard.assertSuccess(setDraftOrderShippingMethod); expect(setDraftOrderShippingMethod.shippingWithTax).toBe(1000); expect(setDraftOrderShippingMethod.shippingLines.length).toBe(1); expect(setDraftOrderShippingMethod.shippingLines[0].shippingMethod.id).toBe('T_2'); }); // https://github.com/vendure-ecommerce/vendure/issues/2105 it('sets order as placed when payment is settled', async () => { TestOrderPlacedStrategy.spy.mockClear(); expect(TestOrderPlacedStrategy.spy.mock.calls.length).toBe(0); const { transitionOrderToState } = await adminClient.query(AdminTransitionDocument, { id: draftOrder.id, state: 'ArrangingPayment', }); orderGuard.assertSuccess(transitionOrderToState); expect(transitionOrderToState.state).toBe('ArrangingPayment'); const { addManualPaymentToOrder } = await adminClient.query(AddManualPaymentDocument, { input: { orderId: draftOrder.id, metadata: {}, method: singleStageRefundablePaymentMethod.code, transactionId: '12345', }, }); orderGuard.assertSuccess(addManualPaymentToOrder); expect(addManualPaymentToOrder.state).toBe('PaymentSettled'); const { order } = await adminClient.query(GetOrderPlacedAtDocument, { id: draftOrder.id, }); expect(order?.orderPlacedAt).not.toBeNull(); expect(TestOrderPlacedStrategy.spy.mock.calls.length).toBe(1); expect(TestOrderPlacedStrategy.spy.mock.calls[0][0].code).toBe(draftOrder.code); }); }); export const CREATE_DRAFT_ORDER = gql` mutation CreateDraftOrder { createDraftOrder { ...OrderWithLines } } ${ORDER_WITH_LINES_FRAGMENT} `; export const ADD_ITEM_TO_DRAFT_ORDER = gql` mutation AddItemToDraftOrder($orderId: ID!, $input: AddItemToDraftOrderInput!) { addItemToDraftOrder(orderId: $orderId, input: $input) { ...OrderWithLines ... on ErrorResult { errorCode message } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const ADJUST_DRAFT_ORDER_LINE = gql` mutation AdjustDraftOrderLine($orderId: ID!, $input: AdjustDraftOrderLineInput!) { adjustDraftOrderLine(orderId: $orderId, input: $input) { ...OrderWithLines ... on ErrorResult { errorCode message } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const REMOVE_DRAFT_ORDER_LINE = gql` mutation RemoveDraftOrderLine($orderId: ID!, $orderLineId: ID!) { removeDraftOrderLine(orderId: $orderId, orderLineId: $orderLineId) { ...OrderWithLines ... on ErrorResult { errorCode message } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const SET_CUSTOMER_FOR_DRAFT_ORDER = gql` mutation SetCustomerForDraftOrder($orderId: ID!, $customerId: ID, $input: CreateCustomerInput) { setCustomerForDraftOrder(orderId: $orderId, customerId: $customerId, input: $input) { ...OrderWithLines ... on ErrorResult { errorCode message } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const SET_SHIPPING_ADDRESS_FOR_DRAFT_ORDER = gql` mutation SetDraftOrderShippingAddress($orderId: ID!, $input: CreateAddressInput!) { setDraftOrderShippingAddress(orderId: $orderId, input: $input) { ...OrderWithLines } } ${ORDER_WITH_LINES_FRAGMENT} `; export const SET_BILLING_ADDRESS_FOR_DRAFT_ORDER = gql` mutation SetDraftOrderBillingAddress($orderId: ID!, $input: CreateAddressInput!) { setDraftOrderBillingAddress(orderId: $orderId, input: $input) { ...OrderWithLines billingAddress { ...ShippingAddress } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const APPLY_COUPON_CODE_TO_DRAFT_ORDER = gql` mutation ApplyCouponCodeToDraftOrder($orderId: ID!, $couponCode: String!) { applyCouponCodeToDraftOrder(orderId: $orderId, couponCode: $couponCode) { ...OrderWithLines ... on Order { couponCodes } ... on ErrorResult { errorCode message } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const REMOVE_COUPON_CODE_FROM_DRAFT_ORDER = gql` mutation RemoveCouponCodeFromDraftOrder($orderId: ID!, $couponCode: String!) { removeCouponCodeFromDraftOrder(orderId: $orderId, couponCode: $couponCode) { ...OrderWithLines ... on Order { couponCodes } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const DRAFT_ORDER_ELIGIBLE_SHIPPING_METHODS = gql` query DraftOrderEligibleShippingMethods($orderId: ID!) { eligibleShippingMethodsForDraftOrder(orderId: $orderId) { id name code description price priceWithTax metadata } } `; export const SET_DRAFT_ORDER_SHIPPING_METHOD = gql` mutation SetDraftOrderShippingMethod($orderId: ID!, $shippingMethodId: ID!) { setDraftOrderShippingMethod(orderId: $orderId, shippingMethodId: $shippingMethodId) { ...OrderWithLines ... on ErrorResult { errorCode message } } } ${ORDER_WITH_LINES_FRAGMENT} `; export const GET_ORDER_PLACED_AT = gql` query GetOrderPlacedAt($id: ID!) { order(id: $id) { id createdAt updatedAt state orderPlacedAt } } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { pick } from '@vendure/common/lib/pick'; import { Collection, CollectionService, defaultEntityDuplicators, EntityDuplicator, freeShipping, LanguageCode, mergeConfig, minimumOrderAmount, PermissionDefinition, TransactionalConnection, variantIdCollectionFilter, } from '@vendure/core'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config'; import * as Codegen from './graphql/generated-e2e-admin-types'; import { AdministratorFragment, CreateAdministratorMutation, CreateAdministratorMutationVariables, CreateRoleMutation, CreateRoleMutationVariables, Permission, RoleFragment, } from './graphql/generated-e2e-admin-types'; import { CREATE_ADMINISTRATOR, CREATE_COLLECTION, CREATE_PROMOTION, CREATE_ROLE, GET_COLLECTION, GET_COLLECTIONS, GET_FACET_WITH_VALUES, GET_PRODUCT_WITH_VARIANTS, GET_PROMOTION, UPDATE_PRODUCT_VARIANTS, } from './graphql/shared-definitions'; const customPermission = new PermissionDefinition({ name: 'custom', }); let collectionService: CollectionService; let connection: TransactionalConnection; const customCollectionDuplicator = new EntityDuplicator({ code: 'custom-collection-duplicator', description: [{ languageCode: LanguageCode.en, value: 'Custom Collection Duplicator' }], args: { throwError: { type: 'boolean', defaultValue: false, }, }, forEntities: ['Collection'], requiresPermission: customPermission.Permission, init(injector) { collectionService = injector.get(CollectionService); connection = injector.get(TransactionalConnection); }, duplicate: async input => { const { ctx, id, args } = input; const original = await connection.getEntityOrThrow(ctx, Collection, id, { relations: { assets: true, featuredAsset: true, }, }); const newCollection = await collectionService.create(ctx, { isPrivate: original.isPrivate, customFields: original.customFields, assetIds: original.assets.map(a => a.id), featuredAssetId: original.featuredAsset?.id, parentId: original.parentId, filters: original.filters.map(f => ({ code: f.code, arguments: f.args, })), inheritFilters: original.inheritFilters, translations: original.translations.map(t => ({ languageCode: t.languageCode, name: `${t.name} (copy)`, slug: `${t.slug}-copy`, description: t.description, customFields: t.customFields, })), }); if (args.throwError) { throw new Error('Dummy error'); } return newCollection; }, }); describe('Duplicating entities', () => { const { server, adminClient } = createTestEnvironment( mergeConfig(testConfig(), { authOptions: { customPermissions: [customPermission], }, entityOptions: { entityDuplicators: [...defaultEntityDuplicators, customCollectionDuplicator], }, }), ); const duplicateEntityGuard: ErrorResultGuard<{ newEntityId: string }> = createErrorResultGuard( result => !!result.newEntityId, ); let testRole: RoleFragment; let testAdmin: AdministratorFragment; let newEntityId: string; beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); // create a new role and Admin and sign in as that Admin const { createRole } = await adminClient.query<CreateRoleMutation, CreateRoleMutationVariables>( CREATE_ROLE, { input: { channelIds: ['T_1'], code: 'test-role', description: 'Testing custom permissions', permissions: [ Permission.CreateCollection, Permission.UpdateCollection, Permission.ReadCollection, ], }, }, ); testRole = createRole; const { createAdministrator } = await adminClient.query< CreateAdministratorMutation, CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input: { firstName: 'Test', lastName: 'Admin', emailAddress: 'test@admin.com', password: 'test', roleIds: [testRole.id], }, }); testAdmin = createAdministrator; }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('get entity duplicators', async () => { const { entityDuplicators } = await adminClient.query<Codegen.GetEntityDuplicatorsQuery>( GET_ENTITY_DUPLICATORS, ); expect(entityDuplicators.find(d => d.code === 'custom-collection-duplicator')).toEqual({ args: [ { defaultValue: false, name: 'throwError', type: 'boolean', }, ], code: 'custom-collection-duplicator', description: 'Custom Collection Duplicator', forEntities: ['Collection'], requiresPermission: ['custom'], }); }); it('cannot duplicate if lacking permissions', async () => { await adminClient.asUserWithCredentials(testAdmin.emailAddress, 'test'); const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Collection', entityId: 'T_2', duplicatorInput: { code: 'custom-collection-duplicator', arguments: [ { name: 'throwError', value: 'false', }, ], }, }, }); duplicateEntityGuard.assertErrorResult(duplicateEntity); expect(duplicateEntity.message).toBe('The entity could not be duplicated'); expect(duplicateEntity.duplicationError).toBe( 'You do not have the required permissions to duplicate this entity', ); }); it('errors thrown in duplicator cause ErrorResult', async () => { await adminClient.asSuperAdmin(); const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Collection', entityId: 'T_2', duplicatorInput: { code: 'custom-collection-duplicator', arguments: [ { name: 'throwError', value: 'true', }, ], }, }, }); duplicateEntityGuard.assertErrorResult(duplicateEntity); expect(duplicateEntity.message).toBe('The entity could not be duplicated'); expect(duplicateEntity.duplicationError).toBe('Dummy error'); }); it('errors thrown cause all DB changes to be rolled back', async () => { await adminClient.asSuperAdmin(); const { collections } = await adminClient.query<Codegen.GetCollectionsQuery>(GET_COLLECTIONS); expect(collections.items.length).toBe(1); expect(collections.items.map(i => i.name)).toEqual(['Plants']); }); it('returns ID of new entity', async () => { await adminClient.asSuperAdmin(); const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Collection', entityId: 'T_2', duplicatorInput: { code: 'custom-collection-duplicator', arguments: [ { name: 'throwError', value: 'false', }, ], }, }, }); duplicateEntityGuard.assertSuccess(duplicateEntity); expect(duplicateEntity.newEntityId).toBeDefined(); newEntityId = duplicateEntity.newEntityId; }); it('duplicate gets created', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: newEntityId, }); expect(pick(collection, ['id', 'name', 'slug'])).toEqual({ id: newEntityId, name: 'Plants (copy)', slug: 'plants-copy', }); }); describe('default entity duplicators', () => { describe('Product duplicator', () => { let originalProduct: NonNullable<Codegen.GetProductWithVariantsQuery['product']>; let originalFirstVariant: NonNullable< Codegen.GetProductWithVariantsQuery['product'] >['variants'][0]; let newProduct1Id: string; let newProduct2Id: string; beforeAll(async () => { await adminClient.asSuperAdmin(); // Add asset and facet values to the first product variant const { updateProductVariants } = await adminClient.query< Codegen.UpdateProductVariantsMutation, Codegen.UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, { input: [ { id: 'T_1', assetIds: ['T_1'], featuredAssetId: 'T_1', facetValueIds: ['T_1', 'T_2'], }, ], }); const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: 'T_1', }); originalProduct = product!; originalFirstVariant = product!.variants.find(v => v.id === 'T_1')!; }); it('duplicate product without variants', async () => { const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Product', entityId: 'T_1', duplicatorInput: { code: 'product-duplicator', arguments: [ { name: 'includeVariants', value: 'false', }, ], }, }, }); duplicateEntityGuard.assertSuccess(duplicateEntity); newProduct1Id = duplicateEntity.newEntityId; expect(newProduct1Id).toBe('T_2'); }); it('new product has no variants', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct1Id, }); expect(product?.variants.length).toBe(0); }); it('is initially disabled', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct1Id, }); expect(product?.enabled).toBe(false); }); it('assets are duplicated', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct1Id, }); expect(product?.featuredAsset).toEqual(originalProduct.featuredAsset); expect(product?.assets.length).toBe(1); expect(product?.assets).toEqual(originalProduct.assets); }); it('facet values are duplicated', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct1Id, }); expect(product?.facetValues).toEqual(originalProduct.facetValues); expect(product?.facetValues.map(fv => fv.name).sort()).toEqual(['computers', 'electronics']); }); it('duplicate product with variants', async () => { const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Product', entityId: 'T_1', duplicatorInput: { code: 'product-duplicator', arguments: [ { name: 'includeVariants', value: 'true', }, ], }, }, }); duplicateEntityGuard.assertSuccess(duplicateEntity); newProduct2Id = duplicateEntity.newEntityId; expect(newProduct2Id).toBe('T_3'); }); it('new product has variants', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct2Id, }); expect(product?.variants.length).toBe(4); expect(product?.variants.length).toBe(originalProduct.variants.length); expect(product?.variants.map(v => v.name).sort()).toEqual( originalProduct.variants.map(v => v.name).sort(), ); }); it('product name is suffixed', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct2Id, }); expect(product?.name).toBe('Laptop (copy)'); }); it('variant SKUs are suffixed', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct2Id, }); expect(product?.variants.map(v => v.sku).sort()).toEqual([ 'L2201308-copy', 'L2201316-copy', 'L2201508-copy', 'L2201516-copy', ]); }); it('variant assets are preserved', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct2Id, }); expect(product?.variants.find(v => v.name === originalFirstVariant.name)?.assets).toEqual( originalFirstVariant.assets, ); expect( product?.variants.find(v => v.name === originalFirstVariant.name)?.featuredAsset, ).toEqual(originalFirstVariant.featuredAsset); }); it('variant facet values are preserved', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct2Id, }); expect( product?.variants.find(v => v.name === originalFirstVariant.name)?.facetValues.length, ).toBe(2); expect( product?.variants.find(v => v.name === originalFirstVariant.name)?.facetValues, ).toEqual(originalFirstVariant.facetValues); }); it('variant stock levels are preserved', async () => { const { product } = await adminClient.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id: newProduct2Id, }); expect(product?.variants.find(v => v.name === originalFirstVariant.name)?.stockOnHand).toBe( 100, ); }); }); describe('Collection duplicator', () => { let testCollection: Codegen.CreateCollectionMutation['createCollection']; let duplicatedCollectionId: string; beforeAll(async () => { await adminClient.asSuperAdmin(); const { createCollection } = await adminClient.query< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: { parentId: 'T_2', assetIds: ['T_1'], featuredAssetId: 'T_1', isPrivate: false, inheritFilters: false, translations: [ { languageCode: LanguageCode.en, name: 'Test Collection', description: 'Test Collection description', slug: 'test-collection', }, ], filters: [ { code: variantIdCollectionFilter.code, arguments: [ { name: 'variantIds', value: '["T_1"]', }, { name: 'combineWithAnd', value: 'true', }, ], }, ], }, }); testCollection = createCollection; }); it('duplicate collection', async () => { const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Collection', entityId: testCollection.id, duplicatorInput: { code: 'collection-duplicator', arguments: [], }, }, }); duplicateEntityGuard.assertSuccess(duplicateEntity); expect(duplicateEntity.newEntityId).toBeDefined(); duplicatedCollectionId = duplicateEntity.newEntityId; }); it('collection name is suffixed', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: duplicatedCollectionId, }); expect(collection?.name).toBe('Test Collection (copy)'); }); it('is initially private', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: duplicatedCollectionId, }); expect(collection?.isPrivate).toBe(true); }); it('assets are duplicated', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: duplicatedCollectionId, }); expect(collection?.featuredAsset).toEqual(testCollection.featuredAsset); expect(collection?.assets.length).toBe(1); expect(collection?.assets).toEqual(testCollection.assets); }); it('parentId matches', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: duplicatedCollectionId, }); expect(collection?.parent?.id).toBe(testCollection.parent?.id); }); it('filters are duplicated', async () => { const { collection } = await adminClient.query< Codegen.GetCollectionQuery, Codegen.GetCollectionQueryVariables >(GET_COLLECTION, { id: duplicatedCollectionId, }); expect(collection?.filters).toEqual(testCollection.filters); }); }); describe('Facet duplicator', () => { let newFacetId: string; it('duplicate facet', async () => { const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Facet', entityId: 'T_1', duplicatorInput: { code: 'facet-duplicator', arguments: [ { name: 'includeFacetValues', value: 'true', }, ], }, }, }); duplicateEntityGuard.assertSuccess(duplicateEntity); expect(duplicateEntity.newEntityId).toBe('T_2'); newFacetId = duplicateEntity.newEntityId; }); it('facet name is suffixed', async () => { const { facet } = await adminClient.query< Codegen.GetFacetWithValuesQuery, Codegen.GetFacetWithValuesQueryVariables >(GET_FACET_WITH_VALUES, { id: newFacetId, }); expect(facet?.name).toBe('category (copy)'); }); it('is initially private', async () => { const { facet } = await adminClient.query< Codegen.GetFacetWithValuesQuery, Codegen.GetFacetWithValuesQueryVariables >(GET_FACET_WITH_VALUES, { id: newFacetId, }); expect(facet?.isPrivate).toBe(true); }); it('facet values are duplicated', async () => { const { facet } = await adminClient.query< Codegen.GetFacetWithValuesQuery, Codegen.GetFacetWithValuesQueryVariables >(GET_FACET_WITH_VALUES, { id: newFacetId, }); expect(facet?.values.map(v => v.name).sort()).toEqual([ 'computers (copy)', 'electronics (copy)', ]); }); }); describe('Promotion duplicator', () => { let testPromotion: Codegen.PromotionFragment; let duplicatedPromotionId: string; const promotionGuard: ErrorResultGuard<{ id: string }> = createErrorResultGuard( result => !!result.id, ); beforeAll(async () => { await adminClient.asSuperAdmin(); const { createPromotion } = await adminClient.query< Codegen.CreatePromotionMutation, Codegen.CreatePromotionMutationVariables >(CREATE_PROMOTION, { input: { enabled: true, couponCode: 'TEST', perCustomerUsageLimit: 1, usageLimit: 100, startsAt: new Date().toISOString(), endsAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30).toISOString(), translations: [ { name: 'Test Promotion', description: 'Test Promotion description', languageCode: LanguageCode.en, }, ], conditions: [ { code: minimumOrderAmount.code, arguments: [ { name: 'amount', value: '1000', }, { name: 'taxInclusive', value: 'true', }, ], }, ], actions: [ { code: freeShipping.code, arguments: [], }, ], }, }); promotionGuard.assertSuccess(createPromotion); testPromotion = createPromotion; }); it('duplicate promotion', async () => { const { duplicateEntity } = await adminClient.query< Codegen.DuplicateEntityMutation, Codegen.DuplicateEntityMutationVariables >(DUPLICATE_ENTITY, { input: { entityName: 'Promotion', entityId: testPromotion.id, duplicatorInput: { code: 'promotion-duplicator', arguments: [], }, }, }); duplicateEntityGuard.assertSuccess(duplicateEntity); expect(testPromotion.id).toBe('T_1'); expect(duplicateEntity.newEntityId).toBe('T_2'); duplicatedPromotionId = duplicateEntity.newEntityId; }); it('promotion name is suffixed', async () => { const { promotion } = await adminClient.query< Codegen.GetPromotionQuery, Codegen.GetPromotionQueryVariables >(GET_PROMOTION, { id: duplicatedPromotionId, }); expect(promotion?.name).toBe('Test Promotion (copy)'); }); it('is initially disabled', async () => { const { promotion } = await adminClient.query< Codegen.GetPromotionQuery, Codegen.GetPromotionQueryVariables >(GET_PROMOTION, { id: duplicatedPromotionId, }); expect(promotion?.enabled).toBe(false); }); it('properties are duplicated', async () => { const { promotion } = await adminClient.query< Codegen.GetPromotionQuery, Codegen.GetPromotionQueryVariables >(GET_PROMOTION, { id: duplicatedPromotionId, }); expect(promotion?.startsAt).toBe(testPromotion.startsAt); expect(promotion?.endsAt).toBe(testPromotion.endsAt); expect(promotion?.couponCode).toBe(testPromotion.couponCode); expect(promotion?.perCustomerUsageLimit).toBe(testPromotion.perCustomerUsageLimit); expect(promotion?.usageLimit).toBe(testPromotion.usageLimit); }); it('conditions are duplicated', async () => { const { promotion } = await adminClient.query< Codegen.GetPromotionQuery, Codegen.GetPromotionQueryVariables >(GET_PROMOTION, { id: duplicatedPromotionId, }); expect(promotion?.conditions).toEqual(testPromotion.conditions); }); it('actions are duplicated', async () => { const { promotion } = await adminClient.query< Codegen.GetPromotionQuery, Codegen.GetPromotionQueryVariables >(GET_PROMOTION, { id: duplicatedPromotionId, }); expect(promotion?.actions).toEqual(testPromotion.actions); }); }); }); }); const GET_ENTITY_DUPLICATORS = gql` query GetEntityDuplicators { entityDuplicators { code description requiresPermission forEntities args { name type defaultValue } } } `; const DUPLICATE_ENTITY = gql` mutation DuplicateEntity($input: DuplicateEntityInput!) { duplicateEntity(input: $input) { ... on DuplicateEntitySuccess { newEntityId } ... on DuplicateEntityError { message duplicationError } } } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { Asset, ChannelService, EntityHydrator, mergeConfig, Order, Product, ProductVariant, RequestContext, ActiveOrderService, OrderService, TransactionalConnection, OrderLine, RequestContextService, } from '@vendure/core'; import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { AdditionalConfig, HydrationTestPlugin } from './fixtures/test-plugins/hydration-test-plugin'; import { UpdateChannelMutation, UpdateChannelMutationVariables } from './graphql/generated-e2e-admin-types'; import { AddItemToOrderDocument, AddItemToOrderMutation, AddItemToOrderMutationVariables, UpdatedOrderFragment, } from './graphql/generated-e2e-shop-types'; import { UPDATE_CHANNEL } from './graphql/shared-definitions'; import { ADD_ITEM_TO_ORDER } from './graphql/shop-definitions'; const orderResultGuard: ErrorResultGuard<UpdatedOrderFragment> = createErrorResultGuard( input => !!input.lines, ); describe('Entity hydration', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { plugins: [HydrationTestPlugin], }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 2, }); await adminClient.asSuperAdmin(); const connection = server.app.get(TransactionalConnection).rawConnection; const asset = await connection.getRepository(Asset).findOne({ where: {} }); await connection.getRepository(AdditionalConfig).save( new AdditionalConfig({ backgroundImage: asset, }), ); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('includes existing relations', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.facetValues).toBeDefined(); expect(hydrateProduct.facetValues.length).toBe(2); }); it('hydrates top-level single relation', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.featuredAsset.name).toBe('derick-david-409858-unsplash.jpg'); }); it('hydrates top-level array relation', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.assets.length).toBe(1); expect(hydrateProduct.assets[0].asset.name).toBe('derick-david-409858-unsplash.jpg'); }); it('hydrates nested single relation', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.variants[0].product.id).toBe('T_1'); }); it('hydrates nested array relation', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.variants[0].options.length).toBe(2); }); it('translates top-level translatable', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.variants.map(v => v.name).sort()).toEqual([ 'Laptop 13 inch 16GB', 'Laptop 13 inch 8GB', 'Laptop 15 inch 16GB', 'Laptop 15 inch 8GB', ]); }); it('translates nested translatable', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect( getVariantWithName(hydrateProduct, 'Laptop 13 inch 8GB') .options.map(o => o.name) .sort(), ).toEqual(['13 inch', '8GB']); }); it('translates nested translatable 2', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(hydrateProduct.assets[0].product.name).toBe('Laptop'); }); it('populates ProductVariant price data', async () => { const { hydrateProduct } = await adminClient.query<HydrateProductQuery>(GET_HYDRATED_PRODUCT, { id: 'T_1', }); expect(getVariantWithName(hydrateProduct, 'Laptop 13 inch 8GB').price).toBe(129900); expect(getVariantWithName(hydrateProduct, 'Laptop 13 inch 8GB').priceWithTax).toBe(155880); expect(getVariantWithName(hydrateProduct, 'Laptop 13 inch 16GB').price).toBe(219900); expect(getVariantWithName(hydrateProduct, 'Laptop 13 inch 16GB').priceWithTax).toBe(263880); expect(getVariantWithName(hydrateProduct, 'Laptop 15 inch 8GB').price).toBe(139900); expect(getVariantWithName(hydrateProduct, 'Laptop 15 inch 8GB').priceWithTax).toBe(167880); expect(getVariantWithName(hydrateProduct, 'Laptop 15 inch 16GB').price).toBe(229900); expect(getVariantWithName(hydrateProduct, 'Laptop 15 inch 16GB').priceWithTax).toBe(275880); }); // https://github.com/vendure-ecommerce/vendure/issues/1153 it('correctly handles empty array relations', async () => { // Product T_5 has no asset defined const { hydrateProductAsset } = await adminClient.query<{ hydrateProductAsset: Product }>( GET_HYDRATED_PRODUCT_ASSET, { id: 'T_5', }, ); expect(hydrateProductAsset.assets).toEqual([]); }); // https://github.com/vendure-ecommerce/vendure/issues/1324 it('correctly handles empty nested array relations', async () => { const { hydrateProductWithNoFacets } = await adminClient.query<{ hydrateProductWithNoFacets: Product; }>(GET_HYDRATED_PRODUCT_NO_FACETS); expect(hydrateProductWithNoFacets.facetValues).toEqual([]); }); // https://github.com/vendure-ecommerce/vendure/issues/1161 it('correctly expands missing relations', async () => { const { hydrateProductVariant } = await adminClient.query<{ hydrateProductVariant: ProductVariant }>( GET_HYDRATED_VARIANT, { id: 'T_1' }, ); expect(hydrateProductVariant.product.id).toBe('T_1'); expect(hydrateProductVariant.product.facetValues.map(fv => fv.id).sort()).toEqual(['T_1', 'T_2']); }); // https://github.com/vendure-ecommerce/vendure/issues/1172 it('can hydrate entity with getters (Order)', async () => { const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 1, }); orderResultGuard.assertSuccess(addItemToOrder); const { hydrateOrder } = await adminClient.query<{ hydrateOrder: Order }>(GET_HYDRATED_ORDER, { id: addItemToOrder.id, }); expect(hydrateOrder.id).toBe('T_1'); expect(hydrateOrder.payments).toEqual([]); }); // https://github.com/vendure-ecommerce/vendure/issues/1229 it('deep merges existing properties', async () => { await shopClient.asAnonymousUser(); const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 2, }); orderResultGuard.assertSuccess(addItemToOrder); const { hydrateOrderReturnQuantities } = await adminClient.query<{ hydrateOrderReturnQuantities: number[]; }>(GET_HYDRATED_ORDER_QUANTITIES, { id: addItemToOrder.id, }); expect(hydrateOrderReturnQuantities).toEqual([2]); }); // https://github.com/vendure-ecommerce/vendure/issues/1284 it('hydrates custom field relations', async () => { await adminClient.query<UpdateChannelMutation, UpdateChannelMutationVariables>(UPDATE_CHANNEL, { input: { id: 'T_1', customFields: { thumbId: 'T_2', }, }, }); const { hydrateChannel } = await adminClient.query<{ hydrateChannel: any; }>(GET_HYDRATED_CHANNEL, { id: 'T_1', }); expect(hydrateChannel.customFields.thumb).toBeDefined(); expect(hydrateChannel.customFields.thumb.id).toBe('T_2'); }); it('hydrates a nested custom field', async () => { await adminClient.query<UpdateChannelMutation, UpdateChannelMutationVariables>(UPDATE_CHANNEL, { input: { id: 'T_1', customFields: { additionalConfigId: 'T_1', }, }, }); const { hydrateChannelWithNestedRelation } = await adminClient.query<{ hydrateChannelWithNestedRelation: any; }>(GET_HYDRATED_CHANNEL_NESTED, { id: 'T_1', }); expect(hydrateChannelWithNestedRelation.customFields.additionalConfig).toBeDefined(); }); // https://github.com/vendure-ecommerce/vendure/issues/2682 it('hydrates a nested custom field where the first level is null', async () => { await adminClient.query<UpdateChannelMutation, UpdateChannelMutationVariables>(UPDATE_CHANNEL, { input: { id: 'T_1', customFields: { additionalConfigId: null, }, }, }); const { hydrateChannelWithNestedRelation } = await adminClient.query<{ hydrateChannelWithNestedRelation: any; }>(GET_HYDRATED_CHANNEL_NESTED, { id: 'T_1', }); expect(hydrateChannelWithNestedRelation.customFields.additionalConfig).toBeNull(); }); // https://github.com/vendure-ecommerce/vendure/issues/2013 describe('hydration of OrderLine ProductVariantPrices', () => { let order: Order | undefined; it('Create order with 3 items', async () => { await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test'); await shopClient.query(AddItemToOrderDocument, { productVariantId: '1', quantity: 1, }); await shopClient.query(AddItemToOrderDocument, { productVariantId: '2', quantity: 1, }); const { addItemToOrder } = await shopClient.query(AddItemToOrderDocument, { productVariantId: '3', quantity: 1, }); orderResultGuard.assertSuccess(addItemToOrder); const channel = await server.app.get(ChannelService).getDefaultChannel(); // This is ugly, but in our real life example we use a CTX constructed by Vendure const internalOrderId = +addItemToOrder.id.replace(/^\D+/g, ''); const ctx = new RequestContext({ channel, authorizedAsOwnerOnly: true, apiType: 'shop', isAuthorized: true, session: { activeOrderId: internalOrderId, activeChannelId: 1, user: { id: 2, }, } as any, }); order = await server.app.get(ActiveOrderService).getActiveOrder(ctx, undefined); await server.app.get(EntityHydrator).hydrate(ctx, order!, { relations: ['lines.productVariant'], applyProductVariantPrices: true, }); }); it('Variant of orderLine 1 has a price', async () => { expect(order!.lines[0].productVariant.priceWithTax).toBeGreaterThan(0); }); it('Variant of orderLine 2 has a price', async () => { expect(order!.lines[1].productVariant.priceWithTax).toBeGreaterThan(0); }); it('Variant of orderLine 3 has a price', async () => { expect(order!.lines[1].productVariant.priceWithTax).toBeGreaterThan(0); }); }); // https://github.com/vendure-ecommerce/vendure/issues/2546 it('Preserves ordering when merging arrays of relations', async () => { await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test'); await shopClient.query(AddItemToOrderDocument, { productVariantId: '1', quantity: 1, }); const { addItemToOrder } = await shopClient.query(AddItemToOrderDocument, { productVariantId: '2', quantity: 2, }); orderResultGuard.assertSuccess(addItemToOrder); const internalOrderId = +addItemToOrder.id.replace(/^\D+/g, ''); const ctx = await server.app.get(RequestContextService).create({ apiType: 'admin' }); const order = await server.app .get(OrderService) .findOne(ctx, internalOrderId, ['lines.productVariant']); for (const line of order?.lines ?? []) { // Assert that things are as we expect before hydrating expect(line.productVariantId).toBe(line.productVariant.id); } // modify the first order line to make postgres tend to return the lines in the wrong order await server.app .get(TransactionalConnection) .getRepository(ctx, OrderLine) .update(order!.lines[0].id, { sellerChannelId: 1, }); await server.app.get(EntityHydrator).hydrate(ctx, order!, { relations: ['lines.sellerChannel'], }); for (const line of order?.lines ?? []) { expect(line.productVariantId).toBe(line.productVariant.id); } }); }); function getVariantWithName(product: Product, name: string) { return product.variants.find(v => v.name === name)!; } type HydrateProductQuery = { hydrateProduct: Product }; const GET_HYDRATED_PRODUCT = gql` query GetHydratedProduct($id: ID!) { hydrateProduct(id: $id) } `; const GET_HYDRATED_PRODUCT_NO_FACETS = gql` query GetHydratedProductWithNoFacets { hydrateProductWithNoFacets } `; const GET_HYDRATED_PRODUCT_ASSET = gql` query GetHydratedProductAsset($id: ID!) { hydrateProductAsset(id: $id) } `; const GET_HYDRATED_VARIANT = gql` query GetHydratedVariant($id: ID!) { hydrateProductVariant(id: $id) } `; const GET_HYDRATED_ORDER = gql` query GetHydratedOrder($id: ID!) { hydrateOrder(id: $id) } `; const GET_HYDRATED_ORDER_QUANTITIES = gql` query GetHydratedOrderQuantities($id: ID!) { hydrateOrderReturnQuantities(id: $id) } `; const GET_HYDRATED_CHANNEL = gql` query GetHydratedChannel($id: ID!) { hydrateChannel(id: $id) } `; const GET_HYDRATED_CHANNEL_NESTED = gql` query GetHydratedChannelNested($id: ID!) { hydrateChannelWithNestedRelation(id: $id) } `;
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { createTestEnvironment } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { IdTest1, IdTest2, IdTest3, IdTest4, IdTest5, IdTest6, IdTest7, IdTest8, LanguageCode, } from './graphql/generated-e2e-admin-types'; import { sortById } from './utils/test-order-utils'; describe('EntityIdStrategy', () => { const { server, adminClient, shopClient } = createTestEnvironment(testConfig()); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('encodes ids', async () => { const { products } = await shopClient.query<IdTest1.Query>(gql` query IdTest1 { products(options: { take: 5 }) { items { id } } } `); expect(products.items.sort(sortById)).toEqual([ { id: 'T_1' }, { id: 'T_2' }, { id: 'T_3' }, { id: 'T_4' }, { id: 'T_5' }, ]); }); it('Does not doubly-encode ids from resolved properties', async () => { const { products } = await shopClient.query<IdTest2.Query>(gql` query IdTest2 { products(options: { take: 1 }) { items { id variants { id options { id name } } } } } `); expect(products.items[0].id).toBe('T_1'); expect(products.items[0].variants[0].id).toBe('T_1'); expect(products.items[0].variants[0].options.map(o => o.id).sort()).toEqual(['T_1', 'T_3']); }); it('decodes embedded argument', async () => { const { product } = await shopClient.query<IdTest3.Query>(gql` query IdTest3 { product(id: "T_1") { id } } `); expect(product).toEqual({ id: 'T_1', }); }); it('decodes embedded nested id', async () => { const { updateProduct } = await adminClient.query<IdTest4.Mutation>(gql` mutation IdTest4 { updateProduct(input: { id: "T_1", featuredAssetId: "T_3" }) { id featuredAsset { id } } } `); expect(updateProduct).toEqual({ id: 'T_1', featuredAsset: { id: 'T_3', }, }); }); it('decodes embedded nested object id', async () => { const { updateProduct } = await adminClient.query<IdTest5.Mutation>(gql` mutation IdTest5 { updateProduct( input: { id: "T_1", translations: [{ id: "T_1", languageCode: en, name: "changed" }] } ) { id name } } `); expect(updateProduct).toEqual({ id: 'T_1', name: 'changed', }); }); it('decodes argument as variable', async () => { const { product } = await shopClient.query<IdTest6.Query, IdTest6.Variables>( gql` query IdTest6($id: ID!) { product(id: $id) { id } } `, { id: 'T_1' }, ); expect(product).toEqual({ id: 'T_1', }); }); it('decodes nested id as variable', async () => { const { updateProduct } = await adminClient.query<IdTest7.Mutation, IdTest7.Variables>( gql` mutation IdTest7($input: UpdateProductInput!) { updateProduct(input: $input) { id featuredAsset { id } } } `, { input: { id: 'T_1', featuredAssetId: 'T_2', }, }, ); expect(updateProduct).toEqual({ id: 'T_1', featuredAsset: { id: 'T_2', }, }); }); it('decodes nested object id as variable', async () => { const { updateProduct } = await adminClient.query<IdTest8.Mutation, IdTest8.Variables>( gql` mutation IdTest8($input: UpdateProductInput!) { updateProduct(input: $input) { id name } } `, { input: { id: 'T_1', translations: [{ id: 'T_1', languageCode: LanguageCode.en, name: 'changed again' }], }, }, ); expect(updateProduct).toEqual({ id: 'T_1', name: 'changed again', }); }); it('encodes ids in fragment', async () => { const { products } = await shopClient.query<IdTest1.Query>(gql` query IdTest9 { products(options: { take: 1 }) { items { ...ProdFragment } } } fragment ProdFragment on Product { id featuredAsset { id } } `); expect(products).toEqual({ items: [ { id: 'T_1', featuredAsset: { id: 'T_2', }, }, ], }); }); it('encodes ids in doubly-nested fragment', async () => { const { products } = await shopClient.query<IdTest1.Query>(gql` query IdTest10 { products(options: { take: 1 }) { items { ...ProdFragment1 } } } fragment ProdFragment1 on Product { ...ProdFragment2 } fragment ProdFragment2 on Product { id featuredAsset { id } } `); expect(products).toEqual({ items: [ { id: 'T_1', featuredAsset: { id: 'T_2', }, }, ], }); }); it('encodes ids in triply-nested fragment', async () => { const { products } = await shopClient.query<IdTest1.Query>(gql` query IdTest11 { products(options: { take: 1 }) { items { ...ProdFragment1_1 } } } fragment ProdFragment1_1 on Product { ...ProdFragment2_1 } fragment ProdFragment2_1 on Product { ...ProdFragment3_1 } fragment ProdFragment3_1 on Product { id featuredAsset { id } } `); expect(products).toEqual({ items: [ { id: 'T_1', featuredAsset: { id: 'T_2', }, }, ], }); }); });
import { mergeConfig } from '@vendure/core'; import { createTestEnvironment } from '@vendure/testing'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { ListQueryPlugin } from './fixtures/test-plugins/list-query-plugin'; import { GetCustomerListQuery, GetCustomerListQueryVariables } from './graphql/generated-e2e-admin-types'; import { GET_CUSTOMER_LIST } from './graphql/shared-definitions'; /** * Tests edge-cases related to configurations with an `entityPrefix` defined in the * dbConnectionOptions. */ describe('Entity prefix edge-cases', () => { const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { dbConnectionOptions: { entityPrefix: 'prefix_', }, plugins: [ListQueryPlugin], }), ); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 5, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); // https://github.com/vendure-ecommerce/vendure/issues/1569 it('customers list filter by postalCode', async () => { const result = await adminClient.query<GetCustomerListQuery, GetCustomerListQueryVariables>( GET_CUSTOMER_LIST, { options: { filter: { postalCode: { eq: 'NU9 0PW', }, }, }, }, ); expect(result.customers.items.length).toBe(1); expect(result.customers.items[0].emailAddress).toBe('eliezer56@yahoo.com'); }); });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { UuidIdStrategy } from '@vendure/core'; // This import is here to simulate the behaviour of // the package end-user importing symbols from the // @vendure/core barrel file. Doing so will then cause the // recursive evaluation of all imported files. This tests // the resilience of the id strategy implementation to the // order of file evaluation. import '@vendure/core/dist/index'; import { createTestEnvironment } from '@vendure/testing'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { GetProductListQuery, GetProductListQueryVariables } from './graphql/generated-e2e-admin-types'; import { GET_PRODUCT_LIST } from './graphql/shared-definitions'; describe('UuidIdStrategy', () => { const { server, adminClient } = createTestEnvironment({ ...testConfig(), entityOptions: { entityIdStrategy: new UuidIdStrategy() }, }); beforeAll(async () => { await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('uses uuids', async () => { const { products } = await adminClient.query<GetProductListQuery, GetProductListQueryVariables>( GET_PRODUCT_LIST, { options: { take: 1, }, }, ); expect(isV4Uuid(products.items[0].id)).toBe(true); }); }); /** * Returns true if the id string matches the format for a v4 UUID. */ function isV4Uuid(id: string): boolean { return /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i.test(id); }