content
stringlengths
28
1.34M
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Dialog, OrderDetailFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-settle-refund-dialog', templateUrl: './settle-refund-dialog.component.html', styleUrls: ['./settle-refund-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SettleRefundDialogComponent implements Dialog<string> { resolveWith: (result?: string) => void; transactionId = ''; refund: NonNullable<OrderDetailFragment['payments']>[number]['refunds'][number]; submit() { this.resolveWith(this.transactionId); } cancel() { this.resolveWith(); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-simple-item-list', templateUrl: './simple-item-list.component.html', styleUrls: ['./simple-item-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SimpleItemListComponent { @Input() items: Array<{ name: string; quantity?: number }>; }
import { Injectable } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DataService, HistoryEntryType, I18nService, ModalService, NotificationService, SortOrder, } from '@vendure/admin-ui/core'; import { EMPTY } from 'rxjs'; import { catchError, delay, map, retryWhen, switchMap, take } from 'rxjs/operators'; import { OrderStateSelectDialogComponent } from '../components/order-state-select-dialog/order-state-select-dialog.component'; @Injectable({ providedIn: 'root', }) export class OrderTransitionService { constructor( private dataService: DataService, private modalService: ModalService, private notificationService: NotificationService, private i18nService: I18nService, ) {} /** * Attempts to transition the Order to the last state it was in before it was transitioned * to the "Modifying" state. If this fails, a manual prompt is used. */ transitionToPreModifyingState(orderId: string, nextStates: string[]) { return this.getPreModifyingState(orderId).pipe( switchMap(state => { const manualTransitionOptions = { orderId, nextStates, message: this.i18nService.translate( _('order.unable-to-transition-to-state-try-another'), { state }, ), cancellable: false, retry: 10, }; if (state) { return this.transitionToStateOrThrow(orderId, state).pipe( catchError(err => this.manuallyTransitionToState(manualTransitionOptions)), ); } else { return this.manuallyTransitionToState(manualTransitionOptions); } }), ); } /** * Displays a modal for manually selecting the next state. */ manuallyTransitionToState(options: { orderId: string; nextStates: string[]; message: string; cancellable: boolean; retry: number; }) { return this.modalService .fromComponent(OrderStateSelectDialogComponent, { locals: { nextStates: options.nextStates, cancellable: options.cancellable, message: options.message, }, closable: false, size: 'md', }) .pipe( switchMap(result => { if (result) { return this.transitionToStateOrThrow(options.orderId, result); } else { if (!options.cancellable) { throw new Error(`An order state must be selected`); } else { return EMPTY; } } }), retryWhen(errors => errors.pipe(delay(2000), take(options.retry))), ); } /** * Attempts to get the last state the Order was in before it was transitioned * to the "Modifying" state. */ private getPreModifyingState(orderId: string) { return this.dataService.order .getOrderHistory(orderId, { filter: { type: { eq: HistoryEntryType.ORDER_STATE_TRANSITION, }, }, sort: { createdAt: SortOrder.DESC, }, }) .mapSingle(result => result.order) .pipe( map(result => { const item = result?.history.items.find(i => i.data.to === 'Modifying'); if (item) { return item.data.from as string; } else { return; } }), ); } private transitionToStateOrThrow(orderId: string, state: string) { return this.dataService.order.transitionToState(orderId, state).pipe( map(({ transitionOrderToState }) => { switch (transitionOrderToState?.__typename) { case 'Order': return transitionOrderToState?.state; case 'OrderStateTransitionError': this.notificationService.error(transitionOrderToState?.transitionError); throw new Error(transitionOrderToState?.transitionError); } }), ); } }
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from '@angular/router'; import { DataService, GetOrderStateQuery, GetOrderStateQueryVariables } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export const GET_ORDER_STATE = gql` query GetOrderState($id: ID!) { order(id: $id) { id state } } `; @Injectable({ providedIn: 'root', }) export class OrderGuard { constructor(private dataService: DataService, private router: Router) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { const isDraft = state.url.includes('orders/draft'); const isModifying = state.url.includes('/modify'); const id = route.paramMap.get('id'); if (isDraft) { if (id === 'create') { return this.dataService.order .createDraftOrder() .pipe( map(({ createDraftOrder }) => this.router.parseUrl(`/orders/draft/${createDraftOrder.id}`), ), ); } else { return true; } } else { return ( this.dataService // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .query<GetOrderStateQuery, GetOrderStateQueryVariables>(GET_ORDER_STATE, { id: id! }) .single$.pipe( map(({ order }) => { if (order?.state === 'Modifying' && !isModifying) { return this.router.parseUrl(`/orders/${id}/modify`); } else { return true; } }), ) ); } } }
// This file was generated by the build-public-api.ts script export * from './components/react-custom-column.component'; export * from './components/react-custom-detail.component'; export * from './components/react-form-input.component'; export * from './components/react-route.component'; export * from './directives/react-component-host.directive'; export * from './react-components/ActionBar'; export * from './react-components/Card'; export * from './react-components/CdsIcon'; export * from './react-components/FormField'; export * from './react-components/Link'; export * from './react-components/PageBlock'; export * from './react-components/PageDetailLayout'; export * from './react-components/RichTextEditor'; export * from './react-hooks/use-detail-component-data'; export * from './react-hooks/use-form-control'; export * from './react-hooks/use-injector'; export * from './react-hooks/use-page-metadata'; export * from './react-hooks/use-query'; export * from './react-hooks/use-rich-text-editor'; export * from './react-hooks/use-route-params'; export * from './register-react-custom-detail-component'; export * from './register-react-data-table-component'; export * from './register-react-form-input-component'; export * from './register-react-route-component'; export * from './types';
import { APP_INITIALIZER } from '@angular/core'; import { CustomDetailComponentLocationId, CustomDetailComponentService } from '@vendure/admin-ui/core'; import { ElementType } from 'react'; import { REACT_CUSTOM_DETAIL_COMPONENT_OPTIONS, ReactCustomDetailComponent, } from './components/react-custom-detail.component'; /** * @description * Configures a React-based component to be placed in a detail page in the given location. * * @docsCategory react-extensions */ export interface ReactCustomDetailComponentConfig { /** * @description * The id of the detail page location in which to place the component. */ locationId: CustomDetailComponentLocationId; /** * @description * The React component to render. */ component: ElementType; /** * @description * Optional props to pass to the React component. */ props?: Record<string, any>; } /** * @description * Registers a React component to be rendered in a detail page in the given location. * Components used as custom detail components can make use of the {@link useDetailComponentData} hook. * * @docsCategory react-extensions */ export function registerReactCustomDetailComponent(config: ReactCustomDetailComponentConfig) { return { provide: APP_INITIALIZER, multi: true, useFactory: (customDetailComponentService: CustomDetailComponentService) => () => { customDetailComponentService.registerCustomDetailComponent({ component: ReactCustomDetailComponent, locationId: config.locationId, providers: [ { provide: REACT_CUSTOM_DETAIL_COMPONENT_OPTIONS, useValue: { component: config.component, props: config.props, }, }, ], }); }, deps: [CustomDetailComponentService], }; }
import { APP_INITIALIZER } from '@angular/core'; import { DataTableColumnId, DataTableCustomComponentService, DataTableLocationId, } from '@vendure/admin-ui/core'; import { ElementType } from 'react'; import { REACT_CUSTOM_COLUMN_COMPONENT_OPTIONS, ReactCustomColumnComponent, } from './components/react-custom-column.component'; /** * @description * Configures a {@link CustomDetailComponent} to be placed in the given location. * * @docsCategory react-extensions */ export interface ReactDataTableComponentConfig { /** * @description * The location in the UI where the custom component should be placed. */ tableId: DataTableLocationId; /** * @description * The column in the table where the custom component should be placed. */ columnId: DataTableColumnId; /** * @description * The component to render in the table cell. This component will receive the `rowItem` prop * which is the data object for the row, e.g. the `Product` object if used in the `product-list` table. */ component: ElementType; /** * @description * Optional props to pass to the React component. */ props?: Record<string, any>; } /** * @description * The props that will be passed to the React component registered via {@link registerReactDataTableComponent}. */ export interface ReactDataTableComponentProps<T = any> { rowItem: T; [prop: string]: any; } /** * @description * Registers a React component to be rendered in a data table in the given location. * The component will receive the `rowItem` prop which is the data object for the row, * e.g. the `Product` object if used in the `product-list` table. * * @example * ```ts title="components/SlugWithLink.tsx" * import { ReactDataTableComponentProps } from '\@vendure/admin-ui/react'; * import React from 'react'; * * export function SlugWithLink({ rowItem }: ReactDataTableComponentProps<{ slug: string }>) { * return ( * <a href={`https://example.com/products/${rowItem.slug}`} target="_blank"> * {rowItem.slug} * </a> * ); * } * ``` * * ```ts title="providers.ts" * import { registerReactDataTableComponent } from '\@vendure/admin-ui/react'; * import { SlugWithLink } from './components/SlugWithLink'; * * export default [ * registerReactDataTableComponent({ * component: SlugWithLink, * tableId: 'product-list', * columnId: 'slug', * props: { * foo: 'bar', * }, * }), * ]; * ``` * * @docsCategory react-extensions */ export function registerReactDataTableComponent(config: ReactDataTableComponentConfig) { return { provide: APP_INITIALIZER, multi: true, useFactory: (dataTableCustomComponentService: DataTableCustomComponentService) => () => { dataTableCustomComponentService.registerCustomComponent({ ...config, component: ReactCustomColumnComponent, providers: [ { provide: REACT_CUSTOM_COLUMN_COMPONENT_OPTIONS, useValue: { component: config.component, props: config.props, }, }, ], }); }, deps: [DataTableCustomComponentService], }; }
import { APP_INITIALIZER, FactoryProvider } from '@angular/core'; import { ComponentRegistryService } from '@vendure/admin-ui/core'; import { ElementType } from 'react'; import { REACT_INPUT_COMPONENT_OPTIONS, ReactFormInputComponent, } from './components/react-form-input.component'; /** * @description * Registers a React component to be used as a {@link FormInputComponent}. * * @docsCategory react-extensions */ export function registerReactFormInputComponent(id: string, component: ElementType): FactoryProvider { return { provide: APP_INITIALIZER, multi: true, useFactory: (registry: ComponentRegistryService) => () => { registry.registerInputComponent(id, ReactFormInputComponent, [ { provide: REACT_INPUT_COMPONENT_OPTIONS, useValue: { component, }, }, ]); }, deps: [ComponentRegistryService], }; }
import { Route } from '@angular/router'; import { ResultOf, TypedDocumentNode } from '@graphql-typed-document-node/core'; import { registerRouteComponent, RegisterRouteComponentOptions } from '@vendure/admin-ui/core'; import { DocumentNode } from 'graphql/index'; import { ElementType } from 'react'; import { REACT_ROUTE_COMPONENT_OPTIONS, ReactRouteComponent } from './components/react-route.component'; import { ReactRouteComponentOptions } from './types'; /** * @description * Configuration for a React-based route component. * * @docsCategory react-extensions */ type RegisterReactRouteComponentOptions< Entity extends { id: string; updatedAt?: string }, T extends DocumentNode | TypedDocumentNode<any, { id: string }>, Field extends keyof ResultOf<T>, R extends Field, > = RegisterRouteComponentOptions<ElementType, Entity, T, Field, R> & { props?: Record<string, any>; }; /** * @description * Registers a React component to be used as a route component. * * @docsCategory react-extensions */ export function registerReactRouteComponent< Entity extends { id: string; updatedAt?: string }, T extends DocumentNode | TypedDocumentNode<any, { id: string }>, Field extends keyof ResultOf<T>, R extends Field, >(options: RegisterReactRouteComponentOptions<Entity, T, Field, R>): Route { const routeDef = registerRouteComponent(options); return { ...routeDef, providers: [ { provide: REACT_ROUTE_COMPONENT_OPTIONS, useValue: { props: options.props, } satisfies ReactRouteComponentOptions, }, ...(routeDef.providers ?? []), ], component: ReactRouteComponent, }; }
import { Injector } from '@angular/core'; import { FormControl } from '@angular/forms'; import { CustomField, PageMetadataService } from '@vendure/admin-ui/core'; export interface ReactFormInputOptions { formControl: FormControl; readonly: boolean; config: CustomField & Record<string, any>; } export interface ReactFormInputProps extends ReactFormInputOptions {} export interface ReactRouteComponentOptions { props?: Record<string, any>; } export type HostedReactComponentContext<T extends Record<string, any> = Record<string, any>> = { injector: Injector; pageMetadataService?: PageMetadataService; } & T;
import { Component, inject, InjectionToken, Input, OnInit, ViewEncapsulation } from '@angular/core'; import { CustomColumnComponent } from '@vendure/admin-ui/core'; import { ElementType } from 'react'; import { ReactComponentHostDirective } from '../directives/react-component-host.directive'; export const REACT_CUSTOM_COLUMN_COMPONENT_OPTIONS = new InjectionToken<{ component: ElementType; props?: Record<string, any>; }>('REACT_CUSTOM_COLUMN_COMPONENT_OPTIONS'); @Component({ selector: 'vdr-react-custom-column-component', template: ` <div [vdrReactComponentHost]="reactComponent" [props]="props"></div> `, styleUrls: ['./react-global-styles.scss'], encapsulation: ViewEncapsulation.None, standalone: true, imports: [ReactComponentHostDirective], }) export class ReactCustomColumnComponent implements CustomColumnComponent, OnInit { @Input() rowItem: any; protected reactComponent = inject(REACT_CUSTOM_COLUMN_COMPONENT_OPTIONS).component; private options = inject(REACT_CUSTOM_COLUMN_COMPONENT_OPTIONS); protected props: Record<string, any>; ngOnInit() { this.props = { rowItem: this.rowItem, ...(this.options.props ?? {}), }; } }
import { Component, inject, InjectionToken, OnInit, ViewEncapsulation } from '@angular/core'; import { FormGroup, UntypedFormGroup } from '@angular/forms'; import { CustomDetailComponent } from '@vendure/admin-ui/core'; import { ElementType } from 'react'; import { Observable } from 'rxjs'; import { ReactComponentHostDirective } from '../directives/react-component-host.directive'; export const REACT_CUSTOM_DETAIL_COMPONENT_OPTIONS = new InjectionToken<{ component: ElementType; props?: Record<string, any>; }>('REACT_CUSTOM_DETAIL_COMPONENT_OPTIONS'); export interface ReactCustomDetailComponentContext { detailForm: FormGroup; entity$: Observable<any>; } @Component({ selector: 'vdr-react-custom-detail-component', template: ` <div [vdrReactComponentHost]="reactComponent" [context]="context" [props]="props"></div> `, styleUrls: ['./react-global-styles.scss'], encapsulation: ViewEncapsulation.None, standalone: true, imports: [ReactComponentHostDirective], }) export class ReactCustomDetailComponent implements CustomDetailComponent, OnInit { detailForm: UntypedFormGroup; entity$: Observable<any>; protected props = inject(REACT_CUSTOM_DETAIL_COMPONENT_OPTIONS).props ?? {}; protected reactComponent = inject(REACT_CUSTOM_DETAIL_COMPONENT_OPTIONS).component; protected context: ReactCustomDetailComponentContext; ngOnInit() { this.context = { detailForm: this.detailForm, entity$: this.entity$, }; } }
import { Component, inject, InjectionToken, OnInit, ViewEncapsulation } from '@angular/core'; import { FormControl } from '@angular/forms'; import { CustomField, FormInputComponent } from '@vendure/admin-ui/core'; import { ElementType } from 'react'; import { ReactComponentHostDirective } from '../directives/react-component-host.directive'; import { ReactFormInputOptions } from '../types'; export const REACT_INPUT_COMPONENT_OPTIONS = new InjectionToken<{ component: ElementType; }>('REACT_INPUT_COMPONENT_OPTIONS'); @Component({ selector: 'vdr-react-form-input-component', template: ` <div [vdrReactComponentHost]="reactComponent" [context]="context" [props]="context"></div> `, styleUrls: ['./react-global-styles.scss'], encapsulation: ViewEncapsulation.None, standalone: true, imports: [ReactComponentHostDirective], }) export class ReactFormInputComponent implements FormInputComponent, OnInit { static readonly id: string = 'react-form-input-component'; readonly: boolean; formControl: FormControl; config: CustomField & Record<string, any>; protected context: ReactFormInputOptions; protected reactComponent = inject(REACT_INPUT_COMPONENT_OPTIONS).component; ngOnInit() { this.context = { formControl: this.formControl, readonly: this.readonly, config: this.config, }; } }
import { Component, inject, InjectionToken, ViewEncapsulation } from '@angular/core'; import { ROUTE_COMPONENT_OPTIONS, RouteComponent, SharedModule } from '@vendure/admin-ui/core'; import { ReactComponentHostDirective } from '../directives/react-component-host.directive'; import { ReactRouteComponentOptions } from '../types'; export const REACT_ROUTE_COMPONENT_OPTIONS = new InjectionToken<ReactRouteComponentOptions>( 'REACT_ROUTE_COMPONENT_OPTIONS', ); @Component({ selector: 'vdr-react-route-component', template: ` <vdr-route-component ><div [vdrReactComponentHost]="reactComponent" [props]="props"></div ></vdr-route-component> `, styleUrls: ['./react-global-styles.scss'], encapsulation: ViewEncapsulation.None, standalone: true, imports: [ReactComponentHostDirective, RouteComponent, SharedModule], }) export class ReactRouteComponent { protected props = inject(REACT_ROUTE_COMPONENT_OPTIONS).props; protected reactComponent = inject(ROUTE_COMPONENT_OPTIONS).component; }
import { Directive, ElementRef, Injector, Input, Optional } from '@angular/core'; import { PageMetadataService } from '@vendure/admin-ui/core'; import { ComponentProps, createContext, createElement, ElementType } from 'react'; import { createRoot, Root } from 'react-dom/client'; import { HostedReactComponentContext } from '../types'; export const HostedComponentContext = createContext<HostedReactComponentContext | null>(null); /** * Based on https://netbasal.com/using-react-in-angular-applications-1bb907ecac91 */ @Directive({ selector: '[vdrReactComponentHost]', standalone: true, }) export class ReactComponentHostDirective<Comp extends ElementType> { @Input('vdrReactComponentHost') reactComponent: Comp; @Input() props: ComponentProps<Comp>; @Input() context: Record<string, any> = {}; private root: Root | null = null; constructor( private host: ElementRef, private injector: Injector, @Optional() private pageMetadataService?: PageMetadataService, ) {} async ngOnChanges() { const Comp = this.reactComponent; if (!this.root) { this.root = createRoot(this.host.nativeElement); } this.root.render( createElement( HostedComponentContext.Provider, { value: { ...this.props, ...this.context, injector: this.injector, pageMetadataService: this.pageMetadataService, }, }, createElement(Comp, this.props), ), ); } ngOnDestroy() { this.root?.unmount(); } }
import { useContext, useEffect, useState } from 'react'; import { ReactCustomDetailComponentContext } from '../components/react-custom-detail.component'; import { HostedComponentContext } from '../directives/react-component-host.directive'; import { HostedReactComponentContext } from '../types'; /** * @description * Provides the data available to React-based CustomDetailComponents. * * @example * ```ts * import { Card, useDetailComponentData } from '\@vendure/admin-ui/react'; * import React from 'react'; * * export function CustomDetailComponent(props: any) { * const { entity, detailForm } = useDetailComponentData(); * const updateName = () => { * detailForm.get('name')?.setValue('New name'); * detailForm.markAsDirty(); * }; * return ( * <Card title={'Custom Detail Component'}> * <button className="button" onClick={updateName}> * Update name * </button> * <pre>{JSON.stringify(entity, null, 2)}</pre> * </Card> * ); * } * ``` * * @docsCategory react-hooks */ export function useDetailComponentData<T = any>() { const context = useContext( HostedComponentContext, ) as HostedReactComponentContext<ReactCustomDetailComponentContext>; if (!context.detailForm || !context.entity$) { throw new Error(`The useDetailComponentData hook can only be used within a CustomDetailComponent`); } const [entity, setEntity] = useState<T | null>(null); useEffect(() => { const subscription = context.entity$.subscribe(value => { setEntity(value); }); return () => subscription.unsubscribe(); }, []); return { entity, detailForm: context.detailForm, }; }
import { CustomFieldType } from '@vendure/common/lib/shared-types'; import { useContext, useEffect, useState } from 'react'; import { HostedComponentContext } from '../directives/react-component-host.directive'; import { HostedReactComponentContext, ReactFormInputOptions } from '../types'; /** * @description * Provides access to the current FormControl value and a method to update the value. * * @example * ```ts * import { useFormControl, ReactFormInputProps } from '\@vendure/admin-ui/react'; * import React from 'react'; * * export function ReactNumberInput({ readonly }: ReactFormInputProps) { * const { value, setFormValue } = useFormControl(); * * const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { * setFormValue(val); * }; * return ( * <div> * <input readOnly={readonly} type="number" onChange={handleChange} value={value} /> * </div> * ); * } * ``` * * @docsCategory react-hooks */ export function useFormControl() { const context = useContext(HostedComponentContext); if (!context) { throw new Error('No HostedComponentContext found'); } if (!isFormInputContext(context)) { throw new Error('useFormControl() can only be used in a form input component'); } const { formControl, config } = context; const [value, setValue] = useState(formControl.value ?? 0); useEffect(() => { const subscription = formControl.valueChanges.subscribe(v => { setValue(v); }); return () => { subscription.unsubscribe(); }; }, []); function setFormValue(newValue: any) { formControl.setValue(coerceFormValue(newValue, config.type as CustomFieldType)); formControl.markAsDirty(); } return { value, setFormValue }; } function isFormInputContext( context: HostedReactComponentContext, ): context is HostedReactComponentContext<ReactFormInputOptions> { return context.config && context.formControl; } function coerceFormValue(value: any, type: CustomFieldType) { switch (type) { case 'int': case 'float': return Number(value); case 'boolean': return Boolean(value); default: return value; } }
import { ProviderToken } from '@angular/core'; import { useContext } from 'react'; import { HostedComponentContext } from '../directives/react-component-host.directive'; /** * @description * Exposes the Angular injector which allows the injection of services into React components. * * @example * ```ts * import { useInjector } from '\@vendure/admin-ui/react'; * import { NotificationService } from '\@vendure/admin-ui/core'; * * export const MyComponent = () => { * const notificationService = useInjector(NotificationService); * * const handleClick = () => { * notificationService.success('Hello world!'); * }; * // ... * return <div>...</div>; * } * ``` * * @docsCategory react-hooks */ export function useInjector<T = any>(token: ProviderToken<T>): T { const context = useContext(HostedComponentContext); const instance = context?.injector.get(token); if (!instance) { throw new Error(`Could not inject ${(token as any).name ?? token.toString()}`); } return instance; }
import { BreadcrumbValue } from '@vendure/admin-ui/core'; import { useContext } from 'react'; import { HostedComponentContext } from '../directives/react-component-host.directive'; import { HostedReactComponentContext, ReactRouteComponentOptions } from '../types'; /** * @description * Provides functions for setting the current page title and breadcrumb. * * @example * ```ts * import { usePageMetadata } from '\@vendure/admin-ui/react'; * import { useEffect } from 'react'; * * export const MyComponent = () => { * const { setTitle, setBreadcrumb } = usePageMetadata(); * useEffect(() => { * setTitle('My Page'); * setBreadcrumb([ * { link: ['./parent'], label: 'Parent Page' }, * { link: ['./'], label: 'This Page' }, * ]); * }, []); * // ... * return <div>...</div>; * } * ``` * * @docsCategory react-hooks */ export function usePageMetadata() { const context = useContext( HostedComponentContext, ) as HostedReactComponentContext<ReactRouteComponentOptions>; const setBreadcrumb = (newValue: BreadcrumbValue) => { context.pageMetadataService?.setBreadcrumbs(newValue); }; const setTitle = (newTitle: string) => { context.pageMetadataService?.setTitle(newTitle); }; return { setBreadcrumb, setTitle, }; }
import { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { DataService } from '@vendure/admin-ui/core'; import { DocumentNode } from 'graphql/index'; import { useCallback, useContext, useEffect, useState } from 'react'; import { firstValueFrom, Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { HostedComponentContext } from '../directives/react-component-host.directive'; /** * @description * A React hook which provides access to the results of a GraphQL query. * * @example * ```ts * import { useQuery } from '\@vendure/admin-ui/react'; * import { gql } from 'graphql-tag'; * * const GET_PRODUCT = gql` * query GetProduct($id: ID!) { * product(id: $id) { * id * name * description * } * }`; * * export const MyComponent = () => { * const { data, loading, error } = useQuery(GET_PRODUCT, { id: '1' }); * * if (loading) return <div>Loading...</div>; * if (error) return <div>Error! { error }</div>; * return ( * <div> * <h1>{data.product.name}</h1> * <p>{data.product.description}</p> * </div> * ); * }; * ``` * * @docsCategory react-hooks */ export function useQuery<T, V extends Record<string, any> = Record<string, any>>( query: DocumentNode | TypedDocumentNode<T, V>, variables?: V, ) { const { data, loading, error, runQuery } = useDataService<T, V>( (dataService, vars) => dataService.query(query, vars).stream$, ); useEffect(() => { const subscription = runQuery(variables).subscribe(); return () => subscription.unsubscribe(); }, [runQuery]); const refetch = (variables?: V) => firstValueFrom(runQuery(variables)); return { data, loading, error, refetch } as const; } /** * @description * A React hook which allows you to execute a GraphQL query. * * @example * ```ts * import { useLazyQuery } from '\@vendure/admin-ui/react'; * import { gql } from 'graphql-tag'; * * const GET_PRODUCT = gql` * query GetProduct($id: ID!) { * product(id: $id) { * id * name * description * } * }`; * type ProductResponse = { * product: { * name: string * description: string * } * } * * export const MyComponent = () => { * const [getProduct, { data, loading, error }] = useLazyQuery<ProductResponse>(GET_PRODUCT); * * const handleClick = () => { * getProduct({ * id: '1', * }).then(result => { * // do something with the result * }); * }; * * if (loading) return <div>Loading...</div>; * if (error) return <div>Error! { error }</div>; * * return ( * <div> * <button onClick={handleClick}>Get product</button> * {data && ( * <div> * <h1>{data.product.name}</h1> * <p>{data.product.description}</p> * </div>)} * </div> * ); * }; * ``` * * @since 2.2.0 * @docsCategory react-hooks */ export function useLazyQuery<T, V extends Record<string, any> = Record<string, any>>( query: DocumentNode | TypedDocumentNode<T, V>, ) { const { data, loading, error, runQuery } = useDataService<T, V>( (dataService, vars) => dataService.query(query, vars).stream$, ); const rest = { data, loading, error }; const execute = (variables?: V) => firstValueFrom(runQuery(variables)); return [execute, rest] as [typeof execute, typeof rest]; } /** * @description * A React hook which allows you to execute a GraphQL mutation. * * @example * ```ts * import { useMutation } from '\@vendure/admin-ui/react'; * import { gql } from 'graphql-tag'; * * const UPDATE_PRODUCT = gql` * mutation UpdateProduct($input: UpdateProductInput!) { * updateProduct(input: $input) { * id * name * } * }`; * * export const MyComponent = () => { * const [updateProduct, { data, loading, error }] = useMutation(UPDATE_PRODUCT); * * const handleClick = () => { * updateProduct({ * input: { * id: '1', * name: 'New name', * }, * }).then(result => { * // do something with the result * }); * }; * * if (loading) return <div>Loading...</div>; * if (error) return <div>Error! { error }</div>; * * return ( * <div> * <button onClick={handleClick}>Update product</button> * {data && <div>Product updated!</div>} * </div> * ); * }; * ``` * * @docsCategory react-hooks */ export function useMutation<T, V extends Record<string, any> = Record<string, any>>( mutation: DocumentNode | TypedDocumentNode<T, V>, ) { const { data, loading, error, runQuery } = useDataService<T, V>((dataService, variables) => dataService.mutate(mutation, variables), ); const rest = { data, loading, error }; const execute = (variables?: V) => firstValueFrom(runQuery(variables)); return [execute, rest] as [typeof execute, typeof rest]; } export function useDataService<T, V extends Record<string, any> = Record<string, any>>( operation: (dataService: DataService, variables?: V) => Observable<T>, ) { const context = useContext(HostedComponentContext); const dataService = context?.injector.get(DataService); if (!dataService) { throw new Error('No DataService found in HostedComponentContext'); } const [data, setData] = useState<T>(); const [error, setError] = useState<string>(); const [loading, setLoading] = useState(false); const runQuery = useCallback((variables?: V) => { setLoading(true); return operation(dataService, variables).pipe( tap({ next: res => { setData(res); setLoading(false); }, error: err => { setError(err.message); setLoading(false); }, }), ); }, []); return { data, loading, error, runQuery }; }
import { useEffect, useRef } from 'react'; import { Injector } from '@angular/core'; import { CreateEditorViewOptions, ProsemirrorService, ContextMenuService } from '@vendure/admin-ui/core'; import { useInjector } from './use-injector'; export interface useRichTextEditorOptions extends Omit<CreateEditorViewOptions, 'element'> { /** * @description * Control the DOM attributes of the editable element. May be either an object or a function going from an editor state to an object. * By default, the element will get a class "ProseMirror", and will have its contentEditable attribute determined by the editable prop. * Additional classes provided here will be added to the class. For other attributes, the value provided first (as in someProp) will be used. * Copied from real property description. */ attributes?: Record<string, string>; } /** * @description * Provides access to the ProseMirror (rich text editor) instance. * * @example * ```ts * import { useRichTextEditor } from '\@vendure/admin-ui/react'; * import React from 'react'; * * export function Component() { * const { ref, editor } = useRichTextEditor({ * attributes: { class: '' }, * onTextInput: (text) => console.log(text), * isReadOnly: () => false, * }); * * return <div className="w-full" ref={ref} /> * } * ``` * * @docsCategory react-hooks */ export const useRichTextEditor = ({ attributes, onTextInput, isReadOnly }: useRichTextEditorOptions) => { const injector = useInjector(Injector); const ref = useRef<HTMLDivElement>(null); const prosemirror = new ProsemirrorService(injector, useInjector(ContextMenuService)); useEffect(() => { if (!ref.current) return; prosemirror.createEditorView({ element: ref.current, isReadOnly, onTextInput, }); const readOnly = isReadOnly(); prosemirror.editorView.setProps({ attributes, editable: readOnly ? () => false : () => true, }); return () => { prosemirror.destroy(); }; }, [ref.current]); return { ref, editor: prosemirror }; };
import { ActivatedRoute } from '@angular/router'; import { useEffect, useState } from 'react'; import { useInjector } from './use-injector'; /** * @description * Provides access to the current route params and query params. * * @example * ```ts * import { useRouteParams } from '\@vendure/admin-ui/react'; * import React from 'react'; * * export function MyComponent() { * const { params, queryParams } = useRouteParams(); * // ... * return <div>{ params.id }</div>; * } * ``` * * @docsCategory react-hooks */ export function useRouteParams() { const activatedRoute = useInjector(ActivatedRoute); const [params, setParams] = useState(activatedRoute.snapshot.params); const [queryParams, setQueryParams] = useState(activatedRoute.snapshot.queryParams); useEffect(() => { const subscription = activatedRoute.params.subscribe(value => { setParams(value); }); subscription.add(activatedRoute.queryParams.subscribe(value => setQueryParams(value))); return () => subscription.unsubscribe(); }, []); activatedRoute; return { params, queryParams, }; }
// This file was generated by the build-public-api.ts script export * from './components/add-country-to-zone-dialog/add-country-to-zone-dialog.component'; export * from './components/admin-detail/admin-detail.component'; export * from './components/administrator-list/administrator-list-bulk-actions'; export * from './components/administrator-list/administrator-list.component'; export * from './components/channel-detail/channel-detail.component'; export * from './components/channel-list/channel-list-bulk-actions'; export * from './components/channel-list/channel-list.component'; export * from './components/country-detail/country-detail.component'; export * from './components/country-list/country-list-bulk-actions'; export * from './components/country-list/country-list.component'; export * from './components/global-settings/global-settings.component'; export * from './components/payment-method-detail/payment-method-detail.component'; export * from './components/payment-method-list/payment-method-list-bulk-actions'; export * from './components/payment-method-list/payment-method-list.component'; export * from './components/permission-grid/permission-grid.component'; export * from './components/profile/profile.component'; export * from './components/role-detail/role-detail.component'; export * from './components/role-list/role-list-bulk-actions'; export * from './components/role-list/role-list.component'; export * from './components/seller-detail/seller-detail.component'; export * from './components/seller-list/seller-list-bulk-actions'; export * from './components/seller-list/seller-list.component'; export * from './components/shipping-eligibility-test-result/shipping-eligibility-test-result.component'; export * from './components/shipping-method-detail/shipping-method-detail.component'; export * from './components/shipping-method-list/shipping-method-list-bulk-actions'; export * from './components/shipping-method-list/shipping-method-list.component'; export * from './components/shipping-method-test-result/shipping-method-test-result.component'; export * from './components/stock-location-detail/stock-location-detail.component'; export * from './components/stock-location-list/stock-location-list-bulk-actions'; export * from './components/stock-location-list/stock-location-list.component'; export * from './components/tax-category-detail/tax-category-detail.component'; export * from './components/tax-category-list/tax-category-list-bulk-actions'; export * from './components/tax-category-list/tax-category-list.component'; export * from './components/tax-rate-detail/tax-rate-detail.component'; export * from './components/tax-rate-list/tax-rate-list-bulk-actions'; export * from './components/tax-rate-list/tax-rate-list.component'; export * from './components/test-address-form/test-address-form.component'; export * from './components/test-order-builder/test-order-builder.component'; export * from './components/test-shipping-methods/test-shipping-methods.component'; export * from './components/zone-detail/zone-detail.component'; export * from './components/zone-list/zone-list-bulk-actions'; export * from './components/zone-list/zone-list.component'; export * from './components/zone-member-list/zone-member-controls.directive'; export * from './components/zone-member-list/zone-member-list-bulk-actions'; export * from './components/zone-member-list/zone-member-list-header.directive'; export * from './components/zone-member-list/zone-member-list.component'; export * from './providers/routing/profile-resolver'; export * from './settings.module'; export * from './settings.routes';
import { NgModule } from '@angular/core'; import { RouterModule, ROUTES } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { BulkActionRegistryService, detailComponentWithResolver, GetAdministratorDetailDocument, GetChannelDetailDocument, GetCountryDetailDocument, GetPaymentMethodDetailDocument, GetRoleDetailDocument, GetSellerDetailDocument, GetShippingMethodDetailDocument, GetStockLocationDetailDocument, GetTaxCategoryDetailDocument, GetTaxRateDetailDocument, GetZoneDetailDocument, PageService, SharedModule, } from '@vendure/admin-ui/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { AddCountryToZoneDialogComponent } from './components/add-country-to-zone-dialog/add-country-to-zone-dialog.component'; import { AdminDetailComponent } from './components/admin-detail/admin-detail.component'; import { deleteAdministratorsBulkAction } from './components/administrator-list/administrator-list-bulk-actions'; import { AdministratorListComponent } from './components/administrator-list/administrator-list.component'; import { ChannelDetailComponent } from './components/channel-detail/channel-detail.component'; import { deleteChannelsBulkAction } from './components/channel-list/channel-list-bulk-actions'; import { ChannelListComponent } from './components/channel-list/channel-list.component'; import { CountryDetailComponent } from './components/country-detail/country-detail.component'; import { deleteCountriesBulkAction } from './components/country-list/country-list-bulk-actions'; import { CountryListComponent } from './components/country-list/country-list.component'; import { GlobalSettingsComponent } from './components/global-settings/global-settings.component'; import { PaymentMethodDetailComponent } from './components/payment-method-detail/payment-method-detail.component'; import { assignPaymentMethodsToChannelBulkAction, deletePaymentMethodsBulkAction, removePaymentMethodsFromChannelBulkAction, } from './components/payment-method-list/payment-method-list-bulk-actions'; import { PaymentMethodListComponent } from './components/payment-method-list/payment-method-list.component'; import { PermissionGridComponent } from './components/permission-grid/permission-grid.component'; import { ProfileComponent } from './components/profile/profile.component'; import { RoleDetailComponent } from './components/role-detail/role-detail.component'; import { deleteRolesBulkAction } from './components/role-list/role-list-bulk-actions'; import { RoleListComponent } from './components/role-list/role-list.component'; import { SellerDetailComponent } from './components/seller-detail/seller-detail.component'; import { deleteSellersBulkAction } from './components/seller-list/seller-list-bulk-actions'; import { SellerListComponent } from './components/seller-list/seller-list.component'; import { ShippingEligibilityTestResultComponent } from './components/shipping-eligibility-test-result/shipping-eligibility-test-result.component'; import { ShippingMethodDetailComponent } from './components/shipping-method-detail/shipping-method-detail.component'; import { assignShippingMethodsToChannelBulkAction, deleteShippingMethodsBulkAction, removeShippingMethodsFromChannelBulkAction, } from './components/shipping-method-list/shipping-method-list-bulk-actions'; import { ShippingMethodListComponent } from './components/shipping-method-list/shipping-method-list.component'; import { ShippingMethodTestResultComponent } from './components/shipping-method-test-result/shipping-method-test-result.component'; import { StockLocationDetailComponent } from './components/stock-location-detail/stock-location-detail.component'; import { assignStockLocationsToChannelBulkAction, deleteStockLocationsBulkAction, removeStockLocationsFromChannelBulkAction, } from './components/stock-location-list/stock-location-list-bulk-actions'; import { StockLocationListComponent } from './components/stock-location-list/stock-location-list.component'; import { TaxCategoryDetailComponent } from './components/tax-category-detail/tax-category-detail.component'; import { deleteTaxCategoriesBulkAction } from './components/tax-category-list/tax-category-list-bulk-actions'; import { TaxCategoryListComponent } from './components/tax-category-list/tax-category-list.component'; import { TaxRateDetailComponent } from './components/tax-rate-detail/tax-rate-detail.component'; import { deleteTaxRatesBulkAction } from './components/tax-rate-list/tax-rate-list-bulk-actions'; import { TaxRateListComponent } from './components/tax-rate-list/tax-rate-list.component'; import { TestAddressFormComponent } from './components/test-address-form/test-address-form.component'; import { TestOrderBuilderComponent } from './components/test-order-builder/test-order-builder.component'; import { TestShippingMethodsComponent } from './components/test-shipping-methods/test-shipping-methods.component'; import { ZoneDetailComponent } from './components/zone-detail/zone-detail.component'; import { deleteZonesBulkAction } from './components/zone-list/zone-list-bulk-actions'; import { ZoneListComponent } from './components/zone-list/zone-list.component'; import { ZoneMemberControlsDirective } from './components/zone-member-list/zone-member-controls.directive'; import { removeZoneMembersBulkAction } from './components/zone-member-list/zone-member-list-bulk-actions'; import { ZoneMemberListHeaderDirective } from './components/zone-member-list/zone-member-list-header.directive'; import { ZoneMemberListComponent } from './components/zone-member-list/zone-member-list.component'; import { createRoutes } from './settings.routes'; @NgModule({ imports: [SharedModule, RouterModule.forChild([])], providers: [ { provide: ROUTES, useFactory: (pageService: PageService) => createRoutes(pageService), multi: true, deps: [PageService], }, ], declarations: [ TaxCategoryListComponent, TaxCategoryDetailComponent, AdministratorListComponent, RoleListComponent, RoleDetailComponent, AdminDetailComponent, PermissionGridComponent, CountryListComponent, CountryDetailComponent, TaxRateListComponent, TaxRateDetailComponent, ChannelListComponent, ChannelDetailComponent, ShippingMethodListComponent, ShippingMethodDetailComponent, PaymentMethodListComponent, PaymentMethodDetailComponent, GlobalSettingsComponent, TestOrderBuilderComponent, TestAddressFormComponent, SellerDetailComponent, SellerListComponent, ShippingMethodTestResultComponent, ShippingEligibilityTestResultComponent, ZoneListComponent, AddCountryToZoneDialogComponent, ZoneMemberListComponent, ZoneMemberListHeaderDirective, ZoneMemberControlsDirective, ProfileComponent, TestShippingMethodsComponent, ZoneDetailComponent, StockLocationListComponent, StockLocationDetailComponent, ], }) export class SettingsModule { private static hasRegisteredTabsAndBulkActions = false; constructor(bulkActionRegistryService: BulkActionRegistryService, pageService: PageService) { if (SettingsModule.hasRegisteredTabsAndBulkActions) { return; } bulkActionRegistryService.registerBulkAction(deleteSellersBulkAction); bulkActionRegistryService.registerBulkAction(deleteChannelsBulkAction); bulkActionRegistryService.registerBulkAction(deleteAdministratorsBulkAction); bulkActionRegistryService.registerBulkAction(deleteRolesBulkAction); bulkActionRegistryService.registerBulkAction(assignShippingMethodsToChannelBulkAction); bulkActionRegistryService.registerBulkAction(removeShippingMethodsFromChannelBulkAction); bulkActionRegistryService.registerBulkAction(deleteShippingMethodsBulkAction); bulkActionRegistryService.registerBulkAction(assignPaymentMethodsToChannelBulkAction); bulkActionRegistryService.registerBulkAction(removePaymentMethodsFromChannelBulkAction); bulkActionRegistryService.registerBulkAction(deletePaymentMethodsBulkAction); bulkActionRegistryService.registerBulkAction(deleteTaxCategoriesBulkAction); bulkActionRegistryService.registerBulkAction(deleteTaxRatesBulkAction); bulkActionRegistryService.registerBulkAction(deleteCountriesBulkAction); bulkActionRegistryService.registerBulkAction(deleteZonesBulkAction); bulkActionRegistryService.registerBulkAction(removeZoneMembersBulkAction); bulkActionRegistryService.registerBulkAction(assignStockLocationsToChannelBulkAction); bulkActionRegistryService.registerBulkAction(removeStockLocationsFromChannelBulkAction); bulkActionRegistryService.registerBulkAction(deleteStockLocationsBulkAction); pageService.registerPageTab({ priority: 0, location: 'seller-list', tab: _('breadcrumb.sellers'), route: '', component: SellerListComponent, }); pageService.registerPageTab({ priority: 0, location: 'seller-detail', tab: _('settings.seller'), route: '', component: detailComponentWithResolver({ component: SellerDetailComponent, query: GetSellerDetailDocument, entityKey: 'seller', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-seller'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'channel-list', tab: _('breadcrumb.channels'), route: '', component: ChannelListComponent, }); pageService.registerPageTab({ priority: 0, location: 'channel-detail', tab: _('settings.channel'), route: '', component: detailComponentWithResolver({ component: ChannelDetailComponent, query: GetChannelDetailDocument, entityKey: 'channel', getBreadcrumbs: entity => [ { label: entity ? entity.code === DEFAULT_CHANNEL_CODE ? 'common.default-channel' : entity.code : _('settings.create-new-channel'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'administrator-list', tab: _('breadcrumb.administrators'), route: '', component: AdministratorListComponent, }); pageService.registerPageTab({ priority: 0, location: 'administrator-detail', tab: _('settings.administrator'), route: '', component: detailComponentWithResolver({ component: AdminDetailComponent, query: GetAdministratorDetailDocument, entityKey: 'administrator', getBreadcrumbs: entity => [ { label: entity ? `${entity.firstName} ${entity.lastName}` : _('admin.create-new-administrator'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'role-list', tab: _('breadcrumb.roles'), route: '', component: RoleListComponent, }); pageService.registerPageTab({ priority: 0, location: 'role-detail', tab: _('settings.role'), route: '', component: detailComponentWithResolver({ component: RoleDetailComponent, query: GetRoleDetailDocument, entityKey: 'role', getBreadcrumbs: entity => [ { label: entity ? entity.description : _('settings.create-new-role'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'shipping-method-list', tab: _('breadcrumb.shipping-methods'), route: '', component: ShippingMethodListComponent, }); pageService.registerPageTab({ priority: 0, location: 'shipping-method-detail', tab: _('settings.shipping-method'), route: '', component: detailComponentWithResolver({ component: ShippingMethodDetailComponent, query: GetShippingMethodDetailDocument, entityKey: 'shippingMethod', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-shipping-method'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'shipping-method-list', tab: _('settings.test-shipping-methods'), route: 'test', component: TestShippingMethodsComponent, }); pageService.registerPageTab({ priority: 0, location: 'payment-method-list', tab: _('breadcrumb.payment-methods'), route: '', component: PaymentMethodListComponent, }); pageService.registerPageTab({ priority: 0, location: 'payment-method-detail', tab: _('settings.payment-method'), route: '', component: detailComponentWithResolver({ component: PaymentMethodDetailComponent, query: GetPaymentMethodDetailDocument, entityKey: 'paymentMethod', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-payment-method'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'tax-category-list', tab: _('breadcrumb.tax-categories'), route: '', component: TaxCategoryListComponent, }); pageService.registerPageTab({ priority: 0, location: 'tax-category-detail', tab: _('settings.tax-category'), route: '', component: detailComponentWithResolver({ component: TaxCategoryDetailComponent, query: GetTaxCategoryDetailDocument, entityKey: 'taxCategory', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-tax-category'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'tax-rate-list', tab: _('breadcrumb.tax-rates'), route: '', component: TaxRateListComponent, }); pageService.registerPageTab({ priority: 0, location: 'tax-rate-detail', tab: _('settings.tax-rate'), route: '', component: detailComponentWithResolver({ component: TaxRateDetailComponent, query: GetTaxRateDetailDocument, entityKey: 'taxRate', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-tax-rate'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'country-list', tab: _('breadcrumb.countries'), route: '', component: CountryListComponent, }); pageService.registerPageTab({ priority: 0, location: 'country-detail', tab: _('settings.country'), route: '', component: detailComponentWithResolver({ component: CountryDetailComponent, query: GetCountryDetailDocument, entityKey: 'country', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-country'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'zone-list', tab: _('breadcrumb.zones'), route: '', component: ZoneListComponent, }); pageService.registerPageTab({ priority: 0, location: 'zone-detail', tab: _('settings.zone'), route: '', component: detailComponentWithResolver({ component: ZoneDetailComponent, query: GetZoneDetailDocument, entityKey: 'zone', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('settings.create-new-zone'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'global-setting-detail', tab: _('breadcrumb.global-settings'), route: '', component: GlobalSettingsComponent, }); pageService.registerPageTab({ priority: 0, location: 'profile', tab: _('breadcrumb.profile'), route: '', component: ProfileComponent, }); pageService.registerPageTab({ priority: 0, location: 'stock-location-list', tab: _('catalog.stock-locations'), route: '', component: StockLocationListComponent, }); pageService.registerPageTab({ priority: 0, location: 'stock-location-detail', tab: _('catalog.stock-location'), route: '', component: detailComponentWithResolver({ component: StockLocationDetailComponent, query: GetStockLocationDetailDocument, entityKey: 'stockLocation', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('catalog.create-new-stock-location'), link: [entity?.id], }, ], }), }); SettingsModule.hasRegisteredTabsAndBulkActions = true; } }
import { inject } from '@angular/core'; import { Route } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DataService, GetGlobalSettingsDetailDocument, GetProfileDetailDocument, PageComponent, PageService, } from '@vendure/admin-ui/core'; import { of } from 'rxjs'; export const createRoutes = (pageService: PageService): Route[] => [ { path: 'profile', component: PageComponent, data: { breadcrumb: _('breadcrumb.profile'), }, resolve: { detail: () => inject(DataService) .query(GetProfileDetailDocument) .mapSingle(data => ({ entity: of(data.activeAdministrator) })), }, children: pageService.getPageTabRoutes('profile'), }, { path: 'administrators', component: PageComponent, data: { locationId: 'administrator-list', breadcrumb: _('breadcrumb.administrators'), }, children: pageService.getPageTabRoutes('administrator-list'), }, { path: 'administrators/:id', component: PageComponent, data: { locationId: 'administrator-detail', breadcrumb: { label: _('breadcrumb.administrators'), link: ['../', 'administrators'] }, }, children: pageService.getPageTabRoutes('administrator-detail'), }, { path: 'channels', component: PageComponent, data: { locationId: 'channel-list', breadcrumb: _('breadcrumb.channels'), }, children: pageService.getPageTabRoutes('channel-list'), }, { path: 'channels/:id', component: PageComponent, data: { locationId: 'channel-detail', breadcrumb: { label: _('breadcrumb.channels'), link: ['../', 'channels'] }, }, children: pageService.getPageTabRoutes('channel-detail'), }, { path: 'stock-locations', component: PageComponent, data: { locationId: 'stock-location-list', breadcrumb: _('breadcrumb.stock-locations'), }, children: pageService.getPageTabRoutes('stock-location-list'), }, { path: 'stock-locations/:id', component: PageComponent, data: { locationId: 'stock-location-detail', breadcrumb: { label: _('breadcrumb.stock-locations'), link: ['../', 'stock-locations'] }, }, children: pageService.getPageTabRoutes('stock-location-detail'), }, { path: 'sellers', component: PageComponent, data: { locationId: 'seller-list', breadcrumb: _('breadcrumb.sellers'), }, children: pageService.getPageTabRoutes('seller-list'), }, { path: 'sellers/:id', component: PageComponent, data: { locationId: 'seller-detail', breadcrumb: { label: _('breadcrumb.sellers'), link: ['../', 'sellers'] }, }, children: pageService.getPageTabRoutes('seller-detail'), }, { path: 'roles', component: PageComponent, data: { locationId: 'role-list', breadcrumb: _('breadcrumb.roles'), }, children: pageService.getPageTabRoutes('role-list'), }, { path: 'roles/:id', component: PageComponent, data: { locationId: 'role-detail', breadcrumb: { label: _('breadcrumb.roles'), link: ['../', 'roles'] }, }, children: pageService.getPageTabRoutes('role-detail'), }, { path: 'tax-categories', component: PageComponent, data: { locationId: 'tax-category-list', breadcrumb: _('breadcrumb.tax-categories'), }, children: pageService.getPageTabRoutes('tax-category-list'), }, { path: 'tax-categories/:id', component: PageComponent, data: { locationId: 'tax-category-detail', breadcrumb: { label: _('breadcrumb.tax-categories'), link: ['../', 'tax-categories'] }, }, children: pageService.getPageTabRoutes('tax-category-detail'), }, { path: 'tax-rates', component: PageComponent, data: { locationId: 'tax-rate-list', breadcrumb: _('breadcrumb.tax-rates'), }, children: pageService.getPageTabRoutes('tax-rate-list'), }, { path: 'tax-rates/:id', component: PageComponent, data: { locationId: 'tax-rate-detail', breadcrumb: { label: _('breadcrumb.tax-rates'), link: ['../', 'tax-rates'] }, }, children: pageService.getPageTabRoutes('tax-rate-detail'), }, { path: 'countries', component: PageComponent, data: { locationId: 'country-list', breadcrumb: _('breadcrumb.countries'), }, children: pageService.getPageTabRoutes('country-list'), }, { path: 'countries/:id', component: PageComponent, data: { locationId: 'country-detail', breadcrumb: { label: _('breadcrumb.countries'), link: ['../', 'countries'] }, }, children: pageService.getPageTabRoutes('country-detail'), }, { path: 'zones', component: PageComponent, data: { locationId: 'zone-list', breadcrumb: _('breadcrumb.zones'), }, children: pageService.getPageTabRoutes('zone-list'), }, { path: 'zones/:id', component: PageComponent, data: { locationId: 'zone-detail', breadcrumb: { label: _('breadcrumb.zones'), link: ['../', 'zones'] }, }, children: pageService.getPageTabRoutes('zone-detail'), }, { path: 'shipping-methods', component: PageComponent, data: { locationId: 'shipping-method-list', breadcrumb: _('breadcrumb.shipping-methods'), }, children: pageService.getPageTabRoutes('shipping-method-list'), }, { path: 'shipping-methods/:id', component: PageComponent, data: { locationId: 'shipping-method-detail', breadcrumb: { label: _('breadcrumb.shipping-methods'), link: ['../', 'shipping-methods'] }, }, children: pageService.getPageTabRoutes('shipping-method-detail'), }, { path: 'payment-methods', component: PageComponent, data: { locationId: 'payment-method-list', breadcrumb: _('breadcrumb.payment-methods'), }, children: pageService.getPageTabRoutes('payment-method-list'), }, { path: 'payment-methods/:id', component: PageComponent, data: { locationId: 'payment-method-detail', breadcrumb: { label: _('breadcrumb.payment-methods'), link: ['../', 'payment-methods'] }, }, children: pageService.getPageTabRoutes('payment-method-detail'), }, { path: 'global-settings', component: PageComponent, data: { breadcrumb: _('breadcrumb.global-settings'), locationId: 'global-setting-detail', }, resolve: { detail: () => inject(DataService) .query(GetGlobalSettingsDetailDocument) .mapSingle(data => ({ entity: of(data.globalSettings) })), }, children: pageService.getPageTabRoutes('global-setting-detail'), }, ];
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { DataService, Dialog, GetCountryListDocument, GetCountryListQuery, GetZoneListQuery, GetZoneMembersDocument, GetZoneMembersQuery, ItemOf, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; import { map, withLatestFrom } from 'rxjs/operators'; export const GET_ZONE_MEMBERS = gql` query GetZoneMembers($zoneId: ID!) { zone(id: $zoneId) { id createdAt updatedAt name members { createdAt updatedAt id name code enabled } } } `; @Component({ selector: 'vdr-add-country-to-zone-dialog', templateUrl: './add-country-to-zone-dialog.component.html', styleUrls: ['./add-country-to-zone-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddCountryToZoneDialogComponent implements Dialog<string[]>, OnInit { resolveWith: (result?: string[]) => void; zoneName: string; zoneId: string; currentMembers$: Observable<NonNullable<GetZoneMembersQuery['zone']>['members']>; availableCountries$: Observable<Array<ItemOf<GetCountryListQuery, 'countries'>>>; selectedMemberIds: string[] = []; constructor(private dataService: DataService) {} ngOnInit(): void { this.currentMembers$ = this.dataService .query(GetZoneMembersDocument, { zoneId: this.zoneId }) .mapSingle(({ zone }) => zone?.members ?? []); this.availableCountries$ = this.dataService .query(GetCountryListDocument, { options: { take: 999 }, }) .mapStream(data => data.countries.items) .pipe( withLatestFrom(this.currentMembers$), map(([countries, currentMembers]) => countries.filter(c => !currentMembers.find(cm => cm.id === c.id)), ), ); } cancel() { this.resolveWith(); } add() { this.resolveWith(this.selectedMemberIds); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { ResultOf } from '@graphql-typed-document-node/core'; import { ADMINISTRATOR_FRAGMENT, CreateAdministratorInput, DataService, GetAdministratorDetailDocument, getCustomFieldsDefaults, LanguageCode, NotificationService, Permission, PermissionDefinition, RoleFragment, TypedBaseDetailComponent, UpdateAdministratorInput, } from '@vendure/admin-ui/core'; import { CUSTOMER_ROLE_CODE } from '@vendure/common/lib/shared-constants'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; import { mergeMap, take } from 'rxjs/operators'; export interface PermissionsByChannel { channelId: string; channelCode: string; permissions: { [K in Permission]: boolean }; } export const GET_ADMINISTRATOR_DETAIL = gql` query GetAdministratorDetail($id: ID!) { administrator(id: $id) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; @Component({ selector: 'vdr-admin-detail', templateUrl: './admin-detail.component.html', styleUrls: ['./admin-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AdminDetailComponent extends TypedBaseDetailComponent<typeof GetAdministratorDetailDocument, 'administrator'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Administrator'); detailForm = this.formBuilder.group({ emailAddress: ['', Validators.required], firstName: ['', Validators.required], lastName: ['', Validators.required], password: [''], roles: [ [] as NonNullable< ResultOf<typeof GetAdministratorDetailDocument>['administrator'] >['user']['roles'], ], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); permissionDefinitions: PermissionDefinition[]; allRoles$: Observable<RoleFragment[]>; selectedRoles: RoleFragment[] = []; selectedRolePermissions: { [channelId: string]: PermissionsByChannel } = {} as any; selectedChannelId: string | null = null; getAvailableChannels(): PermissionsByChannel[] { return Object.values(this.selectedRolePermissions); } constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); this.allRoles$ = this.dataService.administrator .getRoles(999) .mapStream(item => item.roles.items.filter(i => i.code !== CUSTOMER_ROLE_CODE)); this.dataService.client.userStatus().single$.subscribe(({ userStatus }) => { if ( !userStatus.permissions.includes(Permission.CreateAdministrator) && !userStatus.permissions.includes(Permission.UpdateAdministrator) ) { const rolesSelect = this.detailForm.get('roles'); if (rolesSelect) { rolesSelect.disable(); } } }); this.permissionDefinitions = this.serverConfigService.getPermissionDefinitions(); } ngOnDestroy(): void { this.destroy(); } rolesChanged(roles: RoleFragment[]) { this.buildPermissionsMap(); } getPermissionsForSelectedChannel(): string[] { function getActivePermissions(input: PermissionsByChannel['permissions']): string[] { return Object.entries(input) .filter(([permission, active]) => active) .map(([permission, active]) => permission); } if (this.selectedChannelId) { const selectedChannel = this.selectedRolePermissions[this.selectedChannelId]; if (selectedChannel) { const permissionMap = this.selectedRolePermissions[this.selectedChannelId].permissions; return getActivePermissions(permissionMap); } } const channels = Object.values(this.selectedRolePermissions); if (0 < channels.length) { this.selectedChannelId = channels[0].channelId; return getActivePermissions(channels[0].permissions); } return []; } create() { const { emailAddress, firstName, lastName, password, customFields, roles } = this.detailForm.value; if (!emailAddress || !firstName || !lastName || !password) { return; } const administrator: CreateAdministratorInput = { emailAddress, firstName, lastName, password, customFields, roleIds: roles?.map(role => role.id).filter(notNullOrUndefined) ?? [], }; this.dataService.administrator.createAdministrator(administrator).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'Administrator', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createAdministrator.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'Administrator', }); }, ); } save() { this.entity$ .pipe( take(1), mergeMap(({ id }) => { const formValue = this.detailForm.value; const administrator: UpdateAdministratorInput = { id, emailAddress: formValue.emailAddress, firstName: formValue.firstName, lastName: formValue.lastName, password: formValue.password, customFields: formValue.customFields, roleIds: formValue.roles?.map(role => role.id), }; return this.dataService.administrator.updateAdministrator(administrator); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Administrator', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Administrator', }); }, ); } protected setFormValues( entity: NonNullable<ResultOf<typeof GetAdministratorDetailDocument>['administrator']>, languageCode: LanguageCode, ) { this.detailForm.patchValue({ emailAddress: entity.emailAddress, firstName: entity.firstName, lastName: entity.lastName, roles: entity.user.roles, }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get(['customFields']), entity); } const passwordControl = this.detailForm.get('password'); if (passwordControl) { if (!entity.id) { passwordControl.setValidators([Validators.required]); } else { passwordControl.setValidators([]); } } this.buildPermissionsMap(); } private buildPermissionsMap() { const permissionsControl = this.detailForm.get('roles'); if (permissionsControl) { const roles = permissionsControl.value; const channelIdPermissionsMap = new Map<string, Set<Permission>>(); const channelIdCodeMap = new Map<string, string>(); for (const role of roles ?? []) { for (const channel of role.channels) { const channelPermissions = channelIdPermissionsMap.get(channel.id); const permissionSet = channelPermissions || new Set<Permission>(); role.permissions.forEach(p => permissionSet.add(p)); channelIdPermissionsMap.set(channel.id, permissionSet); channelIdCodeMap.set(channel.id, channel.code); } } this.selectedRolePermissions = {} as any; for (const channelId of Array.from(channelIdPermissionsMap.keys())) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const permissionSet = channelIdPermissionsMap.get(channelId)!; const permissionsHash: { [K in Permission]: boolean } = {} as any; for (const def of this.serverConfigService.getPermissionDefinitions()) { permissionsHash[def.name] = permissionSet.has(def.name as Permission); } this.selectedRolePermissions[channelId] = { /* eslint-disable @typescript-eslint/no-non-null-assertion */ channelId, channelCode: channelIdCodeMap.get(channelId)!, permissions: permissionsHash, /* eslint-enable @typescript-eslint/no-non-null-assertion */ }; } } } }
import { createBulkDeleteAction, GetAdministratorListQuery, ItemOf, Permission, } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteAdministratorsBulkAction = createBulkDeleteAction< ItemOf<GetAdministratorListQuery, 'administrators'> >({ location: 'administrator-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteAdministrator), getItemName: item => item.firstName + ' ' + item.lastName, bulkDelete: (dataService, ids) => dataService.administrator.deleteAdministrators(ids).pipe(map(res => res.deleteAdministrators)), });
import { Component } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { ADMINISTRATOR_FRAGMENT, GetAdministratorListDocument, LogicalOperator, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_ADMINISTRATOR_LIST = gql` query GetAdministratorList($options: AdministratorListOptions) { administrators(options: $options) { items { ...AdministratorListItem } totalItems } } fragment AdministratorListItem on Administrator { id createdAt updatedAt firstName lastName emailAddress user { id identifier lastLogin roles { id createdAt updatedAt code description } } } `; @Component({ selector: 'vdr-administrator-list', templateUrl: './administrator-list.component.html', styleUrls: ['./administrator-list.component.scss'], }) export class AdministratorListComponent extends TypedBaseListComponent< typeof GetAdministratorListDocument, 'administrators' > { readonly customFields = this.getCustomFieldConfig('Administrator'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'firstName', type: { kind: 'text' }, label: _('settings.first-name'), filterField: 'firstName', }) .addFilter({ name: 'lastName', type: { kind: 'text' }, label: _('settings.last-name'), filterField: 'lastName', }) .addFilter({ name: 'emailAddress', type: { kind: 'text' }, label: _('settings.email-address'), filterField: 'emailAddress', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'lastName' }) .addSort({ name: 'emailAddress' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetAdministratorListDocument, getItems: data => data.administrators, setVariables: (skip, take) => this.createSearchQuery(skip, take, this.searchTermControl.value), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } createSearchQuery(skip: number, take: number, searchTerm: string | null) { let _filter = {}; let filterOperator: LogicalOperator = LogicalOperator.AND; if (searchTerm) { _filter = { emailAddress: { contains: searchTerm, }, firstName: { contains: searchTerm, }, lastName: { contains: searchTerm, }, }; filterOperator = LogicalOperator.OR; } return { options: { skip, take, filter: { ...(_filter ?? {}), ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), filterOperator, }, }; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CHANNEL_FRAGMENT, ChannelFragment, CreateChannelInput, CurrencyCode, DataService, GetChannelDetailDocument, getCustomFieldsDefaults, GetSellersQuery, LanguageCode, NotificationService, Permission, ServerConfigService, TypedBaseDetailComponent, UpdateChannelInput, } from '@vendure/admin-ui/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; import { map, mergeMap, take } from 'rxjs/operators'; export const GET_CHANNEL_DETAIL = gql` query GetChannelDetail($id: ID!) { channel(id: $id) { ...Channel } } ${CHANNEL_FRAGMENT} `; @Component({ selector: 'vdr-channel-detail', templateUrl: './channel-detail.component.html', styleUrls: ['./channel-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChannelDetailComponent extends TypedBaseDetailComponent<typeof GetChannelDetailDocument, 'channel'> implements OnInit, OnDestroy { DEFAULT_CHANNEL_CODE = DEFAULT_CHANNEL_CODE; customFields = this.getCustomFieldConfig('Channel'); // zones$: Observable<Array<ItemOf<GetZoneListQuery, 'zones'>>>; sellers$: Observable<GetSellersQuery['sellers']['items']>; detailForm = this.formBuilder.group({ code: ['', Validators.required], token: ['', Validators.required], pricesIncludeTax: [false], availableLanguageCodes: [[] as string[]], availableCurrencyCodes: [[] as string[]], defaultCurrencyCode: ['' as CurrencyCode, Validators.required], defaultShippingZoneId: ['', Validators.required], defaultLanguageCode: [undefined as LanguageCode | undefined, Validators.required], defaultTaxZoneId: ['', Validators.required], sellerId: ['', Validators.required], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); availableLanguageCodes$: Observable<LanguageCode[]>; readonly updatePermission = [Permission.SuperAdmin, Permission.UpdateChannel, Permission.CreateChannel]; constructor( protected serverConfigService: ServerConfigService, private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); // this.zones$ = this.dataService.settings.getZones({ take: 100 }).mapSingle(data => data.zones.items); // TODO: make this lazy-loaded autocomplete this.sellers$ = this.dataService.settings.getSellerList().mapSingle(data => data.sellers.items); this.availableLanguageCodes$ = this.serverConfigService.getAvailableLanguages(); } ngOnDestroy() { this.destroy(); } saveButtonEnabled(): boolean { return this.detailForm.dirty && this.detailForm.valid; } create() { if (!this.detailForm.dirty) { return; } const { code, token, defaultLanguageCode, pricesIncludeTax, defaultCurrencyCode, defaultShippingZoneId, defaultTaxZoneId, customFields, sellerId, } = this.detailForm.value; if ( !code || !token || !defaultLanguageCode || !defaultCurrencyCode || !defaultShippingZoneId || !defaultTaxZoneId ) { return; } const input: CreateChannelInput = { code, token, defaultLanguageCode, pricesIncludeTax: !!pricesIncludeTax, defaultCurrencyCode, defaultShippingZoneId, defaultTaxZoneId, customFields, sellerId, }; this.dataService.settings .createChannel(input) .pipe( mergeMap(({ createChannel }) => this.dataService.auth.currentUser().single$.pipe( map(({ me }) => ({ me, createChannel, })), ), ), mergeMap(({ me, createChannel }) => // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.dataService.client.updateUserChannels(me!.channels).pipe(map(() => createChannel)), ), ) .subscribe(data => { switch (data.__typename) { case 'Channel': this.notificationService.success(_('common.notify-create-success'), { entity: 'Channel', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.id], { relativeTo: this.route }); break; case 'LanguageNotAvailableError': this.notificationService.error(data.message); break; } }); } save() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; this.entity$ .pipe( take(1), mergeMap(channel => { const input = { id: channel.id, code: formValue.code, token: formValue.token, pricesIncludeTax: formValue.pricesIncludeTax, availableLanguageCodes: formValue.availableLanguageCodes, availableCurrencyCodes: formValue.availableCurrencyCodes, defaultCurrencyCode: formValue.defaultCurrencyCode, defaultShippingZoneId: formValue.defaultShippingZoneId, defaultLanguageCode: formValue.defaultLanguageCode, defaultTaxZoneId: formValue.defaultTaxZoneId, customFields: formValue.customFields, sellerId: formValue.sellerId, } as UpdateChannelInput; return this.dataService.settings.updateChannel(input); }), ) .subscribe(({ updateChannel }) => { switch (updateChannel.__typename) { case 'Channel': this.notificationService.success(_('common.notify-update-success'), { entity: 'Channel', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); break; case 'LanguageNotAvailableError': this.notificationService.error(updateChannel.message); } }); } /** * Update the form values when the entity changes. */ protected setFormValues(entity: ChannelFragment, languageCode: LanguageCode): void { this.detailForm.patchValue({ code: entity.code, token: entity.token || this.generateToken(), pricesIncludeTax: entity.pricesIncludeTax, availableLanguageCodes: entity.availableLanguageCodes, availableCurrencyCodes: entity.availableCurrencyCodes, defaultCurrencyCode: entity.defaultCurrencyCode, defaultShippingZoneId: entity.defaultShippingZone?.id ?? '', defaultLanguageCode: entity.defaultLanguageCode, defaultTaxZoneId: entity.defaultTaxZone?.id ?? '', sellerId: entity.seller?.id ?? '', }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get(['customFields']), entity); } if (entity.code === DEFAULT_CHANNEL_CODE) { const codeControl = this.detailForm.get('code'); if (codeControl) { codeControl.disable(); } } } private generateToken(): string { return Array.from(crypto.getRandomValues(new Uint8Array(10))) .map(b => b.toString(16).padStart(2, '0')) .join(''); } }
import { createBulkDeleteAction, GetChannelsQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map, mergeMap } from 'rxjs/operators'; export const deleteChannelsBulkAction = createBulkDeleteAction<ItemOf<GetChannelsQuery, 'channels'>>({ location: 'channel-list', requiresPermission: userPermissions => userPermissions.includes(Permission.SuperAdmin) || userPermissions.includes(Permission.DeleteChannel), getItemName: item => item.code, bulkDelete: (dataService, ids) => { return dataService.settings.deleteChannels(ids).pipe( mergeMap(({ deleteChannels }) => dataService.auth.currentUser().single$.pipe( map(({ me }) => ({ me, deleteChannels, })), ), ), mergeMap(({ me, deleteChannels }) => // eslint-disable-next-line @typescript-eslint/no-non-null-assertion dataService.client.updateUserChannels(me!.channels).pipe(map(() => deleteChannels)), ), ); }, });
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CHANNEL_FRAGMENT, GetChannelListDocument, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { gql } from 'apollo-angular'; export const GET_CHANNEL_LIST = gql` query GetChannelList($options: ChannelListOptions) { channels(options: $options) { items { ...Channel } totalItems } } ${CHANNEL_FRAGMENT} `; @Component({ selector: 'vdr-channel-list', templateUrl: './channel-list.component.html', styleUrls: ['./channel-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChannelListComponent extends TypedBaseListComponent<typeof GetChannelListDocument, 'channels'> implements OnInit { readonly customFields = this.getCustomFieldConfig('Channel'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'code', type: { kind: 'text' }, label: _('common.code'), filterField: 'code', }) .addFilter({ name: 'token', type: { kind: 'text' }, label: _('settings.channel-token'), filterField: 'token', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'code' }) .addSort({ name: 'token' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetChannelListDocument, getItems: data => data.channels, setVariables: (skip, take) => ({ options: { skip, take, filter: { code: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } isDefaultChannel(channelCode: string): boolean { return channelCode === DEFAULT_CHANNEL_CODE; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { COUNTRY_FRAGMENT, CountryFragment, createUpdatedTranslatable, DataService, findTranslation, GetCountryDetailDocument, getCustomFieldsDefaults, LanguageCode, NotificationService, Permission, TypedBaseDetailComponent, UpdateCountryInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { combineLatest } from 'rxjs'; import { mergeMap, take } from 'rxjs/operators'; export const GET_COUNTRY_DETAIL = gql` query GetCountryDetail($id: ID!) { country(id: $id) { ...Country } } ${COUNTRY_FRAGMENT} `; @Component({ selector: 'vdr-country-detail', templateUrl: './country-detail.component.html', styleUrls: ['./country-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CountryDetailComponent extends TypedBaseDetailComponent<typeof GetCountryDetailDocument, 'country'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Region'); detailForm = this.formBuilder.group({ code: ['', Validators.required], name: ['', Validators.required], enabled: [true], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); readonly updatePermission = [Permission.UpdateSettings, Permission.UpdateCountry]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy(): void { this.destroy(); } create() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; const input = createUpdatedTranslatable({ translatable: { id: '', createdAt: '', updatedAt: '', code: '', name: '', enabled: false, translations: [], } as CountryFragment, updatedFields: formValue, languageCode: this.languageCode, customFieldConfig: this.customFields, defaultTranslation: { name: formValue.name ?? '', languageCode: this.languageCode, }, }); this.dataService.settings.createCountry(input).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'Country', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createCountry.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'Country', }); }, ); } save() { combineLatest(this.entity$, this.languageCode$) .pipe( take(1), mergeMap(([country, languageCode]) => { const formValue = this.detailForm.value; const input: UpdateCountryInput = createUpdatedTranslatable({ translatable: country, updatedFields: formValue, customFieldConfig: this.customFields, languageCode, defaultTranslation: { name: formValue.name ?? '', languageCode, }, }); return this.dataService.settings.updateCountry(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Country', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Country', }); }, ); } protected setFormValues(country: CountryFragment, languageCode: LanguageCode): void { const currentTranslation = findTranslation(country, languageCode); this.detailForm.patchValue({ code: country.code, name: currentTranslation ? currentTranslation.name : '', enabled: country.enabled, }); if (this.customFields.length) { this.setCustomFieldFormValues( this.customFields, this.detailForm.get(['customFields']), country, currentTranslation, ); } } }
import { createBulkDeleteAction, GetCountryListQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteCountriesBulkAction = createBulkDeleteAction<ItemOf<GetCountryListQuery, 'countries'>>({ location: 'country-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteSettings) || userPermissions.includes(Permission.DeleteCountry), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.settings.deleteCountries(ids).pipe(map(res => res.deleteCountries)), });
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetCountryListDocument, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_COUNTRY_LIST = gql` query GetCountryList($options: CountryListOptions) { countries(options: $options) { items { ...CountryListItem } totalItems } } fragment CountryListItem on Country { id createdAt updatedAt code name type enabled } `; @Component({ selector: 'vdr-country-list', templateUrl: './country-list.component.html', styleUrls: ['./country-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CountryListComponent extends TypedBaseListComponent<typeof GetCountryListDocument, 'countries'> { readonly customFields = this.getCustomFieldConfig('Region'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addFilter({ name: 'code', type: { kind: 'text' }, label: _('common.code'), filterField: 'code', }) .addFilter({ name: 'enabled', type: { kind: 'boolean' }, label: _('common.enabled'), filterField: 'enabled', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('name', 'ASC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addSort({ name: 'code' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetCountryListDocument, getItems: data => data.countries, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DataService, getCustomFieldsDefaults, GetGlobalSettingsDetailDocument, GlobalSettings, LanguageCode, NotificationService, Permission, TypedBaseDetailComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { switchMap, tap, withLatestFrom } from 'rxjs/operators'; export const GET_GLOBAL_SETTINGS_DETAIL = gql` query GetGlobalSettingsDetail { globalSettings { ...GlobalSettingsDetail } } fragment GlobalSettingsDetail on GlobalSettings { id createdAt updatedAt availableLanguages trackInventory outOfStockThreshold } `; @Component({ selector: 'vdr-global-settings', templateUrl: './global-settings.component.html', styleUrls: ['./global-settings.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class GlobalSettingsComponent extends TypedBaseDetailComponent<typeof GetGlobalSettingsDetailDocument, 'globalSettings'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('GlobalSettings'); detailForm = this.formBuilder.group({ availableLanguages: [[] as LanguageCode[]], trackInventory: false, outOfStockThreshold: [0, Validators.required], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); languageCodes = Object.values(LanguageCode); readonly updatePermission = [Permission.UpdateSettings, Permission.UpdateGlobalSettings]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit(): void { this.init(); this.dataService.client.userStatus().single$.subscribe(({ userStatus }) => { if (!userStatus.permissions.includes(Permission.UpdateSettings)) { const languagesSelect = this.detailForm.get('availableLanguages'); if (languagesSelect) { languagesSelect.disable(); } } }); } ngOnDestroy() { this.destroy(); } save() { if (!this.detailForm.dirty) { return; } this.dataService.settings .updateGlobalSettings(this.detailForm.value) .pipe( tap(({ updateGlobalSettings }) => { switch (updateGlobalSettings.__typename) { case 'GlobalSettings': this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.notificationService.success(_('common.notify-update-success'), { entity: 'Settings', }); break; case 'ChannelDefaultLanguageError': this.notificationService.error(updateGlobalSettings.message); } }), switchMap(() => this.serverConfigService.refreshGlobalSettings()), withLatestFrom(this.dataService.client.uiState().single$), ) .subscribe(([{ globalSettings }, { uiState }]) => { const availableLangs = globalSettings.availableLanguages; if (availableLangs.length && !availableLangs.includes(uiState.contentLanguage)) { this.dataService.client.setContentLanguage(availableLangs[0]).subscribe(); } }); } protected setFormValues(entity: GlobalSettings, languageCode: LanguageCode): void { this.detailForm.patchValue({ availableLanguages: entity.availableLanguages, trackInventory: entity.trackInventory, outOfStockThreshold: entity.outOfStockThreshold, }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity); } } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { configurableDefinitionToInstance, ConfigurableOperation, ConfigurableOperationDefinition, CreatePaymentMethodInput, createUpdatedTranslatable, DataService, findTranslation, getConfigArgValue, getCustomFieldsDefaults, GetPaymentMethodDetailDocument, GetPaymentMethodDetailQuery, LanguageCode, NotificationService, PAYMENT_METHOD_FRAGMENT, PaymentMethodFragment, Permission, toConfigurableOperationInput, TypedBaseDetailComponent, UpdatePaymentMethodInput, } from '@vendure/admin-ui/core'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { gql } from 'apollo-angular'; import { combineLatest } from 'rxjs'; import { mergeMap, take } from 'rxjs/operators'; export const GET_PAYMENT_METHOD_DETAIL = gql` query GetPaymentMethodDetail($id: ID!) { paymentMethod(id: $id) { ...PaymentMethod } } ${PAYMENT_METHOD_FRAGMENT} `; @Component({ selector: 'vdr-payment-method-detail', templateUrl: './payment-method-detail.component.html', styleUrls: ['./payment-method-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PaymentMethodDetailComponent extends TypedBaseDetailComponent<typeof GetPaymentMethodDetailDocument, 'paymentMethod'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('PaymentMethod'); detailForm = this.formBuilder.group({ code: ['', Validators.required], name: ['', Validators.required], description: '', enabled: [true, Validators.required], checker: {} as NonNullable<GetPaymentMethodDetailQuery['paymentMethod']>['checker'], handler: {} as NonNullable<GetPaymentMethodDetailQuery['paymentMethod']>['handler'], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); checkers: ConfigurableOperationDefinition[] = []; handlers: ConfigurableOperationDefinition[] = []; selectedChecker?: ConfigurableOperation | null; selectedCheckerDefinition?: ConfigurableOperationDefinition; selectedHandler?: ConfigurableOperation | null; selectedHandlerDefinition?: ConfigurableOperationDefinition; readonly updatePermission = [Permission.UpdateSettings, Permission.UpdatePaymentMethod]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); this.dataService.settings.getPaymentMethodOperations().single$.subscribe(data => { this.checkers = data.paymentMethodEligibilityCheckers; this.handlers = data.paymentMethodHandlers; this.changeDetector.markForCheck(); this.selectedCheckerDefinition = data.paymentMethodEligibilityCheckers.find( c => c.code === this.entity?.checker?.code, ); this.selectedHandlerDefinition = data.paymentMethodHandlers.find( c => c.code === this.entity?.handler?.code, ); }); } ngOnDestroy(): void { this.destroy(); } updateCode(currentCode: string | undefined, nameValue: string) { if (!currentCode) { const codeControl = this.detailForm.get('code'); if (codeControl && codeControl.pristine) { codeControl.setValue(normalizeString(nameValue, '-')); } } } selectChecker(checker: ConfigurableOperationDefinition) { this.selectedCheckerDefinition = checker; this.selectedChecker = configurableDefinitionToInstance(checker); const formControl = this.detailForm.get('checker'); if (formControl) { formControl.clearValidators(); formControl.updateValueAndValidity({ onlySelf: true }); formControl.patchValue(this.selectedChecker); } this.detailForm.markAsDirty(); } selectHandler(handler: ConfigurableOperationDefinition) { this.selectedHandlerDefinition = handler; this.selectedHandler = configurableDefinitionToInstance(handler); const formControl = this.detailForm.get('handler'); if (formControl) { formControl.clearValidators(); formControl.updateValueAndValidity({ onlySelf: true }); formControl.patchValue(this.selectedHandler); } this.detailForm.markAsDirty(); } removeChecker() { this.selectedChecker = null; this.detailForm.markAsDirty(); } removeHandler() { this.selectedHandler = null; this.detailForm.markAsDirty(); } create() { const selectedChecker = this.selectedChecker; const selectedHandler = this.selectedHandler; if (!selectedHandler) { return; } const input = this.getUpdatedPaymentMethod( { id: '', createdAt: '', updatedAt: '', name: '', code: '', description: '', enabled: true, checker: undefined as any, handler: undefined as any, translations: [], }, this.detailForm, this.languageCode, selectedHandler, selectedChecker, ) as CreatePaymentMethodInput; this.dataService.settings.createPaymentMethod(input).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'PaymentMethod', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createPaymentMethod.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'PaymentMethod', }); }, ); } save() { const selectedChecker = this.selectedChecker; const selectedHandler = this.selectedHandler; if (!selectedHandler) { return; } combineLatest(this.entity$, this.languageCode$) .pipe( take(1), mergeMap(([paymentMethod, languageCode]) => { const input = this.getUpdatedPaymentMethod( paymentMethod, this.detailForm, languageCode, selectedHandler, selectedChecker, ) as UpdatePaymentMethodInput; return this.dataService.settings.updatePaymentMethod(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'PaymentMethod', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'PaymentMethod', }); }, ); } /** * Given a PaymentMethod and the value of the detailForm, this method creates an updated copy of it which * can then be persisted to the API. */ private getUpdatedPaymentMethod( paymentMethod: PaymentMethodFragment, formGroup: UntypedFormGroup, languageCode: LanguageCode, selectedHandler: ConfigurableOperation, selectedChecker?: ConfigurableOperation | null, ): UpdatePaymentMethodInput | CreatePaymentMethodInput { const input = createUpdatedTranslatable({ translatable: paymentMethod, updatedFields: formGroup.value, customFieldConfig: this.customFields, languageCode, defaultTranslation: { languageCode, name: paymentMethod.name || '', description: paymentMethod.description || '', }, }); return { ...input, checker: selectedChecker ? toConfigurableOperationInput(selectedChecker, formGroup.value.checker) : null, handler: toConfigurableOperationInput(selectedHandler, formGroup.value.handler), }; } protected setFormValues( paymentMethod: NonNullable<GetPaymentMethodDetailQuery['paymentMethod']>, languageCode: LanguageCode, ): void { const currentTranslation = findTranslation(paymentMethod, languageCode); this.detailForm.patchValue({ name: currentTranslation?.name, code: paymentMethod.code, description: currentTranslation?.description, enabled: paymentMethod.enabled, checker: paymentMethod.checker || ({} as any), handler: paymentMethod.handler || ({} as any), }); if (!this.selectedChecker) { this.selectedChecker = paymentMethod.checker && { code: paymentMethod.checker.code, args: paymentMethod.checker.args.map(a => ({ ...a, value: getConfigArgValue(a.value) })), }; } if (!this.selectedHandler) { this.selectedHandler = paymentMethod.handler && { code: paymentMethod.handler.code, args: paymentMethod.handler.args.map(a => ({ ...a, value: getConfigArgValue(a.value) })), }; } if (this.customFields.length) { this.setCustomFieldFormValues( this.customFields, this.detailForm.get('customFields'), paymentMethod, currentTranslation, ); } } }
import { createBulkAssignToChannelAction, AssignPaymentMethodsToChannelDocument, RemovePaymentMethodsFromChannelDocument, createBulkDeleteAction, createBulkRemoveFromChannelAction, GetPaymentMethodListQuery, ItemOf, Permission, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { map } from 'rxjs/operators'; export const deletePaymentMethodsBulkAction = createBulkDeleteAction< ItemOf<GetPaymentMethodListQuery, 'paymentMethods'> >({ location: 'payment-method-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeletePaymentMethod) || userPermissions.includes(Permission.DeleteSettings), getItemName: item => item.name, shouldRetryItem: (response, item) => !!response.message, bulkDelete: (dataService, ids, retrying) => dataService.settings.deletePaymentMethods(ids, retrying).pipe(map(res => res.deletePaymentMethods)), }); const ASSIGN_PAYMENT_METHODS_TO_CHANNEL = gql` mutation AssignPaymentMethodsToChannel($input: AssignPaymentMethodsToChannelInput!) { assignPaymentMethodsToChannel(input: $input) { id name } } `; const REMOVE_PAYMENT_METHODS_FROM_CHANNEL = gql` mutation RemovePaymentMethodsFromChannel($input: RemovePaymentMethodsFromChannelInput!) { removePaymentMethodsFromChannel(input: $input) { id name } } `; export const assignPaymentMethodsToChannelBulkAction = createBulkAssignToChannelAction< ItemOf<GetPaymentMethodListQuery, 'paymentMethods'> >({ location: 'payment-method-list', requiresPermission: userPermissions => userPermissions.includes(Permission.UpdatePaymentMethod) || userPermissions.includes(Permission.UpdateSettings), getItemName: item => item.name, bulkAssignToChannel: (dataService, paymentMethodIds, channelIds) => channelIds.map(channelId => dataService .mutate(AssignPaymentMethodsToChannelDocument, { input: { channelId, paymentMethodIds, }, }) .pipe(map(res => res.assignPaymentMethodsToChannel)), ), }); export const removePaymentMethodsFromChannelBulkAction = createBulkRemoveFromChannelAction< ItemOf<GetPaymentMethodListQuery, 'paymentMethods'> >({ location: 'payment-method-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeletePaymentMethod) || userPermissions.includes(Permission.DeleteSettings), getItemName: item => item.name, bulkRemoveFromChannel: (dataService, paymentMethodIds, channelId) => dataService .mutate(RemovePaymentMethodsFromChannelDocument, { input: { channelId, paymentMethodIds, }, }) .pipe(map(res => res.removePaymentMethodsFromChannel)), });
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetPaymentMethodListDocument, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_PAYMENT_METHOD_LIST = gql` query GetPaymentMethodList($options: PaymentMethodListOptions!) { paymentMethods(options: $options) { items { ...PaymentMethodListItem } totalItems } } fragment PaymentMethodListItem on PaymentMethod { id createdAt updatedAt name description code enabled } `; @Component({ selector: 'vdr-payment-method-list', templateUrl: './payment-method-list.component.html', styleUrls: ['./payment-method-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PaymentMethodListComponent extends TypedBaseListComponent< typeof GetPaymentMethodListDocument, 'paymentMethods' > { readonly customFields = this.getCustomFieldConfig('PaymentMethod'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addFilter({ name: 'code', type: { kind: 'text' }, label: _('common.code'), filterField: 'code', }) .addFilter({ name: 'enabled', type: { kind: 'boolean' }, label: _('common.enabled'), filterField: 'enabled', }) .addFilter({ name: 'description', type: { kind: 'text' }, label: _('common.description'), filterField: 'description', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'id' }) .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addSort({ name: 'code' }) .addSort({ name: 'description' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetPaymentMethodListDocument, getItems: data => data.paymentMethods, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { PermissionDefinition } from '@vendure/admin-ui/core'; export interface PermissionGridRow { label: string; description: string; permissions: PermissionDefinition[]; } /** * A table showing and allowing the setting of all possible CRUD permissions. */ @Component({ selector: 'vdr-permission-grid', templateUrl: './permission-grid.component.html', styleUrls: ['./permission-grid.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PermissionGridComponent implements OnInit { @Input() permissionDefinitions: PermissionDefinition[]; @Input() activePermissions: string[]; @Input() readonly = false; @Output() permissionChange = new EventEmitter<{ permission: string; value: boolean }>(); gridData: PermissionGridRow[]; ngOnInit() { this.buildGrid(); } setPermission(permission: string, value: boolean) { if (!this.readonly) { this.permissionChange.emit({ permission, value }); } } toggleAll(defs: PermissionDefinition[]) { const value = defs.some(d => !this.activePermissions.includes(d.name)); for (const def of defs) { this.permissionChange.emit({ permission: def.name, value }); } } private buildGrid() { const crudGroups = new Map<string, PermissionDefinition[]>(); const nonCrud: PermissionDefinition[] = []; const crudRe = /^(Create|Read|Update|Delete)([a-zA-Z]+)$/; for (const def of this.permissionDefinitions) { const isCrud = crudRe.test(def.name); if (isCrud) { const groupName = def.name.match(crudRe)?.[2]; if (groupName) { const existing = crudGroups.get(groupName); if (existing) { existing.push(def); } else { crudGroups.set(groupName, [def]); } } } else if (def.assignable) { nonCrud.push(def); } } this.gridData = [ ...nonCrud.map(d => ({ label: d.name, description: d.description, permissions: [d], })), ...Array.from(crudGroups.entries()).map(([label, defs]) => ({ label, description: this.extractCrudDescription(defs[0]), permissions: defs, })), ]; } private extractCrudDescription(def: PermissionDefinition): string { return def.description.replace(/Grants permission to [\w]+/, 'Grants permissions on'); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { Administrator, DataService, getCustomFieldsDefaults, GetProfileDetailDocument, LanguageCode, NotificationService, TypedBaseDetailComponent, UpdateActiveAdministratorInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { mergeMap, take } from 'rxjs/operators'; export const GET_PROFILE_DETAIL = gql` query GetProfileDetail { activeAdministrator { ...ProfileDetail } } fragment ProfileDetail on Administrator { id createdAt updatedAt firstName lastName emailAddress user { id lastLogin verified } } `; @Component({ selector: 'vdr-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProfileComponent extends TypedBaseDetailComponent<typeof GetProfileDetailDocument, 'activeAdministrator'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Administrator'); detailForm = this.formBuilder.group({ emailAddress: ['', Validators.required], firstName: ['', Validators.required], lastName: ['', Validators.required], password: [''], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy(): void { this.destroy(); } save() { this.entity$ .pipe( take(1), mergeMap(({ id }) => { const formValue = this.detailForm.value; const administrator: UpdateActiveAdministratorInput = { emailAddress: formValue.emailAddress, firstName: formValue.firstName, lastName: formValue.lastName, password: formValue.password, customFields: formValue.customFields, }; return this.dataService.administrator.updateActiveAdministrator(administrator); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Administrator', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Administrator', }); }, ); } protected setFormValues(administrator: Administrator, languageCode: LanguageCode): void { this.detailForm.patchValue({ emailAddress: administrator.emailAddress, firstName: administrator.firstName, lastName: administrator.lastName, }); if (this.customFields.length) { this.setCustomFieldFormValues( this.customFields, this.detailForm.get('customFields'), administrator, ); } } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateRoleInput, DataService, GetRoleDetailDocument, LanguageCode, NotificationService, Permission, Role, ROLE_FRAGMENT, TypedBaseDetailComponent, UpdateRoleInput, } from '@vendure/admin-ui/core'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { unique } from '@vendure/common/lib/unique'; import { gql } from 'apollo-angular'; import { mergeMap, take } from 'rxjs/operators'; export const GET_ROLE_DETAIL = gql` query GetRoleDetail($id: ID!) { role(id: $id) { ...Role } } ${ROLE_FRAGMENT} `; @Component({ selector: 'vdr-role-detail', templateUrl: './role-detail.component.html', styleUrls: ['./role-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RoleDetailComponent extends TypedBaseDetailComponent<typeof GetRoleDetailDocument, 'role'> implements OnInit, OnDestroy { detailForm = this.formBuilder.group({ code: ['', Validators.required], description: ['', Validators.required], channelIds: [[] as string[]], permissions: [[] as Permission[]], }); permissionDefinitions = this.serverConfigService.getPermissionDefinitions(); constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy(): void { this.destroy(); } updateCode(nameValue: string) { const codeControl = this.detailForm.get(['code']); if (codeControl && codeControl.pristine) { codeControl.setValue(normalizeString(nameValue, '-')); } } setPermission(change: { permission: string; value: boolean }) { const permissionsControl = this.detailForm.get('permissions'); if (permissionsControl) { const currentPermissions = permissionsControl.value as string[]; const newValue = ( change.value === true ? unique([...currentPermissions, change.permission]) : currentPermissions.filter(p => p !== change.permission) ) as Permission[]; permissionsControl.setValue(newValue); permissionsControl.markAsDirty(); } } create() { const { code, description, permissions, channelIds } = this.detailForm.value; if (!code || !description) { return; } const role: CreateRoleInput = { code, description, permissions: permissions ?? [], channelIds, }; this.dataService.administrator.createRole(role).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'Role' }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createRole.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'Role', }); }, ); } save() { this.entity$ .pipe( take(1), mergeMap(({ id }) => { const formValue = this.detailForm.value; const role: UpdateRoleInput = { id, ...formValue }; return this.dataService.administrator.updateRole(role); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Role' }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Role', }); }, ); } protected setFormValues(role: Role, languageCode: LanguageCode): void { this.detailForm.patchValue({ description: role.description, code: role.code, channelIds: role.channels.map(c => c.id), permissions: role.permissions, }); // This was required to get the channel selector component to // correctly display its contents. A while spent debugging the root // cause did not yield a solution, therefore this next line. this.changeDetector.detectChanges(); } }
import { createBulkDeleteAction, GetRolesQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteRolesBulkAction = createBulkDeleteAction<ItemOf<GetRolesQuery, 'roles'>>({ location: 'role-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteAdministrator), getItemName: item => item.description, bulkDelete: (dataService, ids) => dataService.administrator.deleteRoles(ids).pipe(map(res => res.deleteRoles)), });
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetRoleListDocument, GetRolesQuery, ItemOf, Role, ROLE_FRAGMENT, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { CUSTOMER_ROLE_CODE, SUPER_ADMIN_ROLE_CODE } from '@vendure/common/lib/shared-constants'; import { gql } from 'apollo-angular'; export const GET_ROLE_LIST = gql` query GetRoleList($options: RoleListOptions) { roles(options: $options) { items { ...Role } totalItems } } ${ROLE_FRAGMENT} `; @Component({ selector: 'vdr-role-list', templateUrl: './role-list.component.html', styleUrls: ['./role-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RoleListComponent extends TypedBaseListComponent<typeof GetRoleListDocument, 'roles'> implements OnInit { readonly initialLimit = 3; displayLimit: { [id: string]: number } = {}; readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'code', type: { kind: 'text' }, label: _('common.code'), filterField: 'code', }) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'code' }) .addSort({ name: 'description' }) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetRoleListDocument, getItems: data => data.roles, setVariables: (skip, take) => ({ options: { skip, take, filter: { code: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } toggleDisplayLimit(role: ItemOf<GetRolesQuery, 'roles'>) { if (this.displayLimit[role.id] === role.permissions.length) { this.displayLimit[role.id] = this.initialLimit; } else { this.displayLimit[role.id] = role.permissions.length; } } isDefaultRole(role: Role): boolean { return role.code === SUPER_ADMIN_ROLE_CODE || role.code === CUSTOMER_ROLE_CODE; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateSellerInput, DataService, getCustomFieldsDefaults, GetSellerDetailDocument, LanguageCode, NotificationService, Permission, SellerFragment, TypedBaseDetailComponent, UpdateSellerInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { mergeMap, take } from 'rxjs/operators'; export const GET_SELLER_DETAIL = gql` query GetSellerDetail($id: ID!) { seller(id: $id) { ...SellerDetail } } fragment SellerDetail on Seller { id createdAt updatedAt name } `; @Component({ selector: 'vdr-seller-detail', templateUrl: './seller-detail.component.html', styleUrls: ['./seller-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SellerDetailComponent extends TypedBaseDetailComponent<typeof GetSellerDetailDocument, 'seller'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Seller'); detailForm = this.formBuilder.group({ name: ['', Validators.required], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); readonly updatePermission = [Permission.SuperAdmin, Permission.UpdateSeller, Permission.CreateSeller]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy() { this.destroy(); } saveButtonEnabled(): boolean { return this.detailForm.dirty && this.detailForm.valid; } create() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; if (!formValue.name) { return; } const input: CreateSellerInput = { name: formValue.name, customFields: formValue.customFields, }; this.dataService.settings.createSeller(input).subscribe(data => { switch (data.createSeller.__typename) { case 'Seller': this.notificationService.success(_('common.notify-create-success'), { entity: 'Seller', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createSeller.id], { relativeTo: this.route }); break; } }); } save() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; this.entity$ .pipe( take(1), mergeMap(seller => { const input = { id: seller.id, name: formValue.name, customFields: formValue.customFields, } as UpdateSellerInput; return this.dataService.settings.updateSeller(input); }), ) .subscribe(({ updateSeller }) => { switch (updateSeller.__typename) { case 'Seller': this.notificationService.success(_('common.notify-update-success'), { entity: 'Seller', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); break; // case 'LanguageNotAvailableError': // this.notificationService.error(updateSeller.message); } }); } /** * Update the form values when the entity changes. */ protected setFormValues(entity: SellerFragment, languageCode: LanguageCode): void { this.detailForm.patchValue({ name: entity.name, }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get(['customFields']), entity); } } }
import { createBulkDeleteAction, GetSellersQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteSellersBulkAction = createBulkDeleteAction<ItemOf<GetSellersQuery, 'sellers'>>({ location: 'seller-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteSeller), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.settings.deleteSellers(ids).pipe(map(res => res.deleteSellers)), });
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetSellerListDocument, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; const GET_SELLER_LIST = gql` query GetSellerList($options: SellerListOptions) { sellers(options: $options) { items { ...SellerListItem } totalItems } } fragment SellerListItem on Seller { id createdAt updatedAt name } `; @Component({ selector: 'vdr-seller-list', templateUrl: './seller-list.component.html', styleUrls: ['./seller-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SellerListComponent extends TypedBaseListComponent<typeof GetSellerListDocument, 'sellers'> implements OnInit { readonly customFields = this.getCustomFieldConfig('Seller'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetSellerListDocument, getItems: data => data.sellers, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { CurrencyCode, ShippingMethodQuote } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-shipping-eligibility-test-result', templateUrl: './shipping-eligibility-test-result.component.html', styleUrls: ['./shipping-eligibility-test-result.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ShippingEligibilityTestResultComponent { @Input() testResult: ShippingMethodQuote[]; @Input() okToRun = false; @Input() testDataUpdated = false; @Input() currencyCode: CurrencyCode; @Output() runTest = new EventEmitter<void>(); }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { configurableDefinitionToInstance, ConfigurableOperation, ConfigurableOperationDefinition, CreateShippingMethodInput, createUpdatedTranslatable, DataService, findTranslation, GetActiveChannelQuery, getConfigArgValue, getCustomFieldsDefaults, GetShippingMethodDetailDocument, GetShippingMethodDetailQuery, LanguageCode, NotificationService, Permission, SHIPPING_METHOD_FRAGMENT, ShippingMethodFragment, TestShippingMethodInput, TestShippingMethodResult, toConfigurableOperationInput, TypedBaseDetailComponent, UpdateShippingMethodInput, } from '@vendure/admin-ui/core'; import { normalizeString } from '@vendure/common/lib/normalize-string'; import { gql } from 'apollo-angular'; import { combineLatest, merge, Observable, of, Subject } from 'rxjs'; import { mergeMap, switchMap, take, takeUntil } from 'rxjs/operators'; import { TestAddress } from '../test-address-form/test-address-form.component'; import { TestOrderLine } from '../test-order-builder/test-order-builder.component'; export const GET_SHIPPING_METHOD_DETAIL = gql` query GetShippingMethodDetail($id: ID!) { shippingMethod(id: $id) { ...ShippingMethod } } ${SHIPPING_METHOD_FRAGMENT} `; @Component({ selector: 'vdr-shipping-method-detail', templateUrl: './shipping-method-detail.component.html', styleUrls: ['./shipping-method-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ShippingMethodDetailComponent extends TypedBaseDetailComponent<typeof GetShippingMethodDetailDocument, 'shippingMethod'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('ShippingMethod'); detailForm = this.formBuilder.group({ code: ['', Validators.required], name: ['', Validators.required], description: '', fulfillmentHandler: ['', Validators.required], checker: {} as NonNullable<GetShippingMethodDetailQuery['shippingMethod']>['checker'], calculator: {} as NonNullable<GetShippingMethodDetailQuery['shippingMethod']>['calculator'], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); checkers: ConfigurableOperationDefinition[] = []; calculators: ConfigurableOperationDefinition[] = []; fulfillmentHandlers: ConfigurableOperationDefinition[] = []; selectedChecker?: ConfigurableOperation | null; selectedCheckerDefinition?: ConfigurableOperationDefinition; selectedCalculator?: ConfigurableOperation | null; selectedCalculatorDefinition?: ConfigurableOperationDefinition; activeChannel$: Observable<GetActiveChannelQuery['activeChannel']>; testAddress: TestAddress; testOrderLines: TestOrderLine[]; testDataUpdated = false; testResult$: Observable<TestShippingMethodResult | undefined>; readonly updatePermission = [Permission.UpdateSettings, Permission.UpdateShippingMethod]; private fetchTestResult$ = new Subject<[TestAddress, TestOrderLine[]]>(); constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); this.dataService.shippingMethod.getShippingMethodOperations().single$.subscribe(data => { this.checkers = data.shippingEligibilityCheckers; this.calculators = data.shippingCalculators; this.fulfillmentHandlers = data.fulfillmentHandlers; this.changeDetector.markForCheck(); this.selectedCheckerDefinition = data.shippingEligibilityCheckers.find( c => c.code === this.entity?.checker?.code, ); this.selectedCalculatorDefinition = data.shippingCalculators.find( c => c.code === this.entity?.calculator?.code, ); }); this.activeChannel$ = this.dataService.settings .getActiveChannel() .mapStream(data => data.activeChannel); this.testResult$ = this.fetchTestResult$.pipe( switchMap(([address, lines]) => { const { checker, calculator } = this.detailForm.value; if (!this.selectedChecker || !this.selectedCalculator || !checker || !calculator) { return of(undefined); } const input: TestShippingMethodInput = { shippingAddress: { ...address, streetLine1: 'test' }, lines: lines.map(l => ({ productVariantId: l.id, quantity: l.quantity })), checker: toConfigurableOperationInput(this.selectedChecker, checker), calculator: toConfigurableOperationInput(this.selectedCalculator, calculator), }; return this.dataService.shippingMethod .testShippingMethod(input) .mapSingle(result => result.testShippingMethod); }), ); /* eslint-disable @typescript-eslint/no-non-null-assertion */ merge( this.detailForm.get(['checker'])!.valueChanges, this.detailForm.get(['calculator'])!.valueChanges, ) .pipe(takeUntil(this.destroy$)) .subscribe(() => (this.testDataUpdated = true)); /* eslint-enable @typescript-eslint/no-non-null-assertion */ } ngOnDestroy(): void { this.destroy(); } updateCode(currentCode: string | undefined, nameValue: string) { if (!currentCode) { const codeControl = this.detailForm.get(['code']); if (codeControl && codeControl.pristine) { codeControl.setValue(normalizeString(nameValue, '-')); } } } selectChecker(checker: ConfigurableOperationDefinition) { this.selectedCheckerDefinition = checker; this.selectedChecker = configurableDefinitionToInstance(checker); const formControl = this.detailForm.get('checker'); if (formControl) { formControl.clearValidators(); formControl.updateValueAndValidity({ onlySelf: true }); formControl.patchValue(this.selectedChecker); } this.detailForm.markAsDirty(); } selectCalculator(calculator: ConfigurableOperationDefinition) { this.selectedCalculatorDefinition = calculator; this.selectedCalculator = configurableDefinitionToInstance(calculator); const formControl = this.detailForm.get('calculator'); if (formControl) { formControl.clearValidators(); formControl.updateValueAndValidity({ onlySelf: true }); formControl.patchValue(this.selectedCalculator); } this.detailForm.markAsDirty(); } create() { const selectedChecker = this.selectedChecker; const selectedCalculator = this.selectedCalculator; const { checker, calculator } = this.detailForm.value; if (!selectedChecker || !selectedCalculator || !checker || !calculator) { return; } const formValue = this.detailForm.value; const input = { ...(this.getUpdatedShippingMethod( { createdAt: '', updatedAt: '', id: '', code: '', name: '', description: '', fulfillmentHandlerCode: '', checker: undefined as any, calculator: undefined as any, translations: [], }, this.detailForm, this.languageCode, ) as CreateShippingMethodInput), checker: toConfigurableOperationInput(selectedChecker, checker), calculator: toConfigurableOperationInput(selectedCalculator, calculator), }; this.dataService.shippingMethod.createShippingMethod(input).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'ShippingMethod', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createShippingMethod.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'ShippingMethod', }); }, ); } save() { const selectedChecker = this.selectedChecker; const selectedCalculator = this.selectedCalculator; const { checker, calculator } = this.detailForm.value; if (!selectedChecker || !selectedCalculator || !checker || !calculator) { return; } combineLatest([this.entity$, this.languageCode$]) .pipe( take(1), mergeMap(([shippingMethod, languageCode]) => { const formValue = this.detailForm.value; const input = { ...(this.getUpdatedShippingMethod( shippingMethod, this.detailForm, languageCode, ) as UpdateShippingMethodInput), checker: toConfigurableOperationInput(selectedChecker, checker), calculator: toConfigurableOperationInput(selectedCalculator, calculator), }; return this.dataService.shippingMethod.updateShippingMethod(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'ShippingMethod', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { // eslint-disable-next-line no-console console.error(err); this.notificationService.error(_('common.notify-update-error'), { entity: 'ShippingMethod', }); }, ); } setTestOrderLines(event: TestOrderLine[]) { this.testOrderLines = event; this.testDataUpdated = true; } setTestAddress(event: TestAddress) { this.testAddress = event; this.testDataUpdated = true; } allTestDataPresent(): boolean { return !!( this.testAddress && this.testOrderLines && this.testOrderLines.length && this.selectedChecker && this.selectedCalculator ); } runTest() { this.fetchTestResult$.next([this.testAddress, this.testOrderLines]); this.testDataUpdated = false; } /** * Given a ShippingMethod and the value of the detailForm, this method creates an updated copy which * can then be persisted to the API. */ private getUpdatedShippingMethod( shippingMethod: NonNullable<GetShippingMethodDetailQuery['shippingMethod']>, formGroup: typeof this.detailForm, languageCode: LanguageCode, ): Omit<CreateShippingMethodInput | UpdateShippingMethodInput, 'checker' | 'calculator'> { const formValue = formGroup.value; const input = createUpdatedTranslatable({ translatable: shippingMethod, updatedFields: formValue, customFieldConfig: this.customFields, languageCode, defaultTranslation: { languageCode, name: shippingMethod.name || '', description: shippingMethod.description || '', }, }); return { ...input, fulfillmentHandler: formValue.fulfillmentHandler }; } protected setFormValues(shippingMethod: ShippingMethodFragment, languageCode: LanguageCode): void { const currentTranslation = findTranslation(shippingMethod, languageCode); this.detailForm.patchValue({ name: currentTranslation?.name ?? '', description: currentTranslation?.description ?? '', code: shippingMethod.code, fulfillmentHandler: shippingMethod.fulfillmentHandlerCode, checker: shippingMethod.checker || {}, calculator: shippingMethod.calculator || {}, }); if (!this.selectedChecker) { this.selectedChecker = shippingMethod.checker && { code: shippingMethod.checker.code, args: shippingMethod.checker.args.map(a => ({ ...a, value: getConfigArgValue(a.value) })), }; } if (!this.selectedCalculator) { this.selectedCalculator = shippingMethod.calculator && { code: shippingMethod.calculator?.code, args: shippingMethod.calculator?.args.map(a => ({ ...a, value: getConfigArgValue(a.value) })), }; } if (this.customFields.length) { this.setCustomFieldFormValues( this.customFields, this.detailForm.get(['customFields']), shippingMethod, currentTranslation, ); } } }
import { createBulkAssignToChannelAction, createBulkDeleteAction, createBulkRemoveFromChannelAction, GetShippingMethodListQuery, GetRolesQuery, ItemOf, Permission, AssignShippingMethodsToChannelDocument, RemoveShippingMethodsFromChannelDocument, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { map } from 'rxjs/operators'; export const deleteShippingMethodsBulkAction = createBulkDeleteAction< ItemOf<GetShippingMethodListQuery, 'shippingMethods'> >({ location: 'shipping-method-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteShippingMethod), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.shippingMethod.deleteShippingMethods(ids).pipe(map(res => res.deleteShippingMethods)), }); const ASSIGN_SHIPPING_METHODS_TO_CHANNEL = gql` mutation AssignShippingMethodsToChannel($input: AssignShippingMethodsToChannelInput!) { assignShippingMethodsToChannel(input: $input) { id name } } `; const REMOVE_SHIPPING_METHODS_FROM_CHANNEL = gql` mutation RemoveShippingMethodsFromChannel($input: RemoveShippingMethodsFromChannelInput!) { removeShippingMethodsFromChannel(input: $input) { id name } } `; export const assignShippingMethodsToChannelBulkAction = createBulkAssignToChannelAction< ItemOf<GetShippingMethodListQuery, 'shippingMethods'> >({ location: 'shipping-method-list', requiresPermission: userPermissions => userPermissions.includes(Permission.UpdateShippingMethod) || userPermissions.includes(Permission.UpdateSettings), getItemName: item => item.name, bulkAssignToChannel: (dataService, shippingMethodIds, channelIds) => channelIds.map(channelId => dataService .mutate(AssignShippingMethodsToChannelDocument, { input: { channelId, shippingMethodIds, }, }) .pipe(map(res => res.assignShippingMethodsToChannel)), ), }); export const removeShippingMethodsFromChannelBulkAction = createBulkRemoveFromChannelAction< ItemOf<GetShippingMethodListQuery, 'shippingMethods'> >({ location: 'shipping-method-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteShippingMethod) || userPermissions.includes(Permission.DeleteSettings), getItemName: item => item.name, bulkRemoveFromChannel: (dataService, shippingMethodIds, channelId) => dataService .mutate(RemoveShippingMethodsFromChannelDocument, { input: { channelId, shippingMethodIds, }, }) .pipe(map(res => res.removeShippingMethodsFromChannel)), });
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetShippingMethodListDocument, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_SHIPPING_METHOD_LIST = gql` query GetShippingMethodList($options: ShippingMethodListOptions) { shippingMethods(options: $options) { items { ...ShippingMethodListItem } totalItems } } fragment ShippingMethodListItem on ShippingMethod { id createdAt updatedAt code name description fulfillmentHandlerCode } `; @Component({ selector: 'vdr-shipping-method-list', templateUrl: './shipping-method-list.component.html', styleUrls: ['./shipping-method-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ShippingMethodListComponent extends TypedBaseListComponent<typeof GetShippingMethodListDocument, 'shippingMethods'> implements OnInit { readonly customFields = this.getCustomFieldConfig('ShippingMethod'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addFilter({ name: 'code', type: { kind: 'text' }, label: _('common.code'), filterField: 'code', }) .addFilter({ name: 'description', type: { kind: 'text' }, label: _('common.description'), filterField: 'description', }) .addFilter({ name: 'fulfillmentHandler', type: { kind: 'text' }, label: _('settings.fulfillment-handler'), filterField: 'fulfillmentHandlerCode', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addSort({ name: 'code' }) .addSort({ name: 'description' }) .addSort({ name: 'fulfillmentHandlerCode' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetShippingMethodListDocument, getItems: data => data.shippingMethods, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { CurrencyCode, TestShippingMethodResult } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-shipping-method-test-result', templateUrl: './shipping-method-test-result.component.html', styleUrls: ['./shipping-method-test-result.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ShippingMethodTestResultComponent { @Input() testResult: TestShippingMethodResult; @Input() okToRun = false; @Input() testDataUpdated = false; @Input() currencyCode: CurrencyCode; @Output() runTest = new EventEmitter<void>(); }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateStockLocationDocument, CreateStockLocationInput, DataService, getCustomFieldsDefaults, GetStockLocationDetailDocument, NotificationService, StockLocationDetailFragment, TypedBaseDetailComponent, UpdateStockLocationDocument, UpdateStockLocationInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { mergeMap, take } from 'rxjs/operators'; const STOCK_LOCATION_DETAIL_FRAGMENT = gql` fragment StockLocationDetail on StockLocation { id createdAt updatedAt name description } `; export const GET_STOCK_LOCATION_DETAIL = gql` query GetStockLocationDetail($id: ID!) { stockLocation(id: $id) { ...StockLocationDetail } } ${STOCK_LOCATION_DETAIL_FRAGMENT} `; export const CREATE_STOCK_LOCATION = gql` mutation CreateStockLocation($input: CreateStockLocationInput!) { createStockLocation(input: $input) { ...StockLocationDetail } } ${STOCK_LOCATION_DETAIL_FRAGMENT} `; export const UPDATE_STOCK_LOCATION = gql` mutation UpdateStockLocation($input: UpdateStockLocationInput!) { updateStockLocation(input: $input) { ...StockLocationDetail } } ${STOCK_LOCATION_DETAIL_FRAGMENT} `; @Component({ selector: 'vdr-stock-location-detail', templateUrl: './stock-location-detail.component.html', styleUrls: ['./stock-location-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class StockLocationDetailComponent extends TypedBaseDetailComponent<typeof GetStockLocationDetailDocument, 'stockLocation'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('StockLocation'); detailForm = this.formBuilder.group({ name: ['', Validators.required], description: [''], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy() { this.destroy(); } create() { if (!this.detailForm.dirty) { return; } const { name, description, customFields } = this.detailForm.value; if (!name) { return; } const input = { name, description, customFields, } satisfies CreateStockLocationInput; this.dataService.mutate(CreateStockLocationDocument, { input }).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'StockLocation', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createStockLocation.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'StockLocation', }); }, ); } save() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; this.entity$ .pipe( take(1), mergeMap(taxRate => { const input = { id: taxRate.id, name: formValue.name, description: formValue.description, customFields: formValue.customFields, } satisfies UpdateStockLocationInput; return this.dataService.mutate(UpdateStockLocationDocument, { input }); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'StockLocation', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'StockLocation', }); }, ); } /** * Update the form values when the entity changes. */ protected setFormValues(entity: StockLocationDetailFragment): void { this.detailForm.patchValue({ name: entity.name, description: entity.description, }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity); } } }
import { AssignStockLocationsToChannelDocument, createBulkAssignToChannelAction, createBulkDeleteAction, createBulkRemoveFromChannelAction, DeleteStockLocationsDocument, DeletionResult, GetStockLocationListQuery, ItemOf, Permission, RemoveStockLocationsFromChannelDocument, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { map } from 'rxjs/operators'; const DELETE_STOCK_LOCATIONS = gql` mutation DeleteStockLocations($input: [DeleteStockLocationInput!]!) { deleteStockLocations(input: $input) { result message } } `; const ASSIGN_STOCK_LOCATIONS_TO_CHANNEL = gql` mutation AssignStockLocationsToChannel($input: AssignStockLocationsToChannelInput!) { assignStockLocationsToChannel(input: $input) { id name } } `; const REMOVE_STOCK_LOCATIONS_FROM_CHANNEL = gql` mutation RemoveStockLocationsFromChannel($input: RemoveStockLocationsFromChannelInput!) { removeStockLocationsFromChannel(input: $input) { id name } } `; export const deleteStockLocationsBulkAction = createBulkDeleteAction< ItemOf<GetStockLocationListQuery, 'stockLocations'> >({ location: 'stock-location-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteStockLocation) || userPermissions.includes(Permission.DeleteCatalog), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService .mutate(DeleteStockLocationsDocument, { input: ids.map(id => ({ id })), }) .pipe(map(res => res.deleteStockLocations)), shouldRetryItem: response => response.result === DeletionResult.NOT_DELETED, }); export const assignStockLocationsToChannelBulkAction = createBulkAssignToChannelAction< ItemOf<GetStockLocationListQuery, 'stockLocations'> >({ location: 'stock-location-list', requiresPermission: userPermissions => userPermissions.includes(Permission.UpdateCatalog) || userPermissions.includes(Permission.UpdateStockLocation), getItemName: item => item.name, bulkAssignToChannel: (dataService, stockLocationIds, channelIds) => channelIds.map(channelId => dataService .mutate(AssignStockLocationsToChannelDocument, { input: { channelId, stockLocationIds, }, }) .pipe(map(res => res.assignStockLocationsToChannel)), ), }); export const removeStockLocationsFromChannelBulkAction = createBulkRemoveFromChannelAction< ItemOf<GetStockLocationListQuery, 'stockLocations'> >({ location: 'stock-location-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteCatalog) || userPermissions.includes(Permission.DeleteStockLocation), getItemName: item => item.name, bulkRemoveFromChannel: (dataService, stockLocationIds, channelId) => dataService .mutate(RemoveStockLocationsFromChannelDocument, { input: { channelId, stockLocationIds, }, }) .pipe(map(res => res.removeStockLocationsFromChannel)), });
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetStockLocationListDocument, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_STOCK_LOCATION_LIST = gql` query GetStockLocationList($options: StockLocationListOptions) { stockLocations(options: $options) { items { ...StockLocationListItem } totalItems } } fragment StockLocationListItem on StockLocation { id createdAt updatedAt name description } `; @Component({ selector: 'vdr-stock-location-list', templateUrl: './stock-location-list.component.html', styleUrls: ['./stock-location-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class StockLocationListComponent extends TypedBaseListComponent<typeof GetStockLocationListDocument, 'stockLocations'> implements OnInit { readonly customFields = this.getCustomFieldConfig('StockLocation'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilters([ { name: 'enabled', type: { kind: 'text' }, label: _('common.enabled'), filterField: 'name', }, { name: 'sku', type: { kind: 'text' }, label: _('catalog.sku'), filterField: 'description', }, ]) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .addSorts([ { name: 'id' }, { name: 'createdAt' }, { name: 'updatedAt' }, { name: 'name' }, { name: 'description' }, ]) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); this.configure({ document: GetStockLocationListDocument, getItems: data => data.stockLocations, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.sorts.valueChanges, this.filters.valueChanges], }); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateTaxCategoryInput, DataService, getCustomFieldsDefaults, GetTaxCategoryDetailDocument, LanguageCode, NotificationService, Permission, TAX_CATEGORY_FRAGMENT, TaxCategoryFragment, TypedBaseDetailComponent, UpdateTaxCategoryInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { mergeMap, take } from 'rxjs/operators'; export const GET_TAX_CATEGORY_DETAIL = gql` query GetTaxCategoryDetail($id: ID!) { taxCategory(id: $id) { ...TaxCategory } } ${TAX_CATEGORY_FRAGMENT} `; @Component({ selector: 'vdr-tax-detail', templateUrl: './tax-category-detail.component.html', styleUrls: ['./tax-category-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TaxCategoryDetailComponent extends TypedBaseDetailComponent<typeof GetTaxCategoryDetailDocument, 'taxCategory'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('TaxCategory'); detailForm = this.formBuilder.group({ name: ['', Validators.required], isDefault: false, customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); readonly updatePermission = [Permission.UpdateSettings, Permission.UpdateTaxCategory]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy() { this.destroy(); } saveButtonEnabled(): boolean { return this.detailForm.dirty && this.detailForm.valid; } create() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; const input = { name: formValue.name, isDefault: formValue.isDefault, customFields: formValue.customFields, } as CreateTaxCategoryInput; this.dataService.settings.createTaxCategory(input).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'TaxCategory', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createTaxCategory.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'TaxCategory', }); }, ); } save() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; this.entity$ .pipe( take(1), mergeMap(taxCategory => { const input = { id: taxCategory.id, name: formValue.name, isDefault: formValue.isDefault, customFields: formValue.customFields, } as UpdateTaxCategoryInput; return this.dataService.settings.updateTaxCategory(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'TaxCategory', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'TaxCategory', }); }, ); } /** * Update the form values when the entity changes. */ protected setFormValues(entity: TaxCategoryFragment, languageCode: LanguageCode): void { this.detailForm.patchValue({ name: entity.name, isDefault: entity.isDefault, }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity); } } }
import { createBulkDeleteAction, GetTaxCategoryListQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteTaxCategoriesBulkAction = createBulkDeleteAction< ItemOf<GetTaxCategoryListQuery, 'taxCategories'> >({ location: 'tax-category-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteSettings) || userPermissions.includes(Permission.DeleteTaxCategory), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.settings.deleteTaxCategories(ids).pipe(map(res => res.deleteTaxCategories)), });
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetTaxCategoryListDocument, TAX_CATEGORY_FRAGMENT, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_TAX_CATEGORY_LIST = gql` query GetTaxCategoryList($options: TaxCategoryListOptions) { taxCategories(options: $options) { items { ...TaxCategory } totalItems } } ${TAX_CATEGORY_FRAGMENT} `; @Component({ selector: 'vdr-tax-list', templateUrl: './tax-category-list.component.html', styleUrls: ['./tax-category-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TaxCategoryListComponent extends TypedBaseListComponent< typeof GetTaxCategoryListDocument, 'taxCategories' > { readonly customFields = this.serverConfigService.getCustomFieldsFor('TaxCategory'); readonly filters = this.createFilterCollection() .addIdFilter() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetTaxCategoryListDocument, getItems: data => data.taxCategories, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateTaxRateInput, CustomerGroup, DataService, getCustomFieldsDefaults, GetTaxRateDetailDocument, LanguageCode, NotificationService, Permission, TAX_RATE_FRAGMENT, TaxCategoryFragment, TaxRateFragment, TypedBaseDetailComponent, UpdateTaxRateInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; import { mergeMap, take } from 'rxjs/operators'; export const GET_TAX_RATE_DETAIL = gql` query GetTaxRateDetail($id: ID!) { taxRate(id: $id) { ...TaxRate } } ${TAX_RATE_FRAGMENT} `; @Component({ selector: 'vdr-tax-rate-detail', templateUrl: './tax-rate-detail.component.html', styleUrls: ['./tax-rate-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TaxRateDetailComponent extends TypedBaseDetailComponent<typeof GetTaxRateDetailDocument, 'taxRate'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('TaxRate'); detailForm = this.formBuilder.group({ name: ['', Validators.required], enabled: [true], value: [0, Validators.required], taxCategoryId: ['', Validators.required], zoneId: ['', Validators.required], customerGroupId: [''], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); taxCategories$: Observable<TaxCategoryFragment[]>; groups$: Observable<CustomerGroup[]>; readonly updatePermission = [Permission.UpdateSettings, Permission.UpdateTaxRate]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); this.taxCategories$ = this.dataService.settings .getTaxCategories({ take: 100 }) .mapSingle(data => data.taxCategories.items); } ngOnDestroy() { this.destroy(); } saveButtonEnabled(): boolean { return this.detailForm.dirty && this.detailForm.valid; } create() { if (!this.detailForm.dirty) { return; } const { name, enabled, value, taxCategoryId, zoneId, customerGroupId, customFields } = this.detailForm.value; if (!name || enabled == null || value == null || !taxCategoryId || !zoneId) { return; } const formValue = this.detailForm.value; const input = { name, enabled, value, categoryId: taxCategoryId, zoneId, customerGroupId: formValue.customerGroupId, customFields: formValue.customFields, } satisfies CreateTaxRateInput; this.dataService.settings.createTaxRate(input).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'TaxRate', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createTaxRate.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'TaxRate', }); }, ); } save() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; this.entity$ .pipe( take(1), mergeMap(taxRate => { const input = { id: taxRate.id, name: formValue.name, enabled: formValue.enabled, value: formValue.value, categoryId: formValue.taxCategoryId, zoneId: formValue.zoneId, customerGroupId: formValue.customerGroupId, customFields: formValue.customFields, } satisfies UpdateTaxRateInput; return this.dataService.settings.updateTaxRate(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'TaxRate', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'TaxRate', }); }, ); } /** * Update the form values when the entity changes. */ protected setFormValues(entity: TaxRateFragment, languageCode: LanguageCode): void { this.detailForm.patchValue({ name: entity.name, enabled: entity.enabled, value: entity.value, taxCategoryId: entity.category ? entity.category.id : '', zoneId: entity.zone ? entity.zone.id : '', customerGroupId: entity.customerGroup ? entity.customerGroup.id : '', }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity); } } }
import { createBulkDeleteAction, GetTaxRateListQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteTaxRatesBulkAction = createBulkDeleteAction<ItemOf<GetTaxRateListQuery, 'taxRates'>>({ location: 'tax-rate-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteSettings) || userPermissions.includes(Permission.DeleteTaxRate), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.settings.deleteTaxRates(ids).pipe(map(res => res.deleteTaxRates)), });
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetTaxRateListDocument, TAX_RATE_FRAGMENT, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_TAX_RATE_LIST = gql` query GetTaxRateList($options: TaxRateListOptions) { taxRates(options: $options) { items { ...TaxRate } totalItems } } ${TAX_RATE_FRAGMENT} `; @Component({ selector: 'vdr-tax-rate-list', templateUrl: './tax-rate-list.component.html', styleUrls: ['./tax-rate-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TaxRateListComponent extends TypedBaseListComponent<typeof GetTaxRateListDocument, 'taxRates'> { readonly customFields = this.getCustomFieldConfig('TaxRate'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addFilter({ name: 'enabled', type: { kind: 'boolean' }, label: _('common.enabled'), filterField: 'enabled', }) .addFilter({ name: 'value', type: { kind: 'number' }, label: _('common.value'), filterField: 'value', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addSort({ name: 'value' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetTaxRateListDocument, getItems: data => data.taxRates, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } }
import { ChangeDetectionStrategy, Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { DataService, GetAvailableCountriesQuery, ItemOf, LocalStorageService } from '@vendure/admin-ui/core'; import { Observable, Subscription } from 'rxjs'; export interface TestAddress { city: string; province: string; postalCode: string; countryCode: string; } @Component({ selector: 'vdr-test-address-form', templateUrl: './test-address-form.component.html', styleUrls: ['./test-address-form.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TestAddressFormComponent implements OnInit, OnDestroy { @Output() addressChange = new EventEmitter<TestAddress>(); availableCountries$: Observable<Array<ItemOf<GetAvailableCountriesQuery, 'countries'>>>; form: UntypedFormGroup; private subscription: Subscription; constructor( private formBuilder: UntypedFormBuilder, private dataService: DataService, private localStorageService: LocalStorageService, ) {} ngOnInit() { this.availableCountries$ = this.dataService.settings .getAvailableCountries() .mapSingle(result => result.countries.items); const storedValue = this.localStorageService.getForCurrentLocation('shippingTestAddress'); const initialValue: TestAddress = storedValue ? storedValue : { city: '', countryCode: '', postalCode: '', province: '', }; this.addressChange.emit(initialValue); this.form = this.formBuilder.group(initialValue); this.subscription = this.form.valueChanges.subscribe(value => { this.localStorageService.setForCurrentLocation('shippingTestAddress', value); this.addressChange.emit(value); }); } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } }
import { ChangeDetectionStrategy, Component, EventEmitter, OnInit, Output } from '@angular/core'; import { CurrencyCode, DataService, LocalStorageService, ProductSelectorSearchQuery, } from '@vendure/admin-ui/core'; type SearchItem = ProductSelectorSearchQuery['search']['items'][number]; export interface TestOrderLine { id: string; name: string; preview: string; sku: string; unitPriceWithTax: number; quantity: number; } @Component({ selector: 'vdr-test-order-builder', templateUrl: './test-order-builder.component.html', styleUrls: ['./test-order-builder.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TestOrderBuilderComponent implements OnInit { @Output() orderLinesChange = new EventEmitter<TestOrderLine[]>(); lines: TestOrderLine[] = []; currencyCode: CurrencyCode; get subTotal(): number { return this.lines.reduce((sum, l) => sum + l.unitPriceWithTax * l.quantity, 0); } constructor(private dataService: DataService, private localStorageService: LocalStorageService) {} ngOnInit() { this.lines = this.loadFromLocalStorage(); if (this.lines) { this.orderLinesChange.emit(this.lines); } this.dataService.settings.getActiveChannel('cache-first').single$.subscribe(result => { this.currencyCode = result.activeChannel.defaultCurrencyCode; }); } selectResult(result: SearchItem) { if (result) { this.addToLines(result); } } private addToLines(result: SearchItem) { if (!this.lines.find(l => l.id === result.productVariantId)) { this.lines.push({ id: result.productVariantId, name: result.productVariantName, preview: result.productAsset?.preview ?? '', quantity: 1, sku: result.sku, unitPriceWithTax: (result.priceWithTax.__typename === 'SinglePrice' && result.priceWithTax.value) || 0, }); this.persistToLocalStorage(); this.orderLinesChange.emit(this.lines); } } updateQuantity() { this.persistToLocalStorage(); this.orderLinesChange.emit(this.lines); } removeLine(line: TestOrderLine) { this.lines = this.lines.filter(l => l.id !== line.id); this.persistToLocalStorage(); this.orderLinesChange.emit(this.lines); } private persistToLocalStorage() { this.localStorageService.setForCurrentLocation('shippingTestOrder', this.lines); } private loadFromLocalStorage(): TestOrderLine[] { return this.localStorageService.getForCurrentLocation('shippingTestOrder') || []; } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { DataService, GetActiveChannelQuery, ShippingMethodQuote, TestEligibleShippingMethodsInput, } from '@vendure/admin-ui/core'; import { Observable, Subject } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { TestAddress } from '../test-address-form/test-address-form.component'; import { TestOrderLine } from '../test-order-builder/test-order-builder.component'; @Component({ selector: 'vdr-test-shipping-methods', templateUrl: './test-shipping-methods.component.html', styleUrls: ['./test-shipping-methods.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TestShippingMethodsComponent implements OnInit { activeChannel$: Observable<GetActiveChannelQuery['activeChannel']>; testAddress: TestAddress; testOrderLines: TestOrderLine[]; testDataUpdated = false; testResult$: Observable<ShippingMethodQuote[] | undefined>; private fetchTestResult$ = new Subject<[TestAddress, TestOrderLine[]]>(); constructor(private dataService: DataService) {} ngOnInit() { this.activeChannel$ = this.dataService.settings .getActiveChannel() .mapStream(data => data.activeChannel); this.testResult$ = this.fetchTestResult$.pipe( switchMap(([address, lines]) => { const input: TestEligibleShippingMethodsInput = { shippingAddress: { ...address, streetLine1: 'test' }, lines: lines.map(l => ({ productVariantId: l.id, quantity: l.quantity })), }; return this.dataService.shippingMethod .testEligibleShippingMethods(input) .mapSingle(result => result.testEligibleShippingMethods); }), ); } setTestOrderLines(event: TestOrderLine[]) { this.testOrderLines = event; this.testDataUpdated = true; } setTestAddress(event: TestAddress) { this.testAddress = event; this.testDataUpdated = true; } allTestDataPresent(): boolean { return !!(this.testAddress && this.testOrderLines && this.testOrderLines.length); } runTest() { this.fetchTestResult$.next([this.testAddress, this.testOrderLines]); this.testDataUpdated = false; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateZoneInput, DataService, getCustomFieldsDefaults, GetZoneDetailDocument, GetZoneDetailQuery, LanguageCode, NotificationService, Permission, TypedBaseDetailComponent, UpdateTaxCategoryInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { mergeMap, take } from 'rxjs/operators'; export const GET_ZONE_DETAIL = gql` query GetZoneDetail($id: ID!) { zone(id: $id) { ...ZoneDetail } } fragment ZoneDetail on Zone { id createdAt updatedAt name } `; @Component({ selector: 'vdr-zone-detail', templateUrl: './zone-detail.component.html', styleUrls: ['./zone-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ZoneDetailComponent extends TypedBaseDetailComponent<typeof GetZoneDetailDocument, 'zone'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Zone'); detailForm = this.formBuilder.group({ name: ['', Validators.required], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); readonly updatePermission = [Permission.UpdateSettings, Permission.UpdateZone]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); } ngOnDestroy() { this.destroy(); } saveButtonEnabled(): boolean { return this.detailForm.dirty && this.detailForm.valid; } create() { if (!this.detailForm.dirty) { return; } const { name, customFields } = this.detailForm.value; if (!name) { return; } const input = { name, customFields, } satisfies CreateZoneInput; this.dataService.settings.createZone(input).subscribe( data => { this.notificationService.success(_('common.notify-create-success'), { entity: 'Zone', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', data.createZone.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'Zone', }); }, ); } save() { if (!this.detailForm.dirty) { return; } const formValue = this.detailForm.value; this.entity$ .pipe( take(1), mergeMap(zone => { const input = { id: zone.id, name: formValue.name, customFields: formValue.customFields, } satisfies UpdateTaxCategoryInput; return this.dataService.settings.updateZone(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Zone', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Zone', }); }, ); } /** * Update the form values when the entity changes. */ protected setFormValues( entity: NonNullable<GetZoneDetailQuery['zone']>, languageCode: LanguageCode, ): void { this.detailForm.patchValue({ name: entity.name, }); if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity); } } }
import { createBulkDeleteAction, GetZoneListQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteZonesBulkAction = createBulkDeleteAction<ItemOf<GetZoneListQuery, 'zones'>>({ location: 'zone-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteSettings) || userPermissions.includes(Permission.DeleteZone), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.settings.deleteZones(ids).pipe(map(res => res.deleteZones)), });
import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DataService, GetZoneListDocument, GetZoneListQuery, ItemOf, LanguageCode, LogicalOperator, ModalService, NotificationService, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { combineLatest, EMPTY, Observable } from 'rxjs'; import { distinctUntilChanged, map, mapTo, switchMap, tap } from 'rxjs/operators'; import { AddCountryToZoneDialogComponent } from '../add-country-to-zone-dialog/add-country-to-zone-dialog.component'; import { ZoneMemberListComponent } from '../zone-member-list/zone-member-list.component'; export const GET_ZONE_LIST = gql` query GetZoneList($options: ZoneListOptions) { zones(options: $options) { items { ...ZoneListItem } totalItems } } fragment ZoneListItem on Zone { id createdAt updatedAt name } `; @Component({ selector: 'vdr-zone-list', templateUrl: './zone-list.component.html', styleUrls: ['./zone-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ZoneListComponent extends TypedBaseListComponent<typeof GetZoneListDocument, 'zones'> implements OnInit { activeZone$: Observable<ItemOf<GetZoneListQuery, 'zones'> | undefined>; activeIndex$: Observable<number>; selectedMemberIds: string[] = []; @ViewChild(ZoneMemberListComponent) zoneMemberList: ZoneMemberListComponent; readonly customFields = this.serverConfigService.getCustomFieldsFor('Zone'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor( protected dataService: DataService, private notificationService: NotificationService, private modalService: ModalService, ) { super(); super.configure({ document: GetZoneListDocument, getItems: data => data.zones, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value, }, ...this.filters.createFilterInput(), }, filterOperator: this.searchTermControl.value ? LogicalOperator.OR : LogicalOperator.AND, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } ngOnInit(): void { super.ngOnInit(); const activeZoneId$ = this.route.paramMap.pipe( map(pm => pm.get('contents')), distinctUntilChanged(), tap(() => (this.selectedMemberIds = [])), ); this.activeZone$ = combineLatest(this.items$, activeZoneId$).pipe( map(([zones, activeZoneId]) => { if (activeZoneId) { return zones.find(z => z.id === activeZoneId); } }), ); this.activeIndex$ = combineLatest(this.items$, activeZoneId$).pipe( map(([zones, activeZoneId]) => { if (activeZoneId) { return zones.findIndex(g => g.id === activeZoneId); } else { return -1; } }), ); } setLanguage(code: LanguageCode) { this.dataService.client.setContentLanguage(code).subscribe(); } closeMembers() { const params = { ...this.route.snapshot.params }; delete params.contents; this.router.navigate(['./', params], { relativeTo: this.route, queryParamsHandling: 'preserve' }); } addToZone(zone: ItemOf<GetZoneListQuery, 'zones'>) { this.modalService .fromComponent(AddCountryToZoneDialogComponent, { locals: { zoneName: zone.name, zoneId: zone.id, }, size: 'md', }) .pipe( switchMap(memberIds => memberIds ? this.dataService.settings .addMembersToZone(zone.id, memberIds) .pipe(mapTo(memberIds)) : EMPTY, ), ) .subscribe({ next: result => { this.notificationService.success(_(`settings.add-countries-to-zone-success`), { countryCount: result.length, zoneName: zone.name, }); this.refreshMemberList(); }, error: err => { this.notificationService.error(err); }, }); } refreshMemberList() { this.zoneMemberList?.refresh(); } }
import { Directive, TemplateRef } from '@angular/core'; @Directive({ selector: '[vdrZoneMemberControls]', }) export class ZoneMemberControlsDirective { constructor(public templateRef: TemplateRef<any>) {} }
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { BulkAction, DataService, NotificationService, Permission } from '@vendure/admin-ui/core'; import { ZoneMember, ZoneMemberListComponent } from './zone-member-list.component'; export const removeZoneMembersBulkAction: BulkAction<ZoneMember, ZoneMemberListComponent> = { location: 'zone-members-list', label: _('settings.remove-from-zone'), icon: 'trash', iconClass: 'is-danger', requiresPermission: Permission.UpdateCustomerGroup, onClick: ({ injector, selection, hostComponent, clearSelection }) => { const dataService = injector.get(DataService); const notificationService = injector.get(NotificationService); const zone = hostComponent.activeZone; const memberIds = selection.map(s => s.id); dataService.settings.removeMembersFromZone(zone.id, memberIds).subscribe({ complete: () => { notificationService.success(_(`settings.remove-countries-from-zone-success`), { countryCount: memberIds.length, zoneName: zone.name, }); hostComponent.refresh(); clearSelection(); }, }); }, };
import { Directive, TemplateRef } from '@angular/core'; @Directive({ selector: '[vdrZoneMemberListHeader]', }) export class ZoneMemberListHeaderDirective { constructor(public templateRef: TemplateRef<any>) {} }
import { ChangeDetectionStrategy, Component, ContentChild, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, } from '@angular/core'; import { FormControl } from '@angular/forms'; import { BulkActionLocationId, DataService, GetZoneListQuery, GetZoneMembersDocument, GetZoneMembersQuery, ItemOf, SelectionManager, } from '@vendure/admin-ui/core'; import { BehaviorSubject, combineLatest, merge, Observable, of, Subject, switchMap } from 'rxjs'; import { map, startWith, take, takeUntil } from 'rxjs/operators'; import { ZoneMemberControlsDirective } from './zone-member-controls.directive'; import { ZoneMemberListHeaderDirective } from './zone-member-list-header.directive'; export type ZoneMember = { id: string; name: string; code: string }; @Component({ selector: 'vdr-zone-member-list', templateUrl: './zone-member-list.component.html', styleUrls: ['./zone-member-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ZoneMemberListComponent implements OnInit, OnChanges, OnDestroy { @Input() locationId: BulkActionLocationId; @Input() members?: ZoneMember[]; @Input() selectedMemberIds: string[] = []; @Input() activeZone: ItemOf<GetZoneListQuery, 'zones'>; @Output() selectionChange = new EventEmitter<string[]>(); @ContentChild(ZoneMemberListHeaderDirective) headerTemplate: ZoneMemberListHeaderDirective; @ContentChild(ZoneMemberControlsDirective) controlsTemplate: ZoneMemberControlsDirective; members$: Observable<NonNullable<GetZoneMembersQuery['zone']>['members'] | ZoneMember[]>; filterTermControl = new FormControl(''); filteredMembers$: Observable<ZoneMember[]>; totalItems$: Observable<number>; currentPage = 1; itemsPerPage = 10; selectionManager = new SelectionManager<ZoneMember>({ multiSelect: true, itemsAreEqual: (a, b) => a.id === b.id, additiveMode: true, }); private membersInput$ = new Subject<ZoneMember[]>(); private activeZoneInput$ = new BehaviorSubject<ItemOf<GetZoneListQuery, 'zones'> | undefined>(undefined); private destroy$ = new Subject<void>(); private refresh$ = new Subject<void>(); constructor(private dataService: DataService) {} ngOnInit() { const activeZoneMembers$ = merge(this.activeZoneInput$, this.refresh$).pipe( switchMap(activeZone => this.activeZone ? this.dataService .query(GetZoneMembersDocument, { zoneId: this.activeZone.id }) .mapSingle(({ zone }) => zone?.members ?? []) : of([]), ), ); this.members$ = merge(activeZoneMembers$, this.membersInput$); this.members$.pipe(take(1)).subscribe(members => { this.selectionManager.setCurrentItems( members?.filter(m => this.selectedMemberIds.includes(m.id)) ?? [], ); }); this.selectionManager.selectionChanges$.pipe(takeUntil(this.destroy$)).subscribe(selection => { this.selectionChange.emit(selection.map(s => s.id)); }); this.filteredMembers$ = combineLatest( this.members$, this.filterTermControl.valueChanges.pipe(startWith('')), ).pipe( map(([members, filterTerm]) => { if (filterTerm) { const term = filterTerm?.toLocaleLowerCase() ?? ''; return members.filter( m => m.name.toLocaleLowerCase().includes(term) || m.code.toLocaleLowerCase().includes(term), ); } else { return members; } }), ); this.totalItems$ = this.filteredMembers$.pipe(map(members => members.length)); } ngOnChanges(changes: SimpleChanges) { if ('members' in changes) { this.membersInput$.next(this.members ?? []); } if ('activeZone' in changes) { this.activeZoneInput$.next(this.activeZone); } } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } refresh() { this.refresh$.next(); } }
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { AdministratorFragment, BaseEntityResolver, DataService } from '@vendure/admin-ui/core'; @Injectable({ providedIn: 'root', }) export class ProfileResolver extends BaseEntityResolver<AdministratorFragment> { constructor(router: Router, dataService: DataService) { super( router, { __typename: 'Administrator' as const, id: '', createdAt: '', updatedAt: '', emailAddress: '', firstName: '', lastName: '', user: { roles: [] } as any, }, id => dataService.administrator .getActiveAdministrator() .mapStream(data => data.activeAdministrator), ); } }
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html */ /* eslint-disable import/order */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE9, IE10 and IE11 requires all of the following polyfills. **/ // import 'core-js/es6/symbol'; // import 'core-js/es6/object'; // import 'core-js/es6/function'; // import 'core-js/es6/parse-int'; // import 'core-js/es6/parse-float'; // import 'core-js/es6/number'; // import 'core-js/es6/math'; // import 'core-js/es6/string'; // import 'core-js/es6/date'; // import 'core-js/es6/array'; // import 'core-js/es6/regexp'; // import 'core-js/es6/map'; // import 'core-js/es6/weak-map'; // import 'core-js/es6/set'; /** IE10 and IE11 requires the following for the Reflect API. */ // import 'core-js/es6/reflect'; /** Evergreen browsers require these. **/ // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. // import 'core-js/es/reflect'; /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags */ // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames /* * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge */ // (window as any).__Zone_enable_cross_context_check = true; /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */
// This file was generated by the build-public-api.ts script export * from './components/health-check/health-check.component'; export * from './components/job-list/job-list.component'; export * from './components/job-state-label/job-state-label.component'; export * from './system.module'; export * from './system.routes';
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { SharedModule } from '@vendure/admin-ui/core'; import { HealthCheckComponent } from './components/health-check/health-check.component'; import { JobListComponent } from './components/job-list/job-list.component'; import { JobStateLabelComponent } from './components/job-state-label/job-state-label.component'; import { systemRoutes } from './system.routes'; @NgModule({ declarations: [HealthCheckComponent, JobListComponent, JobStateLabelComponent], imports: [SharedModule, RouterModule.forChild(systemRoutes)], }) export class SystemModule {}
import { Route } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { HealthCheckComponent } from './components/health-check/health-check.component'; import { JobListComponent } from './components/job-list/job-list.component'; export const systemRoutes: Route[] = [ { path: 'jobs', component: JobListComponent, data: { breadcrumb: _('breadcrumb.job-queue'), }, }, { path: 'system-status', component: HealthCheckComponent, data: { breadcrumb: _('breadcrumb.system-status'), }, }, ];
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { HealthCheckService } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-health-check', templateUrl: './health-check.component.html', styleUrls: ['./health-check.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class HealthCheckComponent { constructor(public healthCheckService: HealthCheckService) {} }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { BaseListComponent, DataService, GetAllJobsQuery, GetJobQueueListQuery, ItemOf, JobState, SortOrder, } from '@vendure/admin-ui/core'; import { Observable, timer } from 'rxjs'; import { filter, map, takeUntil } from 'rxjs/operators'; @Component({ selector: 'vdr-job-list', templateUrl: './job-list.component.html', styleUrls: ['./job-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class JobListComponent extends BaseListComponent<GetAllJobsQuery, ItemOf<GetAllJobsQuery, 'jobs'>> implements OnInit { queues$: Observable<GetJobQueueListQuery['jobQueues']>; liveUpdate = new FormControl(true); queueFilter = new FormControl('all'); stateFilter = new FormControl<JobState | string>(''); constructor(private dataService: DataService, router: Router, route: ActivatedRoute) { super(router, route); super.setQueryFn( (...args: any[]) => this.dataService.settings.getAllJobs(...args), data => data.jobs, (skip, take) => { const queueFilter = this.queueFilter.value === 'all' ? null : { queueName: { eq: this.queueFilter.value } }; const stateFilter = this.stateFilter.value; return { options: { skip, take, filter: { ...queueFilter, ...(stateFilter ? { state: { eq: stateFilter } } : {}), }, sort: { createdAt: SortOrder.DESC, }, }, }; }, ); } ngOnInit(): void { super.ngOnInit(); timer(5000, 2000) .pipe( takeUntil(this.destroy$), filter(() => !!this.liveUpdate.value), ) .subscribe(() => { this.refresh(); }); this.queues$ = this.dataService.settings .getJobQueues() .mapStream(res => res.jobQueues) .pipe(map(queues => [{ name: 'all', running: true }, ...queues])); } hasResult(job: ItemOf<GetAllJobsQuery, 'jobs'>): boolean { const result = job.result; if (result == null) { return false; } if (typeof result === 'object') { return Object.keys(result).length > 0; } return true; } cancelJob(id: string) { this.dataService.settings.cancelJob(id).subscribe(() => this.refresh()); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { JobInfoFragment, JobState } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-job-state-label', templateUrl: './job-state-label.component.html', styleUrls: ['./job-state-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class JobStateLabelComponent { @Input() job: JobInfoFragment; get iconShape(): string { switch (this.job.state) { case JobState.COMPLETED: return 'check-circle'; case JobState.FAILED: return 'exclamation-circle'; case JobState.CANCELLED: return 'ban'; case JobState.PENDING: case JobState.RETRYING: return 'hourglass'; case JobState.RUNNING: return 'sync'; } } get colorType(): string { switch (this.job.state) { case JobState.COMPLETED: return 'success'; case JobState.FAILED: case JobState.CANCELLED: return 'error'; case JobState.PENDING: case JobState.RETRYING: return ''; case JobState.RUNNING: return 'warning'; } } }
import { CommonModule } from '@angular/common'; import { NgModule, Provider } from '@angular/core'; import { ClarityModule } from '@clr/angular'; import { DataService, FormFieldComponent, FormFieldControlDirective } from '../lib/core/src/public_api'; import { MockTranslatePipe } from './translate.pipe.mock'; const DECLARATIONS = [MockTranslatePipe, FormFieldComponent, FormFieldControlDirective]; const PROVIDERS: Provider[] = [{ provide: DataService, useValue: {} }]; /** * This module is for use in unit testing, and provides common directives and providers * that are used across most component, reducing the boilerplate needed to declare these * in each individual test. */ @NgModule({ imports: [CommonModule, ClarityModule], exports: [...DECLARATIONS, ClarityModule], declarations: DECLARATIONS, providers: PROVIDERS, }) export class TestingCommonModule {}
export type MockOf<T> = { [K in keyof T]: T[K] };
import { NgModule, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'translate', }) export class MockTranslatePipe implements PipeTransform { transform(value: any, ...args: any[]): any { return value; } } // Work around for https://github.com/angular/angular/issues/13590 @NgModule({ declarations: [MockTranslatePipe], }) export class MockTranslatePipeModule {}
export * from './src/plugin'; export * from './src/s3-asset-storage-strategy'; export * from './src/sharp-asset-preview-strategy'; export * from './src/types';
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { mergeConfig } from '@vendure/core'; import { AssetFragment } from '@vendure/core/e2e/graphql/generated-e2e-admin-types'; import { createTestEnvironment } from '@vendure/testing'; import fs from 'fs-extra'; import gql from 'graphql-tag'; import fetch from 'node-fetch'; import path from 'path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { initialData } from '../../../e2e-common/e2e-initial-data'; import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config'; import { AssetServerPlugin } from '../src/plugin'; import { CreateAssetsMutation, DeleteAssetMutation, DeleteAssetMutationVariables, DeletionResult, } from './graphql/generated-e2e-asset-server-plugin-types'; const TEST_ASSET_DIR = 'test-assets'; const IMAGE_BASENAME = 'derick-david-409858-unsplash'; describe('AssetServerPlugin', () => { let asset: AssetFragment; const sourceFilePath = path.join(__dirname, TEST_ASSET_DIR, `source/b6/${IMAGE_BASENAME}.jpg`); const previewFilePath = path.join(__dirname, TEST_ASSET_DIR, `preview/71/${IMAGE_BASENAME}__preview.jpg`); const { server, adminClient, shopClient } = createTestEnvironment( mergeConfig(testConfig(), { // logger: new DefaultLogger({ level: LogLevel.Info }), plugins: [ AssetServerPlugin.init({ assetUploadDir: path.join(__dirname, TEST_ASSET_DIR), route: 'assets', }), ], }), ); beforeAll(async () => { await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'source')); await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'preview')); await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'cache')); await server.init({ initialData, productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-empty.csv'), customerCount: 1, }); await adminClient.asSuperAdmin(); }, TEST_SETUP_TIMEOUT_MS); afterAll(async () => { await server.destroy(); }); it('names the Asset correctly', async () => { const filesToUpload = [path.join(__dirname, `fixtures/assets/${IMAGE_BASENAME}.jpg`)]; const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); asset = createAssets[0] as AssetFragment; expect(asset.name).toBe(`${IMAGE_BASENAME}.jpg`); }); it('creates the expected asset files', async () => { expect(fs.existsSync(sourceFilePath)).toBe(true); expect(fs.existsSync(previewFilePath)).toBe(true); }); it('serves the source file', async () => { const res = await fetch(`${asset.source}`); const responseBuffer = await res.buffer(); const sourceFile = await fs.readFile(sourceFilePath); expect(Buffer.compare(responseBuffer, sourceFile)).toBe(0); }); it('serves the untransformed preview file', async () => { const res = await fetch(`${asset.preview}`); const responseBuffer = await res.buffer(); const previewFile = await fs.readFile(previewFilePath); expect(Buffer.compare(responseBuffer, previewFile)).toBe(0); }); it('can handle non-latin filenames', async () => { const FILE_NAME_ZH = '白飯'; const filesToUpload = [path.join(__dirname, `fixtures/assets/${FILE_NAME_ZH}.jpg`)]; const { createAssets }: { createAssets: AssetFragment[] } = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets[0].name).toBe(`${FILE_NAME_ZH}.jpg`); expect(createAssets[0].source).toContain(`${FILE_NAME_ZH}.jpg`); const previewUrl = encodeURI(`${createAssets[0].preview}`); const res = await fetch(previewUrl); expect(res.status).toBe(200); const previewFilePathZH = path.join( __dirname, TEST_ASSET_DIR, `preview/3f/${FILE_NAME_ZH}__preview.jpg`, ); const responseBuffer = await res.buffer(); const previewFile = await fs.readFile(previewFilePathZH); expect(Buffer.compare(responseBuffer, previewFile)).toBe(0); }); describe('caching', () => { const cacheDir = path.join(__dirname, TEST_ASSET_DIR, 'cache'); const cacheFileDir = path.join(__dirname, TEST_ASSET_DIR, 'cache', 'preview', '71'); it('cache initially empty', async () => { const files = await fs.readdir(cacheDir); expect(files.length).toBe(0); }); it('creates cached image on first request', async () => { const res = await fetch(`${asset.preview}?preset=thumb`); const responseBuffer = await res.buffer(); expect(fs.existsSync(cacheFileDir)).toBe(true); const files = await fs.readdir(cacheFileDir); expect(files.length).toBe(1); expect(files[0]).toContain(`${IMAGE_BASENAME}__preview`); const cachedFile = await fs.readFile(path.join(cacheFileDir, files[0])); // was the file returned the exact same file as is stored in the cache dir? expect(Buffer.compare(responseBuffer, cachedFile)).toBe(0); }); it('does not create a new cached image on a second request', async () => { const res = await fetch(`${asset.preview}?preset=thumb`); const files = await fs.readdir(cacheFileDir); expect(files.length).toBe(1); }); it('does not create a new cached image for an untransformed image', async () => { const res = await fetch(`${asset.preview}`); const files = await fs.readdir(cacheFileDir); expect(files.length).toBe(1); }); it('does not create a new cached image for an invalid preset', async () => { const res = await fetch(`${asset.preview}?preset=invalid`); const files = await fs.readdir(cacheFileDir); expect(files.length).toBe(1); const previewFile = await fs.readFile(previewFilePath); const responseBuffer = await res.buffer(); expect(Buffer.compare(responseBuffer, previewFile)).toBe(0); }); it('does not create a new cached image if cache=false', async () => { const res = await fetch(`${asset.preview}?preset=tiny&cache=false`); const files = await fs.readdir(cacheFileDir); expect(files.length).toBe(1); }); it('creates a new cached image if cache=true', async () => { const res = await fetch(`${asset.preview}?preset=tiny&cache=true`); const files = await fs.readdir(cacheFileDir); expect(files.length).toBe(2); }); }); describe('unexpected input', () => { it('does not error on non-integer width', async () => { return fetch(`${asset.preview}?w=10.5`); }); it('does not error on non-integer height', async () => { return fetch(`${asset.preview}?h=10.5`); }); }); describe('deletion', () => { it('deleting Asset deletes binary file', async () => { const { deleteAsset } = await adminClient.query< DeleteAssetMutation, DeleteAssetMutationVariables >(DELETE_ASSET, { input: { assetId: asset.id, force: true, }, }); expect(deleteAsset.result).toBe(DeletionResult.DELETED); expect(fs.existsSync(sourceFilePath)).toBe(false); expect(fs.existsSync(previewFilePath)).toBe(false); }); }); describe('MIME type detection', () => { let testImages: AssetFragment[] = []; async function testMimeTypeOfAssetWithExt(ext: string, expectedMimeType: string) { const testImage = testImages.find(i => i.source.endsWith(ext))!; const result = await fetch(testImage.source); const contentType = result.headers.get('Content-Type'); expect(contentType).toBe(expectedMimeType); } beforeAll(async () => { const formats = ['gif', 'jpg', 'png', 'svg', 'tiff', 'webp']; const filesToUpload = formats.map(ext => path.join(__dirname, `fixtures/assets/test.${ext}`)); const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); testImages = createAssets as AssetFragment[]; }); it('gif', async () => { await testMimeTypeOfAssetWithExt('gif', 'image/gif'); }); it('jpg', async () => { await testMimeTypeOfAssetWithExt('jpg', 'image/jpeg'); }); it('png', async () => { await testMimeTypeOfAssetWithExt('png', 'image/png'); }); it('svg', async () => { await testMimeTypeOfAssetWithExt('svg', 'image/svg+xml'); }); it('tiff', async () => { await testMimeTypeOfAssetWithExt('tiff', 'image/tiff'); }); it('webp', async () => { await testMimeTypeOfAssetWithExt('webp', 'image/webp'); }); }); // https://github.com/vendure-ecommerce/vendure/issues/1563 it('falls back to binary preview if image file cannot be processed', async () => { const filesToUpload = [path.join(__dirname, 'fixtures/assets/bad-image.jpg')]; const { createAssets }: CreateAssets.Mutation = await adminClient.fileUploadMutation({ mutation: CREATE_ASSETS, filePaths: filesToUpload, mapVariables: filePaths => ({ input: filePaths.map(p => ({ file: null })), }), }); expect(createAssets.length).toBe(1); expect(createAssets[0].name).toBe('bad-image.jpg'); }); }); export const CREATE_ASSETS = gql` mutation CreateAssets($input: [CreateAssetInput!]!) { createAssets(input: $input) { ... on Asset { id name source preview focalPoint { x y } } } } `; export const DELETE_ASSET = gql` mutation DeleteAsset($input: DeleteAssetInput!) { deleteAsset(input: $input) { result } } `;
/* 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 CreateAssetsMutationVariables = Exact<{ input: Array<CreateAssetInput> | CreateAssetInput; }>; export type CreateAssetsMutation = { createAssets: Array<{ id: string, name: string, source: string, preview: string, focalPoint?: { x: number, y: number } | null } | {}> }; export type DeleteAssetMutationVariables = Exact<{ input: DeleteAssetInput; }>; export type DeleteAssetMutation = { deleteAsset: { result: DeletionResult } }; export const CreateAssetsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateAssets"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateAssetInput"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createAssets"},"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":"Asset"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"source"}},{"kind":"Field","name":{"kind":"Name","value":"preview"}},{"kind":"Field","name":{"kind":"Name","value":"focalPoint"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]}}]} as unknown as DocumentNode<CreateAssetsMutation, CreateAssetsMutationVariables>; export const DeleteAssetDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteAsset"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DeleteAssetInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteAsset"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"result"}}]}}]}}]} as unknown as DocumentNode<DeleteAssetMutation, DeleteAssetMutationVariables>;
import { REQUEST_CONTEXT_KEY } from '@vendure/core/dist/common/constants'; import { Request } from 'express'; import { AssetServerOptions, ImageTransformFormat } from './types'; export function getAssetUrlPrefixFn(options: AssetServerOptions) { const { assetUrlPrefix, route } = options; if (assetUrlPrefix == null) { return (request: Request, identifier: string) => { const protocol = request.headers['x-forwarded-proto'] ?? request.protocol; return `${Array.isArray(protocol) ? protocol[0] : protocol}://${ request.get('host') ?? 'could-not-determine-host' }/${route}/`; }; } if (typeof assetUrlPrefix === 'string') { return (...args: any[]) => assetUrlPrefix; } if (typeof assetUrlPrefix === 'function') { return (request: Request, identifier: string) => { const ctx = (request as any)[REQUEST_CONTEXT_KEY]; return assetUrlPrefix(ctx, identifier); }; } throw new Error(`The assetUrlPrefix option was of an unexpected type: ${JSON.stringify(assetUrlPrefix)}`); } export function getValidFormat(format?: unknown): ImageTransformFormat | undefined { if (typeof format !== 'string') { return undefined; } switch (format) { case 'jpg': case 'jpeg': case 'png': case 'webp': case 'avif': return format; default: return undefined; } }
export const loggerCtx = 'AssetServerPlugin'; export const DEFAULT_CACHE_HEADER = 'public, max-age=15552000';
import { Request } from 'express'; import { getAssetUrlPrefixFn } from './common'; import { LocalAssetStorageStrategy } from './local-asset-storage-strategy'; import { AssetServerOptions } from './types'; /** * By default the AssetServerPlugin will configure and use the LocalStorageStrategy to persist Assets. */ export function defaultAssetStorageStrategyFactory(options: AssetServerOptions) { const { assetUrlPrefix, assetUploadDir, route } = options; const prefixFn = getAssetUrlPrefixFn(options); const toAbsoluteUrlFn = (request: Request, identifier: string): string => { if (!identifier) { return ''; } const prefix = prefixFn(request, identifier); return identifier.startsWith(prefix) ? identifier : `${prefix}${identifier}`; }; return new LocalAssetStorageStrategy(assetUploadDir, toAbsoluteUrlFn); }
import { DefaultAssetNamingStrategy, RequestContext } from '@vendure/core'; import { createHash } from 'crypto'; import path from 'path'; /** * @description * An extension of the {@link DefaultAssetNamingStrategy} which prefixes file names with * the type (`'source'` or `'preview'`) as well as a 2-character sub-directory based on * the md5 hash of the original file name. * * This is an implementation of the technique knows as "hashed directory" file storage, * and the purpose is to reduce the number of files in a single directory, since a very large * number of files can lead to performance issues when reading and writing to that directory. * * With this strategy, even with 200,000 total assets stored, each directory would * only contain less than 800 files. * * @docsCategory core plugins/AssetServerPlugin */ export class HashedAssetNamingStrategy extends DefaultAssetNamingStrategy { generateSourceFileName(ctx: RequestContext, originalFileName: string, conflictFileName?: string): string { const filename = super.generateSourceFileName(ctx, originalFileName, conflictFileName); return path.join('source', this.getHashedDir(filename), filename); } generatePreviewFileName( ctx: RequestContext, originalFileName: string, conflictFileName?: string, ): string { const filename = super.generatePreviewFileName(ctx, originalFileName, conflictFileName); return path.join('preview', this.getHashedDir(filename), filename); } private getHashedDir(filename: string): string { return createHash('md5').update(filename).digest('hex').slice(0, 2); } }
import { AssetStorageStrategy } from '@vendure/core'; import { createHash } from 'crypto'; import { Request } from 'express'; import { ReadStream } from 'fs'; import fs from 'fs-extra'; import path from 'path'; import { Stream } from 'stream'; /** * @description * A persistence strategy which saves files to the local file system. * * @docsCategory core plugins/AssetServerPlugin */ export class LocalAssetStorageStrategy implements AssetStorageStrategy { toAbsoluteUrl: ((reqest: Request, identifier: string) => string) | undefined; constructor( private readonly uploadPath: string, private readonly toAbsoluteUrlFn?: (reqest: Request, identifier: string) => string, ) { fs.ensureDirSync(this.uploadPath); if (toAbsoluteUrlFn) { this.toAbsoluteUrl = toAbsoluteUrlFn; } } async writeFileFromStream(fileName: string, data: ReadStream): Promise<string> { const filePath = path.join(this.uploadPath, fileName); await fs.ensureDir(path.dirname(filePath)); const writeStream = fs.createWriteStream(filePath, 'binary'); return new Promise<string>((resolve, reject) => { data.pipe(writeStream); writeStream.on('close', () => resolve(this.filePathToIdentifier(filePath))); writeStream.on('error', reject); }); } async writeFileFromBuffer(fileName: string, data: Buffer): Promise<string> { const filePath = path.join(this.uploadPath, fileName); await fs.ensureDir(path.dirname(filePath)); await fs.writeFile(filePath, data, 'binary'); return this.filePathToIdentifier(filePath); } fileExists(fileName: string): Promise<boolean> { return new Promise(resolve => { fs.access(this.identifierToFilePath(fileName), fs.constants.F_OK, err => { resolve(!err); }); }); } readFileToBuffer(identifier: string): Promise<Buffer> { return fs.readFile(this.identifierToFilePath(identifier)); } readFileToStream(identifier: string): Promise<Stream> { const readStream = fs.createReadStream(this.identifierToFilePath(identifier), 'binary'); return Promise.resolve(readStream); } deleteFile(identifier: string): Promise<void> { return fs.unlink(this.identifierToFilePath(identifier)); } private filePathToIdentifier(filePath: string): string { const filePathDirname = path.dirname(filePath); const deltaDirname = filePathDirname.replace(this.uploadPath, ''); const identifier = path.join(deltaDirname, path.basename(filePath)); return identifier.replace(/^[\\/]+/, ''); } private identifierToFilePath(identifier: string): string { return path.join(this.uploadPath, identifier); } }
import { MiddlewareConsumer, NestModule, OnApplicationBootstrap } from '@nestjs/common'; import { Type } from '@vendure/common/lib/shared-types'; import { AssetStorageStrategy, Logger, PluginCommonModule, ProcessContext, registerPluginStartupMessage, RuntimeVendureConfig, VendurePlugin, } from '@vendure/core'; import { createHash } from 'crypto'; import express, { NextFunction, Request, Response } from 'express'; import fs from 'fs-extra'; import path from 'path'; import { getValidFormat } from './common'; import { DEFAULT_CACHE_HEADER, loggerCtx } from './constants'; import { defaultAssetStorageStrategyFactory } from './default-asset-storage-strategy-factory'; import { HashedAssetNamingStrategy } from './hashed-asset-naming-strategy'; import { SharpAssetPreviewStrategy } from './sharp-asset-preview-strategy'; import { transformImage } from './transform-image'; import { AssetServerOptions, ImageTransformPreset } from './types'; async function getFileType(buffer: Buffer) { const { fileTypeFromBuffer } = await import('file-type'); return fileTypeFromBuffer(buffer); } /** * @description * The `AssetServerPlugin` serves assets (images and other files) from the local file system, and can also be configured to use * other storage strategies (e.g. {@link S3AssetStorageStrategy}. It can also perform on-the-fly image transformations * and caches the results for subsequent calls. * * ## Installation * * `yarn add \@vendure/asset-server-plugin` * * or * * `npm install \@vendure/asset-server-plugin` * * @example * ```ts * import { AssetServerPlugin } from '\@vendure/asset-server-plugin'; * * const config: VendureConfig = { * // Add an instance of the plugin to the plugins array * plugins: [ * AssetServerPlugin.init({ * route: 'assets', * assetUploadDir: path.join(__dirname, 'assets'), * }), * ], * }; * ``` * * The full configuration is documented at [AssetServerOptions](/reference/core-plugins/asset-server-plugin/asset-server-options) * * ## Image transformation * * Asset preview images can be transformed (resized & cropped) on the fly by appending query parameters to the url: * * `http://localhost:3000/assets/some-asset.jpg?w=500&h=300&mode=resize` * * The above URL will return `some-asset.jpg`, resized to fit in the bounds of a 500px x 300px rectangle. * * ### Preview mode * * The `mode` parameter can be either `crop` or `resize`. See the [ImageTransformMode](/reference/core-plugins/asset-server-plugin/image-transform-mode) docs for details. * * ### Focal point * * When cropping an image (`mode=crop`), Vendure will attempt to keep the most "interesting" area of the image in the cropped frame. It does this * by finding the area of the image with highest entropy (the busiest area of the image). However, sometimes this does not yield a satisfactory * result - part or all of the main subject may still be cropped out. * * This is where specifying the focal point can help. The focal point of the image may be specified by passing the `fpx` and `fpy` query parameters. * These are normalized coordinates (i.e. a number between 0 and 1), so the `fpx=0&fpy=0` corresponds to the top left of the image. * * For example, let's say there is a very wide landscape image which we want to crop to be square. The main subject is a house to the far left of the * image. The following query would crop it to a square with the house centered: * * `http://localhost:3000/assets/landscape.jpg?w=150&h=150&mode=crop&fpx=0.2&fpy=0.7` * * ### Format * * Since v1.7.0, the image format can be specified by adding the `format` query parameter: * * `http://localhost:3000/assets/some-asset.jpg?format=webp` * * This means that, no matter the format of your original asset files, you can use more modern formats in your storefront if the browser * supports them. Supported values for `format` are: * * * `jpeg` or `jpg` * * `png` * * `webp` * * `avif` * * The `format` parameter can also be combined with presets (see below). * * ### Quality * * Since v2.2.0, the image quality can be specified by adding the `q` query parameter: * * `http://localhost:3000/assets/some-asset.jpg?q=75` * * This applies to the `jpg`, `webp` and `avif` formats. The default quality value for `jpg` and `webp` is 80, and for `avif` is 50. * * The `q` parameter can also be combined with presets (see below). * * ### Transform presets * * Presets can be defined which allow a single preset name to be used instead of specifying the width, height and mode. Presets are * configured via the AssetServerOptions [presets property](/reference/core-plugins/asset-server-plugin/asset-server-options/#presets). * * For example, defining the following preset: * * ```ts * AssetServerPlugin.init({ * // ... * presets: [ * { name: 'my-preset', width: 85, height: 85, mode: 'crop' }, * ], * }), * ``` * * means that a request to: * * `http://localhost:3000/assets/some-asset.jpg?preset=my-preset` * * is equivalent to: * * `http://localhost:3000/assets/some-asset.jpg?w=85&h=85&mode=crop` * * The AssetServerPlugin comes pre-configured with the following presets: * * name | width | height | mode * -----|-------|--------|----- * tiny | 50px | 50px | crop * thumb | 150px | 150px | crop * small | 300px | 300px | resize * medium | 500px | 500px | resize * large | 800px | 800px | resize * * ### Caching * By default, the AssetServerPlugin will cache every transformed image, so that the transformation only needs to be performed a single time for * a given configuration. Caching can be disabled per-request by setting the `?cache=false` query parameter. * * @docsCategory core plugins/AssetServerPlugin */ @VendurePlugin({ imports: [PluginCommonModule], configuration: config => AssetServerPlugin.configure(config), compatibility: '^2.0.0', }) export class AssetServerPlugin implements NestModule, OnApplicationBootstrap { private static assetStorage: AssetStorageStrategy; private readonly cacheDir = 'cache'; private presets: ImageTransformPreset[] = [ { name: 'tiny', width: 50, height: 50, mode: 'crop' }, { name: 'thumb', width: 150, height: 150, mode: 'crop' }, { name: 'small', width: 300, height: 300, mode: 'resize' }, { name: 'medium', width: 500, height: 500, mode: 'resize' }, { name: 'large', width: 800, height: 800, mode: 'resize' }, ]; private static options: AssetServerOptions; private cacheHeader: string; /** * @description * Set the plugin options. */ static init(options: AssetServerOptions): Type<AssetServerPlugin> { AssetServerPlugin.options = options; return this; } /** @internal */ static async configure(config: RuntimeVendureConfig) { const storageStrategyFactory = this.options.storageStrategyFactory || defaultAssetStorageStrategyFactory; this.assetStorage = await storageStrategyFactory(this.options); config.assetOptions.assetPreviewStrategy = this.options.previewStrategy ?? new SharpAssetPreviewStrategy({ maxWidth: this.options.previewMaxWidth, maxHeight: this.options.previewMaxHeight, }); config.assetOptions.assetStorageStrategy = this.assetStorage; config.assetOptions.assetNamingStrategy = this.options.namingStrategy || new HashedAssetNamingStrategy(); return config; } constructor(private processContext: ProcessContext) {} /** @internal */ onApplicationBootstrap(): void { if (this.processContext.isWorker) { return; } if (AssetServerPlugin.options.presets) { for (const preset of AssetServerPlugin.options.presets) { const existingIndex = this.presets.findIndex(p => p.name === preset.name); if (-1 < existingIndex) { this.presets.splice(existingIndex, 1, preset); } else { this.presets.push(preset); } } } // Configure Cache-Control header const { cacheHeader } = AssetServerPlugin.options; if (!cacheHeader) { this.cacheHeader = DEFAULT_CACHE_HEADER; } else { if (typeof cacheHeader === 'string') { this.cacheHeader = cacheHeader; } else { this.cacheHeader = [cacheHeader.restriction, `max-age: ${cacheHeader.maxAge}`] .filter(value => !!value) .join(', '); } } const cachePath = path.join(AssetServerPlugin.options.assetUploadDir, this.cacheDir); fs.ensureDirSync(cachePath); } configure(consumer: MiddlewareConsumer) { if (this.processContext.isWorker) { return; } Logger.info('Creating asset server middleware', loggerCtx); consumer.apply(this.createAssetServer()).forRoutes(AssetServerPlugin.options.route); registerPluginStartupMessage('Asset server', AssetServerPlugin.options.route); } /** * Creates the image server instance */ private createAssetServer() { const assetServer = express.Router(); assetServer.use(this.sendAsset(), this.generateTransformedImage()); return assetServer; } /** * Reads the file requested and send the response to the browser. */ private sendAsset() { return async (req: Request, res: Response, next: NextFunction) => { const key = this.getFileNameFromRequest(req); try { const file = await AssetServerPlugin.assetStorage.readFileToBuffer(key); let mimeType = this.getMimeType(key); if (!mimeType) { mimeType = (await getFileType(file))?.mime || 'application/octet-stream'; } res.contentType(mimeType); res.setHeader('content-security-policy', "default-src 'self'"); res.setHeader('Cache-Control', this.cacheHeader); res.send(file); } catch (e: any) { const err = new Error('File not found'); (err as any).status = 404; return next(err); } }; } /** * If an exception was thrown by the first handler, then it may be because a transformed image * is being requested which does not yet exist. In this case, this handler will generate the * transformed image, save it to cache, and serve the result as a response. */ private generateTransformedImage() { return async (err: any, req: Request, res: Response, next: NextFunction) => { if (err && (err.status === 404 || err.statusCode === 404)) { if (req.query) { const decodedReqPath = decodeURIComponent(req.path); Logger.debug(`Pre-cached Asset not found: ${decodedReqPath}`, loggerCtx); let file: Buffer; try { file = await AssetServerPlugin.assetStorage.readFileToBuffer(decodedReqPath); } catch (_err: any) { res.status(404).send('Resource not found'); return; } const image = await transformImage(file, req.query as any, this.presets || []); try { const imageBuffer = await image.toBuffer(); const cachedFileName = this.getFileNameFromRequest(req); if (!req.query.cache || req.query.cache === 'true') { await AssetServerPlugin.assetStorage.writeFileFromBuffer( cachedFileName, imageBuffer, ); Logger.debug(`Saved cached asset: ${cachedFileName}`, loggerCtx); } let mimeType = this.getMimeType(cachedFileName); if (!mimeType) { mimeType = (await getFileType(imageBuffer))?.mime || 'image/jpeg'; } res.set('Content-Type', mimeType); res.setHeader('content-security-policy', "default-src 'self'"); res.send(imageBuffer); return; } catch (e: any) { Logger.error(e, loggerCtx, e.stack); res.status(500).send(e.message); return; } } } next(); }; } private getFileNameFromRequest(req: Request): string { const { w, h, mode, preset, fpx, fpy, format, q } = req.query; /* eslint-disable @typescript-eslint/restrict-template-expressions */ const focalPoint = fpx && fpy ? `_fpx${fpx}_fpy${fpy}` : ''; const quality = q ? `_q${q}` : ''; const imageFormat = getValidFormat(format); let imageParamsString = ''; if (w || h) { const width = w || ''; const height = h || ''; imageParamsString = `_transform_w${width}_h${height}_m${mode}`; } else if (preset) { if (this.presets && !!this.presets.find(p => p.name === preset)) { imageParamsString = `_transform_pre_${preset}`; } } if (focalPoint) { imageParamsString += focalPoint; } if (imageFormat) { imageParamsString += imageFormat; } if (quality) { imageParamsString += quality; } /* eslint-enable @typescript-eslint/restrict-template-expressions */ const decodedReqPath = decodeURIComponent(req.path); if (imageParamsString !== '') { const imageParamHash = this.md5(imageParamsString); return path.join(this.cacheDir, this.addSuffix(decodedReqPath, imageParamHash, imageFormat)); } else { return decodedReqPath; } } private md5(input: string): string { return createHash('md5').update(input).digest('hex'); } private addSuffix(fileName: string, suffix: string, ext?: string): string { const originalExt = path.extname(fileName); const effectiveExt = ext ? `.${ext}` : originalExt; const baseName = path.basename(fileName, originalExt); const dirName = path.dirname(fileName); return path.join(dirName, `${baseName}${suffix}${effectiveExt}`); } /** * Attempt to get the mime type from the file name. */ private getMimeType(fileName: string): string | undefined { const ext = path.extname(fileName); switch (ext) { case '.jpg': case '.jpeg': return 'image/jpeg'; case '.png': return 'image/png'; case '.gif': return 'image/gif'; case '.svg': return 'image/svg+xml'; case '.tiff': return 'image/tiff'; case '.webp': return 'image/webp'; } } }
import { PutObjectRequest, S3ClientConfig } from '@aws-sdk/client-s3'; import { AwsCredentialIdentity, AwsCredentialIdentityProvider } from '@aws-sdk/types'; import { AssetStorageStrategy, Logger } from '@vendure/core'; import { Request } from 'express'; import * as path from 'node:path'; import { Readable } from 'node:stream'; import { getAssetUrlPrefixFn } from './common'; import { loggerCtx } from './constants'; import { AssetServerOptions } from './types'; /** * @description * Configuration for connecting to AWS S3. * * @docsCategory core plugins/AssetServerPlugin * @docsPage S3AssetStorageStrategy */ export interface S3Config { /** * @description * The credentials used to access your s3 account. You can supply either the access key ID & secret, or you can make use of a * [shared credentials file](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html) * To use a shared credentials file, import the `fromIni()` function from the "@aws-sdk/credential-provider-ini" or "@aws-sdk/credential-providers" package and supply * the profile name (e.g. `{ profile: 'default' }`) as its argument. */ credentials: AwsCredentialIdentity | AwsCredentialIdentityProvider; /** * @description * The S3 bucket in which to store the assets. If it does not exist, it will be created on startup. */ bucket: string; /** * @description * Configuration object passed directly to the AWS SDK. * S3.Types.ClientConfiguration can be used after importing aws-sdk. * Using type `any` in order to avoid the need to include `aws-sdk` dependency in general. */ nativeS3Configuration?: any; /** * @description * Configuration object passed directly to the AWS SDK. * ManagedUpload.ManagedUploadOptions can be used after importing aws-sdk. * Using type `any` in order to avoid the need to include `aws-sdk` dependency in general. */ nativeS3UploadConfiguration?: any; } /** * @description * Returns a configured instance of the {@link S3AssetStorageStrategy} which can then be passed to the {@link AssetServerOptions} * `storageStrategyFactory` property. * * Before using this strategy, make sure you have the `@aws-sdk/client-s3` and `@aws-sdk/lib-storage` package installed: * * ```sh * npm install \@aws-sdk/client-s3 \@aws-sdk/lib-storage * ``` * * @example * ```ts * import { AssetServerPlugin, configureS3AssetStorage } from '\@vendure/asset-server-plugin'; * import { DefaultAssetNamingStrategy } from '\@vendure/core'; * import { fromEnv } from '\@aws-sdk/credential-providers'; * * // ... * * plugins: [ * AssetServerPlugin.init({ * route: 'assets', * assetUploadDir: path.join(__dirname, 'assets'), * namingStrategy: new DefaultAssetNamingStrategy(), * storageStrategyFactory: configureS3AssetStorage({ * bucket: 'my-s3-bucket', * credentials: fromEnv(), // or any other credential provider * nativeS3Configuration: { * region: process.env.AWS_REGION, * }, * }), * }), * ``` * * ## Usage with MinIO * * Reference: [How to use AWS SDK for Javascript with MinIO Server](https://docs.min.io/docs/how-to-use-aws-sdk-for-javascript-with-minio-server.html) * * @example * ```ts * import { AssetServerPlugin, configureS3AssetStorage } from '\@vendure/asset-server-plugin'; * import { DefaultAssetNamingStrategy } from '\@vendure/core'; * * // ... * * plugins: [ * AssetServerPlugin.init({ * route: 'assets', * assetUploadDir: path.join(__dirname, 'assets'), * namingStrategy: new DefaultAssetNamingStrategy(), * storageStrategyFactory: configureS3AssetStorage({ * bucket: 'my-minio-bucket', * credentials: { * accessKeyId: process.env.MINIO_ACCESS_KEY_ID, * secretAccessKey: process.env.MINIO_SECRET_ACCESS_KEY, * }, * nativeS3Configuration: { * endpoint: process.env.MINIO_ENDPOINT ?? 'http://localhost:9000', * forcePathStyle: true, * signatureVersion: 'v4', * // The `region` is required by the AWS SDK even when using MinIO, * // so we just use a dummy value here. * region: 'eu-west-1', * }, * }), * }), * ``` * @docsCategory core plugins/AssetServerPlugin * @docsPage S3AssetStorageStrategy */ export function configureS3AssetStorage(s3Config: S3Config) { return (options: AssetServerOptions) => { const prefixFn = getAssetUrlPrefixFn(options); const toAbsoluteUrlFn = (request: Request, identifier: string): string => { if (!identifier) { return ''; } const prefix = prefixFn(request, identifier); return identifier.startsWith(prefix) ? identifier : `${prefix}${identifier}`; }; return new S3AssetStorageStrategy(s3Config, toAbsoluteUrlFn); }; } /** * @description * An {@link AssetStorageStrategy} which uses [Amazon S3](https://aws.amazon.com/s3/) object storage service. * To us this strategy you must first have access to an AWS account. * See their [getting started guide](https://aws.amazon.com/s3/getting-started/) for how to get set up. * * Before using this strategy, make sure you have the `@aws-sdk/client-s3` and `@aws-sdk/lib-storage` package installed: * * ```sh * npm install \@aws-sdk/client-s3 \@aws-sdk/lib-storage * ``` * * **Note:** Rather than instantiating this manually, use the {@link configureS3AssetStorage} function. * * ## Use with S3-compatible services (MinIO) * This strategy will also work with any S3-compatible object storage solutions, such as [MinIO](https://min.io/). * See the {@link configureS3AssetStorage} for an example with MinIO. * * @docsCategory asset-server-plugin * @docsPage S3AssetStorageStrategy * @docsWeight 0 */ export class S3AssetStorageStrategy implements AssetStorageStrategy { private AWS: typeof import('@aws-sdk/client-s3'); private libStorage: typeof import('@aws-sdk/lib-storage'); private s3Client: import('@aws-sdk/client-s3').S3Client; constructor( private s3Config: S3Config, public readonly toAbsoluteUrl: (request: Request, identifier: string) => string, ) {} async init() { try { this.AWS = await import('@aws-sdk/client-s3'); } catch (err: any) { Logger.error( 'Could not find the "@aws-sdk/client-s3" package. Make sure it is installed', loggerCtx, err.stack, ); } try { this.libStorage = await import('@aws-sdk/lib-storage'); } catch (err: any) { Logger.error( 'Could not find the "@aws-sdk/lib-storage" package. Make sure it is installed', loggerCtx, err.stack, ); } const config = { ...this.s3Config.nativeS3Configuration, credentials: await this.getCredentials(), // Avoid credentials overriden by nativeS3Configuration } satisfies S3ClientConfig; this.s3Client = new this.AWS.S3Client(config); await this.ensureBucket(); } destroy?: (() => void | Promise<void>) | undefined; async writeFileFromBuffer(fileName: string, data: Buffer) { return this.writeFile(fileName, data); } async writeFileFromStream(fileName: string, data: Readable) { return this.writeFile(fileName, data); } async readFileToBuffer(identifier: string) { const body = await this.readFile(identifier); if (!body) { Logger.error(`Got undefined Body for ${identifier}`, loggerCtx); return Buffer.from(''); } const chunks: Buffer[] = []; for await (const chunk of body) { chunks.push(chunk); } return Buffer.concat(chunks); } async readFileToStream(identifier: string) { const body = await this.readFile(identifier); if (!body) { return new Readable({ read() { this.push(null); }, }); } return body; } private async readFile(identifier: string) { const { GetObjectCommand } = this.AWS; const result = await this.s3Client.send(new GetObjectCommand(this.getObjectParams(identifier))); return result.Body as Readable | undefined; } private async writeFile(fileName: string, data: PutObjectRequest['Body'] | string | Uint8Array | Buffer) { const { Upload } = this.libStorage; const upload = new Upload({ client: this.s3Client, params: { ...this.s3Config.nativeS3UploadConfiguration, Bucket: this.s3Config.bucket, Key: fileName, Body: data, }, }); return upload.done().then(result => { if (!('Key' in result) || !result.Key) { Logger.error(`Got undefined Key for ${fileName}`, loggerCtx); throw new Error(`Got undefined Key for ${fileName}`); } return result.Key; }); } async deleteFile(identifier: string) { const { DeleteObjectCommand } = this.AWS; await this.s3Client.send(new DeleteObjectCommand(this.getObjectParams(identifier))); } async fileExists(fileName: string) { const { HeadObjectCommand } = this.AWS; try { await this.s3Client.send(new HeadObjectCommand(this.getObjectParams(fileName))); return true; } catch (err: any) { return false; } } private getObjectParams(identifier: string) { return { Bucket: this.s3Config.bucket, Key: path.join(identifier.replace(/^\//, '')), }; } private async ensureBucket(bucket = this.s3Config.bucket) { const { HeadBucketCommand, CreateBucketCommand } = this.AWS; try { await this.s3Client.send(new HeadBucketCommand({ Bucket: bucket })); Logger.verbose(`Found S3 bucket "${bucket}"`, loggerCtx); return; } catch (err: any) { Logger.verbose( `Could not find bucket "${bucket}: ${JSON.stringify(err.message)}". Attempting to create...`, ); } try { await this.s3Client.send(new CreateBucketCommand({ Bucket: bucket, ACL: 'private' })); Logger.verbose(`Created S3 bucket "${bucket}"`, loggerCtx); } catch (err: any) { Logger.error( `Could not find nor create the S3 bucket "${bucket}: ${JSON.stringify(err.message)}"`, loggerCtx, err.stack, ); } } private async getCredentials() { if (this.s3Config.credentials == null) { return undefined; } if (this.isCredentialsProfile(this.s3Config.credentials)) { Logger.warn( 'The "profile" property of the "s3Config.credentials" is deprecated. ' + 'Please use the "fromIni()" function from the "@aws-sdk/credential-provider-ini" or "@aws-sdk/credential-providers" package instead.', loggerCtx, ); return (await import('@aws-sdk/credential-provider-ini')).fromIni({ profile: this.s3Config.credentials.profile, }); } return this.s3Config.credentials; } private isCredentialsProfile( credentials: AwsCredentialIdentity | AwsCredentialIdentityProvider, ): credentials is AwsCredentialIdentity & { profile: string } { return ( credentials !== null && typeof credentials === 'object' && 'profile' in credentials && Object.keys(credentials).length === 1 ); } }
import { AssetType } from '@vendure/common/lib/generated-types'; import { AssetPreviewStrategy, getAssetType, Logger, RequestContext } from '@vendure/core'; import path from 'path'; import sharp from 'sharp'; import { loggerCtx } from './constants'; /** * @description * This {@link AssetPreviewStrategy} uses the [Sharp library](https://sharp.pixelplumbing.com/) to generate * preview images of uploaded binary files. For non-image binaries, a generic "file" icon with the mime type * overlay will be generated. * * @docsCategory core plugins/AssetServerPlugin * @docsPage SharpAssetPreviewStrategy */ interface SharpAssetPreviewConfig { /** * @description * The max height in pixels of a generated preview image. * * @default 1600 */ maxHeight?: number; /** * @description * The max width in pixels of a generated preview image. * * @default 1600 */ maxWidth?: number; /** * @description * Set Sharp's options for encoding jpeg files: https://sharp.pixelplumbing.com/api-output#jpeg * * @since 1.7.0 */ jpegOptions?: sharp.JpegOptions; /** * @description * Set Sharp's options for encoding png files: https://sharp.pixelplumbing.com/api-output#png * * @since 1.7.0 */ pngOptions?: sharp.PngOptions; /** * @description * Set Sharp's options for encoding webp files: https://sharp.pixelplumbing.com/api-output#webp * * @since 1.7.0 */ webpOptions?: sharp.WebpOptions; /** * @description * Set Sharp's options for encoding gif files: https://sharp.pixelplumbing.com/api-output#gif * * @since 1.7.0 */ gifOptions?: sharp.GifOptions; /** * @description * Set Sharp's options for encoding avif files: https://sharp.pixelplumbing.com/api-output#avif * * @since 1.7.0 */ avifOptions?: sharp.AvifOptions; } /** * @description * This {@link AssetPreviewStrategy} uses the [Sharp library](https://sharp.pixelplumbing.com/) to generate * preview images of uploaded binary files. For non-image binaries, a generic "file" icon with the mime type * overlay will be generated. * * By default, this strategy will produce previews up to maximum dimensions of 1600 x 1600 pixels. The created * preview images will match the input format - so a source file in jpeg format will output a jpeg preview, * a webp source file will output a webp preview, and so on. * * The settings for the outputs will default to Sharp's defaults (https://sharp.pixelplumbing.com/api-output). * However, it is possible to pass your own configurations to control the output of each format: * * ```ts * AssetServerPlugin.init({ * previewStrategy: new SharpAssetPreviewStrategy({ * jpegOptions: { quality: 95 }, * webpOptions: { quality: 95 }, * }), * }), * ``` * * @docsCategory core plugins/AssetServerPlugin * @docsPage SharpAssetPreviewStrategy * @docsWeight 0 */ export class SharpAssetPreviewStrategy implements AssetPreviewStrategy { private readonly defaultConfig: Required<SharpAssetPreviewConfig> = { maxHeight: 1600, maxWidth: 1600, jpegOptions: {}, pngOptions: {}, webpOptions: {}, gifOptions: {}, avifOptions: {}, }; private readonly config: Required<SharpAssetPreviewConfig>; constructor(config?: SharpAssetPreviewConfig) { this.config = { ...this.defaultConfig, ...(config ?? {}), }; } async generatePreviewImage(ctx: RequestContext, mimeType: string, data: Buffer): Promise<Buffer> { const assetType = getAssetType(mimeType); const { maxWidth, maxHeight } = this.config; if (assetType === AssetType.IMAGE) { try { const image = sharp(data, { failOn: 'truncated' }).rotate(); const metadata = await image.metadata(); const width = metadata.width || 0; const height = metadata.height || 0; if (maxWidth < width || maxHeight < height) { image.resize(maxWidth, maxHeight, { fit: 'inside' }); } if (mimeType === 'image/svg+xml') { // Convert the SVG to a raster for the preview return image.toBuffer(); } else { switch (metadata.format) { case 'jpeg': case 'jpg': return image.jpeg(this.config.jpegOptions).toBuffer(); case 'png': return image.png(this.config.pngOptions).toBuffer(); case 'webp': return image.webp(this.config.webpOptions).toBuffer(); case 'gif': return image.gif(this.config.jpegOptions).toBuffer(); case 'avif': return image.avif(this.config.avifOptions).toBuffer(); default: return image.toBuffer(); } } } catch (err: any) { Logger.error( `An error occurred when generating preview for image with mimeType ${mimeType}: ${JSON.stringify( err.message, )}`, loggerCtx, ); return this.generateBinaryFilePreview(mimeType); } } else { return this.generateBinaryFilePreview(mimeType); } } private generateMimeTypeOverlay(mimeType: string): Buffer { return Buffer.from(` <svg xmlns="http://www.w3.org/2000/svg" height="150" width="800"> <style> text { font-size: 64px; font-family: Arial, sans-serif; fill: #666; } </style> <text x="400" y="110" text-anchor="middle" width="800">${mimeType}</text> </svg>`); } private generateBinaryFilePreview(mimeType: string): Promise<Buffer> { return sharp(path.join(__dirname, 'file-icon.png')) .resize(800, 800, { fit: 'outside' }) .composite([ { input: this.generateMimeTypeOverlay(mimeType), gravity: sharp.gravity.center, }, ]) .toBuffer(); } }
import { describe, expect, it } from 'vitest'; import { Dimensions, Point, resizeToFocalPoint } from './transform-image'; describe('resizeToFocalPoint', () => { it('no resize, crop left', () => { const original: Dimensions = { w: 200, h: 100 }; const target: Dimensions = { w: 100, h: 100 }; const focalPoint: Point = { x: 50, y: 50 }; const result = resizeToFocalPoint(original, target, focalPoint); expect(result.width).toBe(200); expect(result.height).toBe(100); expect(result.region).toEqual({ left: 0, top: 0, width: 100, height: 100, }); }); it('no resize, crop top left', () => { const original: Dimensions = { w: 200, h: 100 }; const target: Dimensions = { w: 100, h: 100 }; const focalPoint: Point = { x: 0, y: 0 }; const result = resizeToFocalPoint(original, target, focalPoint); expect(result.width).toBe(200); expect(result.height).toBe(100); expect(result.region).toEqual({ left: 0, top: 0, width: 100, height: 100, }); }); it('no resize, crop center', () => { const original: Dimensions = { w: 200, h: 100 }; const target: Dimensions = { w: 100, h: 100 }; const focalPoint: Point = { x: 100, y: 50 }; const result = resizeToFocalPoint(original, target, focalPoint); expect(result.width).toBe(200); expect(result.height).toBe(100); expect(result.region).toEqual({ left: 50, top: 0, width: 100, height: 100, }); }); it('crop with resize', () => { const original: Dimensions = { w: 200, h: 100 }; const target: Dimensions = { w: 25, h: 50 }; const focalPoint: Point = { x: 50, y: 50 }; const result = resizeToFocalPoint(original, target, focalPoint); expect(result.width).toBe(100); expect(result.height).toBe(50); expect(result.region).toEqual({ left: 13, top: 0, width: 25, height: 50, }); }); });
import { Logger } from '@vendure/core'; import sharp, { FormatEnum, Region, ResizeOptions } from 'sharp'; import { getValidFormat } from './common'; import { loggerCtx } from './constants'; import { ImageTransformFormat, ImageTransformPreset } from './types'; export type Dimensions = { w: number; h: number }; export type Point = { x: number; y: number }; /** * Applies transforms to the given image according to the query params passed. */ export async function transformImage( originalImage: Buffer, queryParams: Record<string, string>, presets: ImageTransformPreset[], ): Promise<sharp.Sharp> { let targetWidth = Math.round(+queryParams.w) || undefined; let targetHeight = Math.round(+queryParams.h) || undefined; const quality = queryParams.q != null ? Math.round(Math.max(Math.min(+queryParams.q, 100), 1)) : undefined; let mode = queryParams.mode || 'crop'; const fpx = +queryParams.fpx || undefined; const fpy = +queryParams.fpy || undefined; const imageFormat = getValidFormat(queryParams.format); if (queryParams.preset) { const matchingPreset = presets.find(p => p.name === queryParams.preset); if (matchingPreset) { targetWidth = matchingPreset.width; targetHeight = matchingPreset.height; mode = matchingPreset.mode; } } const options: ResizeOptions = {}; if (mode === 'crop') { options.position = sharp.strategy.entropy; } else { options.fit = 'inside'; } const image = sharp(originalImage); try { await applyFormat(image, imageFormat, quality); } catch (e: any) { Logger.error(e.message, loggerCtx, e.stack); } if (fpx && fpy && targetWidth && targetHeight && mode === 'crop') { const metadata = await image.metadata(); if (metadata.width && metadata.height) { const xCenter = fpx * metadata.width; const yCenter = fpy * metadata.height; const { width, height, region } = resizeToFocalPoint( { w: metadata.width, h: metadata.height }, { w: targetWidth, h: targetHeight }, { x: xCenter, y: yCenter }, ); return image.resize(width, height).extract(region); } } return image.resize(targetWidth, targetHeight, options); } async function applyFormat( image: sharp.Sharp, format: ImageTransformFormat | undefined, quality: number | undefined, ) { switch (format) { case 'jpg': case 'jpeg': return image.jpeg({ quality }); case 'png': return image.png(); case 'webp': return image.webp({ quality }); case 'avif': return image.avif({ quality }); default: { if (quality) { // If a quality has been specified but no format, we need to determine the format from the image // and apply the quality to that format. const metadata = await image.metadata(); if (isImageTransformFormat(metadata.format)) { return applyFormat(image, metadata.format, quality); } } return image; } } } function isImageTransformFormat(input: keyof FormatEnum | undefined): input is ImageTransformFormat { return !!input && ['jpg', 'jpeg', 'webp', 'avif'].includes(input); } /** * Resize an image but keep it centered on the focal point. * Based on the method outlined in https://github.com/lovell/sharp/issues/1198#issuecomment-384591756 */ export function resizeToFocalPoint( original: Dimensions, target: Dimensions, focalPoint: Point, ): { width: number; height: number; region: Region } { const { width, height, factor } = getIntermediateDimensions(original, target); const region = getExtractionRegion(factor, focalPoint, target, { w: width, h: height }); return { width, height, region }; } /** * Calculates the dimensions of the intermediate (resized) image. */ function getIntermediateDimensions( original: Dimensions, target: Dimensions, ): { width: number; height: number; factor: number } { const hRatio = original.h / target.h; const wRatio = original.w / target.w; let factor: number; let width: number; let height: number; if (hRatio < wRatio) { factor = hRatio; height = Math.round(target.h); width = Math.round(original.w / factor); } else { factor = wRatio; width = Math.round(target.w); height = Math.round(original.h / factor); } return { width, height, factor }; } /** * Calculates the Region to extract from the intermediate image. */ function getExtractionRegion( factor: number, focalPoint: Point, target: Dimensions, intermediate: Dimensions, ): Region { const newXCenter = focalPoint.x / factor; const newYCenter = focalPoint.y / factor; const region: Region = { left: 0, top: 0, width: target.w, height: target.h, }; if (intermediate.h < intermediate.w) { region.left = clamp(0, intermediate.w - target.w, Math.round(newXCenter - target.w / 2)); } else { region.top = clamp(0, intermediate.h - target.h, Math.round(newYCenter - target.h / 2)); } return region; } /** * Limit the input value to the specified min and max values. */ function clamp(min: number, max: number, input: number) { return Math.min(Math.max(min, input), max); }
import { AssetNamingStrategy, AssetPreviewStrategy, AssetStorageStrategy, RequestContext, } from '@vendure/core'; export type ImageTransformFormat = 'jpg' | 'jpeg' | 'png' | 'webp' | 'avif'; /** * @description * Specifies the way in which an asset preview image will be resized to fit in the * proscribed dimensions: * * * crop: crops the image to cover both provided dimensions * * resize: Preserving aspect ratio, resizes the image to be as large as possible * while ensuring its dimensions are less than or equal to both those specified. * * @docsCategory core plugins/AssetServerPlugin */ export type ImageTransformMode = 'crop' | 'resize'; /** * @description * A configuration option for an image size preset for the AssetServerPlugin. * * Presets allow a shorthand way to generate a thumbnail preview of an asset. For example, * the built-in "tiny" preset generates a 50px x 50px cropped preview, which can be accessed * by appending the string `preset=tiny` to the asset url: * * `http://localhost:3000/assets/some-asset.jpg?preset=tiny` * * is equivalent to: * * `http://localhost:3000/assets/some-asset.jpg?w=50&h=50&mode=crop` * * @docsCategory core plugins/AssetServerPlugin */ export interface ImageTransformPreset { name: string; width: number; height: number; mode: ImageTransformMode; } /** * @description * A configuration option for the Cache-Control header in the AssetServerPlugin asset response. * * @docsCategory core plugins/AssetServerPlugin */ export type CacheConfig = { /** * @description * The max-age=N response directive indicates that the response remains fresh until N seconds after the response is generated. */ maxAge: number; /** * @description * The `private` response directive indicates that the response can be stored only in a private cache (e.g. local caches in browsers). * The `public` response directive indicates that the response can be stored in a shared cache. */ restriction?: 'public' | 'private'; }; /** * @description * The configuration options for the AssetServerPlugin. * * @docsCategory core plugins/AssetServerPlugin */ export interface AssetServerOptions { /** * @description * The route to the asset server. */ route: string; /** * @description * The local directory to which assets will be uploaded when using the {@link LocalAssetStorageStrategy}. */ assetUploadDir: string; // TODO: this is strategy-specific and should be moved out of the global options /** * @description * The complete URL prefix of the asset files. For example, "https://demo.vendure.io/assets/". A * function can also be provided to handle more complex cases, such as serving multiple domains * from a single server. In this case, the function should return a string url prefix. * * If not provided, the plugin will attempt to guess based off the incoming * request and the configured route. However, in all but the simplest cases, * this guess may not yield correct results. */ assetUrlPrefix?: string | ((ctx: RequestContext, identifier: string) => string); /** * @description * The max width in pixels of a generated preview image. * * @default 1600 * @deprecated Use `previewStrategy: new SharpAssetPreviewStrategy({ maxWidth })` instead */ previewMaxWidth?: number; /** * @description * The max height in pixels of a generated preview image. * * @default 1600 * @deprecated Use `previewStrategy: new SharpAssetPreviewStrategy({ maxHeight })` instead */ previewMaxHeight?: number; /** * @description * An array of additional {@link ImageTransformPreset} objects. */ presets?: ImageTransformPreset[]; /** * @description * Defines how asset files and preview images are named before being saved. * * @default HashedAssetNamingStrategy */ namingStrategy?: AssetNamingStrategy; /** * @description * Defines how previews are generated for a given Asset binary. By default, this uses * the {@link SharpAssetPreviewStrategy} * * @since 1.7.0 */ previewStrategy?: AssetPreviewStrategy; /** * @description * A function which can be used to configure an {@link AssetStorageStrategy}. This is useful e.g. if you wish to store your assets * using a cloud storage provider. By default, the {@link LocalAssetStorageStrategy} is used. * * @default () => LocalAssetStorageStrategy */ storageStrategyFactory?: ( options: AssetServerOptions, ) => AssetStorageStrategy | Promise<AssetStorageStrategy>; /** * @description * Configures the `Cache-Control` directive for response to control caching in browsers and shared caches (e.g. Proxies, CDNs). * Defaults to publicly cached for 6 months. * * @default 'public, max-age=15552000' * @since 1.9.3 */ cacheHeader?: CacheConfig | string; }
import fs from 'fs-extra'; import path from 'path'; // This build script copies all .template.ts files from the "src" directory to the "dist" directory. // This is necessary because the .template.ts files are used to generate the actual source files. const templateFiles = findFilesWithSuffix(path.join(__dirname, 'src'), '.template.ts'); for (const file of templateFiles) { // copy to the equivalent path in the "dist" rather than "src" directory const relativePath = path.relative(path.join(__dirname, 'src'), file); const distPath = path.join(__dirname, 'dist', relativePath); fs.ensureDirSync(path.dirname(distPath)); fs.copyFileSync(file, distPath); } function findFilesWithSuffix(directory: string, suffix: string): string[] { const files: string[] = []; function traverseDirectory(dir: string) { const dirContents = fs.readdirSync(dir); dirContents.forEach(item => { const itemPath = path.join(dir, item); const stats = fs.statSync(itemPath); if (stats.isDirectory()) { traverseDirectory(itemPath); } else { if (item.endsWith(suffix)) { files.push(itemPath); } } }); } traverseDirectory(directory); return files; }
// This file is for any 3rd party JS libs which don't have a corresponding @types/ package. declare module 'opn' { declare const opn: (path: string) => Promise<any>; export default opn; } declare module 'i18next-icu' { // default } declare module 'i18next-fs-backend' { // default }
#! /usr/bin/env node import { Command } from 'commander'; import pc from 'picocolors'; const program = new Command(); // eslint-disable-next-line @typescript-eslint/no-var-requires const version = require('../package.json').version; program .version(version) .usage(`vendure <command>`) .description( pc.blue(` 888 888 888 888 888 .d88b. 88888b. .d88888 888 888 888d888 .d88b. 888 888 d8P Y8b 888 "88b d88" 888 888 888 888P" d8P Y8b Y88 88P 88888888 888 888 888 888 888 888 888 88888888 Y8bd8P Y8b. 888 888 Y88b 888 Y88b 888 888 Y8b. Y88P "Y8888 888 888 "Y88888 "Y88888 888 "Y8888 `), ); program .command('add') .description('Add a feature to your Vendure project') .action(async () => { const { addCommand } = await import('./commands/add/add'); await addCommand(); process.exit(0); }); program .command('migrate') .description('Generate, run or revert a database migration') .action(async () => { const { migrateCommand } = await import('./commands/migrate/migrate'); await migrateCommand(); process.exit(0); }); void program.parseAsync(process.argv);
import { ManipulationSettings, QuoteKind } from 'ts-morph'; export const defaultManipulationSettings: Partial<ManipulationSettings> = { quoteKind: QuoteKind.Single, useTrailingCommas: true, }; export const pascalCaseRegex = /^[A-Z][a-zA-Z0-9]*$/; export const AdminUiExtensionTypeName = 'AdminUiExtension'; export const AdminUiAppConfigName = 'AdminUiAppConfig'; export const Messages = { NoPluginsFound: `No plugins were found in this project. Create a plugin first by selecting "[Plugin] Create a new Vendure plugin"`, NoEntitiesFound: `No entities were found in this plugin.`, NoServicesFound: `No services were found in this plugin. Create a service first by selecting "[Plugin: Service] Add a new service to a plugin"`, };