content
stringlengths
28
1.34M
import { Message, PubSub, Subscription, Topic } from '@google-cloud/pubsub'; import { JobState } from '@vendure/common/lib/generated-types'; import { InjectableJobQueueStrategy, Injector, Job, JobData, JobQueueStrategy, Logger, QueueNameProcessStorage, } from '@vendure/core'; import { loggerCtx, PUB_SUB_OPTIONS } from './constants'; import { PubSubOptions } from './options'; export class PubSubJobQueueStrategy extends InjectableJobQueueStrategy implements JobQueueStrategy { private concurrency: number; private queueNamePubSubPair: Map<string, [string, string]>; private pubSubClient: PubSub; private topics = new Map<string, Topic>(); private subscriptions = new Map<string, Subscription>(); private listeners = new QueueNameProcessStorage<(message: Message) => void>(); init(injector: Injector) { this.pubSubClient = injector.get(PubSub); const options = injector.get<PubSubOptions>(PUB_SUB_OPTIONS); this.concurrency = options.concurrency ?? 20; this.queueNamePubSubPair = options.queueNamePubSubPair ?? new Map(); super.init(injector); } destroy() { super.destroy(); for (const subscription of this.subscriptions.values()) { subscription.removeAllListeners('message'); } this.subscriptions.clear(); this.topics.clear(); } async add<Data extends JobData<Data> = object>(job: Job<Data>): Promise<Job<Data>> { if (!this.hasInitialized) { throw new Error('Cannot add job before init'); } const id = await this.topic(job.queueName).publish(Buffer.from(JSON.stringify(job.data))); Logger.debug(`Sent message ${job.queueName}: ${id}`); return new Job<Data>({ id, queueName: job.queueName, data: job.data, attempts: 0, state: JobState.PENDING, createdAt: new Date(), }); } async start<Data extends JobData<Data> = object>( queueName: string, process: (job: Job<Data>) => Promise<any>, ) { if (!this.hasInitialized) { this.started.set(queueName, process); return; } if (this.listeners.has(queueName, process)) { return; } const subscription = this.subscription(queueName); const processMessage = async (message: Message) => { Logger.verbose(`Received message: ${queueName}: ${message.id}`, loggerCtx); const job = new Job<Data>({ id: message.id, queueName, data: JSON.parse(message.data.toString()), attempts: message.deliveryAttempt, state: JobState.RUNNING, startedAt: new Date(), createdAt: message.publishTime, }); await process(job); }; const listener = (message: Message) => { processMessage(message) .then(() => { message.ack(); Logger.verbose(`Finished handling: ${queueName}: ${message.id}`, loggerCtx); }) .catch(err => { message.nack(); Logger.error( `Error handling: ${queueName}: ${message.id}: ${String(err.message)}`, loggerCtx, ); }); }; this.listeners.set(queueName, process, listener); subscription.on('message', listener); } async stop<Data extends JobData<Data> = object>( queueName: string, process: (job: Job<Data>) => Promise<any>, ) { const listener = this.listeners.getAndDelete(queueName, process); if (!listener) { return; } this.subscription(queueName).off('message', listener); } private topic(queueName: string): Topic { let topic = this.topics.get(queueName); if (topic) { return topic; } const pair = this.queueNamePubSubPair.get(queueName); if (!pair) { throw new Error(`Topic name not set for queue: ${queueName}`); } const [topicName, subscriptionName] = pair; topic = this.pubSubClient.topic(topicName); this.topics.set(queueName, topic); return topic; } private subscription(queueName: string): Subscription { let subscription = this.subscriptions.get(queueName); if (subscription) { return subscription; } const pair = this.queueNamePubSubPair.get(queueName); if (!pair) { throw new Error(`Subscription name not set for queue: ${queueName}`); } const [topicName, subscriptionName] = pair; subscription = this.topic(queueName).subscription(subscriptionName, { flowControl: { maxMessages: this.concurrency, }, }); this.subscriptions.set(queueName, subscription); return subscription; } }
import { AdminUiPlugin } from '@vendure/admin-ui-plugin'; import { ChannelService, DefaultLogger, DefaultSearchPlugin, LogLevel, mergeConfig, RequestContext, } from '@vendure/core'; import { createTestEnvironment, registerInitializer, SqljsInitializer, testConfig } from '@vendure/testing'; import { compileUiExtensions } from '@vendure/ui-devkit/compiler'; import gql from 'graphql-tag'; import localtunnel from 'localtunnel'; import path from 'path'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { molliePaymentHandler } from '../package/mollie/mollie.handler'; import { MolliePlugin } from '../src/mollie'; import { CREATE_PAYMENT_METHOD } from './graphql/admin-queries'; import { CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables, LanguageCode, } from './graphql/generated-admin-types'; import { AddItemToOrderMutation, AddItemToOrderMutationVariables } from './graphql/generated-shop-types'; import { ADD_ITEM_TO_ORDER, ADJUST_ORDER_LINE } from './graphql/shop-queries'; import { CREATE_MOLLIE_PAYMENT_INTENT, setShipping } from './payment-helpers'; /** * This should only be used to locally test the Mollie payment plugin * Make sure you have `MOLLIE_APIKEY=test_xxxx` in your .env file * Make sure you have `MOLLIE_APIKEY=test_xxxx` in your .env file */ /* eslint-disable @typescript-eslint/no-floating-promises */ async function runMollieDevServer() { // eslint-disable-next-line @typescript-eslint/no-var-requires require('dotenv').config(); registerInitializer('sqljs', new SqljsInitializer(path.join(__dirname, '__data__'))); const tunnel = await localtunnel({ port: 3050 }); const config = mergeConfig(testConfig, { plugins: [ ...testConfig.plugins, DefaultSearchPlugin, AdminUiPlugin.init({ route: 'admin', port: 5001, }), MolliePlugin.init({ vendureHost: tunnel.url }), ], logger: new DefaultLogger({ level: LogLevel.Debug }), apiOptions: { adminApiPlayground: true, shopApiPlayground: true, }, }); const { server, shopClient, adminClient } = createTestEnvironment(config as any); await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); // Set EUR as currency for Mollie await adminClient.asSuperAdmin(); await adminClient.query(gql` mutation { updateChannel(input: { id: "T_1", currencyCode: EUR }) { __typename } } `); // Create method await adminClient.query<CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables>( CREATE_PAYMENT_METHOD, { input: { code: 'mollie', translations: [ { languageCode: LanguageCode.en, name: 'Mollie payment test', description: 'This is a Mollie test payment method', }, ], enabled: true, handler: { code: molliePaymentHandler.code, arguments: [ { name: 'redirectUrl', value: `${tunnel.url}/admin/orders?filter=open&page=1`, }, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion { name: 'apiKey', value: process.env.MOLLIE_APIKEY! }, { name: 'autoCapture', value: 'false' }, ], }, }, }, ); // Prepare order with 2 items await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test'); // Add another item to the order await shopClient.query<AddItemToOrderMutation, AddItemToOrderMutationVariables>(ADD_ITEM_TO_ORDER, { productVariantId: 'T_4', quantity: 1, }); await shopClient.query<AddItemToOrderMutation, AddItemToOrderMutationVariables>(ADD_ITEM_TO_ORDER, { productVariantId: 'T_5', quantity: 1, }); await setShipping(shopClient); // Create payment intent // Create payment intent const { createMolliePaymentIntent } = await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { redirectUrl: `${tunnel.url}/admin/orders?filter=open&page=1`, paymentMethodCode: 'mollie', // molliePaymentMethodCode: 'klarnapaylater' }, }); if (createMolliePaymentIntent.errorCode) { throw createMolliePaymentIntent; } // eslint-disable-next-line no-console console.log('\x1b[41m', `Mollie payment link: ${createMolliePaymentIntent.url as string}`, '\x1b[0m'); // Remove first orderLine await shopClient.query(ADJUST_ORDER_LINE, { orderLineId: 'T_1', quantity: 0, }); await setShipping(shopClient); // Create another intent after Xs, should update the mollie order await new Promise(resolve => setTimeout(resolve, 5000)); const { createMolliePaymentIntent: secondIntent } = await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { redirectUrl: `${tunnel.url}/admin/orders?filter=open&page=1&dynamicRedirectUrl=true`, paymentMethodCode: 'mollie', }, }); // eslint-disable-next-line no-console console.log('\x1b[41m', `Second payment link: ${secondIntent.url as string}`, '\x1b[0m'); } (async () => { await runMollieDevServer(); })();
import { OrderStatus } from '@mollie/api-client'; import { ChannelService, EventBus, LanguageCode, mergeConfig, OrderPlacedEvent, OrderService, RequestContext, } from '@vendure/core'; import { SettlePaymentMutation, SettlePaymentMutationVariables, } from '@vendure/core/e2e/graphql/generated-e2e-admin-types'; import { SETTLE_PAYMENT } from '@vendure/core/e2e/graphql/shared-definitions'; import { createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN, SimpleGraphQLClient, TestServer, } from '@vendure/testing'; import nock from 'nock'; import fetch from 'node-fetch'; import path from 'path'; import { afterAll, afterEach, 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 { UPDATE_PRODUCT_VARIANTS } from '../../core/e2e/graphql/shared-definitions'; import { MolliePlugin } from '../src/mollie'; import { molliePaymentHandler } from '../src/mollie/mollie.handler'; import { CREATE_PAYMENT_METHOD, GET_CUSTOMER_LIST, GET_ORDER_PAYMENTS } from './graphql/admin-queries'; import { CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables, GetCustomerListQuery, GetCustomerListQueryVariables, } from './graphql/generated-admin-types'; import { AddItemToOrderMutation, AddItemToOrderMutationVariables, GetOrderByCodeQuery, GetOrderByCodeQueryVariables, TestOrderFragmentFragment, } from './graphql/generated-shop-types'; import { ADD_ITEM_TO_ORDER, GET_ORDER_BY_CODE } from './graphql/shop-queries'; import { addManualPayment, CREATE_MOLLIE_PAYMENT_INTENT, GET_MOLLIE_PAYMENT_METHODS, refundOrderLine, setShipping, } from './payment-helpers'; const mockData = { host: 'https://my-vendure.io', redirectUrl: 'https://fallback-redirect/order', apiKey: 'myApiKey', methodCode: `mollie-payment-${E2E_DEFAULT_CHANNEL_TOKEN}`, methodCodeBroken: `mollie-payment-broken-${E2E_DEFAULT_CHANNEL_TOKEN}`, mollieOrderResponse: { id: 'ord_mockId', _links: { checkout: { href: 'https://www.mollie.com/payscreen/select-method/mock-payment', }, }, lines: [], _embedded: { payments: [ { id: 'tr_mockPayment', status: 'paid', resource: 'payment', }, ], }, resource: 'order', metadata: { languageCode: 'nl', }, mode: 'test', method: 'test-method', profileId: '123', settlementAmount: 'test amount', customerId: '456', authorizedAt: new Date(), paidAt: new Date(), }, molliePaymentMethodsResponse: { count: 1, _embedded: { methods: [ { resource: 'method', id: 'ideal', description: 'iDEAL', minimumAmount: { value: '0.01', currency: 'EUR', }, maximumAmount: { value: '50000.00', currency: 'EUR', }, image: { size1x: 'https://www.mollie.com/external/icons/payment-methods/ideal.png', size2x: 'https://www.mollie.com/external/icons/payment-methods/ideal%402x.png', svg: 'https://www.mollie.com/external/icons/payment-methods/ideal.svg', }, _links: { self: { href: 'https://api.mollie.com/v2/methods/ideal', type: 'application/hal+json', }, }, }, ], }, _links: { self: { href: 'https://api.mollie.com/v2/methods', type: 'application/hal+json', }, documentation: { href: 'https://docs.mollie.com/reference/v2/methods-api/list-methods', type: 'text/html', }, }, }, }; let shopClient: SimpleGraphQLClient; let adminClient: SimpleGraphQLClient; let server: TestServer; let started = false; let customers: GetCustomerListQuery['customers']['items']; let order: TestOrderFragmentFragment; let serverPort: number; const SURCHARGE_AMOUNT = -20000; describe('Mollie payments', () => { beforeAll(async () => { const devConfig = mergeConfig(testConfig(), { plugins: [MolliePlugin.init({ vendureHost: mockData.host })], }); const env = createTestEnvironment(devConfig); serverPort = devConfig.apiOptions.port; shopClient = env.shopClient; adminClient = env.adminClient; server = env.server; await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 2, }); started = true; await adminClient.asSuperAdmin(); ({ customers: { items: customers }, } = await adminClient.query<GetCustomerListQuery, GetCustomerListQueryVariables>(GET_CUSTOMER_LIST, { options: { take: 2, }, })); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); afterEach(() => { nock.cleanAll(); }); it('Should start successfully', () => { expect(started).toEqual(true); expect(customers).toHaveLength(2); }); describe('Payment intent creation', () => { it('Should prepare an order', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_5', quantity: 10, }); order = addItemToOrder as TestOrderFragmentFragment; // Add surcharge const ctx = new RequestContext({ apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, channel: await server.app.get(ChannelService).getDefaultChannel(), }); await server.app.get(OrderService).addSurchargeToOrder(ctx, 1, { description: 'Negative test surcharge', listPrice: SURCHARGE_AMOUNT, }); expect(order.code).toBeDefined(); }); it('Should add a Mollie paymentMethod', async () => { const { createPaymentMethod } = await adminClient.query< CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables >(CREATE_PAYMENT_METHOD, { input: { code: mockData.methodCode, enabled: true, handler: { code: molliePaymentHandler.code, arguments: [ { name: 'redirectUrl', value: mockData.redirectUrl }, { name: 'apiKey', value: mockData.apiKey }, { name: 'autoCapture', value: 'false' }, ], }, translations: [ { languageCode: LanguageCode.en, name: 'Mollie payment test', description: 'This is a Mollie test payment method', }, ], }, }); expect(createPaymentMethod.code).toBe(mockData.methodCode); }); it('Should fail to create payment intent without shippingmethod', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { createMolliePaymentIntent: result } = await shopClient.query( CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, }, }, ); expect(result.errorCode).toBe('ORDER_PAYMENT_STATE_ERROR'); }); it('Should fail to create payment intent with invalid Mollie method', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); await setShipping(shopClient); const { createMolliePaymentIntent: result } = await shopClient.query( CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, molliePaymentMethodCode: 'invalid', }, }, ); expect(result.errorCode).toBe('INELIGIBLE_PAYMENT_METHOD_ERROR'); }); it('Should fail to get payment url when items are out of stock', async () => { let { updateProductVariants } = await adminClient.query(UPDATE_PRODUCT_VARIANTS, { input: { id: 'T_5', trackInventory: 'TRUE', outOfStockThreshold: 0, stockOnHand: 1, }, }); expect(updateProductVariants[0].stockOnHand).toBe(1); const { createMolliePaymentIntent: result } = await shopClient.query( CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, }, }, ); expect(result.message).toContain('insufficient stock of Pinelab stickers'); // Set stock back to not tracking ({ updateProductVariants } = await adminClient.query(UPDATE_PRODUCT_VARIANTS, { input: { id: 'T_5', trackInventory: 'FALSE', }, })); expect(updateProductVariants[0].trackInventory).toBe('FALSE'); }); it('Should get payment url without Mollie method', async () => { let mollieRequest: any | undefined; nock('https://api.mollie.com/') .post('/v2/orders', body => { mollieRequest = body; return true; }) .reply(200, mockData.mollieOrderResponse); const { createMolliePaymentIntent } = await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, redirectUrl: 'given-storefront-redirect-url', }, }); expect(createMolliePaymentIntent).toEqual({ url: 'https://www.mollie.com/payscreen/select-method/mock-payment', }); expect(mollieRequest?.orderNumber).toEqual(order.code); expect(mollieRequest?.redirectUrl).toEqual('given-storefront-redirect-url'); expect(mollieRequest?.webhookUrl).toEqual( `${mockData.host}/payments/mollie/${E2E_DEFAULT_CHANNEL_TOKEN}/1`, ); expect(mollieRequest?.amount?.value).toBe('1009.90'); expect(mollieRequest?.amount?.currency).toBe('USD'); expect(mollieRequest.lines[0].vatAmount.value).toEqual('199.98'); let totalLineAmount = 0; for (const line of mollieRequest.lines) { totalLineAmount += Number(line.totalAmount.value); } // Sum of lines should equal order total expect(mollieRequest.amount.value).toEqual(totalLineAmount.toFixed(2)); }); it('Should use fallback redirect appended with order code, when no redirect is given', async () => { let mollieRequest: any | undefined; nock('https://api.mollie.com/') .post('/v2/orders', body => { mollieRequest = body; return true; }) .reply(200, mockData.mollieOrderResponse); await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, }, }); expect(mollieRequest?.redirectUrl).toEqual(`${mockData.redirectUrl}/${order.code}`); }); it('Should get payment url with Mollie method', async () => { nock('https://api.mollie.com/').post('/v2/orders').reply(200, mockData.mollieOrderResponse); await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); await setShipping(shopClient); const { createMolliePaymentIntent } = await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, molliePaymentMethodCode: 'ideal', }, }); expect(createMolliePaymentIntent).toEqual({ url: 'https://www.mollie.com/payscreen/select-method/mock-payment', }); }); it('Should update existing Mollie order', async () => { // Should fetch the existing order from Mollie nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId') .reply(200, mockData.mollieOrderResponse); // Should patch existing order nock('https://api.mollie.com/') .patch(`/v2/orders/${mockData.mollieOrderResponse.id}`) .reply(200, mockData.mollieOrderResponse); // Should patch existing order lines let molliePatchRequest: any | undefined; nock('https://api.mollie.com/') .patch(`/v2/orders/${mockData.mollieOrderResponse.id}/lines`, body => { molliePatchRequest = body; return true; }) .reply(200, mockData.mollieOrderResponse); const { createMolliePaymentIntent } = await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, }, }); // We expect the patch request to add 3 order lines, because the mock response has 0 lines expect(createMolliePaymentIntent.url).toBeDefined(); expect(molliePatchRequest.operations).toBeDefined(); expect(molliePatchRequest.operations[0].operation).toBe('add'); expect(molliePatchRequest.operations[0].data).toHaveProperty('name'); expect(molliePatchRequest.operations[0].data).toHaveProperty('quantity'); expect(molliePatchRequest.operations[0].data).toHaveProperty('unitPrice'); expect(molliePatchRequest.operations[0].data).toHaveProperty('totalAmount'); expect(molliePatchRequest.operations[0].data).toHaveProperty('vatRate'); expect(molliePatchRequest.operations[0].data).toHaveProperty('vatAmount'); expect(molliePatchRequest.operations[1].operation).toBe('add'); expect(molliePatchRequest.operations[2].operation).toBe('add'); }); it('Should get payment url with deducted amount if a payment is already made', async () => { let mollieRequest: any | undefined; nock('https://api.mollie.com/') .post('/v2/orders', body => { mollieRequest = body; return true; }) .reply(200, mockData.mollieOrderResponse); await addManualPayment(server, 1, 10000); await shopClient.query(CREATE_MOLLIE_PAYMENT_INTENT, { input: { paymentMethodCode: mockData.methodCode, }, }); expect(mollieRequest.amount?.value).toBe('909.90'); // minus 100,00 from manual payment let totalLineAmount = 0; for (const line of mollieRequest?.lines) { totalLineAmount += Number(line.totalAmount.value); } // Sum of lines should equal order total expect(mollieRequest.amount.value).toEqual(totalLineAmount.toFixed(2)); }); it('Should create intent as admin', async () => { nock('https://api.mollie.com/').post('/v2/orders').reply(200, mockData.mollieOrderResponse); // Admin API passes order ID, and no payment method code const { createMolliePaymentIntent: intent } = await adminClient.query( CREATE_MOLLIE_PAYMENT_INTENT, { input: { orderId: '1', }, }, ); expect(intent.url).toBe(mockData.mollieOrderResponse._links.checkout.href); }); it('Should get available paymentMethods', async () => { nock('https://api.mollie.com/') .get('/v2/methods?resource=orders') .reply(200, mockData.molliePaymentMethodsResponse); await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { molliePaymentMethods } = await shopClient.query(GET_MOLLIE_PAYMENT_METHODS, { input: { paymentMethodCode: mockData.methodCode, }, }); const method = molliePaymentMethods[0]; expect(method.code).toEqual('ideal'); expect(method.minimumAmount).toBeDefined(); expect(method.maximumAmount).toBeDefined(); expect(method.image).toBeDefined(); }); }); describe('Handle standard payment methods', () => { it('Should transition to ArrangingPayment when partially paid', async () => { nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId') .reply(200, { ...mockData.mollieOrderResponse, // Add a payment of 20.00 amount: { value: '20.00', currency: 'EUR' }, orderNumber: order.code, status: OrderStatus.paid, }); await fetch(`http://localhost:${serverPort}/payments/mollie/${E2E_DEFAULT_CHANNEL_TOKEN}/1`, { method: 'post', body: JSON.stringify({ id: mockData.mollieOrderResponse.id }), headers: { 'Content-Type': 'application/json' }, }); const { order: adminOrder } = await adminClient.query(GET_ORDER_PAYMENTS, { id: order?.id }); expect(adminOrder.state).toBe('ArrangingPayment'); }); let orderPlacedEvent: OrderPlacedEvent | undefined; it('Should place order after paying outstanding amount', async () => { server.app .get(EventBus) .ofType(OrderPlacedEvent) .subscribe(event => { orderPlacedEvent = event; }); nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId') .reply(200, { ...mockData.mollieOrderResponse, // Add a payment of 1089.90 amount: { value: '1089.90', currency: 'EUR' }, // 1109.90 minus the previously paid 20.00 orderNumber: order.code, status: OrderStatus.paid, }); await fetch(`http://localhost:${serverPort}/payments/mollie/${E2E_DEFAULT_CHANNEL_TOKEN}/1`, { method: 'post', body: JSON.stringify({ id: mockData.mollieOrderResponse.id }), headers: { 'Content-Type': 'application/json' }, }); const { orderByCode } = await shopClient.query<GetOrderByCodeQuery, GetOrderByCodeQueryVariables>( GET_ORDER_BY_CODE, { code: order.code, }, ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion order = orderByCode!; expect(order.state).toBe('PaymentSettled'); }); it('Should have preserved original languageCode ', () => { // We've set the languageCode to 'nl' in the mock response's metadata expect(orderPlacedEvent?.ctx.languageCode).toBe('nl'); }); it('Should have Mollie metadata on payment', async () => { const { order: { payments }, } = await adminClient.query(GET_ORDER_PAYMENTS, { id: order.id }); const metadata = payments[1].metadata; expect(metadata.mode).toBe(mockData.mollieOrderResponse.mode); expect(metadata.method).toBe(mockData.mollieOrderResponse.method); expect(metadata.profileId).toBe(mockData.mollieOrderResponse.profileId); expect(metadata.authorizedAt).toEqual(mockData.mollieOrderResponse.authorizedAt.toISOString()); expect(metadata.paidAt).toEqual(mockData.mollieOrderResponse.paidAt.toISOString()); }); it('Should fail to refund', async () => { nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId?embed=payments') .reply(200, mockData.mollieOrderResponse); nock('https://api.mollie.com/') .post('/v2/payments/tr_mockPayment/refunds') .reply(200, { status: 'failed', resource: 'payment' }); const refund = await refundOrderLine( adminClient, order.lines[0].id, 1, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion order!.payments![1].id, SURCHARGE_AMOUNT, ); expect(refund.state).toBe('Failed'); }); it('Should successfully refund the Mollie payment', async () => { let mollieRequest: any; nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId?embed=payments') .reply(200, mockData.mollieOrderResponse); nock('https://api.mollie.com/') .post('/v2/payments/tr_mockPayment/refunds', body => { mollieRequest = body; return true; }) .reply(200, { status: 'pending', resource: 'payment' }); const refund = await refundOrderLine( adminClient, order.lines[0].id, 10, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion order.payments!.find(p => p.amount === 108990)!.id, SURCHARGE_AMOUNT, ); expect(mollieRequest?.amount.value).toBe('999.90'); // Only refund mollie amount, not the gift card expect(refund.total).toBe(99990); expect(refund.state).toBe('Settled'); }); }); describe('Handle pay-later methods', () => { // TODO: Add testcases that mock incoming webhook to: 1. Authorize payment and 2. AutoCapture payments it('Should prepare a new order', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 2, }); order = addItemToOrder as TestOrderFragmentFragment; await setShipping(shopClient); expect(order.code).toBeDefined(); }); it('Should authorize payment for pay-later payment methods', async () => { nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId') .reply(200, { ...mockData.mollieOrderResponse, amount: { value: '3127.60', currency: 'EUR' }, orderNumber: order.code, status: OrderStatus.authorized, }); await fetch(`http://localhost:${serverPort}/payments/mollie/${E2E_DEFAULT_CHANNEL_TOKEN}/1`, { method: 'post', body: JSON.stringify({ id: mockData.mollieOrderResponse.id }), headers: { 'Content-Type': 'application/json' }, }); const { orderByCode } = await shopClient.query<GetOrderByCodeQuery, GetOrderByCodeQueryVariables>( GET_ORDER_BY_CODE, { code: order.code, }, ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion order = orderByCode!; expect(order.state).toBe('PaymentAuthorized'); }); it('Should settle payment via settlePayment mutation', async () => { // Mock the getOrder Mollie call nock('https://api.mollie.com/') .get('/v2/orders/ord_mockId') .reply(200, { ...mockData.mollieOrderResponse, orderNumber: order.code, status: OrderStatus.authorized, }); // Mock the createShipment call let createShipmentBody; nock('https://api.mollie.com/') .post('/v2/orders/ord_mockId/shipments', body => { createShipmentBody = body; return true; }) .reply(200, { resource: 'shipment', lines: [] }); const { settlePayment } = await adminClient.query< SettlePaymentMutation, SettlePaymentMutationVariables >(SETTLE_PAYMENT, { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion id: order.payments![0].id, }); const { orderByCode } = await shopClient.query<GetOrderByCodeQuery, GetOrderByCodeQueryVariables>( GET_ORDER_BY_CODE, { code: order.code, }, ); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion order = orderByCode!; expect(createShipmentBody).toBeDefined(); expect(order.state).toBe('PaymentSettled'); }); it('Should fail to add payment method without redirect url', async () => { let error = ''; try { const { createPaymentMethod } = await adminClient.query< CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables >(CREATE_PAYMENT_METHOD, { input: { code: mockData.methodCodeBroken, enabled: true, handler: { code: molliePaymentHandler.code, arguments: [ { name: 'apiKey', value: mockData.apiKey }, { name: 'autoCapture', value: 'false' }, ], }, translations: [ { languageCode: LanguageCode.en, name: 'Mollie payment test', description: 'This is a Mollie test payment method', }, ], }, }); } catch (e: any) { error = e.message; } expect(error).toBe('The argument "redirectUrl" is required'); }); }); });
import { ID } from '@vendure/common/lib/shared-types'; import { ChannelService, OrderService, PaymentService, RequestContext } from '@vendure/core'; import { SimpleGraphQLClient, TestServer } from '@vendure/testing'; import gql from 'graphql-tag'; import { REFUND_ORDER } from './graphql/admin-queries'; import { RefundFragment, RefundOrderMutation, RefundOrderMutationVariables } from './graphql/generated-admin-types'; import { GetShippingMethodsQuery, SetShippingMethodMutation, SetShippingMethodMutationVariables, TestOrderFragmentFragment, TransitionToStateMutation, TransitionToStateMutationVariables, } from './graphql/generated-shop-types'; import { GET_ELIGIBLE_SHIPPING_METHODS, SET_SHIPPING_ADDRESS, SET_SHIPPING_METHOD, TRANSITION_TO_STATE, } from './graphql/shop-queries'; export async function setShipping(shopClient: SimpleGraphQLClient): Promise<void> { await shopClient.query(SET_SHIPPING_ADDRESS, { input: { fullName: 'name', streetLine1: '12 the street', city: 'Leeuwarden', postalCode: '123456', countryCode: 'AT', }, }); const { eligibleShippingMethods } = await shopClient.query<GetShippingMethodsQuery>( GET_ELIGIBLE_SHIPPING_METHODS, ); await shopClient.query<SetShippingMethodMutation, SetShippingMethodMutationVariables>(SET_SHIPPING_METHOD, { id: eligibleShippingMethods[1].id, }); } export async function proceedToArrangingPayment(shopClient: SimpleGraphQLClient): Promise<ID> { await setShipping(shopClient); const { transitionOrderToState } = await shopClient.query< TransitionToStateMutation, TransitionToStateMutationVariables >(TRANSITION_TO_STATE, { state: 'ArrangingPayment' }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return (transitionOrderToState as TestOrderFragmentFragment)!.id; } export async function refundOrderLine( adminClient: SimpleGraphQLClient, orderLineId: string, quantity: number, paymentId: string, adjustment: number, ): Promise<RefundFragment> { const { refundOrder } = await adminClient.query<RefundOrderMutation, RefundOrderMutationVariables>( REFUND_ORDER, { input: { lines: [{ orderLineId, quantity }], shipping: 0, adjustment, paymentId, }, }, ); return refundOrder as RefundFragment; } /** * Add a partial payment to an order. This happens, for example, when using Gift cards */ export async function addManualPayment(server: TestServer, orderId: ID, amount: number): Promise<void> { const ctx = new RequestContext({ apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, channel: await server.app.get(ChannelService).getDefaultChannel(), }); const order = await server.app.get(OrderService).findOne(ctx, orderId); // tslint:disable-next-line:no-non-null-assertion await server.app.get(PaymentService).createManualPayment(ctx, order!, amount, { method: 'Gift card', // tslint:disable-next-line:no-non-null-assertion orderId: order!.id, metadata: { bogus: 'test', }, }); } export const CREATE_MOLLIE_PAYMENT_INTENT = gql` mutation createMolliePaymentIntent($input: MolliePaymentIntentInput!) { createMolliePaymentIntent(input: $input) { ... on MolliePaymentIntent { url } ... on MolliePaymentIntentError { errorCode message } } } `; export const CREATE_STRIPE_PAYMENT_INTENT = gql` mutation createStripePaymentIntent{ createStripePaymentIntent }`; export const GET_MOLLIE_PAYMENT_METHODS = gql` query molliePaymentMethods($input: MolliePaymentMethodsInput!) { molliePaymentMethods(input: $input) { id code description minimumAmount { value currency } maximumAmount { value currency } image { size1x size2x svg } } } `;
/* eslint-disable */ import { Controller, Res, Get } from '@nestjs/common'; import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { Response } from 'express'; import { clientSecret } from './stripe-dev-server'; /** * This test controller returns the Stripe intent checkout page * with the client secret generated by the dev-server */ @Controller() export class StripeTestCheckoutController { @Get('checkout') async webhook(@Res() res: Response): Promise<void> { res.send(` <head> <title>Checkout</title> <script src="https://js.stripe.com/v3/"></script> </head> <html> <form id="payment-form"> <div id="payment-element"> <!-- Elements will create form elements here --> </div> <button id="submit">Submit</button> <div id="error-message"> <!-- Display error message to your customers here --> </div> </form> <script> // Set your publishable key: remember to change this to your live publishable key in production // See your keys here: https://dashboard.stripe.com/apikeys const stripe = Stripe('${process.env.STRIPE_PUBLISHABLE_KEY}'); const options = { clientSecret: '${clientSecret}', // Fully customizable with appearance API. appearance: {/*...*/}, }; // Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in step 3 const elements = stripe.elements(options); // Create and mount the Payment Element const paymentElement = elements.create('payment'); paymentElement.mount('#payment-element'); const form = document.getElementById('payment-form'); form.addEventListener('submit', async (event) => { event.preventDefault(); // const {error} = await stripe.confirmSetup({ const {error} = await stripe.confirmPayment({ //\`Elements\` instance that was used to create the Payment Element elements, confirmParams: { return_url: 'http://localhost:3050/checkout?success=true', } }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) const messageContainer = document.querySelector('#error-message'); messageContainer.textContent = error.message; } else { // Your customer will be redirected to your \`return_url\`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the \`return_url\`. } }); </script> </html> `); } } /** * Test plugin for serving the Stripe intent checkout page */ @VendurePlugin({ imports: [PluginCommonModule], controllers: [StripeTestCheckoutController], }) export class StripeCheckoutTestPlugin {}
import { AdminUiPlugin } from '@vendure/admin-ui-plugin'; import { ChannelService, DefaultLogger, LanguageCode, Logger, LogLevel, mergeConfig, OrderService, RequestContext, } from '@vendure/core'; import { createTestEnvironment, registerInitializer, SqljsInitializer, testConfig } from '@vendure/testing'; import gql from 'graphql-tag'; import path from 'path'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { StripePlugin } from '../src/stripe'; import { stripePaymentMethodHandler } from '../src/stripe/stripe.handler'; /* eslint-disable */ import { CREATE_PAYMENT_METHOD } from './graphql/admin-queries'; import { CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables, } from './graphql/generated-admin-types'; import { AddItemToOrderMutation, AddItemToOrderMutationVariables } from './graphql/generated-shop-types'; import { ADD_ITEM_TO_ORDER } from './graphql/shop-queries'; import { CREATE_STRIPE_PAYMENT_INTENT, setShipping } from './payment-helpers'; import { StripeCheckoutTestPlugin } from './stripe-checkout-test.plugin'; export let clientSecret: string; /** * The actual starting of the dev server */ (async () => { require('dotenv').config(); registerInitializer('sqljs', new SqljsInitializer(path.join(__dirname, '__data__'))); const config = mergeConfig(testConfig, { plugins: [ ...testConfig.plugins, AdminUiPlugin.init({ route: 'admin', port: 5001, }), StripePlugin.init({}), StripeCheckoutTestPlugin, ], logger: new DefaultLogger({ level: LogLevel.Debug }), }); const { server, shopClient, adminClient } = createTestEnvironment(config as any); await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 1, }); // Create method await adminClient.asSuperAdmin(); await adminClient.query<CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables>( CREATE_PAYMENT_METHOD, { input: { code: 'stripe-payment-method', enabled: true, translations: [ { name: 'Stripe', description: 'This is a Stripe test payment method', languageCode: LanguageCode.en, }, ], handler: { code: stripePaymentMethodHandler.code, arguments: [ { name: 'apiKey', value: process.env.STRIPE_APIKEY! }, { name: 'webhookSecret', value: process.env.STRIPE_WEBHOOK_SECRET! }, ], }, }, }, ); // Prepare order for payment await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test'); await shopClient.query<AddItemToOrderMutation, AddItemToOrderMutationVariables>(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 1, }); const ctx = new RequestContext({ apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, channel: await server.app.get(ChannelService).getDefaultChannel(), }); await server.app.get(OrderService).addSurchargeToOrder(ctx, 1, { description: 'Negative test surcharge', listPrice: -20000, }); await setShipping(shopClient); const { createStripePaymentIntent } = await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); clientSecret = createStripePaymentIntent; Logger.info('http://localhost:3050/checkout', 'Stripe DevServer'); })();
import { describe, expect, it } from 'vitest'; import { sanitizeMetadata } from '../src/stripe/metadata-sanitize'; describe('Stripe Metadata Sanitize', () => { const metadata = { customerEmail: 'test@gmail.com', }; it('should sanitize and create new object metadata', () => { const newMetadata = sanitizeMetadata(metadata); expect(newMetadata).toEqual(metadata); expect(newMetadata).not.toBe(metadata); }); it('should omit fields that have key length exceed 40 characters', () => { const newMetadata = sanitizeMetadata({ ...metadata, reallylongkey_reallylongkey_reallylongkey_reallylongkey_reallylongkey: 1, }); expect(newMetadata).toEqual(metadata); }); it('should omit fields that have value length exceed 500 characters', () => { const reallyLongText = Array(501).fill('a').join(); const newMetadata = sanitizeMetadata({ ...metadata, complexField: reallyLongText, }); expect(newMetadata).toEqual(metadata); }); it('should truncate metadata that have more than 50 keys', () => { const moreThan50KeysMetadata = Array(51) .fill('a') .reduce((obj, val, idx) => { obj[idx] = val; return obj; }, {}); const newMetadata = sanitizeMetadata(moreThan50KeysMetadata); expect(Object.keys(newMetadata).length).toEqual(50); delete moreThan50KeysMetadata['50']; expect(newMetadata).toEqual(moreThan50KeysMetadata); }); });
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { EntityHydrator, mergeConfig } from '@vendure/core'; import { CreateProductMutation, CreateProductMutationVariables, CreateProductVariantsMutation, CreateProductVariantsMutationVariables, } from '@vendure/core/e2e/graphql/generated-e2e-admin-types'; import { CREATE_PRODUCT, CREATE_PRODUCT_VARIANTS } from '@vendure/core/e2e/graphql/shared-definitions'; import { createTestEnvironment, E2E_DEFAULT_CHANNEL_TOKEN } from '@vendure/testing'; import gql from 'graphql-tag'; import nock from 'nock'; import fetch from 'node-fetch'; import path from 'path'; import { Stripe } from 'stripe'; 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 { StripePlugin } from '../src/stripe'; import { stripePaymentMethodHandler } from '../src/stripe/stripe.handler'; import { CREATE_CHANNEL, CREATE_PAYMENT_METHOD, GET_CUSTOMER_LIST } from './graphql/admin-queries'; import { CreateChannelMutation, CreateChannelMutationVariables, CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables, CurrencyCode, GetCustomerListQuery, GetCustomerListQueryVariables, LanguageCode, } from './graphql/generated-admin-types'; import { AddItemToOrderMutation, AddItemToOrderMutationVariables, GetActiveOrderQuery, TestOrderFragmentFragment, } from './graphql/generated-shop-types'; import { ADD_ITEM_TO_ORDER, GET_ACTIVE_ORDER } from './graphql/shop-queries'; import { setShipping } from './payment-helpers'; export const CREATE_STRIPE_PAYMENT_INTENT = gql` mutation createStripePaymentIntent { createStripePaymentIntent } `; describe('Stripe payments', () => { const devConfig = mergeConfig(testConfig(), { plugins: [ StripePlugin.init({ storeCustomersInStripe: true, }), ], }); const { shopClient, adminClient, server } = createTestEnvironment(devConfig); let started = false; let customers: GetCustomerListQuery['customers']['items']; let order: TestOrderFragmentFragment; let serverPort: number; beforeAll(async () => { serverPort = devConfig.apiOptions.port; await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'), customerCount: 2, }); started = true; await adminClient.asSuperAdmin(); ({ customers: { items: customers }, } = await adminClient.query<GetCustomerListQuery, GetCustomerListQueryVariables>(GET_CUSTOMER_LIST, { options: { take: 2, }, })); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('Should start successfully', () => { expect(started).toEqual(true); expect(customers).toHaveLength(2); }); it('Should prepare an order', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 2, }); order = addItemToOrder as TestOrderFragmentFragment; expect(order.code).toBeDefined(); }); it('Should add a Stripe paymentMethod', async () => { const { createPaymentMethod } = await adminClient.query< CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables >(CREATE_PAYMENT_METHOD, { input: { code: `stripe-payment-${E2E_DEFAULT_CHANNEL_TOKEN}`, translations: [ { name: 'Stripe payment test', description: 'This is a Stripe test payment method', languageCode: LanguageCode.en, }, ], enabled: true, handler: { code: stripePaymentMethodHandler.code, arguments: [ { name: 'apiKey', value: 'test-api-key' }, { name: 'webhookSecret', value: 'test-signing-secret' }, ], }, }, }); expect(createPaymentMethod.code).toBe(`stripe-payment-${E2E_DEFAULT_CHANNEL_TOKEN}`); await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); await setShipping(shopClient); }); it('if no customer id exists, makes a call to create', async () => { let createCustomerPayload: { name: string; email: string } | undefined; const emptyList = { data: [] }; nock('https://api.stripe.com/') .get(/\/v1\/customers.*/) .reply(200, emptyList); nock('https://api.stripe.com/') .post('/v1/customers', body => { createCustomerPayload = body; return true; }) .reply(201, { id: 'new-customer-id', }); nock('https://api.stripe.com/').post('/v1/payment_intents').reply(200, { client_secret: 'test-client-secret', }); const { createStripePaymentIntent } = await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); expect(createCustomerPayload).toEqual({ email: 'hayden.zieme12@hotmail.com', name: 'Hayden Zieme', }); }); it('should send correct payload to create payment intent', async () => { let createPaymentIntentPayload: any; const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); nock('https://api.stripe.com/') .post('/v1/payment_intents', body => { createPaymentIntentPayload = body; return true; }) .reply(200, { client_secret: 'test-client-secret', }); const { createStripePaymentIntent } = await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); expect(createPaymentIntentPayload).toEqual({ amount: activeOrder?.totalWithTax.toString(), currency: activeOrder?.currencyCode?.toLowerCase(), customer: 'new-customer-id', 'automatic_payment_methods[enabled]': 'true', 'metadata[channelToken]': E2E_DEFAULT_CHANNEL_TOKEN, 'metadata[orderId]': '1', 'metadata[orderCode]': activeOrder?.code, }); expect(createStripePaymentIntent).toEqual('test-client-secret'); }); // https://github.com/vendure-ecommerce/vendure/issues/1935 it('should attach metadata to stripe payment intent', async () => { StripePlugin.options.metadata = async (injector, ctx, currentOrder) => { const hydrator = injector.get(EntityHydrator); await hydrator.hydrate(ctx, currentOrder, { relations: ['customer'] }); return { customerEmail: currentOrder.customer?.emailAddress ?? 'demo', }; }; let createPaymentIntentPayload: any; const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); nock('https://api.stripe.com/') .post('/v1/payment_intents', body => { createPaymentIntentPayload = body; return true; }) .reply(200, { client_secret: 'test-client-secret', }); const { createStripePaymentIntent } = await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); expect(createPaymentIntentPayload).toEqual({ amount: activeOrder?.totalWithTax.toString(), currency: activeOrder?.currencyCode?.toLowerCase(), customer: 'new-customer-id', 'automatic_payment_methods[enabled]': 'true', 'metadata[channelToken]': E2E_DEFAULT_CHANNEL_TOKEN, 'metadata[orderId]': '1', 'metadata[orderCode]': activeOrder?.code, 'metadata[customerEmail]': customers[0].emailAddress, }); expect(createStripePaymentIntent).toEqual('test-client-secret'); StripePlugin.options.metadata = undefined; }); // https://github.com/vendure-ecommerce/vendure/issues/2412 it('should attach additional params to payment intent using paymentIntentCreateParams', async () => { StripePlugin.options.paymentIntentCreateParams = async (injector, ctx, currentOrder) => { const hydrator = injector.get(EntityHydrator); await hydrator.hydrate(ctx, currentOrder, { relations: ['customer'] }); return { description: `Order #${currentOrder.code} for ${currentOrder.customer!.emailAddress}`, }; }; let createPaymentIntentPayload: any; const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); nock('https://api.stripe.com/') .post('/v1/payment_intents', body => { createPaymentIntentPayload = body; return true; }) .reply(200, { client_secret: 'test-client-secret', }); const { createStripePaymentIntent } = await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); expect(createPaymentIntentPayload).toEqual({ amount: activeOrder?.totalWithTax.toString(), currency: activeOrder?.currencyCode?.toLowerCase(), customer: 'new-customer-id', description: `Order #${activeOrder!.code} for ${activeOrder!.customer!.emailAddress}`, 'automatic_payment_methods[enabled]': 'true', 'metadata[channelToken]': E2E_DEFAULT_CHANNEL_TOKEN, 'metadata[orderId]': '1', 'metadata[orderCode]': activeOrder?.code, }); expect(createStripePaymentIntent).toEqual('test-client-secret'); StripePlugin.options.paymentIntentCreateParams = undefined; }); // https://github.com/vendure-ecommerce/vendure/issues/2412 it('should attach additional params to customer using customerCreateParams', async () => { StripePlugin.options.customerCreateParams = async (injector, ctx, currentOrder) => { const hydrator = injector.get(EntityHydrator); await hydrator.hydrate(ctx, currentOrder, { relations: ['customer'] }); return { description: `Description for ${currentOrder.customer!.emailAddress}`, phone: '12345', }; }; await shopClient.asUserWithCredentials(customers[1].emailAddress, 'test'); const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: 'T_1', quantity: 2, }); order = addItemToOrder as TestOrderFragmentFragment; let createCustomerPayload: { name: string; email: string } | undefined; const emptyList = { data: [] }; nock('https://api.stripe.com/') .get(/\/v1\/customers.*/) .reply(200, emptyList); nock('https://api.stripe.com/') .post('/v1/customers', body => { createCustomerPayload = body; return true; }) .reply(201, { id: 'new-customer-id', }); nock('https://api.stripe.com/').post('/v1/payment_intents').reply(200, { client_secret: 'test-client-secret', }); const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); expect(createCustomerPayload).toEqual({ email: 'trevor_donnelly96@hotmail.com', name: 'Trevor Donnelly', description: `Description for ${activeOrder!.customer!.emailAddress}`, phone: '12345', }); }); // https://github.com/vendure-ecommerce/vendure/issues/2450 it('Should not crash on signature validation failure', async () => { const MOCKED_WEBHOOK_PAYLOAD = { id: 'evt_0', object: 'event', api_version: '2022-11-15', data: { object: { id: 'pi_0', currency: 'usd', status: 'succeeded', }, }, livemode: false, pending_webhooks: 1, request: { id: 'req_0', idempotency_key: '00000000-0000-0000-0000-000000000000', }, type: 'payment_intent.succeeded', }; const payloadString = JSON.stringify(MOCKED_WEBHOOK_PAYLOAD, null, 2); const result = await fetch(`http://localhost:${serverPort}/payments/stripe`, { method: 'post', body: payloadString, headers: { 'Content-Type': 'application/json' }, }); // We didn't provided any signatures, it should result in a 400 - Bad request expect(result.status).toEqual(400); }); // TODO: Contribution welcome: test webhook handling and order settlement // https://github.com/vendure-ecommerce/vendure/issues/2450 it("Should validate the webhook's signature properly", async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); order = activeOrder!; const MOCKED_WEBHOOK_PAYLOAD = { id: 'evt_0', object: 'event', api_version: '2022-11-15', data: { object: { id: 'pi_0', currency: 'usd', metadata: { orderCode: order.code, orderId: parseInt(order.id.replace('T_', ''), 10), channelToken: E2E_DEFAULT_CHANNEL_TOKEN, }, amount_received: order.totalWithTax, status: 'succeeded', }, }, livemode: false, pending_webhooks: 1, request: { id: 'req_0', idempotency_key: '00000000-0000-0000-0000-000000000000', }, type: 'payment_intent.succeeded', }; const payloadString = JSON.stringify(MOCKED_WEBHOOK_PAYLOAD, null, 2); const stripeWebhooks = new Stripe('test-api-secret', { apiVersion: '2023-08-16' }).webhooks; const header = stripeWebhooks.generateTestHeaderString({ payload: payloadString, secret: 'test-signing-secret', }); const event = stripeWebhooks.constructEvent(payloadString, header, 'test-signing-secret'); expect(event.id).to.equal(MOCKED_WEBHOOK_PAYLOAD.id); await setShipping(shopClient); // Due to the `this.orderService.transitionToState(...)` fails with the internal lookup by id, // we need to put the order into `ArrangingPayment` state manually before calling the webhook handler. // const transitionResult = await adminClient.query(TRANSITION_TO_ARRANGING_PAYMENT, { id: order.id }); // expect(transitionResult.transitionOrderToState.__typename).toBe('Order') const result = await fetch(`http://localhost:${serverPort}/payments/stripe`, { method: 'post', body: payloadString, headers: { 'Content-Type': 'application/json', 'Stripe-Signature': header }, }); // I would expect to the status to be 200, but at the moment either the // `orderService.transitionToState()` or the `orderService.addPaymentToOrder()` // throws an error of 'error.entity-with-id-not-found' expect(result.status).toEqual(200); }); // https://github.com/vendure-ecommerce/vendure/issues/1630 describe('currencies with no fractional units', () => { let japanProductId: string; beforeAll(async () => { const JAPAN_CHANNEL_TOKEN = 'japan-channel-token'; const { createChannel } = await adminClient.query< CreateChannelMutation, CreateChannelMutationVariables >(CREATE_CHANNEL, { input: { code: 'japan-channel', currencyCode: CurrencyCode.JPY, token: JAPAN_CHANNEL_TOKEN, defaultLanguageCode: LanguageCode.en, defaultShippingZoneId: 'T_1', defaultTaxZoneId: 'T_1', pricesIncludeTax: true, }, }); adminClient.setChannelToken(JAPAN_CHANNEL_TOKEN); shopClient.setChannelToken(JAPAN_CHANNEL_TOKEN); const { createProduct } = await adminClient.query< CreateProductMutation, CreateProductMutationVariables >(CREATE_PRODUCT, { input: { translations: [ { languageCode: LanguageCode.en, name: 'Channel Product', slug: 'channel-product', description: 'Channel product', }, ], }, }); const { createProductVariants } = await adminClient.query< CreateProductVariantsMutation, CreateProductVariantsMutationVariables >(CREATE_PRODUCT_VARIANTS, { input: [ { productId: createProduct.id, sku: 'PV1', optionIds: [], price: 5000, stockOnHand: 100, translations: [{ languageCode: LanguageCode.en, name: 'Variant 1' }], }, ], }); japanProductId = createProductVariants[0]!.id; // Create a payment method for the Japan channel await adminClient.query<CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables>( CREATE_PAYMENT_METHOD, { input: { code: `stripe-payment-${E2E_DEFAULT_CHANNEL_TOKEN}`, translations: [ { name: 'Stripe payment test', description: 'This is a Stripe test payment method', languageCode: LanguageCode.en, }, ], enabled: true, handler: { code: stripePaymentMethodHandler.code, arguments: [ { name: 'apiKey', value: 'test-api-key' }, { name: 'webhookSecret', value: 'test-signing-secret' }, ], }, }, }, ); }); it('prepares order', async () => { await shopClient.asUserWithCredentials(customers[0].emailAddress, 'test'); const { addItemToOrder } = await shopClient.query< AddItemToOrderMutation, AddItemToOrderMutationVariables >(ADD_ITEM_TO_ORDER, { productVariantId: japanProductId, quantity: 1, }); expect((addItemToOrder as any).totalWithTax).toBe(5000); }); it('sends correct amount when creating payment intent', async () => { let createPaymentIntentPayload: any; const { activeOrder } = await shopClient.query<GetActiveOrderQuery>(GET_ACTIVE_ORDER); nock('https://api.stripe.com/') .post('/v1/payment_intents', body => { createPaymentIntentPayload = body; return true; }) .reply(200, { client_secret: 'test-client-secret', }); const { createStripePaymentIntent } = await shopClient.query(CREATE_STRIPE_PAYMENT_INTENT); expect(createPaymentIntentPayload.amount).toBe((activeOrder!.totalWithTax / 100).toString()); expect(createPaymentIntentPayload.currency).toBe('jpy'); }); }); });
import { CHANNEL_FRAGMENT } from '@vendure/core/e2e/graphql/fragments'; import gql from 'graphql-tag'; export const PAYMENT_METHOD_FRAGMENT = gql` fragment PaymentMethod on PaymentMethod { id code name description enabled checker { code args { name value } } handler { code args { name value } } } `; export const CREATE_PAYMENT_METHOD = gql` mutation CreatePaymentMethod($input: CreatePaymentMethodInput!) { createPaymentMethod(input: $input) { ...PaymentMethod } } ${PAYMENT_METHOD_FRAGMENT} `; export const GET_CUSTOMER_LIST = gql` query GetCustomerList($options: CustomerListOptions) { customers(options: $options) { items { id title firstName lastName emailAddress phoneNumber user { id verified } } totalItems } } `; const REFUND_FRAGMENT = gql` fragment Refund on Refund { id state items transactionId shipping total metadata } `; export const REFUND_ORDER = gql` mutation RefundOrder($input: RefundOrderInput!) { refundOrder(input: $input) { ...Refund ... on ErrorResult { errorCode message } } } ${REFUND_FRAGMENT} `; export const GET_ORDER_PAYMENTS = gql` query order($id: ID!) { order(id: $id) { id state totalWithTax payments { id transactionId method amount state errorMessage metadata } } } `; export const CREATE_CHANNEL = gql` mutation CreateChannel($input: CreateChannelInput!) { createChannel(input: $input) { ... on Channel { id code token currencyCode } ... on ErrorResult { errorCode message } } } `;
/* eslint-disable */ import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<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; output: string; } 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 & { 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 = { 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 & { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; refundId: Scalars['ID']['output']; }; export type ApplyCouponCodeResult = CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError | Order; export type Asset = Node & { 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 & { 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 & { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; paymentErrorMessage: Scalars['String']['output']; }; export type CancelPaymentResult = CancelPaymentError | Payment | PaymentStateTransitionError; export type Cancellation = Node & StockMovement & { 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 & { 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 & { 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 & { 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 & { 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 = { 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 & { 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 = { 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 = { 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 = { name: Scalars['String']['output']; value: Scalars['String']['output']; }; export type 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 = { args: Array<ConfigArg>; code: Scalars['String']['output']; }; export type 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 = { x: Scalars['Float']['output']; y: Scalars['Float']['output']; }; export type CoordinateInput = { x: Scalars['Float']['input']; y: Scalars['Float']['input']; }; export type Country = Node & Region & { 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 & { 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 & { couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeInvalidError = ErrorResult & { couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeLimitError = ErrorResult & { 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 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 & { 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 = { channels: Array<CurrentUserChannel>; id: Scalars['ID']['output']; identifier: Scalars['String']['output']; }; export type 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 = { 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 & { 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 & { 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 & { 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 & { 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 & { 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 = { 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 = { adjustmentSource: Scalars['String']['output']; amount: Scalars['Money']['output']; amountWithTax: Scalars['Money']['output']; description: Scalars['String']['output']; type: AdjustmentType; }; export type DuplicateEntityError = ErrorResult & { 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if no OrderLines have been specified for the operation */ export type EmptyOrderLineSelectionError = ErrorResult & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type EntityCustomFields = { customFields: Array<CustomFieldConfig>; entityName: Scalars['String']['output']; }; export type 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 & { 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 & { errorCode: ErrorCode; facetCode: Scalars['String']['output']; message: Scalars['String']['output']; productCount: Scalars['Int']['output']; variantCount: Scalars['Int']['output']; }; export type FacetList = PaginatedList & { 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 = { 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 & { 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 & { 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 = { 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 = { 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 & { 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 & { 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 = { 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 & { 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 = { 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 & { errorCode: ErrorCode; errorDetail: Scalars['String']['output']; message: Scalars['String']['output']; }; export type HistoryEntry = Node & { 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 & { 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to add more items to the Order than are available */ export type InsufficientStockError = ErrorResult & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; productVariantId: Scalars['ID']['output']; productVariantName: Scalars['String']['output']; stockOnHand: Scalars['Int']['output']; }; export type IntCustomFieldConfig = CustomField & { 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 & { authenticationError: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the specified FulfillmentHandler code is not valid */ export type InvalidFulfillmentHandlerError = ErrorResult & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the specified items are already part of a Fulfillment */ export type ItemsAlreadyFulfilledError = ErrorResult & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type Job = Node & { 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 = { 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 & { 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 = { 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 & { errorCode: ErrorCode; languageCode: Scalars['String']['output']; message: Scalars['String']['output']; }; export type LocaleStringCustomFieldConfig = CustomField & { 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 & { 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export enum MetricInterval { Daily = 'Daily' } export type MetricSummary = { entries: Array<MetricSummaryEntry>; interval: MetricInterval; title: Scalars['String']['output']; type: MetricType; }; export type 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when a call to modifyOrder fails to specify any changes */ export type NoChangesSpecifiedError = ErrorResult & { 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 & { 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 & { /** 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 = { 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 & { errorCode: ErrorCode; maxItems: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type OrderLine = Node & { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type 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 & { 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 = { /** 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 & { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when there is an error in transitioning the Payment state */ export type PaymentStateTransitionError = ErrorResult & { 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 = { 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 = { max: Scalars['Money']['output']; min: Scalars['Money']['output']; }; export type Product = Node & { 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 & { 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 & { 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 & { 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; optionGroupCode: Scalars['String']['output']; productVariantCount: Scalars['Int']['output']; }; export type 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 = { 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 & { 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 & { 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 = { 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 = { 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 & { 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 & { 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 = { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type 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 & { 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 & { errorCode: ErrorCode; maximumRefundable: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when there is an error in transitioning the Refund state */ export type RefundStateTransitionError = ErrorResult & { 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 = { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type RelationCustomFieldConfig = CustomField & { 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 & { 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 & { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type Role = Node & { 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 & { 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 & { 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 = { success: Scalars['Boolean']['output']; }; export type SearchResponse = { collections: Array<CollectionResult>; facetValues: Array<FacetValueResult>; items: Array<SearchResult>; totalItems: Scalars['Int']['output']; }; export type 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 = { 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 & { 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 & { 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 = { /** * 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 & { 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 = { 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 & { 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 & { 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 = { 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 = { 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 = { value: Scalars['Money']['output']; }; export enum SortOrder { ASC = 'ASC', DESC = 'DESC' } export type StockAdjustment = Node & StockMovement & { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; productVariant: ProductVariant; quantity: Scalars['Int']['output']; type: StockMovementType; updatedAt: Scalars['DateTime']['output']; }; export type StockLevel = Node & { 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 & { 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 & { 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 = { 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 & { 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 = { 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 = { success: Scalars['Boolean']['output']; }; export type Surcharge = Node & { 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 & { 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 & { 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 & { 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 & { 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 = { description: Scalars['String']['output']; taxRate: Scalars['Float']['output']; }; export type TaxRate = Node & { 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 & { 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 = { metadata?: Maybe<Scalars['JSON']['output']>; price: Scalars['Money']['output']; priceWithTax: Scalars['Money']['output']; }; export type TestShippingMethodResult = { eligible: Scalars['Boolean']['output']; quote?: Maybe<TestShippingMethodQuote>; }; export type TextCustomFieldConfig = 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 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']>; }; 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 & { 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 & { 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 & { 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>; }; export type PaymentMethodFragment = { id: string, code: string, name: string, description: string, enabled: boolean, checker?: { code: string, args: Array<{ name: string, value: string }> } | null, handler: { code: string, args: Array<{ name: string, value: string }> } }; export type CreatePaymentMethodMutationVariables = Exact<{ input: CreatePaymentMethodInput; }>; export type CreatePaymentMethodMutation = { createPaymentMethod: { id: string, code: string, name: string, description: string, enabled: boolean, checker?: { code: string, args: Array<{ name: string, value: string }> } | null, handler: { code: string, args: Array<{ name: string, value: string }> } } }; export type GetCustomerListQueryVariables = Exact<{ options?: InputMaybe<CustomerListOptions>; }>; export type GetCustomerListQuery = { customers: { totalItems: number, items: Array<{ id: string, title?: string | null, firstName: string, lastName: string, emailAddress: string, phoneNumber?: string | null, user?: { id: string, verified: boolean } | null }> } }; export type RefundFragment = { id: string, state: string, items: number, transactionId?: string | null, shipping: number, total: number, metadata?: any | null }; export type RefundOrderMutationVariables = Exact<{ input: RefundOrderInput; }>; export type RefundOrderMutation = { refundOrder: { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } | { id: string, state: string, items: number, transactionId?: string | null, shipping: number, total: number, metadata?: any | null } | { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } | { errorCode: ErrorCode, message: string } }; export type OrderQueryVariables = Exact<{ id: Scalars['ID']['input']; }>; export type OrderQuery = { order?: { id: string, state: string, totalWithTax: number, payments?: Array<{ id: string, transactionId?: string | null, method: string, amount: number, state: string, errorMessage?: string | null, metadata?: any | null }> | null } | null }; export type CreateChannelMutationVariables = Exact<{ input: CreateChannelInput; }>; export type CreateChannelMutation = { createChannel: { id: string, code: string, token: string, currencyCode: CurrencyCode } | { errorCode: ErrorCode, message: string } }; export const PaymentMethodFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PaymentMethod"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PaymentMethod"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"enabled"}},{"kind":"Field","name":{"kind":"Name","value":"checker"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"args"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"handler"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"args"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]} as unknown as DocumentNode<PaymentMethodFragment, unknown>; export const RefundFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"Refund"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Refund"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"items"}},{"kind":"Field","name":{"kind":"Name","value":"transactionId"}},{"kind":"Field","name":{"kind":"Name","value":"shipping"}},{"kind":"Field","name":{"kind":"Name","value":"total"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}}]} as unknown as DocumentNode<RefundFragment, unknown>; export const CreatePaymentMethodDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreatePaymentMethod"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreatePaymentMethodInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createPaymentMethod"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PaymentMethod"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PaymentMethod"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PaymentMethod"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"enabled"}},{"kind":"Field","name":{"kind":"Name","value":"checker"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"args"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"handler"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"args"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]} as unknown as DocumentNode<CreatePaymentMethodMutation, CreatePaymentMethodMutationVariables>; export const GetCustomerListDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCustomerList"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"options"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CustomerListOptions"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customers"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"options"},"value":{"kind":"Variable","name":{"kind":"Name","value":"options"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"emailAddress"}},{"kind":"Field","name":{"kind":"Name","value":"phoneNumber"}},{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"verified"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalItems"}}]}}]}}]} as unknown as DocumentNode<GetCustomerListQuery, GetCustomerListQueryVariables>; export const RefundOrderDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RefundOrder"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RefundOrderInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"refundOrder"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"Refund"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ErrorResult"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"errorCode"}},{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"Refund"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Refund"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"items"}},{"kind":"Field","name":{"kind":"Name","value":"transactionId"}},{"kind":"Field","name":{"kind":"Name","value":"shipping"}},{"kind":"Field","name":{"kind":"Name","value":"total"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}}]} as unknown as DocumentNode<RefundOrderMutation, RefundOrderMutationVariables>; export const OrderDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"order"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"order"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"totalWithTax"}},{"kind":"Field","name":{"kind":"Name","value":"payments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"transactionId"}},{"kind":"Field","name":{"kind":"Name","value":"method"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}}]}}]}}]} as unknown as DocumentNode<OrderQuery, OrderQueryVariables>; export const CreateChannelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateChannel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateChannelInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createChannel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Channel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"currencyCode"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ErrorResult"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"errorCode"}},{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}}]} as unknown as DocumentNode<CreateChannelMutation, CreateChannelMutationVariables>;
/* eslint-disable */ import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<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; output: string }; 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 & { 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type ApplyCouponCodeResult = | CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError | Order; export type Asset = Node & { 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 & { 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 & { 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 & { 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 & { 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 & { 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 = { 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 & { 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 = { 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 = { 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 = { name: Scalars['String']['output']; value: Scalars['String']['output']; }; export type 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 = { args: Array<ConfigArg>; code: Scalars['String']['output']; }; export type 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 = { x: Scalars['Float']['output']; y: Scalars['Float']['output']; }; export type Country = Node & Region & { 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 & { items: Array<Country>; totalItems: Scalars['Int']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeExpiredError = ErrorResult & { couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeInvalidError = ErrorResult & { couponCode: Scalars['String']['output']; errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned if the provided coupon code is invalid */ export type CouponCodeLimitError = ErrorResult & { 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 = { channels: Array<CurrentUserChannel>; id: Scalars['ID']['output']; identifier: Scalars['String']['output']; }; export type 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 & { 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 & { 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 & { 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 & { 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 = { 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 = { 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 & { 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 & { 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 & { 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 = { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type FacetValue = Node & { 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 & { 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 = { 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 = { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type FloatCustomFieldConfig = CustomField & { 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 & { 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 = { 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 & { errorCode: ErrorCode; errorDetail: Scalars['String']['output']; message: Scalars['String']['output']; }; export type HistoryEntry = Node & { 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 & { 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 & { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; /** Returned when attempting to add more items to the Order than are available */ export type InsufficientStockError = ErrorResult & { errorCode: ErrorCode; message: Scalars['String']['output']; order: Order; quantityAvailable: Scalars['Int']['output']; }; export type IntCustomFieldConfig = CustomField & { 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 & { 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 & { 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 & { 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 = { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type 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 & { 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 & { 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 & { 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 & { 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 & { /** 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 = { 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 & { errorCode: ErrorCode; maxItems: Scalars['Int']['output']; message: Scalars['String']['output']; }; export type OrderLine = Node & { 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 & { 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 & { 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 & { 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 & { 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 = { /** 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 & { 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; validationErrorMessage: Scalars['String']['output']; }; export type Payment = Node & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; paymentErrorMessage: Scalars['String']['output']; }; /** Returned when a Payment fails due to an error. */ export type PaymentFailedError = ErrorResult & { 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 & { 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 = { 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 = { 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 = { max: Scalars['Money']['output']; min: Scalars['Money']['output']; }; export type Product = Node & { 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 & { 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 & { 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 & { 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 = { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type 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 = { 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 & { 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 & { 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 = { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; languageCode: LanguageCode; name: Scalars['String']['output']; updatedAt: Scalars['DateTime']['output']; }; export type Promotion = Node & { 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 & { items: Array<Promotion>; totalItems: Scalars['Int']['output']; }; export type 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 & { 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 & { items: Array<Province>; totalItems: Scalars['Int']['output']; }; export type 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 & { 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 = { 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 = { 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 & { 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 & { 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 & { 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 = { success: Scalars['Boolean']['output']; }; export type SearchResponse = { collections: Array<CollectionResult>; facetValues: Array<FacetValueResult>; items: Array<SearchResult>; totalItems: Scalars['Int']['output']; }; export type 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 = { 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 & { 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 = { 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 & { 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 & { items: Array<ShippingMethod>; totalItems: Scalars['Int']['output']; }; export type 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 = { 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 = { value: Scalars['Money']['output']; }; export enum SortOrder { ASC = 'ASC', DESC = 'DESC', } export type StringCustomFieldConfig = CustomField & { 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 = { 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 = { success: Scalars['Boolean']['output']; }; export type Surcharge = Node & { 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 & { createdAt: Scalars['DateTime']['output']; id: Scalars['ID']['output']; updatedAt: Scalars['DateTime']['output']; value: Scalars['String']['output']; }; export type TagList = PaginatedList & { items: Array<Tag>; totalItems: Scalars['Int']['output']; }; export type TaxCategory = Node & { 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 = { description: Scalars['String']['output']; taxRate: Scalars['Float']['output']; }; export type TaxRate = Node & { 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 & { items: Array<TaxRate>; totalItems: Scalars['Int']['output']; }; export type TextCustomFieldConfig = 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 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 & { 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 & { 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 & { errorCode: ErrorCode; message: Scalars['String']['output']; }; export type VerifyCustomerAccountResult = | CurrentUser | MissingPasswordError | NativeAuthStrategyError | PasswordAlreadySetError | PasswordValidationError | VerificationTokenExpiredError | VerificationTokenInvalidError; export type Zone = Node & { 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 TestOrderFragmentFragment = { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; }; export type AddPaymentToOrderMutationVariables = Exact<{ input: PaymentInput; }>; export type AddPaymentToOrderMutation = { addPaymentToOrder: | { errorCode: ErrorCode; message: string; eligibilityCheckerMessage?: string | null } | { errorCode: ErrorCode; message: string } | { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; } | { errorCode: ErrorCode; message: string } | { errorCode: ErrorCode; message: string; transitionError: string } | { errorCode: ErrorCode; message: string; paymentErrorMessage: string } | { errorCode: ErrorCode; message: string; paymentErrorMessage: string }; }; export type SetShippingAddressMutationVariables = Exact<{ input: CreateAddressInput; }>; export type SetShippingAddressMutation = { setOrderShippingAddress: | { errorCode: ErrorCode; message: string } | { shippingAddress?: { fullName?: string | null; company?: string | null; streetLine1?: string | null; streetLine2?: string | null; city?: string | null; province?: string | null; postalCode?: string | null; country?: string | null; phoneNumber?: string | null; } | null; }; }; export type GetShippingMethodsQueryVariables = Exact<{ [key: string]: never }>; export type GetShippingMethodsQuery = { eligibleShippingMethods: Array<{ id: string; code: string; price: number; name: string; description: string; }>; }; export type TransitionToStateMutationVariables = Exact<{ state: Scalars['String']['input']; }>; export type TransitionToStateMutation = { transitionOrderToState?: | { id: string } | { errorCode: ErrorCode; message: string; transitionError: string; fromState: string; toState: string; } | null; }; export type SetShippingMethodMutationVariables = Exact<{ id: Array<Scalars['ID']['input']> | Scalars['ID']['input']; }>; export type SetShippingMethodMutation = { setOrderShippingMethod: | { errorCode: ErrorCode; message: string } | { errorCode: ErrorCode; message: string } | { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; } | { errorCode: ErrorCode; message: string }; }; export type AddItemToOrderMutationVariables = Exact<{ productVariantId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }>; export type AddItemToOrderMutation = { addItemToOrder: | { errorCode: ErrorCode; message: string; quantityAvailable: number; order: { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; }; } | { errorCode: ErrorCode; message: string } | { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; } | { errorCode: ErrorCode; message: string } | { errorCode: ErrorCode; message: string }; }; export type AdjustOrderLineMutationVariables = Exact<{ orderLineId: Scalars['ID']['input']; quantity: Scalars['Int']['input']; }>; export type AdjustOrderLineMutation = { adjustOrderLine: | { errorCode: ErrorCode; message: string; quantityAvailable: number; order: { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; }; } | { errorCode: ErrorCode; message: string } | { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; } | { errorCode: ErrorCode; message: string } | { errorCode: ErrorCode; message: string }; }; export type GetOrderByCodeQueryVariables = Exact<{ code: Scalars['String']['input']; }>; export type GetOrderByCodeQuery = { orderByCode?: { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; } | null; }; export type GetActiveOrderQueryVariables = Exact<{ [key: string]: never }>; export type GetActiveOrderQuery = { activeOrder?: { id: string; code: string; state: string; active: boolean; subTotal: number; subTotalWithTax: number; shipping: number; shippingWithTax: number; total: number; totalWithTax: number; currencyCode: CurrencyCode; couponCodes: Array<string>; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; payments?: Array<{ id: string; transactionId?: string | null; method: string; amount: number; state: string; metadata?: any | null; }> | null; lines: Array<{ id: string; quantity: number; linePrice: number; linePriceWithTax: number; unitPrice: number; unitPriceWithTax: number; unitPriceChangeSinceAdded: number; unitPriceWithTaxChangeSinceAdded: number; proratedUnitPriceWithTax: number; productVariant: { id: string }; discounts: Array<{ adjustmentSource: string; amount: number; amountWithTax: number; description: string; type: AdjustmentType; }>; }>; shippingLines: Array<{ shippingMethod: { id: string; code: string; description: string } }>; customer?: { id: string; emailAddress: string; user?: { id: string; identifier: string } | null; } | null; history: { items: Array<{ id: string; type: HistoryEntryType; data: any }> }; } | null; }; export const TestOrderFragmentFragmentDoc = { kind: 'Document', definitions: [ { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<TestOrderFragmentFragment, unknown>; export const AddPaymentToOrderDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'AddPaymentToOrder' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'PaymentInput' } }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'addPaymentToOrder' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment' }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'ErrorResult' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'errorCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'message' } }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'PaymentDeclinedError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'paymentErrorMessage' }, }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'PaymentFailedError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'paymentErrorMessage' }, }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'OrderStateTransitionError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'transitionError' }, }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'IneligiblePaymentMethodError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'eligibilityCheckerMessage' }, }, ], }, }, ], }, }, ], }, }, { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<AddPaymentToOrderMutation, AddPaymentToOrderMutationVariables>; export const SetShippingAddressDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'SetShippingAddress' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'CreateAddressInput' } }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'setOrderShippingAddress' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'input' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'input' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingAddress' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'fullName' }, }, { kind: 'Field', name: { kind: 'Name', value: 'company' }, }, { kind: 'Field', name: { kind: 'Name', value: 'streetLine1' }, }, { kind: 'Field', name: { kind: 'Name', value: 'streetLine2' }, }, { kind: 'Field', name: { kind: 'Name', value: 'city' }, }, { kind: 'Field', name: { kind: 'Name', value: 'province' }, }, { kind: 'Field', name: { kind: 'Name', value: 'postalCode' }, }, { kind: 'Field', name: { kind: 'Name', value: 'country' }, }, { kind: 'Field', name: { kind: 'Name', value: 'phoneNumber' }, }, ], }, }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'ErrorResult' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'errorCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'message' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<SetShippingAddressMutation, SetShippingAddressMutationVariables>; export const GetShippingMethodsDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'GetShippingMethods' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'eligibleShippingMethods' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'price' } }, { kind: 'Field', name: { kind: 'Name', value: 'name' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, ], } as unknown as DocumentNode<GetShippingMethodsQuery, GetShippingMethodsQueryVariables>; export const TransitionToStateDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'TransitionToState' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'state' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'transitionOrderToState' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'state' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'state' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' }, }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'OrderStateTransitionError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'errorCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'message' } }, { kind: 'Field', name: { kind: 'Name', value: 'transitionError' }, }, { kind: 'Field', name: { kind: 'Name', value: 'fromState' } }, { kind: 'Field', name: { kind: 'Name', value: 'toState' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<TransitionToStateMutation, TransitionToStateMutationVariables>; export const SetShippingMethodDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'SetShippingMethod' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, type: { kind: 'NonNullType', type: { kind: 'ListType', type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, }, }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'setOrderShippingMethod' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'shippingMethodId' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment' }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'ErrorResult' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'errorCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'message' } }, ], }, }, ], }, }, ], }, }, { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<SetShippingMethodMutation, SetShippingMethodMutationVariables>; export const AddItemToOrderDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'AddItemToOrder' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'productVariantId' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, }, }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'quantity' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'Int' } }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'addItemToOrder' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'productVariantId' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'productVariantId' }, }, }, { kind: 'Argument', name: { kind: 'Name', value: 'quantity' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'quantity' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment' }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'ErrorResult' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'errorCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'message' } }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'InsufficientStockError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'quantityAvailable' }, }, { kind: 'Field', name: { kind: 'Name', value: 'order' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment', }, }, ], }, }, ], }, }, ], }, }, ], }, }, { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<AddItemToOrderMutation, AddItemToOrderMutationVariables>; export const AdjustOrderLineDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'AdjustOrderLine' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'orderLineId' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, }, }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'quantity' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'Int' } }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustOrderLine' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'orderLineId' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'orderLineId' } }, }, { kind: 'Argument', name: { kind: 'Name', value: 'quantity' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'quantity' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment' }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'ErrorResult' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'errorCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'message' } }, ], }, }, { kind: 'InlineFragment', typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'InsufficientStockError' }, }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'quantityAvailable' }, }, { kind: 'Field', name: { kind: 'Name', value: 'order' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment', }, }, ], }, }, ], }, }, ], }, }, ], }, }, { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<AdjustOrderLineMutation, AdjustOrderLineMutationVariables>; export const GetOrderByCodeDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'GetOrderByCode' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'code' } }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' } }, }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'orderByCode' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'code' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'code' } }, }, ], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment' }, }, ], }, }, ], }, }, { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<GetOrderByCodeQuery, GetOrderByCodeQueryVariables>; export const GetActiveOrderDocument = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'GetActiveOrder' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'activeOrder' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'FragmentSpread', name: { kind: 'Name', value: 'TestOrderFragment' }, }, ], }, }, ], }, }, { kind: 'FragmentDefinition', name: { kind: 'Name', value: 'TestOrderFragment' }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: 'Order' } }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'active' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotal' } }, { kind: 'Field', name: { kind: 'Name', value: 'subTotalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'shipping' } }, { kind: 'Field', name: { kind: 'Name', value: 'shippingWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'total' } }, { kind: 'Field', name: { kind: 'Name', value: 'totalWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'currencyCode' } }, { kind: 'Field', name: { kind: 'Name', value: 'couponCodes' } }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'payments' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'transactionId' } }, { kind: 'Field', name: { kind: 'Name', value: 'method' } }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'state' } }, { kind: 'Field', name: { kind: 'Name', value: 'metadata' } }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'lines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'quantity' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'linePriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPrice' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceChangeSinceAdded' } }, { kind: 'Field', name: { kind: 'Name', value: 'unitPriceWithTaxChangeSinceAdded' }, }, { kind: 'Field', name: { kind: 'Name', value: 'proratedUnitPriceWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'productVariant' }, selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: 'id' } }], }, }, { kind: 'Field', name: { kind: 'Name', value: 'discounts' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'adjustmentSource' }, }, { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, { kind: 'Field', name: { kind: 'Name', value: 'amountWithTax' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'shippingLines' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'shippingMethod' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'code' } }, { kind: 'Field', name: { kind: 'Name', value: 'description' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'customer' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'emailAddress' } }, { kind: 'Field', name: { kind: 'Name', value: 'user' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'identifier' } }, ], }, }, ], }, }, { kind: 'Field', name: { kind: 'Name', value: 'history' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'items' }, selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' } }, { kind: 'Field', name: { kind: 'Name', value: 'type' } }, { kind: 'Field', name: { kind: 'Name', value: 'data' } }, ], }, }, ], }, }, ], }, }, ], } as unknown as DocumentNode<GetActiveOrderQuery, GetActiveOrderQueryVariables>;
import gql from 'graphql-tag'; export const TEST_ORDER_FRAGMENT = gql` fragment TestOrderFragment on Order { id code state active subTotal subTotalWithTax shipping shippingWithTax total totalWithTax currencyCode couponCodes discounts { adjustmentSource amount amountWithTax description type } payments { id transactionId method amount state metadata } lines { id quantity linePrice linePriceWithTax unitPrice unitPriceWithTax unitPriceChangeSinceAdded unitPriceWithTaxChangeSinceAdded proratedUnitPriceWithTax productVariant { id } discounts { adjustmentSource amount amountWithTax description type } } shippingLines { shippingMethod { id code description } } customer { id emailAddress user { id identifier } } history { items { id type data } } } `; export const ADD_PAYMENT = gql` mutation AddPaymentToOrder($input: PaymentInput!) { addPaymentToOrder(input: $input) { ...TestOrderFragment ... on ErrorResult { errorCode message } ... on PaymentDeclinedError { paymentErrorMessage } ... on PaymentFailedError { paymentErrorMessage } ... on OrderStateTransitionError { transitionError } ... on IneligiblePaymentMethodError { eligibilityCheckerMessage } } } ${TEST_ORDER_FRAGMENT} `; export const SET_SHIPPING_ADDRESS = gql` mutation SetShippingAddress($input: CreateAddressInput!) { setOrderShippingAddress(input: $input) { ... on Order { shippingAddress { fullName company streetLine1 streetLine2 city province postalCode country phoneNumber } } ... on ErrorResult { errorCode message } } } `; export const GET_ELIGIBLE_SHIPPING_METHODS = gql` query GetShippingMethods { eligibleShippingMethods { id code price name description } } `; export const TRANSITION_TO_STATE = gql` mutation TransitionToState($state: String!) { transitionOrderToState(state: $state) { ... on Order { id } ... on OrderStateTransitionError { errorCode message transitionError fromState toState } } } `; export const SET_SHIPPING_METHOD = gql` mutation SetShippingMethod($id: [ID!]!) { setOrderShippingMethod(shippingMethodId: $id) { ...TestOrderFragment ... on ErrorResult { errorCode message } } } ${TEST_ORDER_FRAGMENT} `; export const ADD_ITEM_TO_ORDER = gql` mutation AddItemToOrder($productVariantId: ID!, $quantity: Int!) { addItemToOrder(productVariantId: $productVariantId, quantity: $quantity) { ...TestOrderFragment ... on ErrorResult { errorCode message } ... on InsufficientStockError { quantityAvailable order { ...TestOrderFragment } } } } ${TEST_ORDER_FRAGMENT} `; export const ADJUST_ORDER_LINE = gql` mutation AdjustOrderLine($orderLineId: ID!, $quantity: Int!) { adjustOrderLine(orderLineId: $orderLineId, quantity: $quantity) { ...TestOrderFragment ... on ErrorResult { errorCode message } ... on InsufficientStockError { quantityAvailable order { ...TestOrderFragment } } } } ${TEST_ORDER_FRAGMENT} `; export const GET_ORDER_BY_CODE = gql` query GetOrderByCode($code: String!) { orderByCode(code: $code) { ...TestOrderFragment } } ${TEST_ORDER_FRAGMENT} `; export const GET_ACTIVE_ORDER = gql` query GetActiveOrder { activeOrder { ...TestOrderFragment } } ${TEST_ORDER_FRAGMENT} `;
/** * This is a placeholder. Please import from one of the sub-packages, e.g `@vendure/payments-plugin/package/braintree` */ export const placeholder = 'Vendure Payments Plugin';
import { BraintreeGateway, Environment, Transaction } from 'braintree'; import { BraintreePluginOptions, PaymentMethodArgsHash } from './types'; export function getGateway(args: PaymentMethodArgsHash, options: BraintreePluginOptions): BraintreeGateway { return new BraintreeGateway({ environment: options.environment || Environment.Sandbox, merchantId: args.merchantId, privateKey: args.privateKey, publicKey: args.publicKey, }); } /** * @description * Returns a subset of the Transaction object of interest to the Administrator, plus some * public data which may be useful to display in the storefront account area. */ export function defaultExtractMetadataFn(transaction: Transaction): { [key: string]: any } { const metadata: { [key: string]: any } = { status: transaction.status, currencyIsoCode: transaction.currencyIsoCode, merchantAccountId: transaction.merchantAccountId, cvvCheck: decodeAvsCode(transaction.cvvResponseCode), avsPostCodeCheck: decodeAvsCode(transaction.avsPostalCodeResponseCode), avsStreetAddressCheck: decodeAvsCode(transaction.avsStreetAddressResponseCode), processorAuthorizationCode: transaction.processorAuthorizationCode, processorResponseText: transaction.processorResponseText, paymentMethod: transaction.paymentInstrumentType, public: {}, }; if (transaction.creditCard && transaction.creditCard.cardType) { const cardData = { cardType: transaction.creditCard.cardType, last4: transaction.creditCard.last4, expirationDate: transaction.creditCard.expirationDate, }; metadata.cardData = cardData; metadata.public.cardData = cardData; } if (transaction.paypalAccount && transaction.paypalAccount.authorizationId) { metadata.paypalData = { payerEmail: transaction.paypalAccount.payerEmail, paymentId: transaction.paypalAccount.paymentId, authorizationId: transaction.paypalAccount.authorizationId, payerStatus: transaction.paypalAccount.payerStatus, sellerProtectionStatus: transaction.paypalAccount.sellerProtectionStatus, transactionFeeAmount: transaction.paypalAccount.transactionFeeAmount, }; metadata.public.paypalData = { authorizationId: transaction.paypalAccount.authorizationId }; } return metadata; } function decodeAvsCode(code: string): string { switch (code) { case 'I': return 'Not Provided'; case 'M': return 'Matched'; case 'N': return 'Not Matched'; case 'U': return 'Not Verified'; case 'S': return 'Not Supported'; case 'E': return 'AVS System Error'; case 'A': return 'Not Applicable'; case 'B': return 'Skipped'; default: return 'Unknown'; } }
import { LanguageCode } from '@vendure/common/lib/generated-types'; import { Customer, EntityHydrator, Injector, Logger, Order, PaymentMethodHandler, RequestContext, TransactionalConnection, } from '@vendure/core'; import { BraintreeGateway } from 'braintree'; import { defaultExtractMetadataFn, getGateway } from './braintree-common'; import { BRAINTREE_PLUGIN_OPTIONS, loggerCtx } from './constants'; import { BraintreePluginOptions } from './types'; let options: BraintreePluginOptions; let connection: TransactionalConnection; let entityHydrator: EntityHydrator; /** * The handler for Braintree payments. */ export const braintreePaymentMethodHandler = new PaymentMethodHandler({ code: 'braintree', description: [{ languageCode: LanguageCode.en, value: 'Braintree payments' }], args: { merchantId: { type: 'string', label: [{ languageCode: LanguageCode.en, value: 'Merchant ID' }] }, publicKey: { type: 'string', label: [{ languageCode: LanguageCode.en, value: 'Public Key' }] }, privateKey: { type: 'string', label: [{ languageCode: LanguageCode.en, value: 'Private Key' }] }, }, init(injector: Injector) { options = injector.get<BraintreePluginOptions>(BRAINTREE_PLUGIN_OPTIONS); connection = injector.get(TransactionalConnection); entityHydrator = injector.get(EntityHydrator); }, async createPayment(ctx, order, amount, args, metadata) { const gateway = getGateway(args, options); let customerId: string | undefined; try { await entityHydrator.hydrate(ctx, order, { relations: ['customer'] }); const customer = order.customer; if ( options.storeCustomersInBraintree && ctx.activeUserId && customer && metadata.includeCustomerId !== false ) { customerId = await getBraintreeCustomerId(ctx, gateway, customer); } return processPayment(ctx, gateway, order, amount, metadata.nonce, customerId, options); } catch (e: any) { Logger.error(e, loggerCtx); return { amount, state: 'Error' as const, transactionId: '', errorMessage: e.toString(), metadata: e, }; } }, settlePayment() { return { success: true, }; }, async createRefund(ctx, input, total, order, payment, args) { const gateway = getGateway(args, options); const response = await gateway.transaction.refund(payment.transactionId, (total / 100).toString(10)); if (!response.success) { return { state: 'Failed' as const, transactionId: response.transaction?.id, metadata: response, }; } return { state: 'Settled' as const, transactionId: response.transaction.id, metadata: response, }; }, }); async function processPayment( ctx: RequestContext, gateway: BraintreeGateway, order: Order, amount: number, paymentMethodNonce: any, customerId: string | undefined, pluginOptions: BraintreePluginOptions, ) { const response = await gateway.transaction.sale({ customerId, amount: (amount / 100).toString(10), orderId: order.code, paymentMethodNonce, options: { submitForSettlement: true, storeInVaultOnSuccess: !!customerId, }, }); const extractMetadataFn = pluginOptions.extractMetadata ?? defaultExtractMetadataFn; const metadata = extractMetadataFn(response.transaction); if (!response.success) { return { amount, state: 'Declined' as const, transactionId: response.transaction.id, errorMessage: response.message, metadata, }; } return { amount, state: 'Settled' as const, transactionId: response.transaction.id, metadata, }; } /** * If the Customer has no braintreeCustomerId, create one, else return the existing braintreeCustomerId. */ async function getBraintreeCustomerId( ctx: RequestContext, gateway: BraintreeGateway, customer: Customer, ): Promise<string | undefined> { if (!customer.customFields.braintreeCustomerId) { try { const result = await gateway.customer.create({ firstName: customer.firstName, lastName: customer.lastName, email: customer.emailAddress, }); if (result.success) { const customerId = result.customer.id; Logger.verbose(`Created Braintree Customer record for customerId ${customer.id}`, loggerCtx); customer.customFields.braintreeCustomerId = customerId; await connection.getRepository(ctx, Customer).save(customer, { reload: false }); return customerId; } else { Logger.error( `Failed to create Braintree Customer record for customerId ${customer.id}. View Debug level logs for details.`, loggerCtx, ); Logger.debug(JSON.stringify(result.errors, null, 2), loggerCtx); } } catch (e: any) { Logger.error(e.message, loggerCtx, e.stack); } } else { return customer.customFields.braintreeCustomerId; } }
import { LanguageCode, PluginCommonModule, Type, VendurePlugin } from '@vendure/core'; import { gql } from 'graphql-tag'; import { braintreePaymentMethodHandler } from './braintree.handler'; import { BraintreeResolver } from './braintree.resolver'; import { BRAINTREE_PLUGIN_OPTIONS } from './constants'; import { BraintreePluginOptions } from './types'; /** * @description * This plugin enables payments to be processed by [Braintree](https://www.braintreepayments.com/), a popular payment provider. * * ## Requirements * * 1. You will need to create a Braintree sandbox account as outlined in https://developers.braintreepayments.com/start/overview. * 2. Then install `braintree` and `@types/braintree` from npm. This plugin was written with `v3.x` of the Braintree lib. * ```shell * yarn add \@vendure/payments-plugin braintree * yarn add -D \@types/braintree * ``` * or * ```shell * npm install \@vendure/payments-plugin braintree * npm install -D \@types/braintree * ``` * * ## Setup * * 1. Add the plugin to your VendureConfig `plugins` array: * ```ts * import { BraintreePlugin } from '\@vendure/payments-plugin/package/braintree'; * import { Environment } from 'braintree'; * * // ... * * plugins: [ * BraintreePlugin.init({ * environment: Environment.Sandbox, * // This allows saving customer payment * // methods with Braintree (see "vaulting" * // section below for details) * storeCustomersInBraintree: true, * }), * ] * ``` * 2. Create a new PaymentMethod in the Admin UI, and select "Braintree payments" as the handler. * 2. Fill in the `Merchant ID`, `Public Key` & `Private Key` from your Braintree sandbox account. * * ## Storefront usage * * The plugin is designed to work with the [Braintree drop-in UI](https://developers.braintreepayments.com/guides/drop-in/overview/javascript/v3). * This is a library provided by Braintree which will handle the payment UI for you. You can install it in your storefront project * with: * * ```shell * yarn add braintree-web-drop-in * # or * npm install braintree-web-drop-in * ``` * * The high-level workflow is: * 1. Generate a "client token" on the server by executing the `generateBraintreeClientToken` mutation which is exposed by this plugin. * 2. Use this client token to instantiate the Braintree Dropin UI. * 3. Listen for the `"paymentMethodRequestable"` event which emitted by the Dropin. * 4. Use the Dropin's `requestPaymentMethod()` method to get the required payment metadata. * 5. Pass that metadata to the `addPaymentToOrder` mutation. The metadata should be an object of type `{ nonce: string; }` * * Here is an example of how your storefront code will look. Note that this example is attempting to * be framework-agnostic, so you'll need to adapt it to fit to your framework of choice. * * ```ts * // The Braintree Dropin instance * let dropin: import('braintree-web-drop-in').Dropin; * * // Used to show/hide a "submit" button, which would be bound to the * // `submitPayment()` method below. * let showSubmitButton = false; * * // Used to display a "processing..." spinner * let processing = false; * * // * // This method would be invoked when the payment screen is mounted/created. * // * async function renderDropin(order: Order, clientToken: string) { * // Lazy load braintree dropin because it has a reference * // to `window` which breaks SSR * dropin = await import('braintree-web-drop-in').then((module) => * module.default.create({ * authorization: clientToken, * // This assumes a div in your view with the corresponding ID * container: '#dropin-container', * card: { * cardholderName: { * required: true, * }, * overrides: {}, * }, * // Additional config is passed here depending on * // which payment methods you have enabled in your * // Braintree account. * paypal: { * flow: 'checkout', * amount: order.totalWithTax / 100, * currency: 'GBP', * }, * }), * ); * * // If you are using the `storeCustomersInBraintree` option, then the * // customer might already have a stored payment method selected as * // soon as the dropin script loads. In this case, show the submit * // button immediately. * if (dropin.isPaymentMethodRequestable()) { * showSubmitButton = true; * } * * dropin.on('paymentMethodRequestable', (payload) => { * if (payload.type === 'CreditCard') { * showSubmitButton = true; * } * if (payload.type === 'PayPalAccount') { * this.submitPayment(); * } * }); * * dropin.on('noPaymentMethodRequestable', () => { * // Display an error * }); * } * * async function generateClientToken() { * const { generateBraintreeClientToken } = await graphQlClient.query(gql` * query GenerateBraintreeClientToken { * generateBraintreeClientToken * } * `); * return generateBraintreeClientToken; * } * * async submitPayment() { * if (!dropin.isPaymentMethodRequestable()) { * return; * } * showSubmitButton = false; * processing = true; * * const paymentResult = await dropin.requestPaymentMethod(); * * const { addPaymentToOrder } = await graphQlClient.query(gql` * mutation AddPayment($input: PaymentInput!) { * addPaymentToOrder(input: $input) { * ... on Order { * id * payments { * id * amount * errorMessage * method * state * transactionId * createdAt * } * } * ... on ErrorResult { * errorCode * message * } * } * }`, { * input: { * method: 'braintree', // The code of you Braintree PaymentMethod * metadata: paymentResult, * }, * }, * ); * * switch (addPaymentToOrder?.__typename) { * case 'Order': * // Adding payment succeeded! * break; * case 'OrderStateTransitionError': * case 'OrderPaymentStateError': * case 'PaymentDeclinedError': * case 'PaymentFailedError': * // Display an error to the customer * dropin.clearSelectedPaymentMethod(); * } * } * ``` * * ## Storing payment details (vaulting) * * Braintree has a [vault feature](https://developer.paypal.com/braintree/articles/control-panel/vault/overview) which allows the secure storage * of customer's payment information. Using the vault allows you to offer a faster checkout for repeat customers without needing to worry about * how to securely store payment details. * * To enable this feature, set the `storeCustomersInBraintree` option to `true`. * * ```ts * BraintreePlugin.init({ * environment: Environment.Sandbox, * storeCustomersInBraintree: true, * }), * ``` * * Since v1.8, it is possible to override vaulting on a per-payment basis by passing `includeCustomerId: false` to the `generateBraintreeClientToken` * mutation: * * ```GraphQL * const { generateBraintreeClientToken } = await graphQlClient.query(gql` * query GenerateBraintreeClientToken($includeCustomerId: Boolean) { * generateBraintreeClientToken(includeCustomerId: $includeCustomerId) * } * `, { includeCustomerId: false }); * ``` * * as well as in the metadata of the `addPaymentToOrder` mutation: * * ```ts * const { addPaymentToOrder } = await graphQlClient.query(gql` * mutation AddPayment($input: PaymentInput!) { * addPaymentToOrder(input: $input) { * ...Order * ...ErrorResult * } * }`, { * input: { * method: 'braintree', * metadata: { * ...paymentResult, * includeCustomerId: false, * }, * } * ); * ``` * * @docsCategory core plugins/PaymentsPlugin * @docsPage BraintreePlugin */ @VendurePlugin({ imports: [PluginCommonModule], providers: [ { provide: BRAINTREE_PLUGIN_OPTIONS, useFactory: () => BraintreePlugin.options, }, ], configuration: config => { config.paymentOptions.paymentMethodHandlers.push(braintreePaymentMethodHandler); if (BraintreePlugin.options.storeCustomersInBraintree === true) { config.customFields.Customer.push({ name: 'braintreeCustomerId', type: 'string', label: [{ languageCode: LanguageCode.en, value: 'Braintree Customer ID' }], nullable: true, public: false, readonly: true, }); } return config; }, shopApiExtensions: { schema: gql` extend type Query { generateBraintreeClientToken(orderId: ID, includeCustomerId: Boolean): String! } `, resolvers: [BraintreeResolver], }, compatibility: '^2.0.0', }) export class BraintreePlugin { static options: BraintreePluginOptions = {}; static init(options: BraintreePluginOptions): Type<BraintreePlugin> { this.options = options; return BraintreePlugin; } }
import { Inject } from '@nestjs/common'; import { Args, Query, Resolver } from '@nestjs/graphql'; import { ActiveOrderService, Ctx, Customer, ID, InternalServerError, Logger, OrderService, PaymentMethod, RequestContext, TransactionalConnection, } from '@vendure/core'; import { getGateway } from './braintree-common'; import { braintreePaymentMethodHandler } from './braintree.handler'; import { BRAINTREE_PLUGIN_OPTIONS, loggerCtx } from './constants'; import { BraintreePluginOptions, PaymentMethodArgsHash } from './types'; @Resolver() export class BraintreeResolver { constructor( private connection: TransactionalConnection, private orderService: OrderService, private activeOrderService: ActiveOrderService, @Inject(BRAINTREE_PLUGIN_OPTIONS) private options: BraintreePluginOptions, ) {} @Query() async generateBraintreeClientToken( @Ctx() ctx: RequestContext, @Args() { orderId, includeCustomerId }: { orderId?: ID; includeCustomerId?: boolean }, ) { if (orderId) { Logger.warn( 'The orderId argument to the generateBraintreeClientToken mutation has been deprecated and may be omitted.', ); } const sessionOrder = await this.activeOrderService.getOrderFromContext(ctx); if (!sessionOrder) { throw new InternalServerError( 'Cannot generate Braintree clientToken as there is no active Order.', ); } const order = await this.orderService.findOne(ctx, sessionOrder.id); if (order) { const customerId = order.customer?.customFields.braintreeCustomerId ?? undefined; const args = await this.getPaymentMethodArgs(ctx); const gateway = getGateway(args, this.options); try { let result = await gateway.clientToken.generate({ customerId: includeCustomerId === false ? undefined : customerId, }); if (result.success === true) { return result.clientToken; } else { if (result.message === 'Customer specified by customer_id does not exist') { // For some reason the custom_id is invalid. This could occur e.g. if the ID was created on the Sandbox endpoint and now // we switched to Production. In this case, we will remove it and allow a new one // to be generated when the payment is created. if (this.options.storeCustomersInBraintree) { if (order.customer?.customFields.braintreeCustomerId) { order.customer.customFields.braintreeCustomerId = undefined; await this.connection.getRepository(ctx, Customer).save(order.customer); } } result = await gateway.clientToken.generate({ customerId: undefined }); if (result.success === true) { return result.clientToken; } } Logger.error(`Could not generate Braintree clientToken: ${result.message}`, loggerCtx); throw new InternalServerError( `Could not generate Braintree clientToken: ${result.message}`, ); } } catch (e: any) { Logger.error( 'Could not generate Braintree clientToken. Check the configured credentials.', loggerCtx, ); throw e; } } else { throw new InternalServerError(`[${loggerCtx}] Could not find a Customer for the given Order`); } } private async getPaymentMethodArgs(ctx: RequestContext): Promise<PaymentMethodArgsHash> { const method = (await this.connection.getRepository(ctx, PaymentMethod).find()).find( m => m.handler.code === braintreePaymentMethodHandler.code, ); if (!method) { throw new InternalServerError(`[${loggerCtx}] Could not find Braintree PaymentMethod`); } return method.handler.args.reduce((hash, arg) => { return { ...hash, [arg.name]: arg.value, }; }, {} as PaymentMethodArgsHash); } }
export const loggerCtx = 'BraintreePlugin'; export const BRAINTREE_PLUGIN_OPTIONS = Symbol('BRAINTREE_PLUGIN_OPTIONS');
export * from './braintree.plugin'; export * from './braintree.handler'; export * from './braintree.resolver'; export * from './braintree-common'; export * from './types';
import { PaymentMetadata } from '@vendure/core'; import { ConfigArgValues } from '@vendure/core/dist/common/configurable-operation'; import '@vendure/core/dist/entity/custom-entity-fields'; import { Environment, Transaction } from 'braintree'; import { braintreePaymentMethodHandler } from './braintree.handler'; export type PaymentMethodArgsHash = ConfigArgValues<(typeof braintreePaymentMethodHandler)['args']>; // Note: deep import is necessary here because CustomCustomerFields is also extended in the Stripe // plugin. Reference: https://github.com/microsoft/TypeScript/issues/46617 declare module '@vendure/core/dist/entity/custom-entity-fields' { interface CustomCustomerFields { braintreeCustomerId?: string; } } /** * @description * Options for the Braintree plugin. * * @docsCategory core plugins/PaymentsPlugin * @docsPage BraintreePlugin */ export interface BraintreePluginOptions { /** * @description * The Braintree environment being targeted, e.g. sandbox or production. * * @default Environment.Sandbox */ environment?: Environment; /** * @description * If set to `true`, a [Customer](https://developer.paypal.com/braintree/docs/guides/customers) object * will be created in Braintree, which allows the secure storage ("vaulting") of previously-used payment methods. * This is done by adding a custom field to the Customer entity to store the Braintree customer ID, * so switching this on will require a database migration / synchronization. * * Since v1.8, it is possible to override vaulting on a per-payment basis by passing `includeCustomerId: false` to the * `generateBraintreeClientToken` mutation. * * @default false */ storeCustomersInBraintree?: boolean; /** * @description * Allows you to configure exactly what information from the Braintree * [Transaction object](https://developer.paypal.com/braintree/docs/reference/response/transaction#result-object) (which is returned by the * `transaction.sale()` method of the SDK) should be persisted to the resulting Payment entity metadata. * * By default, the built-in extraction function will return a metadata object that looks like this: * * @example * ```ts * const metadata = { * "status": "settling", * "currencyIsoCode": "GBP", * "merchantAccountId": "my_account_id", * "cvvCheck": "Not Applicable", * "avsPostCodeCheck": "Not Applicable", * "avsStreetAddressCheck": "Not Applicable", * "processorAuthorizationCode": null, * "processorResponseText": "Approved", * // for Paypal payments * "paymentMethod": "paypal_account", * "paypalData": { * "payerEmail": "michael-buyer@paypalsandbox.com", * "paymentId": "PAYID-MLCXYNI74301746XK8807043", * "authorizationId": "3BU93594D85624939", * "payerStatus": "VERIFIED", * "sellerProtectionStatus": "ELIGIBLE", * "transactionFeeAmount": "0.54" * }, * // for credit card payments * "paymentMethod": "credit_card", * "cardData": { * "cardType": "MasterCard", * "last4": "5454", * "expirationDate": "02/2023" * } * // publicly-available metadata that will be * // readable from the Shop API * "public": { * "cardData": { * "cardType": "MasterCard", * "last4": "5454", * "expirationDate": "02/2023" * }, * "paypalData": { * "authorizationId": "3BU93594D85624939", * } * } * } * ``` * * @since 1.7.0 */ extractMetadata?: (transaction: Transaction) => PaymentMetadata; }
import { gql } from 'graphql-tag'; const commonSchemaExtensions = gql` input MolliePaymentIntentInput { """ The code of the Vendure payment method to use for the payment. Must have Mollie as payment method handler. Without this, the first method with Mollie as handler will be used. """ paymentMethodCode: String """ The redirect url to which the customer will be redirected after the payment is completed. The configured fallback redirect will be used if this is not provided. """ redirectUrl: String """ Optional preselected Mollie payment method. When this is passed the payment selection step will be skipped. """ molliePaymentMethodCode: String """ Use this to create a payment intent for a specific order. This allows you to create intents for orders that are not active orders. """ orderId: String } type MolliePaymentIntent { url: String! } type MolliePaymentIntentError implements ErrorResult { errorCode: ErrorCode! message: String! } union MolliePaymentIntentResult = MolliePaymentIntent | MolliePaymentIntentError extend type Mutation { createMolliePaymentIntent(input: MolliePaymentIntentInput!): MolliePaymentIntentResult! } `; export const shopApiExtensions = gql` ${commonSchemaExtensions} type MollieAmount { value: String currency: String } type MolliePaymentMethodImages { size1x: String size2x: String svg: String } type MolliePaymentMethod { id: ID! code: String! description: String minimumAmount: MollieAmount maximumAmount: MollieAmount image: MolliePaymentMethodImages status: String } input MolliePaymentMethodsInput { paymentMethodCode: String! } extend type Query { molliePaymentMethods(input: MolliePaymentMethodsInput!): [MolliePaymentMethod!]! } `; export const adminApiExtensions = gql` ${commonSchemaExtensions} extend enum ErrorCode { ORDER_PAYMENT_STATE_ERROR } `;
export const loggerCtx = 'MolliePlugin'; export const PLUGIN_INIT_OPTIONS = Symbol('PLUGIN_INIT_OPTIONS');
import { CustomFieldConfig, Order, CustomOrderFields } from '@vendure/core'; export interface OrderWithMollieReference extends Order { customFields: CustomOrderFields & { mollieOrderId?: string; }; } export const orderCustomFields: CustomFieldConfig[] = [ { name: 'mollieOrderId', type: 'string', internal: true, nullable: true, }, ];
import createMollieClient, { MollieClient, Order as MollieOrder } from '@mollie/api-client'; import { Amount } from '@mollie/api-client/dist/types/src/data/global'; // We depend on the axios dependency from '@mollie/api-client' import axios, { AxiosInstance } from 'axios'; import { create } from 'domain'; /** * Create an extended Mollie client that also supports the manage order lines endpoint, because * the NodeJS client doesn't support it yet. * * See https://docs.mollie.com/reference/v2/orders-api/manage-order-lines * FIXME: Remove this when the NodeJS client supports it. */ export function createExtendedMollieClient(options: {apiKey: string}): ExtendedMollieClient { const client = createMollieClient(options) as ExtendedMollieClient; // Add our custom method client.manageOrderLines = async (orderId: string, input: ManageOrderLineInput): Promise<MollieOrder> => { const instance = axios.create({ baseURL: `https://api.mollie.com`, timeout: 5000, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${options.apiKey}`, }, validateStatus: () => true, // We handle errors ourselves, for better error messages }); const {status, data} = await instance.patch(`/v2/orders/${orderId}/lines`, input); if (status < 200 || status > 300) { throw Error(JSON.stringify(data, null, 2)) } return data; } return client; } export interface ExtendedMollieClient extends MollieClient { /** * Update all order lines in 1 request. */ manageOrderLines(orderId: string, input: ManageOrderLineInput): Promise<MollieOrder>; } interface CancelOperation { operation: 'cancel'; data: { id: string } } interface UpdateOperation { operation: 'update'; data: { id: string name?: string quantity?: number, unitPrice?: Amount totalAmount?: Amount vatRate?: string vatAmount?: Amount } } interface AddOperation { operation: 'add'; data: { name: string quantity: number, unitPrice: Amount totalAmount: Amount vatRate: string vatAmount: Amount } } export interface ManageOrderLineInput { operations: Array<CancelOperation | AddOperation | UpdateOperation> }
export * from './mollie.plugin'; export { getLocale, toAmount } from './mollie.helpers'; export * from './';
import { Args, Mutation, ResolveField, Resolver } from '@nestjs/graphql'; import { Allow, Ctx, Permission, RequestContext } from '@vendure/core'; import { MolliePaymentIntent, MolliePaymentIntentError, MolliePaymentIntentInput, MolliePaymentIntentResult } from './graphql/generated-shop-types'; import { MollieService } from './mollie.service'; @Resolver() export class MollieCommonResolver { constructor(private mollieService: MollieService) {} @Mutation() @Allow(Permission.Owner) async createMolliePaymentIntent( @Ctx() ctx: RequestContext, @Args('input') input: MolliePaymentIntentInput, ): Promise<MolliePaymentIntentResult> { return this.mollieService.createPaymentIntent(ctx, input); } @ResolveField() @Resolver('MolliePaymentIntentResult') __resolveType(value: MolliePaymentIntentError | MolliePaymentIntent): string { if ((value as MolliePaymentIntentError).errorCode) { return 'MolliePaymentIntentError'; } else { return 'MolliePaymentIntent'; } } }
import { Body, Controller, Param, Post } from '@nestjs/common'; import { Ctx, Logger, RequestContext, Transaction, ChannelService, LanguageCode } from '@vendure/core'; import { loggerCtx } from './constants'; import { MollieService } from './mollie.service'; @Controller('payments') export class MollieController { constructor(private mollieService: MollieService, private channelService: ChannelService) {} @Post('mollie/:channelToken/:paymentMethodId') @Transaction() async webhook( @Param('channelToken') channelToken: string, @Param('paymentMethodId') paymentMethodId: string, @Body() body: any, ): Promise<void> { if (!body.id) { return Logger.warn(' Ignoring incoming webhook, because it has no body.id.', loggerCtx); } try { // We need to construct a RequestContext based on the channelToken, // because this is an incoming webhook, not a graphql request with a valid Ctx const ctx = await this.createContext(channelToken); await this.mollieService.handleMollieStatusUpdate(ctx, { paymentMethodId, orderId: body.id, }); } catch (error: any) { Logger.error( `Failed to process incoming webhook: ${JSON.stringify(error?.message)}`, loggerCtx, error, ); throw error; } } private async createContext(channelToken: string): Promise<RequestContext> { const channel = await this.channelService.getChannelFromToken(channelToken); return new RequestContext({ apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, channel, languageCode: LanguageCode.en, }); } }
import createMollieClient, { OrderEmbed, PaymentStatus, RefundStatus } from '@mollie/api-client'; import { LanguageCode } from '@vendure/common/lib/generated-types'; import { CreatePaymentErrorResult, CreatePaymentResult, CreateRefundResult, Logger, PaymentMethodHandler, SettlePaymentResult, } from '@vendure/core'; import { loggerCtx } from './constants'; import { toAmount } from './mollie.helpers'; import { MollieService } from './mollie.service'; let mollieService: MollieService; export const molliePaymentHandler = new PaymentMethodHandler({ code: 'mollie-payment-handler', description: [ { languageCode: LanguageCode.en, value: 'Mollie payment', }, ], args: { apiKey: { type: 'string', label: [{ languageCode: LanguageCode.en, value: 'API Key' }], }, autoCapture: { type: 'boolean', label: [{ languageCode: LanguageCode.en, value: 'Auto capture payments' }], defaultValue: false, description: [ { languageCode: LanguageCode.en, value: 'This option only affects pay-later methods. Automatically capture payments ' + 'immediately after authorization. Without autoCapture orders will remain in the PaymentAuthorized state, ' + 'and you need to manually settle payments to get paid.', }, ], }, redirectUrl: { type: 'string', required: true, defaultValue: '', label: [{ languageCode: LanguageCode.en, value: 'Fallback redirect URL' }], description: [ { languageCode: LanguageCode.en, value: 'Redirect URL to use when no URL is given by the storefront. Order code is appended to this URL', }, ], }, }, init(injector) { mollieService = injector.get(MollieService); }, createPayment: async ( ctx, order, _amount, // Don't use this amount, but the amount from the metadata args, metadata, ): Promise<CreatePaymentResult | CreatePaymentErrorResult> => { // Only Admins and internal calls should be allowed to settle and authorize payments if (ctx.apiType !== 'admin' && ctx.apiType !== 'custom') { throw Error(`CreatePayment is not allowed for apiType '${ctx.apiType}'`); } if (metadata.status !== 'Authorized' && metadata.status !== 'Settled') { throw Error( `Cannot create payment for status ${metadata.status as string} for order ${ order.code }. Only Authorized or Settled are allowed.`, ); } Logger.info( `Payment for order ${order.code} with amount ${metadata.amount as string} created with state '${ metadata.status as string }'`, loggerCtx, ); return { amount: metadata.amount, state: metadata.status, transactionId: metadata.orderId, // The plugin now only supports 1 payment per order, so a mollie order equals a payment metadata, // Store all given metadata on a payment }; }, settlePayment: async (ctx, order, payment, args): Promise<SettlePaymentResult> => { // Called for Authorized payments const { apiKey } = args; const mollieClient = createMollieClient({ apiKey }); const mollieOrder = await mollieClient.orders.get(payment.transactionId); // Order could have been completed via Mollie dashboard, then we can just settle if (!mollieOrder.isCompleted()) { await mollieClient.orders_shipments.create({ orderId: payment.transactionId }); // Creating a shipment captures the payment } Logger.info(`Settled payment for ${order.code}`, loggerCtx); return { success: true }; }, createRefund: async (ctx, input, amount, order, payment, args): Promise<CreateRefundResult> => { const { apiKey } = args; const mollieClient = createMollieClient({ apiKey }); const mollieOrder = await mollieClient.orders.get(payment.transactionId, { embed: [OrderEmbed.payments], }); const molliePayments = await mollieOrder.getPayments(); const molliePayment = molliePayments.find(p => p.status === PaymentStatus.paid); // Only one paid payment should be there if (!molliePayment) { throw Error( `No payment with status 'paid' was found in Mollie for order ${order.code} (Mollie order ${mollieOrder.id})`, ); } const refund = await mollieClient.payments_refunds.create({ paymentId: molliePayment.id, description: input.reason, amount: toAmount(amount, order.currencyCode), }); if (refund.status === RefundStatus.failed) { Logger.error( `Failed to create refund of ${amount.toFixed()} for order ${order.code} for transaction ${ molliePayment.id }`, loggerCtx, ); return { state: 'Failed', transactionId: payment.transactionId, }; } Logger.info( `Created refund of ${amount.toFixed()} for order ${order.code} for transaction ${ payment.transactionId }`, loggerCtx, ); return { state: 'Settled', transactionId: payment.transactionId, }; }, });
import { CreateParameters } from '@mollie/api-client/dist/types/src/binders/orders/parameters'; import { Amount } from '@mollie/api-client/dist/types/src/data/global'; import { OrderAddress as MollieOrderAddress } from '@mollie/api-client/dist/types/src/data/orders/data'; import { CurrencyCode, Customer, Order } from '@vendure/core'; import currency from 'currency.js'; import { OrderAddress } from './graphql/generated-shop-types'; /** * Check if given address has mandatory fields for Mollie Order and map to a MollieOrderAddress. * Returns undefined if address doesn't have all mandatory fields */ export function toMollieAddress(address: OrderAddress, customer: Customer): MollieOrderAddress | undefined { if (address.city && address.countryCode && address.streetLine1 && address.postalCode) { return { streetAndNumber: `${address.streetLine1} ${address.streetLine2 || ''}`, postalCode: address.postalCode, city: address.city, country: address.countryCode.toUpperCase(), givenName: customer.firstName, familyName: customer.lastName, email: customer.emailAddress, }; } } /** * Map all order and shipping lines to a single array of Mollie order lines */ export function toMollieOrderLines(order: Order, alreadyPaid: number): CreateParameters['lines'] { // Add order lines const lines: CreateParameters['lines'] = order.lines.map(line => ({ name: line.productVariant.name, quantity: line.quantity, unitPrice: toAmount(line.proratedLinePriceWithTax / line.quantity, order.currencyCode), // totalAmount has to match unitPrice * quantity totalAmount: toAmount(line.proratedLinePriceWithTax, order.currencyCode), vatRate: line.taxRate.toFixed(2), vatAmount: toAmount( calculateLineTaxAmount(line.taxRate, line.proratedLinePriceWithTax), order.currencyCode, ), })); // Add shippingLines lines.push( ...order.shippingLines.map(line => ({ name: line.shippingMethod?.name || 'Shipping', quantity: 1, unitPrice: toAmount(line.discountedPriceWithTax, order.currencyCode), totalAmount: toAmount(line.discountedPriceWithTax, order.currencyCode), vatRate: String(line.taxRate), vatAmount: toAmount(line.discountedPriceWithTax - line.discountedPrice, order.currencyCode), })), ); // Add surcharges lines.push( ...order.surcharges.map(surcharge => ({ name: surcharge.description, quantity: 1, unitPrice: toAmount(surcharge.priceWithTax, order.currencyCode), totalAmount: toAmount(surcharge.priceWithTax, order.currencyCode), vatRate: String(surcharge.taxRate), vatAmount: toAmount(surcharge.priceWithTax - surcharge.price, order.currencyCode), })), ); // Deduct amount already paid if (alreadyPaid) { lines.push({ name: 'Already paid', quantity: 1, unitPrice: toAmount(-alreadyPaid, order.currencyCode), totalAmount: toAmount(-alreadyPaid, order.currencyCode), vatRate: String(0), vatAmount: toAmount(0, order.currencyCode), }); } return lines; } /** * Stringify and fixed decimals */ export function toAmount(value: number, orderCurrency: string): Amount { return { value: (value / 100).toFixed(2), currency: orderCurrency, }; } /** * Return to number of cents. E.g. '10.00' => 1000 */ export function amountToCents(amount: Amount): number { return currency(amount.value).intValue; } /** * Recalculate tax amount per order line instead of per unit for Mollie. * Vendure calculates tax per unit, but Mollie expects the tax to be calculated per order line (the total of the quantities). * See https://github.com/vendure-ecommerce/vendure/issues/1939#issuecomment-1362962133 for more information on the rounding issue. */ export function calculateLineTaxAmount(taxRate: number, orderLinePriceWithTax: number): number { const taxMultiplier = taxRate / 100; return orderLinePriceWithTax * (taxMultiplier / (1 + taxMultiplier)); // I.E. €99,99 * (0,2 ÷ 1,2) with a 20% taxrate } /** * Lookup one of Mollies allowed locales based on an orders countrycode or channel default. * If both lookups fail, resolve to en_US to prevent payment failure */ export function getLocale(countryCode: string, channelLanguage: string): string { const allowedLocales = [ 'en_US', 'en_GB', 'nl_NL', 'nl_BE', 'fr_FR', 'fr_BE', 'de_DE', 'de_AT', 'de_CH', 'es_ES', 'ca_ES', 'pt_PT', 'it_IT', 'nb_NO', 'sv_SE', 'fi_FI', 'da_DK', 'is_IS', 'hu_HU', 'pl_PL', 'lv_LV', 'lt_LT', ]; // Prefer order locale if possible const orderLocale = allowedLocales.find( locale => locale.toLowerCase().indexOf(countryCode.toLowerCase()) > -1, ); if (orderLocale) { return orderLocale; } // If no order locale, try channel default const channelLocale = allowedLocales.find( locale => locale.toLowerCase().indexOf(channelLanguage.toLowerCase()) > -1, ); if (channelLocale) { return channelLocale; } // If no order locale and no channel locale, return a default, otherwise order creation will fail return allowedLocales[0]; } export function areOrderLinesEqual(line1: CreateParameters['lines'][0], line2: CreateParameters['lines'][0]): boolean { return ( line1.name === line2.name && line1.quantity === line2.quantity && line1.unitPrice.value === line2.unitPrice.value && line1.unitPrice.currency === line2.unitPrice.currency && line1.totalAmount.value === line2.totalAmount.value && line1.vatRate === line2.vatRate && line1.vatAmount.value === line2.vatAmount.value ); }
import type { ListParameters } from '@mollie/api-client/dist/types/src/binders/methods/parameters'; import { Injector, Order, PluginCommonModule, RequestContext, RuntimeVendureConfig, VendurePlugin, } from '@vendure/core'; import { shopApiExtensions, adminApiExtensions } from './api-extensions'; import { PLUGIN_INIT_OPTIONS } from './constants'; import { orderCustomFields } from './custom-fields'; import { MollieCommonResolver } from './mollie.common-resolver'; import { MollieController } from './mollie.controller'; import { molliePaymentHandler } from './mollie.handler'; import { MollieService } from './mollie.service'; import { MollieShopResolver } from './mollie.shop-resolver'; export type AdditionalEnabledPaymentMethodsParams = Partial<Omit<ListParameters, 'resource'>>; /** * @description * Configuration options for the Mollie payments plugin. * * @docsCategory core plugins/PaymentsPlugin * @docsPage MolliePlugin */ export interface MolliePluginOptions { /** * @description * The host of your Vendure server, e.g. `'https://my-vendure.io'`. * This is used by Mollie to send webhook events to the Vendure server */ vendureHost: string; /** * @description * Provide additional parameters to the Mollie enabled payment methods API call. By default, * the plugin will already pass the `resource` parameter. * * For example, if you want to provide a `locale` and `billingCountry` for the API call, you can do so like this: * * **Note:** The `order` argument is possibly `null`, this could happen when you fetch the available payment methods * before the order is created. * * @example * ```ts * import { VendureConfig } from '\@vendure/core'; * import { MolliePlugin, getLocale } from '\@vendure/payments-plugin/package/mollie'; * * export const config: VendureConfig = { * // ... * plugins: [ * MolliePlugin.init({ * enabledPaymentMethodsParams: (injector, ctx, order) => { * const locale = order?.billingAddress?.countryCode * ? getLocale(order.billingAddress.countryCode, ctx.languageCode) * : undefined; * * return { * locale, * billingCountry: order?.billingAddress?.countryCode, * }, * } * }), * ], * }; * ``` * * @since 2.2.0 */ enabledPaymentMethodsParams?: ( injector: Injector, ctx: RequestContext, order: Order | null, ) => AdditionalEnabledPaymentMethodsParams | Promise<AdditionalEnabledPaymentMethodsParams>; } /** * @description * Plugin to enable payments through the [Mollie platform](https://docs.mollie.com/). * This plugin uses the Order API from Mollie, not the Payments API. * * ## Requirements * * 1. You will need to create a Mollie account and get your apiKey in the dashboard. * 2. Install the Payments plugin and the Mollie client: * * `yarn add \@vendure/payments-plugin \@mollie/api-client` * * or * * `npm install \@vendure/payments-plugin \@mollie/api-client` * * ## Setup * * 1. Add the plugin to your VendureConfig `plugins` array: * ```ts * import { MolliePlugin } from '\@vendure/payments-plugin/package/mollie'; * * // ... * * plugins: [ * MolliePlugin.init({ vendureHost: 'https://yourhost.io/' }), * ] * ``` * 2. Run a database migration to add the `mollieOrderId` custom field to the order entity. * 3. Create a new PaymentMethod in the Admin UI, and select "Mollie payments" as the handler. * 4. Set your Mollie apiKey in the `API Key` field. * 5. Set the `Fallback redirectUrl` to the url that the customer should be redirected to after completing the payment. * You can override this url by passing the `redirectUrl` as an argument to the `createMolliePaymentIntent` mutation. * * ## Storefront usage * * In your storefront you add a payment to an order using the `createMolliePaymentIntent` mutation. In this example, our Mollie * PaymentMethod was given the code "mollie-payment-method". The `redirectUrl``is the url that is used to redirect the end-user * back to your storefront after completing the payment. * * ```GraphQL * mutation CreateMolliePaymentIntent { * createMolliePaymentIntent(input: { * redirectUrl: "https://storefront/order/1234XYZ" * paymentMethodCode: "mollie-payment-method" * molliePaymentMethodCode: "ideal" * }) { * ... on MolliePaymentIntent { * url * } * ... on MolliePaymentIntentError { * errorCode * message * } * } * } * ``` * * The response will contain * a redirectUrl, which can be used to redirect your customer to the Mollie * platform. * * 'molliePaymentMethodCode' is an optional parameter that can be passed to skip Mollie's hosted payment method selection screen * You can get available Mollie payment methods with the following query: * * ```GraphQL * { * molliePaymentMethods(input: { paymentMethodCode: "mollie-payment-method" }) { * id * code * description * minimumAmount { * value * currency * } * maximumAmount { * value * currency * } * image { * size1x * size2x * svg * } * } * } * ``` * You can pass `creditcard` for example, to the `createMolliePaymentIntent` mutation to skip the method selection. * * After completing payment on the Mollie platform, * the user is redirected to the given redirect url, e.g. `https://storefront/order/CH234X5` * * ## Pay later methods * Mollie supports pay-later methods like 'Klarna Pay Later'. For pay-later methods, the status of an order is * 'PaymentAuthorized' after the Mollie hosted checkout. You need to manually settle the payment via the admin ui to capture the payment! * Make sure you capture a payment within 28 days, because this is the Klarna expiry time * * If you don't want this behaviour (Authorized first), you can set 'autoCapture=true' on the payment method. This option will immediately * capture the payment after a customer authorizes the payment. * * ## ArrangingAdditionalPayment state * * In some rare cases, a customer can add items to the active order, while a Mollie payment is still open, * for example by opening your storefront in another browser tab. * This could result in an order being in `ArrangingAdditionalPayment` status after the customer finished payment. * You should check if there is still an active order with status `ArrangingAdditionalPayment` on your order confirmation page, * and if so, allow your customer to pay for the additional items by creating another Mollie payment. * * @docsCategory core plugins/PaymentsPlugin * @docsPage MolliePlugin * @docsWeight 0 */ @VendurePlugin({ imports: [PluginCommonModule], controllers: [MollieController], providers: [MollieService, { provide: PLUGIN_INIT_OPTIONS, useFactory: () => MolliePlugin.options }], configuration: (config: RuntimeVendureConfig) => { config.paymentOptions.paymentMethodHandlers.push(molliePaymentHandler); config.customFields.Order.push(...orderCustomFields); return config; }, shopApiExtensions: { schema: shopApiExtensions, resolvers: [MollieCommonResolver, MollieShopResolver], }, adminApiExtensions: { schema: adminApiExtensions, resolvers: [MollieCommonResolver], }, compatibility: '^2.2.0', }) export class MolliePlugin { static options: MolliePluginOptions; /** * @description * Initialize the mollie payment plugin * @param vendureHost is needed to pass to mollie for callback */ static init(options: MolliePluginOptions): typeof MolliePlugin { this.options = options; return MolliePlugin; } }
import { Order as MollieOrder, OrderStatus, PaymentMethod as MollieClientMethod } from '@mollie/api-client'; import { CreateParameters } from '@mollie/api-client/dist/types/src/binders/orders/parameters'; import { Inject, Injectable } from '@nestjs/common'; import { ModuleRef } from '@nestjs/core'; import { ActiveOrderService, assertFound, EntityHydrator, ErrorResult, ID, Injector, LanguageCode, Logger, Order, OrderService, OrderState, OrderStateTransitionError, PaymentMethod, PaymentMethodService, ProductVariant, ProductVariantService, RequestContext, } from '@vendure/core'; import { OrderStateMachine } from '@vendure/core/'; import { totalCoveredByPayments } from '@vendure/core/dist/service/helpers/utils/order-utils'; import { loggerCtx, PLUGIN_INIT_OPTIONS } from './constants'; import { OrderWithMollieReference } from './custom-fields'; import { createExtendedMollieClient, ExtendedMollieClient, ManageOrderLineInput, } from './extended-mollie-client'; import { ErrorCode, MolliePaymentIntentError, MolliePaymentIntentInput, MolliePaymentIntentResult, MolliePaymentMethod, } from './graphql/generated-shop-types'; import { molliePaymentHandler } from './mollie.handler'; import { amountToCents, areOrderLinesEqual, getLocale, toAmount, toMollieAddress, toMollieOrderLines, } from './mollie.helpers'; import { MolliePluginOptions } from './mollie.plugin'; interface OrderStatusInput { paymentMethodId: string; orderId: string; } class PaymentIntentError implements MolliePaymentIntentError { errorCode = ErrorCode.ORDER_PAYMENT_STATE_ERROR; constructor(public message: string) {} } class InvalidInputError implements MolliePaymentIntentError { errorCode = ErrorCode.INELIGIBLE_PAYMENT_METHOD_ERROR; constructor(public message: string) {} } @Injectable() export class MollieService { private readonly injector: Injector; constructor( private paymentMethodService: PaymentMethodService, @Inject(PLUGIN_INIT_OPTIONS) private options: MolliePluginOptions, private activeOrderService: ActiveOrderService, private orderService: OrderService, private entityHydrator: EntityHydrator, private variantService: ProductVariantService, private moduleRef: ModuleRef, ) { this.injector = new Injector(this.moduleRef); } /** * Creates a redirectUrl to Mollie for the given paymentMethod and current activeOrder */ async createPaymentIntent( ctx: RequestContext, input: MolliePaymentIntentInput, ): Promise<MolliePaymentIntentResult> { const { paymentMethodCode, molliePaymentMethodCode } = input; const allowedMethods = Object.values(MollieClientMethod) as string[]; if (molliePaymentMethodCode && !allowedMethods.includes(molliePaymentMethodCode)) { return new InvalidInputError( `molliePaymentMethodCode has to be one of "${allowedMethods.join(',')}"`, ); } const [order, paymentMethod] = await Promise.all([ this.getOrder(ctx, input.orderId), this.getPaymentMethod(ctx, paymentMethodCode), ]); if (order instanceof PaymentIntentError) { return order; } await this.entityHydrator.hydrate(ctx, order, { relations: [ 'customer', 'surcharges', 'lines.productVariant', 'lines.productVariant.translations', 'shippingLines.shippingMethod', 'payments', ], }); if (order.state !== 'ArrangingPayment' && order.state !== 'ArrangingAdditionalPayment') { // Pre-check if order is transitionable to ArrangingPayment, because that will happen after Mollie payment try { await this.canTransitionTo(ctx, order.id, 'ArrangingPayment'); } catch (e) { if ((e as Error).message) { return new PaymentIntentError((e as Error).message); } throw e; } } if (!order.customer?.firstName.length) { return new PaymentIntentError( 'Cannot create payment intent for order with customer that has no firstName set', ); } if (!order.customer?.lastName.length) { return new PaymentIntentError( 'Cannot create payment intent for order with customer that has no lastName set', ); } if (!paymentMethod) { return new PaymentIntentError(`No paymentMethod found with code ${String(paymentMethodCode)}`); } let redirectUrl = input.redirectUrl; if (!redirectUrl) { // Use fallback redirect if no redirectUrl is given let fallbackRedirect = paymentMethod.handler.args.find(arg => arg.name === 'redirectUrl')?.value; if (!fallbackRedirect) { return new PaymentIntentError( 'No redirect URl was given and no fallback redirect is configured', ); } redirectUrl = fallbackRedirect; // remove appending slash if present fallbackRedirect = fallbackRedirect.endsWith('/') ? fallbackRedirect.slice(0, -1) : fallbackRedirect; redirectUrl = `${fallbackRedirect}/${order.code}`; } const apiKey = paymentMethod.handler.args.find(arg => arg.name === 'apiKey')?.value; if (!apiKey) { Logger.warn( `CreatePaymentIntent failed, because no apiKey is configured for ${paymentMethod.code}`, loggerCtx, ); return new PaymentIntentError(`Paymentmethod ${paymentMethod.code} has no apiKey configured`); } const mollieClient = createExtendedMollieClient({ apiKey }); const vendureHost = this.options.vendureHost.endsWith('/') ? this.options.vendureHost.slice(0, -1) : this.options.vendureHost; // remove appending slash const billingAddress = toMollieAddress(order.billingAddress, order.customer) || toMollieAddress(order.shippingAddress, order.customer); if (!billingAddress) { return new InvalidInputError( "Order doesn't have a complete shipping address or billing address. " + 'At least city, postalCode, streetline1 and country are needed to create a payment intent.', ); } const alreadyPaid = totalCoveredByPayments(order); const amountToPay = order.totalWithTax - alreadyPaid; const orderInput: CreateParameters = { orderNumber: order.code, amount: toAmount(amountToPay, order.currencyCode), redirectUrl, webhookUrl: `${vendureHost}/payments/mollie/${ctx.channel.token}/${paymentMethod.id}`, billingAddress, locale: getLocale(billingAddress.country, ctx.languageCode), lines: toMollieOrderLines(order, alreadyPaid), metadata: { languageCode: ctx.languageCode, }, }; if (molliePaymentMethodCode) { orderInput.method = molliePaymentMethodCode as MollieClientMethod; } const existingMollieOrderId = (order as OrderWithMollieReference).customFields.mollieOrderId; if (existingMollieOrderId) { // Update order and return its checkoutUrl const updateMollieOrder = await this.updateMollieOrder( mollieClient, orderInput, existingMollieOrderId, ).catch(e => { Logger.error( `Failed to update Mollie order '${existingMollieOrderId}' for '${order.code}': ${(e as Error).message}`, loggerCtx, ); }); const checkoutUrl = updateMollieOrder?.getCheckoutUrl(); if (checkoutUrl) { Logger.info( `Updated Mollie order '${updateMollieOrder?.id as string}' for order '${order.code}'`, loggerCtx, ); return { url: checkoutUrl, }; } } // Otherwise create a new Mollie order const mollieOrder = await mollieClient.orders.create(orderInput); // Save async, because this shouldn't impact intent creation this.orderService.updateCustomFields(ctx, order.id, { mollieOrderId: mollieOrder.id }).catch(e => { Logger.error(`Failed to save Mollie order ID: ${(e as Error).message}`, loggerCtx); }); Logger.info(`Created Mollie order ${mollieOrder.id} for order ${order.code}`, loggerCtx); const url = mollieOrder.getCheckoutUrl(); if (!url) { throw Error('Unable to getCheckoutUrl() from Mollie order'); } return { url, }; } /** * Update Vendure payments and order status based on the incoming Mollie order */ async handleMollieStatusUpdate( ctx: RequestContext, { paymentMethodId, orderId }: OrderStatusInput, ): Promise<void> { Logger.info( `Received status update for channel ${ctx.channel.token} for Mollie order ${orderId}`, loggerCtx, ); const paymentMethod = await this.paymentMethodService.findOne(ctx, paymentMethodId); if (!paymentMethod) { // Fail silently, as we don't want to expose if a paymentMethodId exists or not return Logger.warn(`No paymentMethod found with id ${paymentMethodId}`, loggerCtx); } const apiKey = paymentMethod.handler.args.find(a => a.name === 'apiKey')?.value; const autoCapture = paymentMethod.handler.args.find(a => a.name === 'autoCapture')?.value === 'true'; if (!apiKey) { throw Error(`No apiKey found for payment ${paymentMethod.id} for channel ${ctx.channel.token}`); } const client = createExtendedMollieClient({ apiKey }); const mollieOrder = await client.orders.get(orderId); if (mollieOrder.metadata?.languageCode) { // Recreate ctx with the original languageCode ctx = new RequestContext({ apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, channel: ctx.channel, languageCode: mollieOrder.metadata.languageCode as LanguageCode, }); } Logger.info( `Processing status '${mollieOrder.status}' for order ${mollieOrder.orderNumber} for channel ${ctx.channel.token} for Mollie order ${orderId}`, loggerCtx, ); let order = await this.orderService.findOneByCode(ctx, mollieOrder.orderNumber, ['payments']); if (!order) { throw Error( `Unable to find order ${mollieOrder.orderNumber}, unable to process Mollie order ${mollieOrder.id}`, ); } const statesThatRequireAction: OrderState[] = [ 'AddingItems', 'ArrangingPayment', 'ArrangingAdditionalPayment', 'PaymentAuthorized', 'Draft', ]; if (!statesThatRequireAction.includes(order.state)) { // If order is not in one of these states, we don't need to handle the Mollie webhook Logger.info( `Order ${order.code} is already '${order.state}', no need for handling Mollie status '${mollieOrder.status}'`, loggerCtx, ); return; } if (mollieOrder.status === OrderStatus.expired) { // Expired is fine, a customer can retry the payment later return; } if (mollieOrder.status === OrderStatus.paid) { // Paid is only used by 1-step payments without Authorized state. This will settle immediately await this.addPayment(ctx, order, mollieOrder, paymentMethod.code, 'Settled'); return; } if (order.state === 'AddingItems' && mollieOrder.status === OrderStatus.authorized) { order = await this.addPayment(ctx, order, mollieOrder, paymentMethod.code, 'Authorized'); if (autoCapture && mollieOrder.status === OrderStatus.authorized) { // Immediately capture payment if autoCapture is set Logger.info(`Auto capturing payment for order ${order.code}`, loggerCtx); await this.settleExistingPayment(ctx, order, mollieOrder.id); } return; } if (order.state === 'PaymentAuthorized' && mollieOrder.status === OrderStatus.completed) { return this.settleExistingPayment(ctx, order, mollieOrder.id); } if (autoCapture && mollieOrder.status === OrderStatus.completed) { // When autocapture is enabled, we should not handle the completed status from Mollie, // because the order will be transitioned to PaymentSettled during auto capture return; } // Any other combination of Mollie status and Vendure status indicates something is wrong. throw Error( `Unhandled incoming Mollie status '${mollieOrder.status}' for order ${order.code} with status '${order.state}'`, ); } /** * Add payment to order. Can be settled or authorized depending on the payment method. */ async addPayment( ctx: RequestContext, order: Order, mollieOrder: MollieOrder, paymentMethodCode: string, status: 'Authorized' | 'Settled', ): Promise<Order> { if (order.state !== 'ArrangingPayment' && order.state !== 'ArrangingAdditionalPayment') { const transitionToStateResult = await this.orderService.transitionToState( ctx, order.id, 'ArrangingPayment', ); if (transitionToStateResult instanceof OrderStateTransitionError) { throw Error( `Error transitioning order ${order.code} from ${transitionToStateResult.fromState} ` + `to ${transitionToStateResult.toState}: ${transitionToStateResult.message}`, ); } } const addPaymentToOrderResult = await this.orderService.addPaymentToOrder(ctx, order.id, { method: paymentMethodCode, metadata: { amount: amountToCents(mollieOrder.amount), status, orderId: mollieOrder.id, mode: mollieOrder.mode, method: mollieOrder.method, profileId: mollieOrder.profileId, settlementAmount: mollieOrder.amount, authorizedAt: mollieOrder.authorizedAt, paidAt: mollieOrder.paidAt, }, }); if (!(addPaymentToOrderResult instanceof Order)) { throw Error(`Error adding payment to order ${order.code}: ${addPaymentToOrderResult.message}`); } return addPaymentToOrderResult; } /** * Settle an existing payment based on the given mollieOrder */ async settleExistingPayment(ctx: RequestContext, order: Order, mollieOrderId: string): Promise<void> { order = await this.entityHydrator.hydrate(ctx, order, { relations: ['payments'] }); const payment = order.payments.find(p => p.transactionId === mollieOrderId); if (!payment) { throw Error( `Cannot find payment ${mollieOrderId} for ${order.code}. Unable to settle this payment`, ); } const result = await this.orderService.settlePayment(ctx, payment.id); if ((result as ErrorResult).message) { throw Error( `Error settling payment ${payment.id} for order ${order.code}: ${ (result as ErrorResult).errorCode } - ${(result as ErrorResult).message}`, ); } } async getEnabledPaymentMethods( ctx: RequestContext, paymentMethodCode: string, ): Promise<MolliePaymentMethod[]> { const paymentMethod = await this.getPaymentMethod(ctx, paymentMethodCode); const apiKey = paymentMethod?.handler.args.find(arg => arg.name === 'apiKey')?.value; if (!apiKey) { throw Error(`No apiKey configured for payment method ${paymentMethodCode}`); } const client = createExtendedMollieClient({ apiKey }); const activeOrder = await this.activeOrderService.getActiveOrder(ctx, undefined); const additionalParams = await this.options.enabledPaymentMethodsParams?.( this.injector, ctx, activeOrder ?? null, ); // We use the orders API, so list available methods for that API usage const methods = await client.methods.list({ ...additionalParams, resource: 'orders', }); return methods.map(m => ({ ...m, code: m.id, })); } async getVariantsWithInsufficientStock(ctx: RequestContext, order: Order): Promise<ProductVariant[]> { const variantsWithInsufficientSaleableStock: ProductVariant[] = []; for (const line of order.lines) { const availableStock = await this.variantService.getSaleableStockLevel(ctx, line.productVariant); if (line.quantity > availableStock) { variantsWithInsufficientSaleableStock.push(line.productVariant); } } return variantsWithInsufficientSaleableStock; } /** * Update an existing Mollie order based on the given Vendure order. */ async updateMollieOrder( mollieClient: ExtendedMollieClient, newMollieOrderInput: CreateParameters, mollieOrderId: string, ): Promise<MollieOrder> { const existingMollieOrder = await mollieClient.orders.get(mollieOrderId); const [order] = await Promise.all([ this.updateMollieOrderData(mollieClient, existingMollieOrder, newMollieOrderInput), this.updateMollieOrderLines(mollieClient, existingMollieOrder, newMollieOrderInput.lines), ]); return order; } /** * Update the Mollie Order data itself, excluding the order lines. * So, addresses, redirect url etc */ private async updateMollieOrderData( mollieClient: ExtendedMollieClient, existingMollieOrder: MollieOrder, newMollieOrderInput: CreateParameters, ): Promise<MollieOrder> { return await mollieClient.orders.update(existingMollieOrder.id, { billingAddress: newMollieOrderInput.billingAddress, shippingAddress: newMollieOrderInput.shippingAddress, redirectUrl: newMollieOrderInput.redirectUrl, }); } /** * Compare existing order lines with the new input, * and update, add or cancel the order lines accordingly. * * We compare and update order lines based on their index, because there is no unique identifier */ private async updateMollieOrderLines( mollieClient: ExtendedMollieClient, existingMollieOrder: MollieOrder, newMollieOrderLines: CreateParameters['lines'], ): Promise<MollieOrder> { const manageOrderLinesInput: ManageOrderLineInput = { operations: [], }; // Update or add new order lines newMollieOrderLines.forEach((newLine, index) => { const existingLine = existingMollieOrder.lines[index]; if (existingLine && !areOrderLinesEqual(existingLine, newLine)) { // Update if exists but not equal manageOrderLinesInput.operations.push({ operation: 'update', data: { ...newLine, id: existingLine.id, }, }); } else { // Add new line if it doesn't exist manageOrderLinesInput.operations.push({ operation: 'add', data: newLine, }); } }); // Cancel any order lines that are in the existing Mollie order, but not in the new input existingMollieOrder.lines.forEach((existingLine, index) => { const newLine = newMollieOrderLines[index]; if (!newLine) { manageOrderLinesInput.operations.push({ operation: 'cancel', data: { id: existingLine.id }, }); } }); return await mollieClient.manageOrderLines(existingMollieOrder.id, manageOrderLinesInput); } /** * Dry run a transition to a given state. * As long as we don't call 'finalize', the transition never completes. */ private async canTransitionTo(ctx: RequestContext, orderId: ID, state: OrderState) { // Fetch new order object, because `transition()` mutates the order object const orderCopy = await assertFound(this.orderService.findOne(ctx, orderId)); const orderStateMachine = this.injector.get(OrderStateMachine); await orderStateMachine.transition(ctx, orderCopy, state); } private async getPaymentMethod( ctx: RequestContext, paymentMethodCode?: string | null, ): Promise<PaymentMethod | undefined> { if (paymentMethodCode) { const { items } = await this.paymentMethodService.findAll(ctx, { filter: { code: { eq: paymentMethodCode }, }, }); return items.find(pm => pm.code === paymentMethodCode); } else { const { items } = await this.paymentMethodService.findAll(ctx); return items.find(pm => pm.handler.code === molliePaymentHandler.code); } } /** * Get order by id, or active order if no orderId is given */ private async getOrder(ctx: RequestContext, orderId?: ID | null): Promise<Order | PaymentIntentError> { if (orderId) { return await assertFound(this.orderService.findOne(ctx, orderId)); } const order = await this.activeOrderService.getActiveOrder(ctx, undefined); if (!order) { return new PaymentIntentError('No active order found for session'); } return order; } }
import { Args, Query, Resolver } from '@nestjs/graphql'; import { Allow, Ctx, Permission, RequestContext } from '@vendure/core'; import { MolliePaymentMethod, MolliePaymentMethodsInput } from './graphql/generated-shop-types'; import { MollieService } from './mollie.service'; @Resolver() export class MollieShopResolver { constructor(private mollieService: MollieService) {} @Query() @Allow(Permission.Public) async molliePaymentMethods( @Ctx() ctx: RequestContext, @Args('input') { paymentMethodCode }: MolliePaymentMethodsInput, ): Promise<MolliePaymentMethod[]> { return this.mollieService.getEnabledPaymentMethods(ctx, paymentMethodCode); } }
/* eslint-disable */ export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<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; output: string }; String: { input: string; output: string }; Boolean: { input: boolean; output: boolean }; Int: { input: number; output: number }; Float: { input: number; output: number }; /** A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. */ DateTime: { input: any; output: any }; /** The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf). */ JSON: { input: any; output: any }; /** The `Money` scalar type represents monetary values and supports signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point). */ Money: { input: number; output: number }; /** The `Upload` scalar type represents a file upload. */ 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 MollieAmount = { __typename?: 'MollieAmount'; currency?: Maybe<Scalars['String']['output']>; value?: Maybe<Scalars['String']['output']>; }; export type MolliePaymentIntent = { __typename?: 'MolliePaymentIntent'; url: Scalars['String']['output']; }; export type MolliePaymentIntentError = ErrorResult & { __typename?: 'MolliePaymentIntentError'; errorCode: ErrorCode; message: Scalars['String']['output']; }; export type MolliePaymentIntentInput = { molliePaymentMethodCode?: InputMaybe<Scalars['String']['input']>; paymentMethodCode?: InputMaybe<Scalars['String']['input']>; redirectUrl?: InputMaybe<Scalars['String']['input']>; orderId?: InputMaybe<Scalars['ID']['input']>; }; export type MolliePaymentIntentResult = MolliePaymentIntent | MolliePaymentIntentError; export type MolliePaymentMethod = { __typename?: 'MolliePaymentMethod'; code: Scalars['String']['output']; description?: Maybe<Scalars['String']['output']>; id: Scalars['ID']['output']; image?: Maybe<MolliePaymentMethodImages>; maximumAmount?: Maybe<MollieAmount>; minimumAmount?: Maybe<MollieAmount>; status?: Maybe<Scalars['String']['output']>; }; export type MolliePaymentMethodImages = { __typename?: 'MolliePaymentMethodImages'; size1x?: Maybe<Scalars['String']['output']>; size2x?: Maybe<Scalars['String']['output']>; svg?: Maybe<Scalars['String']['output']>; }; export type MolliePaymentMethodsInput = { paymentMethodCode: Scalars['String']['input']; }; 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; createMolliePaymentIntent: MolliePaymentIntentResult; /** 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 MutationCreateMolliePaymentIntentArgs = { input: MolliePaymentIntentInput; }; 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>; molliePaymentMethods: Array<MolliePaymentMethod>; /** 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 QueryMolliePaymentMethodsArgs = { input: MolliePaymentMethodsInput; }; 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']; };
export const loggerCtx = 'StripePlugin'; export const STRIPE_PLUGIN_OPTIONS = Symbol('STRIPE_PLUGIN_OPTIONS');
export { StripePlugin } from './stripe.plugin';
import Stripe from 'stripe'; const MAX_KEYS = 50; const MAX_KEY_NAME_LENGTH = 40; const MAX_VALUE_LENGTH = 500; /** * @description * Santitize metadata to ensure it follow Stripe's instructions * * @link * https://stripe.com/docs/api/metadata * * @Restriction * You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. * */ export function sanitizeMetadata(metadata: Stripe.MetadataParam) { if (typeof metadata !== 'object' && metadata !== null) return {}; const keys = Object.keys(metadata) .filter(keyName => keyName.length <= MAX_KEY_NAME_LENGTH) .filter( keyName => typeof metadata[keyName] !== 'string' || (metadata[keyName] as string).length <= MAX_VALUE_LENGTH, ) .slice(0, MAX_KEYS) as Array<keyof Stripe.MetadataParam>; const sanitizedMetadata = keys.reduce((obj, keyName) => { obj[keyName] = metadata[keyName]; return obj; }, {} as Stripe.MetadataParam); return sanitizedMetadata; }
import { raw } from 'body-parser'; import * as http from 'http'; import { RequestWithRawBody } from './types'; /** * Middleware which adds the raw request body to the incoming message object. This is needed by * Stripe to properly verify webhook events. */ export const rawBodyMiddleware = raw({ type: '*/*', verify(req: RequestWithRawBody, res: http.ServerResponse, buf: Buffer, encoding: string) { if (Buffer.isBuffer(buf)) { req.rawBody = Buffer.from(buf); } return true; }, });
import Stripe from 'stripe'; /** * Wrapper around the Stripe client that exposes ApiKey and WebhookSecret */ export class VendureStripeClient extends Stripe { constructor(private apiKey: string, public webhookSecret: string) { super(apiKey, { apiVersion: null as unknown as Stripe.LatestApiVersion, // Use accounts default version }); } }
import { CurrencyCode, Order } from '@vendure/core'; /** * @description * From the [Stripe docs](https://stripe.com/docs/currencies#zero-decimal): * > All API requests expect amounts to be provided in a currency’s smallest unit. * > For example, to charge 10 USD, provide an amount value of 1000 (that is, 1000 cents). * > For zero-decimal currencies, still provide amounts as an integer but without multiplying by 100. * > For example, to charge ¥500, provide an amount value of 500. * * Therefore, for a fractionless currency like JPY, we need to divide the amount by 100 (since Vendure always * stores money amounts multiplied by 100). See https://github.com/vendure-ecommerce/vendure/issues/1630 */ export function getAmountInStripeMinorUnits(order: Order): number { return currencyHasFractionPart(order.currencyCode) ? order.totalWithTax : Math.round(order.totalWithTax / 100); } /** * @description * Performs the reverse of `getAmountInStripeMinorUnits` - converting the Stripe minor units into the format * used by Vendure. */ export function getAmountFromStripeMinorUnits(order: Order, stripeAmount: number): number { return currencyHasFractionPart(order.currencyCode) ? stripeAmount : stripeAmount * 100; } function currencyHasFractionPart(currencyCode: CurrencyCode): boolean { const parts = new Intl.NumberFormat(undefined, { style: 'currency', currency: currencyCode, currencyDisplay: 'symbol', }).formatToParts(123.45); return !!parts.find(p => p.type === 'fraction'); }
import { Controller, Headers, HttpStatus, Post, Req, Res } from '@nestjs/common'; import type { PaymentMethod, RequestContext } from '@vendure/core'; import { InternalServerError, LanguageCode, Logger, Order, OrderService, PaymentMethodService, RequestContextService, TransactionalConnection, } from '@vendure/core'; import { OrderStateTransitionError } from '@vendure/core/dist/common/error/generated-graphql-shop-errors'; import type { Response } from 'express'; import type Stripe from 'stripe'; import { loggerCtx } from './constants'; import { stripePaymentMethodHandler } from './stripe.handler'; import { StripeService } from './stripe.service'; import { RequestWithRawBody } from './types'; const missingHeaderErrorMessage = 'Missing stripe-signature header'; const signatureErrorMessage = 'Error verifying Stripe webhook signature'; const noPaymentIntentErrorMessage = 'No payment intent in the event payload'; @Controller('payments') export class StripeController { constructor( private paymentMethodService: PaymentMethodService, private orderService: OrderService, private stripeService: StripeService, private requestContextService: RequestContextService, private connection: TransactionalConnection, ) {} @Post('stripe') async webhook( @Headers('stripe-signature') signature: string | undefined, @Req() request: RequestWithRawBody, @Res() response: Response, ): Promise<void> { if (!signature) { Logger.error(missingHeaderErrorMessage, loggerCtx); response.status(HttpStatus.BAD_REQUEST).send(missingHeaderErrorMessage); return; } const event = JSON.parse(request.body.toString()) as Stripe.Event; const paymentIntent = event.data.object as Stripe.PaymentIntent; if (!paymentIntent) { Logger.error(noPaymentIntentErrorMessage, loggerCtx); response.status(HttpStatus.BAD_REQUEST).send(noPaymentIntentErrorMessage); return; } const { metadata: { channelToken, orderCode, orderId } = {} } = paymentIntent; const outerCtx = await this.createContext(channelToken, request); await this.connection.withTransaction(outerCtx, async ctx => { const order = await this.orderService.findOneByCode(ctx, orderCode); if (!order) { throw new Error( `Unable to find order ${orderCode}, unable to settle payment ${paymentIntent.id}!`, ); } try { // Throws an error if the signature is invalid await this.stripeService.constructEventFromPayload(ctx, order, request.rawBody, signature); } catch (e: any) { Logger.error(`${signatureErrorMessage} ${signature}: ${(e as Error)?.message}`, loggerCtx); response.status(HttpStatus.BAD_REQUEST).send(signatureErrorMessage); return; } if (event.type === 'payment_intent.payment_failed') { const message = paymentIntent.last_payment_error?.message ?? 'unknown error'; Logger.warn(`Payment for order ${orderCode} failed: ${message}`, loggerCtx); response.status(HttpStatus.OK).send('Ok'); return; } if (event.type !== 'payment_intent.succeeded') { // This should never happen as the webhook is configured to receive // payment_intent.succeeded and payment_intent.payment_failed events only Logger.info(`Received ${event.type} status update for order ${orderCode}`, loggerCtx); return; } if (order.state !== 'ArrangingPayment') { const transitionToStateResult = await this.orderService.transitionToState( ctx, orderId, 'ArrangingPayment', ); if (transitionToStateResult instanceof OrderStateTransitionError) { Logger.error( `Error transitioning order ${orderCode} to ArrangingPayment state: ${transitionToStateResult.message}`, loggerCtx, ); return; } } const paymentMethod = await this.getPaymentMethod(ctx); const addPaymentToOrderResult = await this.orderService.addPaymentToOrder(ctx, orderId, { method: paymentMethod.code, metadata: { paymentIntentAmountReceived: paymentIntent.amount_received, paymentIntentId: paymentIntent.id, }, }); if (!(addPaymentToOrderResult instanceof Order)) { Logger.error( `Error adding payment to order ${orderCode}: ${addPaymentToOrderResult.message}`, loggerCtx, ); return; } // The payment intent ID is added to the order only if we can reach this point. Logger.info( `Stripe payment intent id ${paymentIntent.id} added to order ${orderCode}`, loggerCtx, ); }); // Send the response status only if we didn't sent anything yet. if (!response.headersSent) { response.status(HttpStatus.OK).send('Ok'); } } private async createContext(channelToken: string, req: RequestWithRawBody): Promise<RequestContext> { return this.requestContextService.create({ apiType: 'admin', channelOrToken: channelToken, req, languageCode: LanguageCode.en, }); } private async getPaymentMethod(ctx: RequestContext): Promise<PaymentMethod> { const method = (await this.paymentMethodService.findAll(ctx)).items.find( m => m.handler.code === stripePaymentMethodHandler.code, ); if (!method) { throw new InternalServerError(`[${loggerCtx}] Could not find Stripe PaymentMethod`); } return method; } }
import { CreatePaymentResult, CreateRefundResult, Injector, LanguageCode, PaymentMethodHandler, SettlePaymentResult, } from '@vendure/core'; import Stripe from 'stripe'; import { getAmountFromStripeMinorUnits } from './stripe-utils'; import { StripeService } from './stripe.service'; const { StripeError } = Stripe.errors; let stripeService: StripeService; /** * The handler for Stripe payments. */ export const stripePaymentMethodHandler = new PaymentMethodHandler({ code: 'stripe', description: [{ languageCode: LanguageCode.en, value: 'Stripe payments' }], args: { apiKey: { type: 'string', label: [{ languageCode: LanguageCode.en, value: 'API Key' }], ui: { component: 'password-form-input' }, }, webhookSecret: { type: 'string', label: [ { languageCode: LanguageCode.en, value: 'Webhook secret', }, ], description: [ { languageCode: LanguageCode.en, value: 'Secret to validate incoming webhooks. Get this from your Stripe dashboard', }, ], ui: { component: 'password-form-input' }, }, }, init(injector: Injector) { stripeService = injector.get(StripeService); }, createPayment(ctx, order, amount, ___, metadata): CreatePaymentResult { // Payment is already settled in Stripe by the time the webhook in stripe.controller.ts // adds the payment to the order if (ctx.apiType !== 'admin') { throw Error(`CreatePayment is not allowed for apiType '${ctx.apiType}'`); } const amountInMinorUnits = getAmountFromStripeMinorUnits(order, metadata.paymentIntentAmountReceived); return { amount: amountInMinorUnits, state: 'Settled' as const, transactionId: metadata.paymentIntentId, }; }, settlePayment(): SettlePaymentResult { return { success: true, }; }, async createRefund(ctx, input, amount, order, payment, args): Promise<CreateRefundResult> { // TODO: Consider passing the "reason" property once this feature request is addressed: // https://github.com/vendure-ecommerce/vendure/issues/893 try { const refund = await stripeService.createRefund(ctx, order, payment, amount); if (refund.status === 'succeeded') { return { state: 'Settled' as const, transactionId: payment.transactionId, }; } if (refund.status === 'pending') { return { state: 'Pending' as const, transactionId: payment.transactionId, }; } return { state: 'Failed' as const, transactionId: payment.transactionId, metadata: { message: refund.failure_reason, }, }; } catch (e: any) { if (e instanceof StripeError) { return { state: 'Failed' as const, transactionId: payment.transactionId, metadata: { type: e.type, message: e.message, }, }; } throw e; } }, });
import { LanguageCode, PluginCommonModule, Type, VendurePlugin } from '@vendure/core'; import { json } from 'body-parser'; import { gql } from 'graphql-tag'; import { STRIPE_PLUGIN_OPTIONS } from './constants'; import { rawBodyMiddleware } from './raw-body.middleware'; import { StripeController } from './stripe.controller'; import { stripePaymentMethodHandler } from './stripe.handler'; import { StripeResolver } from './stripe.resolver'; import { StripeService } from './stripe.service'; import { StripePluginOptions } from './types'; /** * @description * Plugin to enable payments through [Stripe](https://stripe.com/docs) via the Payment Intents API. * * ## Requirements * * 1. You will need to create a Stripe account and get your secret key in the dashboard. * 2. Create a webhook endpoint in the Stripe dashboard (Developers -> Webhooks, "Add an endpoint") which listens to the `payment_intent.succeeded` * and `payment_intent.payment_failed` events. The URL should be `https://my-server.com/payments/stripe`, where * `my-server.com` is the host of your Vendure server. *Note:* for local development, you'll need to use * the Stripe CLI to test your webhook locally. See the _local development_ section below. * 3. Get the signing secret for the newly created webhook. * 4. Install the Payments plugin and the Stripe Node library: * * `yarn add \@vendure/payments-plugin stripe` * * or * * `npm install \@vendure/payments-plugin stripe` * * ## Setup * * 1. Add the plugin to your VendureConfig `plugins` array: * ```ts * import { StripePlugin } from '\@vendure/payments-plugin/package/stripe'; * * // ... * * plugins: [ * StripePlugin.init({ * // This prevents different customers from using the same PaymentIntent * storeCustomersInStripe: true, * }), * ] * ```` * For all the plugin options, see the {@link StripePluginOptions} type. * 2. Create a new PaymentMethod in the Admin UI, and select "Stripe payments" as the handler. * 3. Set the webhook secret and API key in the PaymentMethod form. * * ## Storefront usage * * The plugin is designed to work with the [Custom payment flow](https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=elements). * In this flow, Stripe provides libraries which handle the payment UI and confirmation for you. You can install it in your storefront project * with: * * ```shell * yarn add \@stripe/stripe-js * # or * npm install \@stripe/stripe-js * ``` * * If you are using React, you should also consider installing `@stripe/react-stripe-js`, which is a wrapper around Stripe Elements. * * The high-level workflow is: * 1. Create a "payment intent" on the server by executing the `createStripePaymentIntent` mutation which is exposed by this plugin. * 2. Use the returned client secret to instantiate the Stripe Payment Element: * ```ts * import { Elements } from '\@stripe/react-stripe-js'; * import { loadStripe, Stripe } from '\@stripe/stripe-js'; * import { CheckoutForm } from './CheckoutForm'; * * const stripePromise = getStripe('pk_test_....wr83u'); * * type StripePaymentsProps = { * clientSecret: string; * orderCode: string; * } * * export function StripePayments({ clientSecret, orderCode }: StripePaymentsProps) { * const options = { * // passing the client secret obtained from the server * clientSecret, * } * return ( * <Elements stripe={stripePromise} options={options}> * <CheckoutForm orderCode={orderCode} /> * </Elements> * ); * } * ``` * ```ts * // CheckoutForm.tsx * import { useStripe, useElements, PaymentElement } from '\@stripe/react-stripe-js'; * import { FormEvent } from 'react'; * * export const CheckoutForm = ({ orderCode }: { orderCode: string }) => { * const stripe = useStripe(); * const elements = useElements(); * * const handleSubmit = async (event: FormEvent) => { * // We don't want to let default form submission happen here, * // which would refresh the page. * event.preventDefault(); * * if (!stripe || !elements) { * // Stripe.js has not yet loaded. * // Make sure to disable form submission until Stripe.js has loaded. * return; * } * * const result = await stripe.confirmPayment({ * //`Elements` instance that was used to create the Payment Element * elements, * confirmParams: { * return_url: location.origin + `/checkout/confirmation/${orderCode}`, * }, * }); * * if (result.error) { * // Show error to your customer (for example, payment details incomplete) * console.log(result.error.message); * } else { * // Your customer will be redirected to your `return_url`. For some payment * // methods like iDEAL, your customer will be redirected to an intermediate * // site first to authorize the payment, then redirected to the `return_url`. * } * }; * * return ( * <form onSubmit={handleSubmit}> * <PaymentElement /> * <button disabled={!stripe}>Submit</button> * </form> * ); * }; * ``` * 3. Once the form is submitted and Stripe processes the payment, the webhook takes care of updating the order without additional action * in the storefront. As in the code above, the customer will be redirected to `/checkout/confirmation/${orderCode}`. * * :::info * A full working storefront example of the Stripe integration can be found in the * [Remix Starter repo](https://github.com/vendure-ecommerce/storefront-remix-starter/tree/master/app/components/checkout/stripe) * ::: * * ## Local development * * 1. Download & install the Stripe CLI: https://stripe.com/docs/stripe-cli * 2. From your Stripe dashboard, go to Developers -> Webhooks and click "Add an endpoint" and follow the instructions * under "Test in a local environment". * 3. The Stripe CLI command will look like * ```shell * stripe listen --forward-to localhost:3000/payments/stripe * ``` * 4. The Stripe CLI will create a webhook signing secret you can then use in your config of the StripePlugin. * * @docsCategory core plugins/PaymentsPlugin * @docsPage StripePlugin */ @VendurePlugin({ imports: [PluginCommonModule], controllers: [StripeController], providers: [ { provide: STRIPE_PLUGIN_OPTIONS, useFactory: (): StripePluginOptions => StripePlugin.options, }, StripeService, ], configuration: config => { config.paymentOptions.paymentMethodHandlers.push(stripePaymentMethodHandler); config.apiOptions.middleware.push({ route: '/payments/stripe', handler: rawBodyMiddleware, beforeListen: true, }); if (StripePlugin.options.storeCustomersInStripe) { config.customFields.Customer.push({ name: 'stripeCustomerId', type: 'string', label: [{ languageCode: LanguageCode.en, value: 'Stripe Customer ID' }], nullable: true, public: false, readonly: true, }); } return config; }, shopApiExtensions: { schema: gql` extend type Mutation { createStripePaymentIntent: String! } `, resolvers: [StripeResolver], }, compatibility: '^2.0.0', }) export class StripePlugin { static options: StripePluginOptions; /** * @description * Initialize the Stripe payment plugin */ static init(options: StripePluginOptions): Type<StripePlugin> { this.options = options; return StripePlugin; } }
import { Mutation, Resolver } from '@nestjs/graphql'; import { ActiveOrderService, Allow, Ctx, Permission, RequestContext, UnauthorizedError, UserInputError, } from '@vendure/core'; import { StripeService } from './stripe.service'; @Resolver() export class StripeResolver { constructor(private stripeService: StripeService, private activeOrderService: ActiveOrderService) {} @Mutation() @Allow(Permission.Owner) async createStripePaymentIntent(@Ctx() ctx: RequestContext): Promise<string> { if (!ctx.authorizedAsOwnerOnly) { throw new UnauthorizedError(); } const sessionOrder = await this.activeOrderService.getActiveOrder(ctx, undefined); if (!sessionOrder) { throw new UserInputError('No active order found for session'); } return this.stripeService.createPaymentIntent(ctx, sessionOrder); } }
import { Inject, Injectable } from '@nestjs/common'; import { ModuleRef } from '@nestjs/core'; import { ConfigArg } from '@vendure/common/lib/generated-types'; import { Customer, Injector, Logger, Order, Payment, PaymentMethodService, RequestContext, TransactionalConnection, UserInputError, } from '@vendure/core'; import Stripe from 'stripe'; import { loggerCtx, STRIPE_PLUGIN_OPTIONS } from './constants'; import { sanitizeMetadata } from './metadata-sanitize'; import { VendureStripeClient } from './stripe-client'; import { getAmountInStripeMinorUnits } from './stripe-utils'; import { stripePaymentMethodHandler } from './stripe.handler'; import { StripePluginOptions } from './types'; @Injectable() export class StripeService { constructor( @Inject(STRIPE_PLUGIN_OPTIONS) private options: StripePluginOptions, private connection: TransactionalConnection, private paymentMethodService: PaymentMethodService, private moduleRef: ModuleRef, ) {} async createPaymentIntent(ctx: RequestContext, order: Order): Promise<string> { let customerId: string | undefined; const stripe = await this.getStripeClient(ctx, order); if (this.options.storeCustomersInStripe && ctx.activeUserId) { customerId = await this.getStripeCustomerId(ctx, order); } const amountInMinorUnits = getAmountInStripeMinorUnits(order); const additionalParams = await this.options.paymentIntentCreateParams?.( new Injector(this.moduleRef), ctx, order, ); const metadata = sanitizeMetadata({ ...(typeof this.options.metadata === 'function' ? await this.options.metadata(new Injector(this.moduleRef), ctx, order) : {}), channelToken: ctx.channel.token, orderId: order.id, orderCode: order.code, }); const allMetadata = { ...metadata, ...sanitizeMetadata(additionalParams?.metadata ?? {}), }; const { client_secret } = await stripe.paymentIntents.create( { amount: amountInMinorUnits, currency: order.currencyCode.toLowerCase(), customer: customerId, automatic_payment_methods: { enabled: true, }, ...(additionalParams ?? {}), metadata: allMetadata, }, { idempotencyKey: `${order.code}_${amountInMinorUnits}` }, ); if (!client_secret) { // This should never happen Logger.warn( `Payment intent creation for order ${order.code} did not return client secret`, loggerCtx, ); throw Error('Failed to create payment intent'); } return client_secret ?? undefined; } async constructEventFromPayload( ctx: RequestContext, order: Order, payload: Buffer, signature: string, ): Promise<Stripe.Event> { const stripe = await this.getStripeClient(ctx, order); return stripe.webhooks.constructEvent(payload, signature, stripe.webhookSecret); } async createRefund( ctx: RequestContext, order: Order, payment: Payment, amount: number, ): Promise<Stripe.Response<Stripe.Refund>> { const stripe = await this.getStripeClient(ctx, order); return stripe.refunds.create({ payment_intent: payment.transactionId, amount, }); } /** * Get Stripe client based on eligible payment methods for order */ async getStripeClient(ctx: RequestContext, order: Order): Promise<VendureStripeClient> { const [eligiblePaymentMethods, paymentMethods] = await Promise.all([ this.paymentMethodService.getEligiblePaymentMethods(ctx, order), this.paymentMethodService.findAll(ctx, { filter: { enabled: { eq: true }, }, }), ]); const stripePaymentMethod = paymentMethods.items.find( pm => pm.handler.code === stripePaymentMethodHandler.code, ); if (!stripePaymentMethod) { throw new UserInputError('No enabled Stripe payment method found'); } const isEligible = eligiblePaymentMethods.some(pm => pm.code === stripePaymentMethod.code); if (!isEligible) { throw new UserInputError(`Stripe payment method is not eligible for order ${order.code}`); } const apiKey = this.findOrThrowArgValue(stripePaymentMethod.handler.args, 'apiKey'); const webhookSecret = this.findOrThrowArgValue(stripePaymentMethod.handler.args, 'webhookSecret'); return new VendureStripeClient(apiKey, webhookSecret); } private findOrThrowArgValue(args: ConfigArg[], name: string): string { const value = args.find(arg => arg.name === name)?.value; if (!value) { throw Error(`No argument named '${name}' found!`); } return value; } /** * Returns the stripeCustomerId if the Customer has one. If that's not the case, queries Stripe to check * if the customer is already registered, in which case it saves the id as stripeCustomerId and returns it. * Otherwise, creates a new Customer record in Stripe and returns the generated id. */ private async getStripeCustomerId(ctx: RequestContext, activeOrder: Order): Promise<string | undefined> { const [stripe, order] = await Promise.all([ this.getStripeClient(ctx, activeOrder), // Load relation with customer not available in the response from activeOrderService.getOrderFromContext() this.connection.getRepository(ctx, Order).findOne({ where: { id: activeOrder.id }, relations: ['customer'], }), ]); if (!order || !order.customer) { // This should never happen return undefined; } const { customer } = order; if (customer.customFields.stripeCustomerId) { return customer.customFields.stripeCustomerId; } let stripeCustomerId; const stripeCustomers = await stripe.customers.list({ email: customer.emailAddress }); if (stripeCustomers.data.length > 0) { stripeCustomerId = stripeCustomers.data[0].id; } else { const additionalParams = await this.options.customerCreateParams?.( new Injector(this.moduleRef), ctx, order, ); const newStripeCustomer = await stripe.customers.create({ email: customer.emailAddress, name: `${customer.firstName} ${customer.lastName}`, ...(additionalParams ?? {}), ...(additionalParams?.metadata ? { metadata: sanitizeMetadata(additionalParams.metadata) } : {}), }); stripeCustomerId = newStripeCustomer.id; Logger.info(`Created Stripe Customer record for customerId ${customer.id}`, loggerCtx); } customer.customFields.stripeCustomerId = stripeCustomerId; await this.connection.getRepository(ctx, Customer).save(customer, { reload: false }); return stripeCustomerId; } }
import '@vendure/core/dist/entity/custom-entity-fields'; import type { Injector, Order, RequestContext } from '@vendure/core'; import type { Request } from 'express'; import type Stripe from 'stripe'; // Note: deep import is necessary here because CustomCustomerFields is also extended in the Braintree // plugin. Reference: https://github.com/microsoft/TypeScript/issues/46617 declare module '@vendure/core/dist/entity/custom-entity-fields' { interface CustomCustomerFields { stripeCustomerId?: string; } } type AdditionalPaymentIntentCreateParams = Partial< Omit<Stripe.PaymentIntentCreateParams, 'amount' | 'currency' | 'customer'> >; type AdditionalCustomerCreateParams = Partial<Omit<Stripe.CustomerCreateParams, 'email'>>; /** * @description * Configuration options for the Stripe payments plugin. * * @docsCategory core plugins/PaymentsPlugin * @docsPage StripePlugin */ export interface StripePluginOptions { /** * @description * If set to `true`, a [Customer](https://stripe.com/docs/api/customers) object will be created in Stripe - if * it doesn't already exist - for authenticated users, which prevents payment methods attached to other Customers * to be used with the same PaymentIntent. This is done by adding a custom field to the Customer entity to store * the Stripe customer ID, so switching this on will require a database migration / synchronization. * * @default false */ storeCustomersInStripe?: boolean; /** * @description * Attach extra metadata to Stripe payment intent creation call. * * @example * ```ts * import { EntityHydrator, VendureConfig } from '\@vendure/core'; * import { StripePlugin } from '\@vendure/payments-plugin/package/stripe'; * * export const config: VendureConfig = { * // ... * plugins: [ * StripePlugin.init({ * metadata: async (injector, ctx, order) => { * const hydrator = injector.get(EntityHydrator); * await hydrator.hydrate(ctx, order, { relations: ['customer'] }); * return { * description: `Order #${order.code} for ${order.customer!.emailAddress}` * }, * } * }), * ], * }; * ``` * * Note: If the `paymentIntentCreateParams` is also used and returns a `metadata` key, then the values * returned by both functions will be merged. * * @since 1.9.7 */ metadata?: ( injector: Injector, ctx: RequestContext, order: Order, ) => Stripe.MetadataParam | Promise<Stripe.MetadataParam>; /** * @description * Provide additional parameters to the Stripe payment intent creation. By default, * the plugin will already pass the `amount`, `currency`, `customer` and `automatic_payment_methods: { enabled: true }` parameters. * * For example, if you want to provide a `description` for the payment intent, you can do so like this: * * @example * ```ts * import { VendureConfig } from '\@vendure/core'; * import { StripePlugin } from '\@vendure/payments-plugin/package/stripe'; * * export const config: VendureConfig = { * // ... * plugins: [ * StripePlugin.init({ * paymentIntentCreateParams: (injector, ctx, order) => { * return { * description: `Order #${order.code} for ${order.customer?.emailAddress}` * }, * } * }), * ], * }; * ``` * * @since 2.1.0 * */ paymentIntentCreateParams?: ( injector: Injector, ctx: RequestContext, order: Order, ) => AdditionalPaymentIntentCreateParams | Promise<AdditionalPaymentIntentCreateParams>; /** * @description * Provide additional parameters to the Stripe customer creation. By default, * the plugin will already pass the `email` and `name` parameters. * * For example, if you want to provide an address for the customer: * * @example * ```ts * import { EntityHydrator, VendureConfig } from '\@vendure/core'; * import { StripePlugin } from '\@vendure/payments-plugin/package/stripe'; * * export const config: VendureConfig = { * // ... * plugins: [ * StripePlugin.init({ * storeCustomersInStripe: true, * customerCreateParams: async (injector, ctx, order) => { * const entityHydrator = injector.get(EntityHydrator); * const customer = order.customer; * await entityHydrator.hydrate(ctx, customer, { relations: ['addresses'] }); * const defaultBillingAddress = customer.addresses.find(a => a.defaultBillingAddress) ?? customer.addresses[0]; * return { * address: { * line1: defaultBillingAddress.streetLine1 || order.shippingAddress?.streetLine1, * postal_code: defaultBillingAddress.postalCode || order.shippingAddress?.postalCode, * city: defaultBillingAddress.city || order.shippingAddress?.city, * state: defaultBillingAddress.province || order.shippingAddress?.province, * country: defaultBillingAddress.country.code || order.shippingAddress?.countryCode, * }, * }, * } * }), * ], * }; * ``` * * @since 2.1.0 */ customerCreateParams?: ( injector: Injector, ctx: RequestContext, order: Order, ) => AdditionalCustomerCreateParams | Promise<AdditionalCustomerCreateParams>; } export interface RequestWithRawBody extends Request { rawBody: Buffer; }
export * from './src/sentry-plugin'; export * from './src/sentry.service'; export * from './src/types'; export * from './src/constants';
export const SENTRY_PLUGIN_OPTIONS = 'SENTRY_PLUGIN_OPTIONS'; export const SENTRY_TRANSACTION_KEY = 'SENTRY_PLUGIN_TRANSACTION'; export const loggerCtx = 'SentryPlugin';
/* eslint-disable @typescript-eslint/require-await */ import { ApolloServerPlugin, GraphQLRequestListener, GraphQLRequestContext, GraphQLRequestContextDidEncounterErrors, } from '@apollo/server'; import { Transaction, setContext } from '@sentry/node'; import { SENTRY_TRANSACTION_KEY } from './constants'; /** * Based on https://github.com/ntegral/nestjs-sentry/issues/97#issuecomment-1252446807 */ export class SentryApolloPlugin implements ApolloServerPlugin { constructor(private options: { enableTracing: boolean }) {} async requestDidStart({ request, contextValue, }: GraphQLRequestContext<any>): Promise<GraphQLRequestListener<any>> { const { enableTracing } = this.options; const transaction: Transaction | undefined = contextValue.req[SENTRY_TRANSACTION_KEY]; if (request.operationName) { if (enableTracing) { // set the transaction Name if we have named queries transaction?.setName(request.operationName); } setContext('Graphql Request', { operation_name: request.operationName, variables: request.variables, }); } return { // hook for transaction finished async willSendResponse(context) { transaction?.finish(); }, async executionDidStart() { return { // hook for each new resolver willResolveField({ info }) { if (enableTracing) { const span = transaction?.startChild({ op: 'resolver', description: `${info.parentType.name}.${info.fieldName}`, }); return () => { span?.finish(); }; } }, }; }, }; } }
import { Inject, Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; import { SENTRY_PLUGIN_OPTIONS, SENTRY_TRANSACTION_KEY } from './constants'; import { SentryService } from './sentry.service'; import { SentryPluginOptions } from './types'; @Injectable() export class SentryContextMiddleware implements NestMiddleware { constructor( @Inject(SENTRY_PLUGIN_OPTIONS) private options: SentryPluginOptions, private sentryService: SentryService, ) {} use(req: Request, res: Response, next: NextFunction) { if (this.options.enableTracing) { const transaction = this.sentryService.startTransaction({ op: 'resolver', name: `GraphQLTransaction`, }); req[SENTRY_TRANSACTION_KEY] = transaction; } next(); } }
import { ArgumentsHost, ExecutionContext } from '@nestjs/common'; import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql'; import { setContext } from '@sentry/node'; import { ErrorHandlerStrategy, I18nError, Injector, Job, LogLevel } from '@vendure/core'; import { SentryService } from './sentry.service'; export class SentryErrorHandlerStrategy implements ErrorHandlerStrategy { private sentryService: SentryService; init(injector: Injector) { this.sentryService = injector.get(SentryService); } handleServerError(exception: Error, { host }: { host: ArgumentsHost }) { // We only care about errors which have at least a Warn log level const shouldLogError = exception instanceof I18nError ? exception.logLevel <= LogLevel.Warn : true; if (shouldLogError) { if (host?.getType<GqlContextType>() === 'graphql') { const gqlContext = GqlExecutionContext.create(host as ExecutionContext); const info = gqlContext.getInfo(); setContext('GraphQL Error Context', { fieldName: info.fieldName, path: info.path, }); } const variables = (exception as any).variables; if (variables) { setContext('GraphQL Error Variables', variables); } this.sentryService.captureException(exception); } } handleWorkerError(exception: Error, { job }: { job: Job }) { setContext('Worker Context', { queueName: job.queueName, jobId: job.id, }); this.sentryService.captureException(exception); } }
import { MiddlewareConsumer, NestModule } from '@nestjs/common'; import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { SentryAdminTestResolver } from './api/admin-test.resolver'; import { testApiExtensions } from './api/api-extensions'; import { ErrorTestService } from './api/error-test.service'; import { SENTRY_PLUGIN_OPTIONS } from './constants'; import { SentryApolloPlugin } from './sentry-apollo-plugin'; import { SentryContextMiddleware } from './sentry-context.middleware'; import { SentryErrorHandlerStrategy } from './sentry-error-handler-strategy'; import { SentryService } from './sentry.service'; import { SentryPluginOptions } from './types'; const SentryOptionsProvider = { provide: SENTRY_PLUGIN_OPTIONS, useFactory: () => SentryPlugin.options, }; /** * @description * This plugin integrates the [Sentry](https://sentry.io) error tracking & performance monitoring * service with your Vendure server. In addition to capturing errors, it also provides built-in * support for [tracing](https://docs.sentry.io/product/sentry-basics/concepts/tracing/) as well as * enriching your Sentry events with additional context about the request. * * ## Pre-requisites * * This plugin depends on access to Sentry, which can be self-hosted or used as a cloud service. * * If using the hosted SaaS option, you must have a Sentry account and a project set up ([sign up here](https://sentry.io/signup/)). When setting up your project, * select the "Node.js" platform and no framework. * * Once set up, you will be given a [Data Source Name (DSN)](https://docs.sentry.io/product/sentry-basics/concepts/dsn-explainer/) * which you will need to provide to the plugin. * * ## Installation * * Install this plugin as well as the `@sentry/node` package: * * ```sh * npm install --save \@vendure/sentry-plugin \@sentry/node * ``` * * ## Configuration * * Before using the plugin, you must configure it with the DSN provided by Sentry: * * ```ts * import { VendureConfig } from '\@vendure/core'; * import { SentryPlugin } from '\@vendure/sentry-plugin'; * * export const config: VendureConfig = { * // ... * plugins: [ * // ... * // highlight-start * SentryPlugin.init({ * dsn: process.env.SENTRY_DSN, * // Optional configuration * includeErrorTestMutation: true, * enableTracing: true, * // you can also pass in any of the options from \@sentry/node * // for instance: * tracesSampleRate: 1.0, * }), * // highlight-end * ], * }; *``` * * ## Tracing * * This plugin includes built-in support for [tracing](https://docs.sentry.io/product/sentry-basics/concepts/tracing/), which allows you to see the performance of your * GraphQL resolvers in the Sentry dashboard. To enable tracing, set the `enableTracing` option to `true` as shown above. * * ## Instrumenting your own code * * You may want to add your own custom spans to your code. To do so, you can use the `Sentry` object * just as you would in any Node application. For example: * * ```ts * import * as Sentry from "\@sentry/node"; * * export class MyService { * async myMethod() { * Sentry.setContext('My Custom Context,{ * key: 'value', * }); * } * } * ``` * * ## Error test mutation * * To test whether your Sentry configuration is working correctly, you can set the `includeErrorTestMutation` option to `true`. This will add a mutation to the Admin API * which will throw an error of the type specified in the `errorType` argument. For example: * * ```graphql * mutation CreateTestError { * createTestError(errorType: DATABASE_ERROR) * } * ``` * * You should then be able to see the error in your Sentry dashboard (it may take a couple of minutes to appear). * * @docsCategory core plugins/SentryPlugin */ @VendurePlugin({ imports: [PluginCommonModule], providers: [SentryOptionsProvider, SentryService, ErrorTestService], configuration: config => { config.apiOptions.apolloServerPlugins.push( new SentryApolloPlugin({ enableTracing: !!SentryPlugin.options.enableTracing, }), ); config.systemOptions.errorHandlers.push(new SentryErrorHandlerStrategy()); return config; }, adminApiExtensions: { schema: () => (SentryPlugin.options.includeErrorTestMutation ? testApiExtensions : undefined), resolvers: () => (SentryPlugin.options.includeErrorTestMutation ? [SentryAdminTestResolver] : []), }, exports: [SentryService], compatibility: '^2.2.0-next.2', }) export class SentryPlugin implements NestModule { static options: SentryPluginOptions = {} as any; configure(consumer: MiddlewareConsumer): any { consumer.apply(SentryContextMiddleware).forRoutes('*'); } static init(options: SentryPluginOptions) { this.options = options; return this; } }
import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common'; import { Catch, ExecutionContext } from '@nestjs/common'; import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql'; import { setContext } from '@sentry/node'; import { ExceptionLoggerFilter, ForbiddenError, I18nError, LogLevel } from '@vendure/core'; import { SentryService } from './sentry.service'; export class SentryExceptionsFilter extends ExceptionLoggerFilter { constructor(private readonly sentryService: SentryService) { super(); } catch(exception: Error, host: ArgumentsHost) { const shouldLogError = exception instanceof I18nError ? exception.logLevel <= LogLevel.Warn : true; if (shouldLogError) { if (host.getType<GqlContextType>() === 'graphql') { const gqlContext = GqlExecutionContext.create(host as ExecutionContext); const info = gqlContext.getInfo(); setContext('GraphQL Error Context', { fieldName: info.fieldName, path: info.path, }); } const variables = (exception as any).variables; if (variables) { setContext('GraphQL Error Variables', variables); } this.sentryService.captureException(exception); } return super.catch(exception, host); } }
import { Inject, Injectable, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import * as Sentry from '@sentry/node'; import { CaptureContext, TransactionContext } from '@sentry/types'; import { SENTRY_PLUGIN_OPTIONS } from './constants'; import { SentryPluginOptions } from './types'; @Injectable() export class SentryService implements OnApplicationBootstrap, OnApplicationShutdown { constructor(@Inject(SENTRY_PLUGIN_OPTIONS) private options: SentryPluginOptions) {} onApplicationBootstrap(): any { const integrations = this.options.integrations ?? [ new Sentry.Integrations.Http({ tracing: true }), ...Sentry.autoDiscoverNodePerformanceMonitoringIntegrations(), ]; Sentry.init({ ...this.options, tracesSampleRate: this.options.tracesSampleRate ?? 1.0, integrations, dsn: this.options.dsn, }); } onApplicationShutdown() { return Sentry.close(); } captureException(exception: Error) { Sentry.captureException(exception); } captureMessage(message: string, captureContext?: CaptureContext) { Sentry.captureMessage(message, captureContext); } startTransaction(context: TransactionContext) { return Sentry.startTransaction(context); } }
import { Transaction } from '@sentry/node'; import { NodeOptions } from '@sentry/node/types/types'; import { SENTRY_TRANSACTION_KEY } from './constants'; /** * @description * Configuration options for the {@link SentryPlugin}. * * @docsCategory core plugins/SentryPlugin */ export interface SentryPluginOptions extends NodeOptions { /** * @description * The [Data Source Name](https://docs.sentry.io/product/sentry-basics/concepts/dsn-explainer/) for your Sentry instance. */ dsn: string; enableTracing?: boolean; includeErrorTestMutation?: boolean; } declare module 'express' { interface Request { [SENTRY_TRANSACTION_KEY]: Transaction | undefined; } }
import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { Allow, Permission, UserInputError } from '@vendure/core'; import { SentryService } from '../sentry.service'; import { ErrorTestService } from './error-test.service'; declare const a: number; @Resolver() export class SentryAdminTestResolver { constructor(private sentryService: SentryService, private errorTestService: ErrorTestService) {} @Allow(Permission.SuperAdmin) @Mutation() async createTestError(@Args() args: { errorType: string }) { switch (args.errorType) { case 'UNCAUGHT_ERROR': return a / 10; case 'THROWN_ERROR': throw new UserInputError('SentryPlugin Test Error'); case 'CAPTURED_ERROR': this.sentryService.captureException(new Error('SentryPlugin Direct error')); return true; case 'CAPTURED_MESSAGE': this.sentryService.captureMessage('Captured message'); return true; case 'DATABASE_ERROR': await this.errorTestService.createDatabaseError(); return true; } } }
import gql from 'graphql-tag'; export const testApiExtensions = gql` enum TestErrorType { UNCAUGHT_ERROR THROWN_ERROR CAPTURED_ERROR CAPTURED_MESSAGE DATABASE_ERROR } extend type Mutation { createTestError(errorType: TestErrorType!): Boolean } `;
import { Injectable } from '@nestjs/common'; import { TransactionalConnection } from '@vendure/core'; @Injectable() export class ErrorTestService { constructor(private connection: TransactionalConnection) {} createDatabaseError() { return this.connection.rawConnection.query('SELECT * FROM non_existent_table'); } }
export * from './src/stellate-plugin'; export * from './src/service/stellate.service'; export * from './src/default-purge-rules'; export * from './src/purge-rule'; export * from './src/types'; export * from './src/constants';
export const STELLATE_PLUGIN_OPTIONS = 'STELLATE_PLUGIN_OPTIONS'; export const loggerCtx = 'StellatePlugin';
/* eslint-disable @typescript-eslint/no-floating-promises */ import { CollectionEvent, CollectionModificationEvent, Logger, ProductChannelEvent, ProductEvent, ProductVariantChannelEvent, ProductVariantEvent, StockMovementEvent, TaxRateEvent, } from '@vendure/core'; import { loggerCtx } from './constants'; import { PurgeRule } from './purge-rule'; export const purgeProductsOnProductEvent = new PurgeRule({ eventType: ProductEvent, handler: ({ events, stellateService }) => { const products = events.map(e => e.product); stellateService.purgeProducts(products); stellateService.purgeSearchResults(products); }, }); export const purgeProductVariantsOnProductVariantEvent = new PurgeRule({ eventType: ProductVariantEvent, handler: ({ events, stellateService }) => { const variants = events.map(e => e.variants).flat(); stellateService.purgeProductVariants(variants); stellateService.purgeSearchResults(variants); }, }); export const purgeProductsOnChannelEvent = new PurgeRule({ eventType: ProductChannelEvent, handler: ({ events, stellateService }) => { const products = events.map(e => e.product); stellateService.purgeProducts(products); stellateService.purgeSearchResults(products); }, }); export const purgeProductVariantsOnChannelEvent = new PurgeRule({ eventType: ProductVariantChannelEvent, handler: ({ events, stellateService }) => { const variants = events.map(e => e.productVariant); stellateService.purgeProductVariants(variants); stellateService.purgeSearchResults(variants); }, }); export const purgeProductVariantsOnStockMovementEvent = new PurgeRule({ eventType: StockMovementEvent, handler: ({ events, stellateService }) => { const variants = events.map(e => e.stockMovements.map(m => m.productVariant)).flat(); stellateService.purgeProductVariants(variants); stellateService.purgeSearchResults(variants); }, }); export const purgeCollectionsOnCollectionModificationEvent = new PurgeRule({ eventType: CollectionModificationEvent, handler: ({ events, stellateService }) => { const collectionsToPurge = events.filter(e => e.productVariantIds.length).map(e => e.collection); Logger.debug( `purgeCollectionsOnCollectionModificationEvent, collectionsToPurge: ${collectionsToPurge .map(c => c.id) .join(', ')}`, loggerCtx, ); if (collectionsToPurge.length) { stellateService.purgeCollections(collectionsToPurge); stellateService.purgeSearchResponseCacheIdentifiers(collectionsToPurge); } }, }); export const purgeCollectionsOnCollectionEvent = new PurgeRule({ eventType: CollectionEvent, handler: ({ events, stellateService }) => { const collections = events.map(e => e.entity); stellateService.purgeCollections(collections); }, }); export const purgeAllOnTaxRateEvent = new PurgeRule({ eventType: TaxRateEvent, handler: ({ stellateService }) => { stellateService.purgeAllOfType('ProductVariant'); stellateService.purgeAllOfType('Product'); stellateService.purgeAllOfType('SearchResponse'); }, }); export const defaultPurgeRules = [ purgeAllOnTaxRateEvent, purgeCollectionsOnCollectionEvent, purgeCollectionsOnCollectionModificationEvent, purgeProductsOnChannelEvent, purgeProductsOnProductEvent, purgeProductVariantsOnChannelEvent, purgeProductVariantsOnProductVariantEvent, purgeProductVariantsOnStockMovementEvent, ];
import { Type } from '@vendure/common/lib/shared-types'; import { VendureEvent, Injector } from '@vendure/core'; import { StellateService } from './service/stellate.service'; /** * @description * Configures a {@link PurgeRule}. * * @docsCategory core plugins/StellatePlugin * @docsPage PurgeRule */ export interface PurgeRuleConfig<Event extends VendureEvent> { /** * @description * Specifies which VendureEvent will trigger this purge rule. */ eventType: Type<Event>; /** * @description * How long to buffer events for in milliseconds before executing the handler. This allows * us to efficiently batch calls to the Stellate Purge API. * * @default 5000 */ bufferTime?: number; /** * @description * The function to invoke when the specified event is published. This function should use the * {@link StellateService} instance to call the Stellate Purge API. */ handler: (handlerArgs: { events: Event[]; stellateService: StellateService; injector: Injector; }) => void | Promise<void>; } /** * @description * Defines a rule that listens for a particular VendureEvent and uses that to * make calls to the [Stellate Purging API](https://docs.stellate.co/docs/purging-api) via * the provided {@link StellateService} instance. * * @docsCategory core plugins/StellatePlugin * @docsPage PurgeRule * @docsWeight 0 */ export class PurgeRule<Event extends VendureEvent = VendureEvent> { get eventType(): Type<Event> { return this.config.eventType; } get bufferTimeMs(): number | undefined { return this.config.bufferTime; } handle(handlerArgs: { events: Event[]; stellateService: StellateService; injector: Injector }) { return this.config.handler(handlerArgs); } constructor(private config: PurgeRuleConfig<Event>) {} }
import { Inject, OnApplicationBootstrap } from '@nestjs/common'; import { ModuleRef } from '@nestjs/core'; import { EventBus, Injector, PluginCommonModule, VendurePlugin } from '@vendure/core'; import { buffer, debounceTime } from 'rxjs/operators'; import { shopApiExtensions } from './api/api-extensions'; import { SearchResponseFieldResolver } from './api/search-response.resolver'; import { STELLATE_PLUGIN_OPTIONS } from './constants'; import { StellateService } from './service/stellate.service'; import { StellatePluginOptions } from './types'; const StellateOptionsProvider = { provide: STELLATE_PLUGIN_OPTIONS, useFactory: () => StellatePlugin.options, }; /** * @description * A plugin to integrate the [Stellate](https://stellate.co/) GraphQL caching service with your Vendure server. * The main purpose of this plugin is to ensure that cached data gets correctly purged in * response to events inside Vendure. For example, changes to a Product's description should * purge any associated record for that Product in Stellate's cache. * * ## Pre-requisites * * You will first need to [set up a free Stellate account](https://stellate.co/signup). * * You will also need to generate an **API token** for the Stellate Purging API. For instructions on how to generate the token, * see the [Stellate Purging API docs](https://docs.stellate.co/docs/purging-api#authentication). * * ## Installation * * ``` * npm install \@vendure/stellate-plugin * ``` * * ## Configuration * * The plugin is configured via the `StellatePlugin.init()` method. This method accepts an options object * which defines the Stellate service name and API token, as well as an array of {@link PurgeRule}s which * define how the plugin will respond to Vendure events in order to trigger calls to the * Stellate [Purging API](https://stellate.co/docs/graphql-edge-cache/purging-api). * * @example * ```ts * import { StellatePlugin, defaultPurgeRules } from '\@vendure/stellate-plugin'; * import { VendureConfig } from '\@vendure/core'; * * export const config: VendureConfig = { * // ... * plugins: [ * StellatePlugin.init({ * // The Stellate service name, i.e. `<serviceName>.stellate.sh` * serviceName: 'my-service', * // The API token for the Stellate Purging API. See the "pre-requisites" section above. * apiToken: process.env.STELLATE_PURGE_API_TOKEN, * devMode: !isProd || process.env.STELLATE_DEBUG_MODE ? true : false, * debugLogging: process.env.STELLATE_DEBUG_MODE ? true : false, * purgeRules: [ * ...defaultPurgeRules, * // custom purge rules can be added here * ], * }), * ], * }; * ``` * * In your Stellate dashboard, you can use the following configuration example as a sensible default for a * Vendure application: * * @example * ```ts * import { Config } from "stellate"; * * const config: Config = { * config: { * name: "my-vendure-server", * originUrl: "https://my-vendure-server.com/shop-api", * ignoreOriginCacheControl: true, * passThroughOnly: false, * scopes: { * SESSION_BOUND: "header:authorization|cookie:session", * }, * headers: { * "access-control-expose-headers": "vendure-auth-token", * }, * rootTypeNames: { * query: "Query", * mutation: "Mutation", * }, * keyFields: { * types: { * SearchResult: ["productId"], * SearchResponseCacheIdentifier: ["collectionSlug"], * }, * }, * rules: [ * { * types: [ * "Product", * "Collection", * "ProductVariant", * "SearchResponse", * ], * maxAge: 900, * swr: 900, * description: "Cache Products & Collections", * }, * { * types: ["Channel"], * maxAge: 9000, * swr: 9000, * description: "Cache active channel", * }, * { * types: ["Order", "Customer", "User"], * maxAge: 0, * swr: 0, * description: "Do not cache user data", * }, * ], * }, * }; * export default config; * ``` * * ## Storefront setup * * In your storefront, you should point your GraphQL client to the Stellate GraphQL API endpoint, which is * `https://<service-name>.stellate.sh`. * * Wherever you are using the `search` query (typically in product listing & search pages), you should also add the * `cacheIdentifier` field to the query. This will ensure that the Stellate cache is correctly purged when * a Product or Collection is updated. * * @example * ```ts * import { graphql } from '../generated/gql'; * * export const searchProductsDocument = graphql(` * query SearchProducts($input: SearchInput!) { * search(input: $input) { * // highlight-start * cacheIdentifier { * collectionSlug * } * // highlight-end * items { * # ... * } * } * } * }`); * ``` * * ## Custom PurgeRules * * The configuration above only accounts for caching of some of the built-in Vendure entity types. If you have * custom entity types, you may well want to add them to the Stellate cache. In this case, you'll also need a way to * purge those entities from the cache when they are updated. This is where the {@link PurgeRule} comes in. * * Let's imagine that you have built a simple CMS plugin for Vendure which exposes an `Article` entity in your Shop API, and * you have added this to your Stellate configuration: * * @example * ```ts * import { Config } from "stellate"; * * const config: Config = { * config: { * // ... * rules: [ * // ... * { * types: ["Article"], * maxAge: 900, * swr: 900, * description: "Cache Articles", * }, * ], * }, * // ... * }; * export default config; * ``` * * You can then add a custom {@link PurgeRule} to the StellatePlugin configuration: * * @example * ```ts * import { StellatePlugin, defaultPurgeRules } from "\@vendure/stellate-plugin"; * import { VendureConfig } from "\@vendure/core"; * import { ArticleEvent } from "./plugins/cms/events/article-event"; * * export const config: VendureConfig = { * // ... * plugins: [ * StellatePlugin.init({ * // ... * purgeRules: [ * ...defaultPurgeRules, * new PurgeRule({ * eventType: ArticleEvent, * handler: async ({ events, stellateService }) => { * const articleIds = events.map((e) => e.article.id); * stellateService.purge("Article", articleIds); * }, * }), * ], * }), * ], * }; * ``` * * ## DevMode & Debug Logging * * In development, you can set `devMode: true`, which will prevent any calls being made to the Stellate Purging API. * * If you want to log the calls that _would_ be made to the Stellate Purge API when in devMode, you can set `debugLogging: true`. * Note that debugLogging generates a lot of debug-level logging, so it is recommended to only enable this when needed. * * @example * ```ts * import { StellatePlugin, defaultPurgeRules } from '\@vendure/stellate-plugin'; * import { VendureConfig } from '\@vendure/core'; * * export const config: VendureConfig = { * // ... * plugins: [ * StellatePlugin.init({ * // ... * devMode: !process.env.PRODUCTION, * debugLogging: process.env.STELLATE_DEBUG_MODE ? true : false, * purgeRules: [ * ...defaultPurgeRules, * ], * }), * ], * }; * ``` * * * @since 2.1.5 * @docsCategory core plugins/StellatePlugin */ @VendurePlugin({ imports: [PluginCommonModule], providers: [StellateOptionsProvider, StellateService], shopApiExtensions: { schema: shopApiExtensions, resolvers: [SearchResponseFieldResolver], }, compatibility: '^2.0.0', }) export class StellatePlugin implements OnApplicationBootstrap { static options: StellatePluginOptions; static init(options: StellatePluginOptions) { this.options = options; return this; } constructor( @Inject(STELLATE_PLUGIN_OPTIONS) private options: StellatePluginOptions, private eventBus: EventBus, private stellateService: StellateService, private moduleRef: ModuleRef, ) {} onApplicationBootstrap() { const injector = new Injector(this.moduleRef); for (const purgeRule of this.options.purgeRules ?? []) { const source$ = this.eventBus.ofType(purgeRule.eventType); source$ .pipe( buffer( source$.pipe( debounceTime(purgeRule.bufferTimeMs ?? this.options.defaultBufferTimeMs ?? 2000), ), ), ) .subscribe(events => purgeRule.handle({ events, injector, stellateService: this.stellateService }), ); } } }
import { PurgeRule } from './purge-rule'; /** * @description * Configuration options for the StellatePlugin. * * @docsCategory core plugins/StellatePlugin */ export interface StellatePluginOptions { /** * @description * The Stellate service name, i.e. `<service-name>.stellate.sh` */ serviceName: string; /** * @description * The Stellate Purging API token. For instructions on how to generate the token, * see the [Stellate docs](https://docs.stellate.co/docs/purging-api#authentication) */ apiToken: string; /** * @description * An array of {@link PurgeRule} instances which are used to define how the plugin will * respond to Vendure events in order to trigger calls to the Stellate Purging API. */ purgeRules: PurgeRule[]; /** * @description * When events are published, the PurgeRules will buffer those events in order to efficiently * batch requests to the Stellate Purging API. You may wish to change the default, e.g. if you are * running in a serverless environment and cannot introduce pauses after the main request has completed. * * @default 2000 */ defaultBufferTimeMs?: number; /** * @description * When set to `true`, calls will not be made to the Stellate Purge API. * * @default false */ devMode?: boolean; /** * @description * If set to true, the plugin will log the calls that would be made * to the Stellate Purge API. Note, this generates a * lot of debug-level logging. * * @default false */ debugLogging?: boolean; }
import gql from 'graphql-tag'; export const shopApiExtensions = gql` """ This type is here to allow us to easily purge the Stellate cache of any search results where the collectionSlug is used. We cannot rely on simply purging the SearchResult type, because in the case of an empty 'items' array, Stellate cannot know that that particular query now needs to be purged. """ type SearchResponseCacheIdentifier { collectionSlug: String } extend type SearchResponse { cacheIdentifier: SearchResponseCacheIdentifier } `;
import { Info, ResolveField, Resolver } from '@nestjs/graphql'; import { GraphQLResolveInfo } from 'graphql/type'; @Resolver('SearchResponse') export class SearchResponseFieldResolver { @ResolveField() cacheIdentifier(@Info() info: GraphQLResolveInfo) { const collectionSlug = (info.variableValues.input as any)?.collectionSlug; return { collectionSlug }; } }
import { Inject } from '@nestjs/common'; import { Collection, ID, Logger, Product, ProductVariant } from '@vendure/core'; import fetch from 'node-fetch'; import { loggerCtx, STELLATE_PLUGIN_OPTIONS } from '../constants'; import { StellatePluginOptions } from '../types'; type CachedType = | 'Product' | 'ProductVariant' | 'Collection' | 'SearchResponse' | 'SearchResult' | 'SearchResponseCacheIdentifier' | string; /** * @description * The StellateService is used to purge the Stellate cache when certain events occur. * * @docsCategory core plugins/StellatePlugin */ export class StellateService { private readonly purgeApiUrl: string; constructor(@Inject(STELLATE_PLUGIN_OPTIONS) private options: StellatePluginOptions) { this.purgeApiUrl = `https://admin.stellate.co/${options.serviceName}`; } /** * @description * Purges the cache for the given Products. */ async purgeProducts(products: Product[]) { Logger.verbose(`Purging cache: Product(${products.map(p => p.id).join(', ')})`, loggerCtx); await this.purge( 'Product', products.map(p => p.id), ); } /** * @description * Purges the cache for the given ProductVariants. */ async purgeProductVariants(productVariants: ProductVariant[]) { Logger.verbose( `Purging cache: ProductVariant(${productVariants.map(p => p.id).join(', ')})`, loggerCtx, ); await this.purge( 'ProductVariant', productVariants.map(p => p.id), ); } /** * @description * Purges the cache for SearchResults which contain the given Products or ProductVariants. */ async purgeSearchResults(items: Array<ProductVariant | Product>) { const productIds = items.map(item => (item instanceof Product ? item.id : item.productId)); Logger.verbose(`Purging cache: SearchResult(${productIds.join(', ')})`, loggerCtx); await this.purge('SearchResult', productIds, 'productId'); } /** * @description * Purges the entire cache for the given type. */ async purgeAllOfType(type: CachedType) { Logger.verbose(`Purging cache: All ${type}s`, loggerCtx); await this.purge(type); } /** * @description * Purges the cache for the given Collections. */ async purgeCollections(collections: Collection[]) { Logger.verbose(`Purging cache: Collection(${collections.map(c => c.id).join(', ')})`, loggerCtx); await this.purge( 'Collection', collections.map(p => p.id), ); } /** * @description * Purges the cache of SearchResults for the given Collections based on slug. */ async purgeSearchResponseCacheIdentifiers(collections: Collection[]) { const slugs = collections.map(c => c.slug ?? c.translations?.[0]?.slug); if (slugs.length) { Logger.verbose(`Purging cache: SearchResponseCacheIdentifier(${slugs.join(', ')})`, loggerCtx); await this.purge('SearchResponseCacheIdentifier', slugs); } } /** * @description * Purges the cache for the given type and keys. */ purge(type: CachedType, keys?: ID[], keyName = 'id') { const payload = { query: ` mutation PurgeType($type: String!, $keyFields: [KeyFieldInput!]) { _purgeType(type: $type, keyFields: $keyFields) } `, variables: { type, keyFields: keys?.filter(id => !!id).map(id => ({ name: keyName, value: id.toString() })), }, }; if (this.options.debugLogging === true) { const keyFieldsLength = payload.variables.keyFields?.length ?? 0; if (5 < keyFieldsLength) { payload.variables.keyFields = payload.variables.keyFields?.slice(0, 5); } Logger.debug('Purge arguments:\n' + JSON.stringify(payload.variables, null, 2), loggerCtx); if (5 < keyFieldsLength) { Logger.debug(`(A further ${keyFieldsLength - 5} keyFields truncated)`, loggerCtx); } } if (this.options.devMode === true) { // no-op } else { return fetch(this.purgeApiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'stellate-token': this.options.apiToken, }, body: JSON.stringify(payload), timeout: 5000, }) .then(res => res.json()) .then(json => { if (json.data?._purgeType !== true) { const errors = json.errors?.map((e: any) => e.message) as string[]; Logger.error(`Purge failed: ${errors.join(', ') ?? JSON.stringify(json)}`, loggerCtx); } }) .catch((err: any) => { Logger.error(`Purge error: ${err.message as string}`, loggerCtx); }); } } }
import { VendureConfig } from '@vendure/core'; import { SimpleGraphQLClient } from './simple-graphql-client'; import { TestServer } from './test-server'; /** * @description * The return value of {@link createTestEnvironment}, containing the test server * and clients for the Shop API and Admin API. * * @docsCategory testing */ export interface TestEnvironment { /** * @description * A Vendure server instance against which GraphQL requests can be made. */ server: TestServer; /** * @description * A GraphQL client configured for the Admin API. */ adminClient: SimpleGraphQLClient; /** * @description * A GraphQL client configured for the Shop API. */ shopClient: SimpleGraphQLClient; } /** * @description * Configures a {@link TestServer} and a {@link SimpleGraphQLClient} for each of the GraphQL APIs * for use in end-to-end tests. Returns a {@link TestEnvironment} object. * * @example * ```ts * import { createTestEnvironment, testConfig } from '\@vendure/testing'; * * describe('some feature to test', () => { * * const { server, adminClient, shopClient } = createTestEnvironment(testConfig); * * beforeAll(async () => { * await server.init({ * // ... server options * }); * await adminClient.asSuperAdmin(); * }); * * afterAll(async () => { * await server.destroy(); * }); * * // ... end-to-end tests here * }); * ``` * @docsCategory testing */ export function createTestEnvironment(config: Required<VendureConfig>): TestEnvironment { const server = new TestServer(config); const { port, adminApiPath, shopApiPath } = config.apiOptions; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const adminClient = new SimpleGraphQLClient(config, `http://localhost:${port}/${adminApiPath!}`); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const shopClient = new SimpleGraphQLClient(config, `http://localhost:${port}/${shopApiPath!}`); return { server, adminClient, shopClient, }; }
import { fail } from 'assert'; /** * @description * Convenience method for creating an {@link ErrorResultGuard}. Takes a predicate function which * tests whether the input is considered successful (true) or an error result (false). * * Note that the resulting variable must _still_ be type annotated in order for the TypeScript * type inference to work as expected: * * @example * ```ts * const orderResultGuard: ErrorResultGuard<AddItemToOrderResult> * = createErrorResultGuard(order => !!order.lines); * ``` * @docsCategory testing */ export function createErrorResultGuard<T>(testFn: (input: T) => boolean): ErrorResultGuard<T> { return new ErrorResultGuard<T>(testFn); } /** * @description * A utility class which is used to assert the success of an operation * which returns a union type of `SuccessType | ErrorResponse [ | ErrorResponse ]`. * The methods of this class are used to: * 1. assert that the result is a success or error case * 2. narrow the type so that TypeScript can correctly infer the properties of the result. * * @example * ```ts * const orderResultGuard: ErrorResultGuard<AddItemToOrderResult> * = createErrorResultGuard(order => !!order.lines); * * it('errors when quantity is negative', async () => { * const { addItemToOrder } = await shopClient.query<AddItemToOrder.Query, AddItemToOrder.Mutation>(ADD_ITEM_TO_ORDER, { * productVariantId: 42, quantity: -1, * }); * * // The test will fail * orderResultGuard.assertErrorResult(addItemToOrder); * * // the type of `addItemToOrder` has now been * // narrowed to only include the ErrorResult types. * expect(addItemToOrder.errorCode).toBe(ErrorCode.NegativeQuantityError); * } * ``` * @docsCategory testing */ export class ErrorResultGuard<T> { constructor(private testFn: (input: T) => boolean) {} /** * @description * A type guard which returns `true` if the input passes the `testFn` predicate. */ isSuccess(input: T | any): input is T { return this.testFn(input as T); } /** * @description * Asserts (using the testing library's `fail()` function) that the input is * successful, i.e. it passes the `testFn`. */ assertSuccess<R>(input: T | R): asserts input is T { if (!this.isSuccess(input)) { fail(`Unexpected error: ${JSON.stringify(input)}`); } } /** * @description * Asserts (using the testing library's `fail()` function) that the input is * not successful, i.e. it does not pass the `testFn`. */ assertErrorResult<R>(input: T | R): asserts input is R { if (this.isSuccess(input)) { fail('Should have errored'); } } }
export * from './simple-graphql-client'; export * from './test-server'; export * from './config/test-config'; export * from './create-test-environment'; export * from './data-population/clear-all-tables'; export * from './data-population/populate-customers'; export * from './error-result-guard'; export * from './initializers/initializers'; export * from './initializers/test-db-initializer'; export * from './initializers/mysql-initializer'; export * from './initializers/postgres-initializer'; export * from './initializers/sqljs-initializer'; export * from './testing-logger'; export * from './types';
import { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { SUPER_ADMIN_USER_IDENTIFIER, SUPER_ADMIN_USER_PASSWORD } from '@vendure/common/lib/shared-constants'; import { VendureConfig } from '@vendure/core'; import FormData from 'form-data'; import fs from 'fs'; import { DocumentNode } from 'graphql'; import { print } from 'graphql/language/printer'; import gql from 'graphql-tag'; import fetch, { RequestInit, Response } from 'node-fetch'; import { stringify } from 'querystring'; import { QueryParams } from './types'; import { createUploadPostData } from './utils/create-upload-post-data'; const LOGIN = gql` mutation ($username: String!, $password: String!) { login(username: $username, password: $password) { ... on CurrentUser { id identifier channels { token } } ... on ErrorResult { errorCode message } } } `; /* eslint-disable no-console */ /** * @description * A minimalistic GraphQL client for populating and querying test data. * * @docsCategory testing */ export class SimpleGraphQLClient { private authToken: string; private channelToken: string | null = null; private headers: { [key: string]: any } = { 'Apollo-Require-Preflight': 'true', }; constructor(private vendureConfig: Required<VendureConfig>, private apiUrl: string = '') {} /** * @description * Sets the authToken to be used in each GraphQL request. */ setAuthToken(token: string) { this.authToken = token; this.headers.Authorization = `Bearer ${this.authToken}`; } /** * @description * Sets the authToken to be used in each GraphQL request. */ setChannelToken(token: string | null) { this.channelToken = token; if (this.vendureConfig.apiOptions.channelTokenKey) { this.headers[this.vendureConfig.apiOptions.channelTokenKey] = this.channelToken; } } /** * @description * Returns the authToken currently being used. */ getAuthToken(): string { return this.authToken; } /** * @description * Performs both query and mutation operations. */ async query<T = any, V extends Record<string, any> = Record<string, any>>( query: DocumentNode | TypedDocumentNode<T, V>, variables?: V, queryParams?: QueryParams, ): Promise<T> { const response = await this.makeGraphQlRequest(query, variables, queryParams); const result = await this.getResult(response); if (response.ok && !result.errors && result.data) { return result.data; } else { const errorResult = typeof result === 'string' ? { error: result } : result; throw new ClientError( { ...errorResult, status: response.status }, { query: print(query), variables }, ); } } /** * @description * Performs a raw HTTP request to the given URL, but also includes the authToken & channelToken * headers if they have been set. Useful for testing non-GraphQL endpoints, e.g. for plugins * which make use of REST controllers. */ async fetch(url: string, options: RequestInit = {}): Promise<Response> { const headers = { 'Content-Type': 'application/json', ...this.headers, ...options.headers }; const response = await fetch(url, { ...options, headers, }); const authToken = response.headers.get(this.vendureConfig.authOptions.authTokenHeaderKey || ''); if (authToken != null) { this.setAuthToken(authToken); } return response; } /** * @description * Performs a query or mutation and returns the resulting status code. */ async queryStatus<T = any, V extends Record<string, any> = Record<string, any>>( query: DocumentNode, variables?: V, ): Promise<number> { const response = await this.makeGraphQlRequest(query, variables); return response.status; } /** * @description * Attempts to log in with the specified credentials. */ async asUserWithCredentials(username: string, password: string) { // first log out as the current user if (this.authToken) { await this.query( gql` mutation { logout { success } } `, ); } const result = await this.query(LOGIN, { username, password }); if (result.login.channels?.length === 1) { this.setChannelToken(result.login.channels[0].token); } return result.login; } /** * @description * Logs in as the SuperAdmin user. */ async asSuperAdmin() { const { superadminCredentials } = this.vendureConfig.authOptions; await this.asUserWithCredentials( superadminCredentials?.identifier ?? SUPER_ADMIN_USER_IDENTIFIER, superadminCredentials?.password ?? SUPER_ADMIN_USER_PASSWORD, ); } /** * @description * Logs out so that the client is then treated as an anonymous user. */ async asAnonymousUser() { await this.query( gql` mutation { logout { success } } `, ); } private async makeGraphQlRequest( query: DocumentNode, variables?: { [key: string]: any }, queryParams?: QueryParams, ): Promise<Response> { const queryString = print(query); const body = JSON.stringify({ query: queryString, variables: variables ? variables : undefined, }); const url = queryParams ? this.apiUrl + `?${stringify(queryParams)}` : this.apiUrl; return this.fetch(url, { method: 'POST', body, }); } private async getResult(response: Response): Promise<any> { const contentType = response.headers.get('Content-Type'); if (contentType && contentType.startsWith('application/json')) { return response.json(); } else { return response.text(); } } /** * @description * Perform a file upload mutation. * * Upload spec: https://github.com/jaydenseric/graphql-multipart-request-spec * Discussion of issue: https://github.com/jaydenseric/apollo-upload-client/issues/32 */ async fileUploadMutation(options: { mutation: DocumentNode; filePaths: string[]; mapVariables: (filePaths: string[]) => any; }): Promise<any> { const { mutation, filePaths, mapVariables } = options; const postData = createUploadPostData(mutation, filePaths, mapVariables); const body = new FormData(); body.append('operations', JSON.stringify(postData.operations)); body.append( 'map', '{' + Object.entries(postData.map) .map(([i, path]) => `"${i}":["${path}"]`) .join(',') + '}', ); for (const filePath of postData.filePaths) { const file = fs.readFileSync(filePath.file); body.append(filePath.name, file, { filename: filePath.file }); } const result = await fetch(this.apiUrl, { method: 'POST', body, headers: { ...this.headers, }, }); const response = await result.json(); if (response.errors && response.errors.length) { const error = response.errors[0]; throw new Error(error.message); } return response.data; } } export class ClientError extends Error { constructor(public response: any, public request: any) { super(ClientError.extractMessage(response)); } private static extractMessage(response: any): string { if (response.errors) { return response.errors[0].message; } else { return `GraphQL Error (Code: ${response.status as number})`; } } }
import { INestApplication } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { DefaultLogger, JobQueueService, Logger, VendureConfig } from '@vendure/core'; import { preBootstrapConfig, configureSessionCookies } from '@vendure/core/dist/bootstrap'; import { populateForTesting } from './data-population/populate-for-testing'; import { getInitializerFor } from './initializers/initializers'; import { TestServerOptions } from './types'; /* eslint-disable no-console */ /** * @description * A real Vendure server against which the e2e tests should be run. * * @docsCategory testing */ export class TestServer { public app: INestApplication; constructor(private vendureConfig: Required<VendureConfig>) {} /** * @description * Bootstraps an instance of Vendure server and populates the database according to the options * passed in. Should be called in the `beforeAll` function. * * The populated data is saved into an .sqlite file for each test file. On subsequent runs, this file * is loaded so that the populate step can be skipped, which speeds up the tests significantly. */ async init(options: TestServerOptions): Promise<void> { const { type } = this.vendureConfig.dbConnectionOptions; const { dbConnectionOptions } = this.vendureConfig; const testFilename = this.getCallerFilename(1); const initializer = getInitializerFor(type); try { await initializer.init(testFilename, dbConnectionOptions); const populateFn = () => this.populateInitialData(this.vendureConfig, options); await initializer.populate(populateFn); await initializer.destroy(); } catch (e: any) { throw e; } await this.bootstrap(); } /** * @description * Bootstraps a Vendure server instance. Generally the `.init()` method should be used, as that will also * populate the test data. However, the `bootstrap()` method is sometimes useful in tests which need to * start and stop a Vendure instance multiple times without re-populating data. */ async bootstrap() { this.app = await this.bootstrapForTesting(this.vendureConfig); } /** * @description * Destroy the Vendure server instance and clean up all resources. * Should be called after all tests have run, e.g. in an `afterAll` function. */ async destroy() { // allow a grace period of any outstanding async tasks to complete await new Promise(resolve => global.setTimeout(resolve, 500)); await this.app?.close(); } private getCallerFilename(depth: number): string { let stack: any; let file: any; let frame: any; const pst = Error.prepareStackTrace; Error.prepareStackTrace = (_, _stack) => { Error.prepareStackTrace = pst; return _stack; }; stack = new Error().stack; stack = stack.slice(depth + 1); do { frame = stack.shift(); file = frame && frame.getFileName(); } while (stack.length && file === 'module.js'); return file; } /** * Populates an .sqlite database file based on the PopulateOptions. */ private async populateInitialData( testingConfig: Required<VendureConfig>, options: TestServerOptions, ): Promise<void> { const app = await populateForTesting(testingConfig, this.bootstrapForTesting, { logging: false, ...options, }); await app.close(); } /** * Bootstraps an instance of the Vendure server for testing against. */ private async bootstrapForTesting( this: void, userConfig: Partial<VendureConfig>, ): Promise<INestApplication> { const config = await preBootstrapConfig(userConfig); Logger.useLogger(config.logger); const appModule = await import('@vendure/core/dist/app.module.js'); try { DefaultLogger.hideNestBoostrapLogs(); const app = await NestFactory.create(appModule.AppModule, { cors: config.apiOptions.cors, logger: new Logger(), abortOnError: false, }); const { tokenMethod } = config.authOptions; const usingCookie = tokenMethod === 'cookie' || (Array.isArray(tokenMethod) && tokenMethod.includes('cookie')); if (usingCookie) { configureSessionCookies(app, config); } const earlyMiddlewares = config.apiOptions.middleware.filter(mid => mid.beforeListen); earlyMiddlewares.forEach(mid => { app.use(mid.route, mid.handler); }); await app.listen(config.apiOptions.port); await app.get(JobQueueService).start(); DefaultLogger.restoreOriginalLogLevel(); return app; } catch (e: any) { console.log(e); throw e; } } }
import { VendureLogger } from '@vendure/core'; /** * @description * The TestingLogger can be used in unit tests or e2e tests to make assertions on whether the various * Logger methods have been called, and which arguments. * * Here's some examples of how to use it in e2e tests and unit tests. In both cases we are using * the Jest testing framework, but the TestingLogger should work with other similar frameworks * (e.g. replacing `jest.fn()` with `jasmine.createSpy()`). * * @example * ```ts * // e2e test example * import { createTestEnvironment, TestingLogger } from '\@vendure/testing'; * * const testingLogger = new TestingLogger(() => jest.fn()); * * const { server, adminClient, shopClient } = createTestEnvironment({ * ...testConfig, * logger: testingLogger, * }); * * // e2e testing setup omitted * * it('should log an error', async () => { * // The `errorSpy` property exposes the Jest mock function * testingLogger.errorSpy.mockClear(); * * await doSomethingThatErrors(); * * expect(testingLogger.errorSpy).toHaveBeenCalled(); * }); * ``` * * @example * ```ts * // unit test example * import { Test } from '\@nestjs/testing'; * import { Logger } from '\@vendure/core'; * import { TestingLogger } from '\@vendure/testing'; * * beforeEach(async () => { * const moduleRef = await Test.createTestingModule({ * // Nest testing setup omitted * }).compile(); * * Logger.useLogger(testingLogger); * moduleRef.useLogger(new Logger()); * } * ``` * * @docsCategory testing */ export class TestingLogger<Spy extends (...args: any[]) => any> implements VendureLogger { constructor(private createSpyFn: () => Spy) { this.debugSpy = createSpyFn(); this.errorSpy = createSpyFn(); this.infoSpy = createSpyFn(); this.verboseSpy = createSpyFn(); this.warnSpy = createSpyFn(); } debugSpy: Spy; errorSpy: Spy; infoSpy: Spy; verboseSpy: Spy; warnSpy: Spy; debug(message: string, context?: string): void { this.debugSpy(message, context); } error(message: string, context?: string, trace?: string): void { this.errorSpy(message, context, trace); } info(message: string, context?: string): void { this.infoSpy(message, context); } verbose(message: string, context?: string): void { this.verboseSpy(message, context); } warn(message: string, context?: string): void { this.warnSpy(message, context); } }
import { InitialData } from '@vendure/core'; /** * Creates a mutable version of a type with readonly properties. */ export type Mutable<T> = { -readonly [K in keyof T]: T[K] }; /** * @description * Configuration options used to initialize an instance of the {@link TestServer}. * * @docsCategory testing */ export interface TestServerOptions { /** * @description * The path to an optional CSV file containing product data to import. */ productsCsvPath?: string; /** * @description * An object containing non-product data which is used to populate the database. */ initialData: InitialData; /** * @description * The number of fake Customers to populate into the database. * * @default 10 */ customerCount?: number; /** * @description * Set this to `true` to log some information about the database population process. * * @default false */ logging?: boolean; } export type QueryParams = { [key: string]: string | number };
import { ADMIN_API_PATH, SHOP_API_PATH } from '@vendure/common/lib/shared-constants'; import { DefaultAssetNamingStrategy, defaultConfig, DefaultLogger, mergeConfig, NoopLogger, VendureConfig, } from '@vendure/core'; import { TestingAssetPreviewStrategy } from './testing-asset-preview-strategy'; import { TestingAssetStorageStrategy } from './testing-asset-storage-strategy'; import { TestingEntityIdStrategy } from './testing-entity-id-strategy'; export const E2E_DEFAULT_CHANNEL_TOKEN = 'e2e-default-channel'; const logger = process.env.LOG ? new DefaultLogger() : new NoopLogger(); /** * @description * A {@link VendureConfig} object used for e2e tests. This configuration uses sqljs as the database * and configures some special settings which are optimized for e2e tests: * * * `entityIdStrategy: new TestingEntityIdStrategy()` This ID strategy uses auto-increment IDs but encodes all IDs * to be prepended with the string `'T_'`, so ID `1` becomes `'T_1'`. * * `logger: new NoopLogger()` Do no output logs by default * * `assetStorageStrategy: new TestingAssetStorageStrategy()` This strategy does not actually persist any binary data to disk. * * `assetPreviewStrategy: new TestingAssetPreviewStrategy()` This strategy is a no-op. * * ## Logging * By default, the testConfig does not output any log messages. This is most desirable to keep a clean CI output. * However, for debugging purposes, it can make it hard to figure out why tests fail. * * You can enable default logging behaviour with the environment variable `LOG`: * * ``` * LOG=true yarn e2e * ``` * * @docsCategory testing */ export const testConfig: Required<VendureConfig> = mergeConfig(defaultConfig, { apiOptions: { port: 3050, adminApiPath: ADMIN_API_PATH, shopApiPath: SHOP_API_PATH, cors: true, }, defaultChannelToken: E2E_DEFAULT_CHANNEL_TOKEN, authOptions: { tokenMethod: 'bearer', requireVerification: true, cookieOptions: { secret: 'some-secret', }, }, dbConnectionOptions: { type: 'sqljs', database: new Uint8Array([]), location: '', autoSave: false, logging: false, }, promotionOptions: {}, customFields: {}, entityOptions: { entityIdStrategy: new TestingEntityIdStrategy() }, paymentOptions: { paymentMethodHandlers: [], }, logger, importExportOptions: {}, assetOptions: { assetNamingStrategy: new DefaultAssetNamingStrategy(), assetStorageStrategy: new TestingAssetStorageStrategy(), assetPreviewStrategy: new TestingAssetPreviewStrategy(), }, });
import { AssetPreviewStrategy, RequestContext } from '@vendure/core'; const TEST_IMAGE_BASE_64 = // eslint-disable-next-line max-len 'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyppVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NjcyOSwgMjAxMi8wNS8wMy0xMzo0MDowMyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIEVsZW1lbnRzIDEyLjAgV2luZG93cyIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDowQzYyREUzNEM1QTcxMUU5OEJCNUU3Qzg2NjgyOTVFOSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDowQzYyREUzNUM1QTcxMUU5OEJCNUU3Qzg2NjgyOTVFOSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjBDNjJERTMyQzVBNzExRTk4QkI1RTdDODY2ODI5NUU5IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjBDNjJERTMzQzVBNzExRTk4QkI1RTdDODY2ODI5NUU5Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+1hstBAAAAvxJREFUeNrsmslu4zAQRGlZ8u7DXPL/HzZfMAcH8G7Ly7iEeUKboR0pkWIIQwKMrI2s6i52N4X0FovFb+fcL9fN9p7e/rzd+ryjBLLk9id33W154jreIoFIIBKIBCKB/5tA+qqJe73e3fn1en0NASYWoBAoe41nL5eLO5/PZU+SxI1Gow/vt0pAk202G3c8HgsAOtex3+8XnWsCLZCn06kATtd1SzDLsqLX9UT6VfCaSKB0tIDsM4DzrxcTp2kBWGPICBoj9HxjBACNRfM8LyaVpWez2R0RKxGsDCgrI43BfZFQw4ONEtAE+/3eHQ6HEiBNk8maobVhuyVliTKWCCBHjSejNOoBWUvuFmC5nmtYy7pdvwXk2eLmCCEIIic/AHybAIAULcbjsdvtdqXFACoA2+22OOq54XD4VNN6B2PotwyiMQkCVdZCUpcALhdIe11NEhMATSyCVmqh2O9LjTVTZw1UJsCgVr++PCCDhOw9/SZqPWq67xulEQlhFXWshEYtaEkGcvqNDAC/Wq3cZDIpn/NbyCiNrgENzGLDyr5WtT78TKx3lPR0LpkNBoOHUqrrgaROHgCszQF2Mr9sIP6v1+uCNJ7Q+2paJ/Y5O2bVZFYrE0tChFM/VFIucJ1IIsvrOuR0JIKp20iFVFsjQMJisQFKSQ5rhiTnaxoZ2gxNPgjJq7H9gB9ZZC1NKl2HFiSh9llpAhGerVuRVvaADY3olj6fz+9KA8DbyvNRQsObtkZqrRoVWNYB5TSkCLPURv6Cxtq2yLMEkRpld1VPfJkAiQ0wLGDrGbtHILpI4/a+b3mVFq3kAbsONKmsPJ1O7ypMSmSb7Ci9/Z0bxDjXuzpXomt1Q4NkiOc64na7J7C5w+YLu/mhbiq/lf8r7FolgNVk2eVy+QGsPGO3ltbKoVLaeg/5tLIjs5GIraCO6Nvug0MbeR8UpbRv9R/ZE0v7NhN/BvazLxov+S5U19Xxy1wkEAlEApFAJBAJPCCQdRh/plLij+vuP3y8/xVgAAkZCFP/heS9AAAAAElFTkSuQmCC'; /** * Returns a buffer of a small 48x48 placeholder image */ export function getTestImageBuffer() { return Buffer.from(TEST_IMAGE_BASE_64, 'base64'); } /** * A mock preview strategy which returns a new Buffer without doing any actual work. */ export class TestingAssetPreviewStrategy implements AssetPreviewStrategy { generatePreviewImage(ctx: RequestContext, mimeType: string, data: Buffer): Promise<Buffer> { return Promise.resolve(getTestImageBuffer()); } }
import { AssetStorageStrategy } from '@vendure/core'; import { Request } from 'express'; import { Readable, Stream, Writable } from 'stream'; import { getTestImageBuffer } from './testing-asset-preview-strategy'; /** * A mock storage strategy which does not actually persist the assets anywhere. */ export class TestingAssetStorageStrategy implements AssetStorageStrategy { readFileToBuffer(identifier: string): Promise<Buffer> { return Promise.resolve(getTestImageBuffer()); } readFileToStream(identifier: string): Promise<Stream> { const s = new Readable(); s.push(identifier); s.push(null); return Promise.resolve(s); } toAbsoluteUrl(reqest: Request, identifier: string): string { const prefix = 'test-url/'; return identifier.startsWith(prefix) ? identifier : `${prefix}${identifier}`; } writeFileFromBuffer(fileName: string, data: Buffer): Promise<string> { return Promise.resolve(`test-assets/${fileName}`); } writeFileFromStream(fileName: string, data: Stream): Promise<string> { const writable = new Writable(); writable._write = (chunk, encoding, done) => { done(); }; return new Promise<string>((resolve, reject) => { data.pipe(writable); writable.on('finish', () => resolve(`test-assets/${fileName}`)); writable.on('error', reject); }); } fileExists(fileName: string): Promise<boolean> { return Promise.resolve(false); } deleteFile(identifier: string): Promise<void> { return Promise.resolve(); } }
import { EntityIdStrategy } from '@vendure/core'; /** * A testing entity id strategy which prefixes all IDs with a constant string. This is used in the * e2e tests to ensure that all ID properties in arguments are being * correctly decoded. */ export class TestingEntityIdStrategy implements EntityIdStrategy<'increment'> { readonly primaryKeyType = 'increment'; decodeId(id: string): number { const asNumber = parseInt(id.replace('T_', ''), 10); return Number.isNaN(asNumber) ? -1 : asNumber; } encodeId(primaryKey: number): string { return 'T_' + primaryKey.toString(); } }
import { VendureConfig } from '@vendure/core'; import { preBootstrapConfig } from '@vendure/core/dist/bootstrap'; import { createConnection } from 'typeorm'; /* eslint-disable no-console */ /* eslint-disable @typescript-eslint/no-floating-promises */ /** * Clears all tables in the database specified by the connectionOptions */ export async function clearAllTables(config: VendureConfig, logging = true) { if (logging) { console.log('Clearing all tables...'); } config = await preBootstrapConfig(config); const entityIdStrategy = config.entityIdStrategy ?? config.entityOptions?.entityIdStrategy; const connection = await createConnection({ ...config.dbConnectionOptions }); try { await connection.synchronize(true); } catch (err: any) { console.error('Error occurred when attempting to clear tables!'); console.log(err); } finally { await connection.close(); } if (logging) { console.log('Done!'); } }
import { CreateAddressInput, CreateCustomerInput } from '@vendure/common/lib/generated-types'; import faker from 'faker/locale/en_GB'; import gql from 'graphql-tag'; import { SimpleGraphQLClient } from '../simple-graphql-client'; /* eslint-disable no-console */ /** * A service for creating mock data via the GraphQL API. */ export class MockDataService { apiUrl: string; constructor(private client: SimpleGraphQLClient, private logging = true) { // make the generated results deterministic faker.seed(1); } static getCustomers( count: number, ): Array<{ customer: CreateCustomerInput; address: CreateAddressInput }> { faker.seed(1); const results: Array<{ customer: CreateCustomerInput; address: CreateAddressInput }> = []; for (let i = 0; i < count; i++) { const firstName = faker.name.firstName(); const lastName = faker.name.lastName(); const customer: CreateCustomerInput = { firstName, lastName, emailAddress: faker.internet.email(firstName, lastName), phoneNumber: faker.phone.phoneNumber(), }; const address: CreateAddressInput = { fullName: `${firstName} ${lastName}`, streetLine1: faker.address.streetAddress(), city: faker.address.city(), province: faker.address.county(), postalCode: faker.address.zipCode(), countryCode: 'GB', }; results.push({ customer, address }); } return results; } /** * @deprecated * Use `MockDataService.getCustomers()` and create customers directly with CustomerService. */ async populateCustomers(count: number = 5): Promise<any> { for (let i = 0; i < count; i++) { const firstName = faker.name.firstName(); const lastName = faker.name.lastName(); const query1 = gql` mutation CreateCustomer($input: CreateCustomerInput!, $password: String) { createCustomer(input: $input, password: $password) { ... on Customer { id emailAddress } } } `; const variables1 = { input: { firstName, lastName, emailAddress: faker.internet.email(firstName, lastName), phoneNumber: faker.phone.phoneNumber(), }, password: 'test', }; const customer: { id: string; emailAddress: string } | void = await this.client .query(query1, variables1) .then( (data: any) => data.createCustomer, err => this.log(err), ); if (customer) { const query2 = gql` mutation ($customerId: ID!, $input: CreateAddressInput!) { createCustomerAddress(customerId: $customerId, input: $input) { id streetLine1 } } `; const variables2 = { input: { fullName: `${firstName} ${lastName}`, streetLine1: faker.address.streetAddress(), city: faker.address.city(), province: faker.address.county(), postalCode: faker.address.zipCode(), countryCode: 'GB', }, customerId: customer.id, }; await this.client.query(query2, variables2).catch(err => this.log(err)); } } this.log(`Created ${count} Customers`); } private log(...args: any[]) { if (this.logging) { console.log(...args); } } }
import { INestApplicationContext } from '@nestjs/common'; import { CustomerService, isGraphQlErrorResult, RequestContext } from '@vendure/core'; import { getSuperadminContext } from '../utils/get-superadmin-context'; import { MockDataService } from './mock-data.service'; /** * Creates customers with addresses by making API calls to the Admin API. */ export async function populateCustomers( app: INestApplicationContext, count: number, loggingFn: (message: string) => void, ) { const customerService = app.get(CustomerService); const customerData = MockDataService.getCustomers(count); const ctx = await getSuperadminContext(app); const password = 'test'; for (const { customer, address } of customerData) { try { const createdCustomer = await customerService.create(ctx, customer, password); if (isGraphQlErrorResult(createdCustomer)) { loggingFn(`Failed to create customer: ${createdCustomer.message}`); continue; } await customerService.createAddress(ctx, createdCustomer.id, address); } catch (e: any) { loggingFn(`Failed to create customer: ${JSON.stringify(e.message)}`); } } }
/* eslint-disable no-console */ import { INestApplicationContext } from '@nestjs/common'; import { LanguageCode } from '@vendure/common/lib/generated-types'; import { VendureConfig } from '@vendure/core'; import { importProductsFromCsv, populateCollections, populateInitialData } from '@vendure/core/cli'; import { TestServerOptions } from '../types'; import { populateCustomers } from './populate-customers'; /* eslint-disable @typescript-eslint/no-floating-promises */ /** * Clears all tables from the database and populates with (deterministic) random data. */ export async function populateForTesting<T extends INestApplicationContext>( config: Required<VendureConfig>, bootstrapFn: (config: VendureConfig) => Promise<T>, options: TestServerOptions, ): Promise<T> { (config.dbConnectionOptions as any).logging = false; const logging = options.logging === undefined ? true : options.logging; const originalRequireVerification = config.authOptions.requireVerification; config.authOptions.requireVerification = false; const app = await bootstrapFn(config); const logFn = (message: string) => (logging ? console.log(message) : null); await populateInitialData(app, options.initialData); await populateProducts(app, options.productsCsvPath, logging); await populateCollections(app, options.initialData); await populateCustomers(app, options.customerCount ?? 10, logFn); config.authOptions.requireVerification = originalRequireVerification; return app; } async function populateProducts( app: INestApplicationContext, productsCsvPath: string | undefined, logging: boolean, ) { if (!productsCsvPath) { if (logging) { console.log('\nNo product data provided, skipping product import'); } return; } const importResult = await importProductsFromCsv(app, productsCsvPath, LanguageCode.en); if (importResult.errors && importResult.errors.length) { console.log(`${importResult.errors.length} errors encountered when importing product data:`); console.log(importResult.errors.join('\n')); } if (logging) { console.log(`\nImported ${importResult.imported} products`); } }
import { DataSourceOptions } from 'typeorm'; import { TestDbInitializer } from './test-db-initializer'; export type InitializerRegistry = { [type in DataSourceOptions['type']]?: TestDbInitializer<any> }; const initializerRegistry: InitializerRegistry = {}; /** * @description * Registers a {@link TestDbInitializer} for the given database type. Should be called before invoking * {@link createTestEnvironment}. * * @docsCategory testing */ export function registerInitializer(type: DataSourceOptions['type'], initializer: TestDbInitializer<any>) { initializerRegistry[type] = initializer; } export function getInitializerFor(type: DataSourceOptions['type']): TestDbInitializer<any> { const initializer = initializerRegistry[type]; if (!initializer) { throw new Error(`No initializer has been registered for the database type "${type}"`); } return initializer; }
import path from 'path'; import { DataSourceOptions } from 'typeorm'; import { MysqlConnectionOptions } from 'typeorm/driver/mysql/MysqlConnectionOptions'; import { promisify } from 'util'; import { TestDbInitializer } from './test-db-initializer'; export class MysqlInitializer implements TestDbInitializer<MysqlConnectionOptions> { private conn: import('mysql').Connection; async init( testFileName: string, connectionOptions: MysqlConnectionOptions, ): Promise<MysqlConnectionOptions> { const dbName = this.getDbNameFromFilename(testFileName); this.conn = await this.getMysqlConnection(connectionOptions); (connectionOptions as any).database = dbName; (connectionOptions as any).synchronize = true; const query = promisify(this.conn.query).bind(this.conn); await query(`DROP DATABASE IF EXISTS ${dbName}`); await query(`CREATE DATABASE IF NOT EXISTS ${dbName}`); return connectionOptions; } async populate(populateFn: () => Promise<void>): Promise<void> { await populateFn(); } async destroy() { // eslint-disable-next-line @typescript-eslint/unbound-method await promisify(this.conn.end).bind(this.conn)(); } private async getMysqlConnection( connectionOptions: MysqlConnectionOptions, ): Promise<import('mysql').Connection> { const { createConnection } = await import('mysql'); const conn = createConnection({ host: connectionOptions.host, port: connectionOptions.port, user: connectionOptions.username, password: connectionOptions.password, }); // eslint-disable-next-line @typescript-eslint/unbound-method const connect = promisify(conn.connect).bind(conn); await connect(); return conn; } private getDbNameFromFilename(filename: string): string { return 'e2e_' + path.basename(filename).replace(/[^a-z0-9_]/gi, '_'); } }
import path from 'path'; import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions'; import { TestDbInitializer } from './test-db-initializer'; export class PostgresInitializer implements TestDbInitializer<PostgresConnectionOptions> { private client: import('pg').Client; async init( testFileName: string, connectionOptions: PostgresConnectionOptions, ): Promise<PostgresConnectionOptions> { const dbName = this.getDbNameFromFilename(testFileName); (connectionOptions as any).database = dbName; (connectionOptions as any).synchronize = true; this.client = await this.getPostgresConnection(connectionOptions); await this.client.query(`DROP DATABASE IF EXISTS ${dbName}`); await this.client.query(`CREATE DATABASE ${dbName}`); return connectionOptions; } async populate(populateFn: () => Promise<void>): Promise<void> { await populateFn(); } destroy(): void | Promise<void> { return this.client.end(); } private async getPostgresConnection( connectionOptions: PostgresConnectionOptions, ): Promise<import('pg').Client> { // eslint-disable-next-line @typescript-eslint/no-var-requires const { Client } = require('pg'); const client = new Client({ host: connectionOptions.host, port: connectionOptions.port, user: connectionOptions.username, password: connectionOptions.password, database: 'postgres', }); await client.connect(); return client; } private getDbNameFromFilename(filename: string): string { return 'e2e_' + path.basename(filename).replace(/[^a-z0-9_]/gi, '_'); } }
import fs from 'fs'; import path from 'path'; import { SqljsConnectionOptions } from 'typeorm/driver/sqljs/SqljsConnectionOptions'; import { Mutable } from '../types'; import { TestDbInitializer } from './test-db-initializer'; export class SqljsInitializer implements TestDbInitializer<SqljsConnectionOptions> { private dbFilePath: string; private connectionOptions: SqljsConnectionOptions; /** * @param dataDir * @param postPopulateTimeoutMs Allows you to specify a timeout to wait after the population * step and before the server is shut down. Can resolve occasional race condition issues with * the job queue. */ constructor(private dataDir: string, private postPopulateTimeoutMs: number = 0) {} async init( testFileName: string, connectionOptions: SqljsConnectionOptions, ): Promise<SqljsConnectionOptions> { this.dbFilePath = this.getDbFilePath(testFileName); this.connectionOptions = connectionOptions; (connectionOptions as Mutable<SqljsConnectionOptions>).location = this.dbFilePath; return connectionOptions; } async populate(populateFn: () => Promise<void>): Promise<void> { if (!fs.existsSync(this.dbFilePath)) { const dirName = path.dirname(this.dbFilePath); if (!fs.existsSync(dirName)) { fs.mkdirSync(dirName); } (this.connectionOptions as Mutable<SqljsConnectionOptions>).autoSave = true; (this.connectionOptions as Mutable<SqljsConnectionOptions>).synchronize = true; await populateFn(); await new Promise(resolve => setTimeout(resolve, this.postPopulateTimeoutMs)); (this.connectionOptions as Mutable<SqljsConnectionOptions>).autoSave = false; (this.connectionOptions as Mutable<SqljsConnectionOptions>).synchronize = false; } } destroy(): void | Promise<void> { return undefined; } private getDbFilePath(testFileName: string) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const dbFileName = path.basename(testFileName) + '.sqlite'; const dbFilePath = path.join(this.dataDir, dbFileName); return dbFilePath; } }
import { DataSourceOptions } from 'typeorm'; import { BaseConnectionOptions } from 'typeorm/connection/BaseConnectionOptions'; /** * @description * Defines how the e2e TestService sets up a particular DB to run a single test suite. * The `\@vendure/testing` package ships with initializers for sql.js, MySQL & Postgres. * * Custom initializers can be created by implementing this interface and registering * it with the {@link registerInitializer} function: * * @example * ```ts * export class CockroachDbInitializer implements TestDbInitializer<CockroachConnectionOptions> { * // database-specific implementation goes here * } * * registerInitializer('cockroachdb', new CockroachDbInitializer()); * ``` * * @docsCategory testing */ export interface TestDbInitializer<T extends BaseConnectionOptions> { /** * @description * Responsible for creating a database for the current test suite. * Typically, this method will: * * * use the testFileName parameter to derive a database name * * create the database * * mutate the `connetionOptions` object to point to that new database */ init(testFileName: string, connectionOptions: T): Promise<T>; /** * @description * Execute the populateFn to populate your database. */ populate(populateFn: () => Promise<void>): Promise<void>; /** * @description * Clean up any resources used during the init() phase (i.e. close open DB connections) */ destroy(): void | Promise<void>; }
import gql from 'graphql-tag'; import { createUploadPostData } from './create-upload-post-data'; describe('createUploadPostData()', () => { it('creates correct output for createAssets mutation', () => { const result = createUploadPostData( gql` mutation CreateAssets($input: [CreateAssetInput!]!) { createAssets(input: $input) { id name } } `, ['a.jpg', 'b.jpg'], filePaths => ({ input: filePaths.map(() => ({ file: null })), }), ); expect(result.operations.operationName).toBe('CreateAssets'); expect(result.operations.variables).toEqual({ input: [{ file: null }, { file: null }], }); expect(result.map).toEqual({ 0: 'variables.input.0.file', 1: 'variables.input.1.file', }); expect(result.filePaths).toEqual([{ name: '0', file: 'a.jpg' }, { name: '1', file: 'b.jpg' }]); }); it('creates correct output for importProducts mutation', () => { const result = createUploadPostData( gql` mutation ImportProducts($input: Upload!) { importProducts(csvFile: $input) { errors importedCount } } `, 'data.csv', () => ({ csvFile: null }), ); expect(result.operations.operationName).toBe('ImportProducts'); expect(result.operations.variables).toEqual({ csvFile: null }); expect(result.map).toEqual({ 0: 'variables.csvFile', }); expect(result.filePaths).toEqual([{ name: '0', file: 'data.csv' }]); }); });
import { DocumentNode, Kind, OperationDefinitionNode, print } from 'graphql'; export interface FilePlaceholder { file: null; } export interface UploadPostData<V = any> { operations: { operationName: string; variables: V; query: string; }; map: { [index: number]: string; }; filePaths: Array<{ name: string; file: string; }>; } /** * Creates a data structure which can be used to mae a curl request to upload files to a mutation using * the Upload type. */ export function createUploadPostData<P extends string[] | string, V>( mutation: DocumentNode, filePaths: P, mapVariables: (filePaths: P) => V, ): UploadPostData<V> { const operationDef = mutation.definitions.find( d => d.kind === Kind.OPERATION_DEFINITION, ) as OperationDefinitionNode; const filePathsArray: string[] = Array.isArray(filePaths) ? filePaths : [filePaths]; const variables = mapVariables(filePaths); const postData: UploadPostData = { operations: { operationName: operationDef.name ? operationDef.name.value : 'AnonymousMutation', variables, query: print(mutation), }, map: filePathsArray.reduce((output, filePath, i) => { return { ...output, [i.toString()]: objectPath(variables, i).join('.') }; }, {} as Record<number, string>), filePaths: filePathsArray.map((filePath, i) => ({ name: i.toString(), file: filePath, })), }; return postData; } function objectPath(variables: any, i: number): Array<string | number> { const path: Array<string | number> = ['variables']; let current = variables; while (current !== null) { const props = Object.getOwnPropertyNames(current); if (props) { const firstProp = props[0]; const val = current[firstProp]; if (Array.isArray(val)) { path.push(firstProp); path.push(i); current = val[0]; } else { path.push(firstProp); current = val; } } } return path; }
import { INestApplicationContext } from '@nestjs/common'; import { ChannelService, ConfigService, RequestContext, TransactionalConnection, User } from '@vendure/core'; /** * @description * Creates a {@link RequestContext} configured for the default Channel with the activeUser set * as the superadmin user. Useful for populating data. * * @docsCategory testing */ export async function getSuperadminContext(app: INestApplicationContext): Promise<RequestContext> { const defaultChannel = await app.get(ChannelService).getDefaultChannel(); const connection = app.get(TransactionalConnection); const configService = app.get(ConfigService); const { superadminCredentials } = configService.authOptions; const superAdminUser = await connection .getRepository(User) .findOneOrFail({ where: { identifier: superadminCredentials.identifier } }); return new RequestContext({ channel: defaultChannel, apiType: 'admin', isAuthorized: true, authorizedAsOwnerOnly: false, session: { id: '', token: '', expires: new Date(), cacheExpiry: 999999, user: { id: superAdminUser.id, identifier: superAdminUser.identifier, verified: true, channelPermissions: [], }, }, }); }
import { NgModule } from '@angular/core'; import { Route, RouterModule } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { AppComponent, AppComponentModule, CoreModule } from '@vendure/admin-ui/core'; import { routes } from './app.routes'; import { SharedExtensionsModule } from './shared-extensions.module'; @NgModule({ declarations: [], imports: [ AppComponentModule, RouterModule.forRoot(routes, { useHash: false }), CoreModule, SharedExtensionsModule, ], bootstrap: [AppComponent], }) export class AppModule {}
import { Route } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { AppShellComponent, AuthGuard } from '@vendure/admin-ui/core'; import { extensionRoutes } from './extension.routes'; export const routes: Route[] = [ { path: 'login', loadChildren: () => import('@vendure/admin-ui/login').then(m => m.LoginModule) }, { path: '', canActivate: [AuthGuard], component: AppShellComponent, data: { breadcrumb: _('breadcrumb.dashboard'), }, children: [ // Defining the extension routes before the built-in routes allows // the extension routes to take precedence over the built-in routes, enabling // the extensions to override built-in functionality. ...extensionRoutes, { path: '', pathMatch: 'full', loadChildren: () => import('@vendure/admin-ui/dashboard').then(m => m.DashboardModule), }, { path: 'catalog', loadChildren: () => import('@vendure/admin-ui/catalog').then(m => m.CatalogModule), }, { path: 'customer', loadChildren: () => import('@vendure/admin-ui/customer').then(m => m.CustomerModule), }, { path: 'orders', loadChildren: () => import('@vendure/admin-ui/order').then(m => m.OrderModule), }, { path: 'marketing', loadChildren: () => import('@vendure/admin-ui/marketing').then(m => m.MarketingModule), }, { path: 'settings', loadChildren: () => import('@vendure/admin-ui/settings').then(m => m.SettingsModule), }, { path: 'system', loadChildren: () => import('@vendure/admin-ui/system').then(m => m.SystemModule), }, ], }, ];
export const environment = { production: true, };
// This file can be replaced during build by using the `fileReplacements` array. // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, };
export const extensionRoutes = [];
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { loadAppConfig } from '@vendure/admin-ui/core'; import { AppModule } from './app.module'; import { environment } from './environment'; if (environment.production) { enableProdMode(); } loadAppConfig() .then(() => platformBrowserDynamic().bootstrapModule(AppModule)) .catch((err: any) => { /* eslint-disable no-console */ console.log(err); });
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; @NgModule({ imports: [CommonModule], }) export class SharedExtensionsModule {}
import { ActiveRouteData, BaseExtensionMessage, ExtensionMessage, MessageResponse, NotificationMessage, WatchQueryFetchPolicy, } from '@vendure/common/lib/extension-host-types'; import { Observable } from 'rxjs'; import { take } from 'rxjs/operators'; let targetOrigin = 'http://localhost:3000'; /** * @description * Set the [window.postMessage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) * `targetOrigin`. The Vendure ui-devkit uses the postMessage API to * enable cross-frame and cross-origin communication between the ui extension code and the Admin UI * app. The `targetOrigin` is a security feature intended to provide control over where messages are sent. * * @docsCategory ui-devkit * @docsPage UiDevkitClient */ export function setTargetOrigin(value: string) { targetOrigin = value; } /** * @description * Retrieves information about the current route of the host application, since it is not possible * to otherwise get this information from within the child iframe. * * @example * ```ts * import { getActivatedRoute } from '\@vendure/ui-devkit'; * * const route = await getActivatedRoute(); * const slug = route.params.slug; * ``` * @docsCategory ui-devkit * @docsPage UiDevkitClient */ export function getActivatedRoute(): Promise<ActiveRouteData> { return sendMessage('active-route', {}).toPromise(); } /** * @description * Perform a GraphQL query and returns either an Observable or a Promise of the result. * * @example * ```ts * import { graphQlQuery } from '\@vendure/ui-devkit'; * * const productList = await graphQlQuery(` * query GetProducts($skip: Int, $take: Int) { * products(options: { skip: $skip, take: $take }) { * items { id, name, enabled }, * totalItems * } * }`, { * skip: 0, * take: 10, * }).then(data => data.products); * ``` * * @docsCategory ui-devkit * @docsPage UiDevkitClient */ export function graphQlQuery<T, V extends { [key: string]: any }>( document: string, variables?: { [key: string]: any }, fetchPolicy?: WatchQueryFetchPolicy, ): { then: Promise<T>['then']; stream: Observable<T>; } { const result$ = sendMessage('graphql-query', { document, variables, fetchPolicy }); return { then: (...args: any[]) => result$ .pipe(take(1)) .toPromise() .then(...args), stream: result$, }; } /** * @description * Perform a GraphQL mutation and returns either an Observable or a Promise of the result. * * @example * ```ts * import { graphQlMutation } from '\@vendure/ui-devkit'; * * const disableProduct = (id: string) => { * return graphQlMutation(` * mutation DisableProduct($id: ID!) { * updateProduct(input: { id: $id, enabled: false }) { * id * enabled * } * }`, { id }) * .then(data => data.updateProduct) * } * ``` * * @docsCategory ui-devkit * @docsPage UiDevkitClient */ export function graphQlMutation<T, V extends { [key: string]: any }>( document: string, variables?: { [key: string]: any }, ): { then: Promise<T>['then']; stream: Observable<T>; } { const result$ = sendMessage('graphql-mutation', { document, variables }); return { then: (...args: any[]) => result$ .pipe(take(1)) .toPromise() .then(...args), stream: result$, }; } /** * @description * Display a toast notification. * * @example * ```ts * import { notify } from '\@vendure/ui-devkit'; * * notify({ * message: 'Updated Product', * type: 'success' * }); * ``` * * @docsCategory ui-devkit * @docsPage UiDevkitClient */ export function notify(options: NotificationMessage['data']): void { void sendMessage('notification', options).toPromise(); } function sendMessage<T extends ExtensionMessage>(type: T['type'], data: T['data']): Observable<any> { const requestId = type + '__' + Math.random().toString(36).substr(3); const message: BaseExtensionMessage = { requestId, type, data, }; return new Observable<any>(subscriber => { const hostWindow = window.opener || window.parent; const handleReply = (event: MessageEvent) => { const response: MessageResponse = event.data; if (response && response.requestId === requestId) { if (response.complete) { subscriber.complete(); tearDown(); return; } if (response.error) { subscriber.error(response.data); tearDown(); return; } subscriber.next(response.data); } }; const tearDown = () => { hostWindow.postMessage({ requestId, type: 'cancellation', data: null }, targetOrigin); }; window.addEventListener('message', handleReply); hostWindow.postMessage(message, targetOrigin); return tearDown; }); }
export * from './devkit-client-api';
/* eslint-disable no-console */ import { LanguageCode } from '@vendure/common/lib/generated-types'; import { AdminUiAppConfig, AdminUiAppDevModeConfig } from '@vendure/common/lib/shared-types'; import { ChildProcess, spawn } from 'child_process'; import { FSWatcher, watch as chokidarWatch } from 'chokidar'; import * as fs from 'fs-extra'; import * as path from 'path'; import { DEFAULT_BASE_HREF, MODULES_OUTPUT_DIR } from './constants'; import { copyGlobalStyleFile, setBaseHref, setupScaffold } from './scaffold'; import { getAllTranslationFiles, mergeExtensionTranslations } from './translations'; import { StaticAssetDefinition, UiExtensionCompilerOptions, UiExtensionCompilerProcessArgument, } from './types'; import { copyStaticAsset, copyUiDevkit, getStaticAssetPath, isAdminUiExtension, isGlobalStylesExtension, isStaticAssetExtension, isTranslationExtension, normalizeExtensions, shouldUseYarn, } from './utils'; /** * @description * Compiles the Admin UI app with the specified extensions. * * @docsCategory UiDevkit */ export function compileUiExtensions( options: UiExtensionCompilerOptions, ): AdminUiAppConfig | AdminUiAppDevModeConfig { const { devMode, watchPort, command } = options; const usingYarn = command && command === 'npm' ? false : shouldUseYarn(); if (devMode) { return runWatchMode({ watchPort: watchPort || 4200, usingYarn, ...options, }); } else { return runCompileMode({ usingYarn, ...options, }); } } function runCompileMode({ outputPath, baseHref, extensions, usingYarn, additionalProcessArguments, ngCompilerPath, }: UiExtensionCompilerOptions & { usingYarn: boolean }): AdminUiAppConfig { const distPath = path.join(outputPath, 'dist'); const compile = () => new Promise<void>(async (resolve, reject) => { await setupScaffold(outputPath, extensions); await setBaseHref(outputPath, baseHref || DEFAULT_BASE_HREF); let cmd = usingYarn ? 'yarn' : 'npm'; let commandArgs = ['run', 'build']; if (ngCompilerPath) { cmd = 'node'; commandArgs = [ngCompilerPath, 'build', '--configuration production']; } else { if (!usingYarn) { // npm requires `--` before any command line args being passed to a script commandArgs.splice(2, 0, '--'); } } console.log(`Running ${cmd} ${commandArgs.join(' ')}`); const buildProcess = spawn( cmd, [...commandArgs, ...buildProcessArguments(additionalProcessArguments)], { cwd: outputPath, shell: true, stdio: 'inherit', }, ); buildProcess.on('close', code => { if (code !== 0) { reject(code); } else { resolve(); } }); }); return { path: distPath, compile, route: baseHrefToRoute(baseHref || DEFAULT_BASE_HREF), }; } function runWatchMode({ outputPath, baseHref, watchPort, extensions, usingYarn, additionalProcessArguments, ngCompilerPath, }: UiExtensionCompilerOptions & { usingYarn: boolean }): AdminUiAppDevModeConfig { const devkitPath = require.resolve('@vendure/ui-devkit'); let buildProcess: ChildProcess; let watcher: FSWatcher | undefined; let close: () => void = () => { /* */ }; const compile = () => new Promise<void>(async (resolve, reject) => { await setupScaffold(outputPath, extensions); await setBaseHref(outputPath, baseHref || DEFAULT_BASE_HREF); const adminUiExtensions = extensions.filter(isAdminUiExtension); const normalizedExtensions = normalizeExtensions(adminUiExtensions); const globalStylesExtensions = extensions.filter(isGlobalStylesExtension); const staticAssetExtensions = extensions.filter(isStaticAssetExtension); const allTranslationFiles = getAllTranslationFiles(extensions.filter(isTranslationExtension)); let cmd = usingYarn ? 'yarn' : 'npm'; let commandArgs = ['run', 'start']; if (ngCompilerPath) { cmd = 'node'; commandArgs = [ngCompilerPath, 'serve']; } buildProcess = spawn( cmd, [ ...commandArgs, `--port=${watchPort || 4200}`, ...buildProcessArguments(additionalProcessArguments), ], { cwd: outputPath, shell: true, stdio: 'inherit', }, ); buildProcess.on('close', code => { if (code !== 0) { reject(code); } else { resolve(); } close(); }); for (const extension of normalizedExtensions) { if (!watcher) { watcher = chokidarWatch(extension.extensionPath, { depth: 4, ignored: '**/node_modules/', }); } else { watcher.add(extension.extensionPath); } } for (const extension of staticAssetExtensions) { for (const staticAssetDef of extension.staticAssets) { const assetPath = getStaticAssetPath(staticAssetDef); if (!watcher) { watcher = chokidarWatch(assetPath); } else { watcher.add(assetPath); } } } for (const extension of globalStylesExtensions) { const globalStylePaths = Array.isArray(extension.globalStyles) ? extension.globalStyles : [extension.globalStyles]; for (const stylePath of globalStylePaths) { if (!watcher) { watcher = chokidarWatch(stylePath); } else { watcher.add(stylePath); } } } for (const translationFiles of Object.values(allTranslationFiles)) { if (!translationFiles) { continue; } for (const file of translationFiles) { if (!watcher) { watcher = chokidarWatch(file); } else { watcher.add(file); } } } if (watcher) { // watch the ui-devkit package files too watcher.add(devkitPath); } if (watcher) { const allStaticAssetDefs = staticAssetExtensions.reduce( (defs, e) => [...defs, ...(e.staticAssets || [])], [] as StaticAssetDefinition[], ); const allGlobalStyles = globalStylesExtensions.reduce( (defs, e) => [ ...defs, ...(Array.isArray(e.globalStyles) ? e.globalStyles : [e.globalStyles]), ], [] as string[], ); watcher.on('change', async filePath => { const extension = normalizedExtensions.find(e => filePath.includes(e.extensionPath)); if (extension) { const outputDir = path.join(outputPath, MODULES_OUTPUT_DIR, extension.id); const filePart = path.relative(extension.extensionPath, filePath); const dest = path.join(outputDir, filePart); await fs.copyFile(filePath, dest); } if (filePath.includes(devkitPath)) { copyUiDevkit(outputPath); } for (const staticAssetDef of allStaticAssetDefs) { const assetPath = getStaticAssetPath(staticAssetDef); if (filePath.includes(assetPath)) { await copyStaticAsset(outputPath, staticAssetDef); return; } } for (const stylePath of allGlobalStyles) { if (filePath.includes(stylePath)) { await copyGlobalStyleFile(outputPath, stylePath); return; } } for (const languageCode of Object.keys(allTranslationFiles)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const translationFiles = allTranslationFiles[languageCode as LanguageCode]!; for (const file of translationFiles) { if (filePath.includes(path.normalize(file))) { await mergeExtensionTranslations(outputPath, { [languageCode]: translationFiles, }); } } } }); } resolve(); }); close = () => { if (watcher) { void watcher.close(); } if (buildProcess) { buildProcess.kill(); } process.exit(); }; process.on('SIGINT', close); return { sourcePath: outputPath, port: watchPort || 4200, compile, route: baseHrefToRoute(baseHref || DEFAULT_BASE_HREF), }; } function buildProcessArguments(args?: UiExtensionCompilerProcessArgument[]): string[] { return (args ?? []).map(arg => { if (Array.isArray(arg)) { const [key, value] = arg; return `${key}=${value as string}`; } return arg; }); } function baseHrefToRoute(baseHref: string): string { return baseHref.replace(/^\//, '').replace(/\/$/, ''); }
export const STATIC_ASSETS_OUTPUT_DIR = 'static-assets'; export const GLOBAL_STYLES_OUTPUT_DIR = 'global-styles'; export const EXTENSION_ROUTES_FILE = 'src/extension.routes.ts'; export const SHARED_EXTENSIONS_FILE = 'src/shared-extensions.module.ts'; export const MODULES_OUTPUT_DIR = 'src/extensions'; export const DEFAULT_BASE_HREF = '/admin/';