content
stringlengths
28
1.34M
import { Component, isDevMode, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { EMPTY, Observable } from 'rxjs'; import { map, switchMap, take } from 'rxjs/operators'; import { getAppConfig } from '../../app.config'; import { LanguageCode } from '../../common/generated-types'; import { ADMIN_UI_VERSION } from '../../common/version'; import { DataService } from '../../data/providers/data.service'; import { AuthService } from '../../providers/auth/auth.service'; import { BreadcrumbService } from '../../providers/breadcrumb/breadcrumb.service'; import { I18nService } from '../../providers/i18n/i18n.service'; import { LocalStorageService } from '../../providers/local-storage/local-storage.service'; import { ModalService } from '../../providers/modal/modal.service'; import { UiLanguageSwitcherDialogComponent } from '../ui-language-switcher-dialog/ui-language-switcher-dialog.component'; import { LocalizationDirectionType, LocalizationLanguageCodeType, LocalizationService, } from '../../providers/localization/localization.service'; @Component({ selector: 'vdr-app-shell', templateUrl: './app-shell.component.html', styleUrls: ['./app-shell.component.scss'], }) export class AppShellComponent implements OnInit { version = ADMIN_UI_VERSION; userName$: Observable<string>; uiLanguageAndLocale$: LocalizationLanguageCodeType; direction$: LocalizationDirectionType; availableLanguages: LanguageCode[] = []; availableLocales: string[] = []; hideVendureBranding = getAppConfig().hideVendureBranding; hideVersion = getAppConfig().hideVersion; pageTitle$: Observable<string>; mainNavExpanded$: Observable<boolean>; devMode = isDevMode(); constructor( private authService: AuthService, private dataService: DataService, private router: Router, private i18nService: I18nService, private modalService: ModalService, private localStorageService: LocalStorageService, private breadcrumbService: BreadcrumbService, private localizationService: LocalizationService, ) {} ngOnInit() { this.direction$ = this.localizationService.direction$; this.uiLanguageAndLocale$ = this.localizationService.uiLanguageAndLocale$; this.userName$ = this.dataService.client .userStatus() .single$.pipe(map(data => data.userStatus.username)); this.availableLanguages = this.i18nService.availableLanguages; this.availableLocales = this.i18nService.availableLocales; this.pageTitle$ = this.breadcrumbService.breadcrumbs$.pipe( map(breadcrumbs => breadcrumbs[breadcrumbs.length - 1].label), ); this.mainNavExpanded$ = this.dataService.client .uiState() .stream$.pipe(map(({ uiState }) => uiState.mainNavExpanded)); } selectUiLanguage() { this.uiLanguageAndLocale$ .pipe( take(1), switchMap(([currentLanguage, currentLocale]) => { return this.modalService.fromComponent(UiLanguageSwitcherDialogComponent, { closable: true, size: 'lg', locals: { availableLocales: this.availableLocales, availableLanguages: this.availableLanguages, currentLanguage: currentLanguage, currentLocale: currentLocale, }, }); }), switchMap(result => result ? this.dataService.client.setUiLanguage(result[0], result[1]) : EMPTY, ), ) .subscribe(result => { if (result.setUiLanguage) { this.i18nService.setLanguage(result.setUiLanguage); this.localStorageService.set('uiLanguageCode', result.setUiLanguage); this.localStorageService.set('uiLocale', result.setUiLocale ?? undefined); } }); } expandNav() { this.dataService.client.setMainNavExpanded(true).subscribe(); } collapseNav() { this.dataService.client.setMainNavExpanded(false).subscribe(); } logOut() { this.authService.logOut().subscribe(() => { const { loginUrl } = getAppConfig(); if (loginUrl) { window.location.href = loginUrl; } else { this.router.navigate(['/login']); } }); } }
import { Directive, Injector, OnDestroy, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { of, Subscription } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; import { Permission } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; import { HealthCheckService } from '../../providers/health-check/health-check.service'; import { JobQueueService } from '../../providers/job-queue/job-queue.service'; import { ActionBarContext, NavMenuBadge, NavMenuItem } from '../../providers/nav-builder/nav-builder-types'; import { NavBuilderService } from '../../providers/nav-builder/nav-builder.service'; import { NotificationService } from '../../providers/notification/notification.service'; @Directive({ selector: '[vdrBaseNav]', }) // eslint-disable-next-line @angular-eslint/directive-class-suffix export class BaseNavComponent implements OnInit, OnDestroy { constructor( protected route: ActivatedRoute, protected router: Router, public navBuilderService: NavBuilderService, protected healthCheckService: HealthCheckService, protected jobQueueService: JobQueueService, protected dataService: DataService, protected notificationService: NotificationService, protected injector: Injector, ) {} private userPermissions: string[]; private subscription: Subscription; shouldDisplayLink(menuItem: Pick<NavMenuItem, 'requiresPermission'>) { if (!this.userPermissions) { return false; } if (!menuItem.requiresPermission) { return true; } if (typeof menuItem.requiresPermission === 'string') { return this.userPermissions.includes(menuItem.requiresPermission); } if (typeof menuItem.requiresPermission === 'function') { return menuItem.requiresPermission(this.userPermissions); } } ngOnInit(): void { this.defineNavMenu(); this.subscription = this.dataService.client .userStatus() .mapStream(({ userStatus }) => { this.userPermissions = userStatus.permissions; }) .subscribe(); } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } getRouterLink(item: NavMenuItem) { return this.navBuilderService.getRouterLink( { routerLink: item.routerLink, context: this.createContext() }, this.route, ); } private defineNavMenu() { function allow(...permissions: string[]): (userPermissions: string[]) => boolean { return userPermissions => { for (const permission of permissions) { if (userPermissions.includes(permission)) { return true; } } return false; }; } this.navBuilderService.defineNavMenuSections([ { requiresPermission: allow( Permission.ReadCatalog, Permission.ReadProduct, Permission.ReadFacet, Permission.ReadCollection, Permission.ReadAsset, ), id: 'catalog', label: _('nav.catalog'), items: [ { requiresPermission: allow(Permission.ReadCatalog, Permission.ReadProduct), id: 'products', label: _('nav.products'), icon: 'library', routerLink: ['/catalog', 'products'], }, { requiresPermission: allow(Permission.ReadCatalog, Permission.ReadFacet), id: 'facets', label: _('nav.facets'), icon: 'tag', routerLink: ['/catalog', 'facets'], }, { requiresPermission: allow(Permission.ReadCatalog, Permission.ReadCollection), id: 'collections', label: _('nav.collections'), icon: 'folder-open', routerLink: ['/catalog', 'collections'], }, { requiresPermission: allow(Permission.ReadCatalog, Permission.ReadAsset), id: 'assets', label: _('nav.assets'), icon: 'image-gallery', routerLink: ['/catalog', 'assets'], }, ], }, { id: 'sales', label: _('nav.sales'), requiresPermission: allow(Permission.ReadOrder), items: [ { requiresPermission: allow(Permission.ReadOrder), id: 'orders', label: _('nav.orders'), routerLink: ['/orders'], icon: 'shopping-cart', }, ], }, { id: 'customers', label: _('nav.customers'), requiresPermission: allow(Permission.ReadCustomer, Permission.ReadCustomerGroup), items: [ { requiresPermission: allow(Permission.ReadCustomer), id: 'customers', label: _('nav.customers'), routerLink: ['/customer', 'customers'], icon: 'user', }, { requiresPermission: allow(Permission.ReadCustomerGroup), id: 'customer-groups', label: _('nav.customer-groups'), routerLink: ['/customer', 'groups'], icon: 'users', }, ], }, { id: 'marketing', label: _('nav.marketing'), requiresPermission: allow(Permission.ReadPromotion), items: [ { requiresPermission: allow(Permission.ReadPromotion), id: 'promotions', label: _('nav.promotions'), routerLink: ['/marketing', 'promotions'], icon: 'asterisk', }, ], }, { id: 'settings', label: _('nav.settings'), icon: 'cog', displayMode: 'settings', requiresPermission: allow( Permission.ReadSettings, Permission.ReadChannel, Permission.ReadAdministrator, Permission.ReadShippingMethod, Permission.ReadPaymentMethod, Permission.ReadTaxCategory, Permission.ReadTaxRate, Permission.ReadCountry, Permission.ReadZone, Permission.UpdateGlobalSettings, ), collapsible: true, collapsedByDefault: true, items: [ { requiresPermission: allow(Permission.ReadSeller), id: 'sellers', label: _('nav.sellers'), routerLink: ['/settings', 'sellers'], icon: 'store', }, { requiresPermission: allow(Permission.ReadChannel), id: 'channels', label: _('nav.channels'), routerLink: ['/settings', 'channels'], icon: 'layers', }, { requiresPermission: allow(Permission.ReadStockLocation), id: 'stock-locations', label: _('nav.stock-locations'), icon: 'map-marker', routerLink: ['/settings', 'stock-locations'], }, { requiresPermission: allow(Permission.ReadAdministrator), id: 'administrators', label: _('nav.administrators'), routerLink: ['/settings', 'administrators'], icon: 'administrator', }, { requiresPermission: allow(Permission.ReadAdministrator), id: 'roles', label: _('nav.roles'), routerLink: ['/settings', 'roles'], icon: 'users', }, { requiresPermission: allow(Permission.ReadShippingMethod), id: 'shipping-methods', label: _('nav.shipping-methods'), routerLink: ['/settings', 'shipping-methods'], icon: 'truck', }, { requiresPermission: allow(Permission.ReadPaymentMethod), id: 'payment-methods', label: _('nav.payment-methods'), routerLink: ['/settings', 'payment-methods'], icon: 'credit-card', }, { requiresPermission: allow(Permission.ReadTaxCategory), id: 'tax-categories', label: _('nav.tax-categories'), routerLink: ['/settings', 'tax-categories'], icon: 'view-list', }, { requiresPermission: allow(Permission.ReadTaxRate), id: 'tax-rates', label: _('nav.tax-rates'), routerLink: ['/settings', 'tax-rates'], icon: 'calculator', }, { requiresPermission: allow(Permission.ReadCountry), id: 'countries', label: _('nav.countries'), routerLink: ['/settings', 'countries'], icon: 'flag', }, { requiresPermission: allow(Permission.ReadZone), id: 'zones', label: _('nav.zones'), routerLink: ['/settings', 'zones'], icon: 'world', }, { requiresPermission: allow(Permission.UpdateGlobalSettings), id: 'global-settings', label: _('nav.global-settings'), routerLink: ['/settings', 'global-settings'], icon: 'cog', }, ], }, { id: 'system', label: _('nav.system'), icon: 'computer', displayMode: 'settings', requiresPermission: Permission.ReadSystem, collapsible: true, collapsedByDefault: true, items: [ { id: 'job-queue', label: _('nav.job-queue'), routerLink: ['/system', 'jobs'], icon: 'tick-chart', statusBadge: this.jobQueueService.activeJobs$.pipe( startWith([]), map( jobs => ({ type: jobs.length === 0 ? 'none' : 'info', propagateToSection: jobs.length > 0, } as NavMenuBadge), ), ), }, { id: 'system-status', label: _('nav.system-status'), routerLink: ['/system', 'system-status'], icon: 'rack-server', statusBadge: this.healthCheckService.status$.pipe( map(status => ({ type: status === 'ok' ? 'success' : 'error', propagateToSection: status === 'error', })), ), }, ], }, ]); } private createContext(): ActionBarContext { return { route: this.route, injector: this.injector, dataService: this.dataService, notificationService: this.notificationService, entity$: of(undefined), }; } }
import { Component, DebugElement } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { BehaviorSubject, Observable, of as observableOf } from 'rxjs'; import { MockTranslatePipe } from '../../../../../testing/translate.pipe.mock'; import { DataService } from '../../data/providers/data.service'; import { BreadcrumbLabelLinkPair } from '../../providers/breadcrumb/breadcrumb.service'; import { BreadcrumbComponent } from './breadcrumb.component'; describe('BeadcrumbsComponent', () => { let baseRouteConfig: Routes; let router: Router; let breadcrumbSubject: BehaviorSubject<string>; beforeEach(() => { breadcrumbSubject = new BehaviorSubject<string>('Initial Value'); const leafRoute = { path: 'string-grandchild', data: { breadcrumb: 'Grandchild' }, component: TestChildComponent, }; baseRouteConfig = [ { path: '', component: TestParentComponent, data: { breadcrumb: 'Root' }, children: [ { path: 'string-child', component: TestParentComponent, data: { breadcrumb: 'Child' }, children: [leafRoute], }, { path: 'no-breadcrumb-child', component: TestParentComponent, children: [leafRoute], }, { path: 'simple-function-child', component: TestParentComponent, data: { breadcrumb: () => 'String From Function', }, children: [leafRoute], }, { path: 'resolved-function-child', component: TestParentComponent, data: { breadcrumb: (data: any) => data.foo, }, resolve: { foo: FooResolver }, children: [leafRoute], }, { path: 'params-child/:name', component: TestParentComponent, data: { breadcrumb: (data: any, params: any) => params['name'], }, children: [leafRoute], }, { path: 'single-pair-child', component: TestParentComponent, data: { breadcrumb: { label: 'Pair', link: ['foo', 'bar', { p: 1 }], } as BreadcrumbLabelLinkPair, }, children: [leafRoute], }, { path: 'array-pair-child', component: TestParentComponent, data: { breadcrumb: [ { label: 'PairA', link: ['foo', 'bar'], }, { label: 'PairB', link: ['baz', 'quux'], }, ] as BreadcrumbLabelLinkPair[], }, children: [leafRoute], }, { path: 'pair-function-child', component: TestParentComponent, data: { breadcrumb: () => [ { label: 'PairA', link: ['foo', 'bar'], }, { label: 'PairB', link: ['baz', 'quux'], }, ] as BreadcrumbLabelLinkPair[], }, children: [leafRoute], }, { path: 'relative-parent', component: TestParentComponent, data: { breadcrumb: 'Parent' }, children: [ { path: 'relative-child', component: TestParentComponent, data: { breadcrumb: { label: 'Child', link: ['./', 'foo', { p: 1 }], } as BreadcrumbLabelLinkPair, }, children: [leafRoute], }, { path: 'relative-sibling', component: TestParentComponent, data: { breadcrumb: { label: 'Sibling', link: ['../', 'foo', { p: 1 }], } as BreadcrumbLabelLinkPair, }, children: [leafRoute], }, ], }, { path: 'deep-pair-child-1', component: TestParentComponent, data: { breadcrumb: 'Child 1', }, children: [ { path: 'deep-pair-child-2', component: TestParentComponent, data: { breadcrumb: () => [ { label: 'PairA', link: ['./', 'child', 'path'], }, { label: 'PairB', link: ['../', 'sibling', 'path'], }, { label: 'PairC', link: ['absolute', 'path'], }, ] as BreadcrumbLabelLinkPair[], }, children: [leafRoute], }, ], }, { path: 'observable-string', component: TestParentComponent, data: { breadcrumb: observableOf('Observable String'), }, }, { path: 'observable-pair', component: TestParentComponent, data: { breadcrumb: observableOf({ label: 'Observable Pair', link: ['foo', 'bar', { p: 1 }], } as BreadcrumbLabelLinkPair), }, }, { path: 'observable-array-pair', component: TestParentComponent, data: { breadcrumb: [ { label: 'Observable PairA', link: ['foo', 'bar'], }, { label: 'Observable PairB', link: ['baz', 'quux'], }, ] as BreadcrumbLabelLinkPair[], }, }, { path: 'function-observable', component: TestParentComponent, data: { breadcrumb: () => observableOf('Observable String From Function'), }, }, { path: 'observable-string-subject', component: TestParentComponent, data: { breadcrumb: breadcrumbSubject.asObservable(), }, children: [leafRoute], }, ], }, ]; TestBed.configureTestingModule({ imports: [RouterTestingModule.withRoutes(baseRouteConfig)], declarations: [BreadcrumbComponent, TestParentComponent, TestChildComponent, MockTranslatePipe], providers: [FooResolver, { provide: DataService, useClass: class {} }], }).compileComponents(); router = TestBed.get(Router); }); /** * Navigates to the provided route and returns the fixture for the TestChildComponent at that route. */ function getFixtureForRoute( route: string[], testFn: (fixture: ComponentFixture<TestComponent>) => void, ): () => void { return fakeAsync(() => { const fixture = TestBed.createComponent(TestChildComponent); // Run in ngZone to prevent warning: https://github.com/angular/angular/issues/25837#issuecomment-445796236 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion fixture.ngZone!.run(() => { router.navigate(route); }); fixture.detectChanges(); tick(); fixture.detectChanges(); testFn(fixture); }); } it( 'shows correct labels for string breadcrumbs', getFixtureForRoute(['', 'string-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); expect(labels).toEqual(['Root', 'Child', 'Grandchild']); }), ); it( 'links have correct href', getFixtureForRoute(['', 'string-child', 'string-grandchild'], fixture => { const links = getBreadcrumbLinks(fixture); expect(links).toEqual(['/', '/string-child']); }), ); it( 'skips a route with no breadcrumbs configured', getFixtureForRoute(['', 'no-breadcrumb-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); expect(labels).toEqual(['Root', 'Grandchild']); }), ); it( 'shows correct label for function breadcrumb', getFixtureForRoute(['', 'simple-function-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); expect(labels).toEqual(['Root', 'String From Function', 'Grandchild']); }), ); it( 'works with resolved data', getFixtureForRoute(['', 'resolved-function-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); expect(labels).toEqual(['Root', 'Foo', 'Grandchild']); }), ); it( 'works with data from parameters', getFixtureForRoute(['', 'params-child', 'Bar', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); expect(labels).toEqual(['Root', 'Bar', 'Grandchild']); }), ); it( 'works with a BreadcrumbLabelLinkPair', getFixtureForRoute(['', 'single-pair-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Pair', 'Grandchild']); expect(links).toEqual(['/', '/foo/bar;p=1']); }), ); it( 'works with array of BreadcrumbLabelLinkPairs', getFixtureForRoute(['', 'array-pair-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'PairA', 'PairB', 'Grandchild']); expect(links).toEqual(['/', '/foo/bar', '/baz/quux']); }), ); it( 'works with function returning BreadcrumbLabelLinkPairs', getFixtureForRoute(['', 'pair-function-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); console.log(`labels: ${labels}`); expect(labels).toEqual(['Root', 'PairA', 'PairB', 'Grandchild']); expect(links).toEqual(['/', '/foo/bar', '/baz/quux']); }), ); it( 'works with relative child paths in a BreadcrumbLabelLinkPair', getFixtureForRoute(['', 'relative-parent', 'relative-child', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Parent', 'Child', 'Grandchild']); expect(links).toEqual(['/', '/relative-parent', '/relative-parent/relative-child/foo;p=1']); }), ); it( 'works with relative sibling paths in a BreadcrumbLabelLinkPair', getFixtureForRoute(['', 'relative-parent', 'relative-sibling', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Parent', 'Sibling', 'Grandchild']); expect(links).toEqual(['/', '/relative-parent', '/relative-parent/foo;p=1']); }), ); it( 'array of BreadcrumbLabelLinkPairs paths compose correctly', getFixtureForRoute(['', 'deep-pair-child-1', 'deep-pair-child-2', 'string-grandchild'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Child 1', 'PairA', 'PairB', 'PairC', 'Grandchild']); expect(links).toEqual([ '/', '/deep-pair-child-1', '/deep-pair-child-1/deep-pair-child-2/child/path', '/deep-pair-child-1/sibling/path', '/absolute/path', ]); }), ); it( 'shows correct labels for observable of string', getFixtureForRoute(['', 'observable-string'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Observable String']); }), ); it( 'shows correct labels for observable of BreadcrumbLabelLinkPair', getFixtureForRoute(['', 'observable-pair'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Observable Pair']); }), ); it( 'shows correct labels for observable of BreadcrumbLabelLinkPair array', getFixtureForRoute(['', 'observable-array-pair'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Observable PairA', 'Observable PairB']); expect(links).toEqual(['/', '/foo/bar']); }), ); it( 'shows correct labels for function returning observable string', getFixtureForRoute(['', 'function-observable'], fixture => { const labels = getBreadcrumbLabels(fixture); const links = getBreadcrumbLinks(fixture); expect(labels).toEqual(['Root', 'Observable String From Function']); }), ); it( 'labels update when observables emit new values', getFixtureForRoute(['', 'observable-string-subject', 'string-grandchild'], fixture => { expect(getBreadcrumbLabels(fixture)).toEqual(['Root', 'Initial Value', 'Grandchild']); breadcrumbSubject.next('New Value'); fixture.detectChanges(); expect(getBreadcrumbLabels(fixture)).toEqual(['Root', 'New Value', 'Grandchild']); }), ); }); function getBreadcrumbsElement(fixture: ComponentFixture<TestComponent>): DebugElement { return fixture.debugElement.query(By.directive(BreadcrumbComponent)); } function getBreadcrumbListItems(fixture: ComponentFixture<TestComponent>): HTMLLIElement[] { return fixture.debugElement.queryAll(By.css('.breadcrumbs:not(.mobile) li')).map(de => de.nativeElement); } function getBreadcrumbLabels(fixture: ComponentFixture<TestComponent>): string[] { const labels = getBreadcrumbListItems(fixture).map(item => item.innerText.trim()); return labels; } function getBreadcrumbLinks(fixture: ComponentFixture<TestComponent>): string[] { return getBreadcrumbListItems(fixture) .map(el => el.querySelector('a')) .filter(notNullOrUndefined) .map(a => a.getAttribute('href')) .filter(notNullOrUndefined); } @Component({ // eslint-disable-next-line @angular-eslint/component-selector selector: 'test-root-component', template: ` <vdr-breadcrumb></vdr-breadcrumb> <router-outlet></router-outlet> `, }) class TestParentComponent {} @Component({ // eslint-disable-next-line @angular-eslint/component-selector selector: 'test-child-component', template: ` <vdr-breadcrumb></vdr-breadcrumb> `, }) class TestChildComponent {} type TestComponent = TestParentComponent | TestChildComponent; class FooResolver { resolve(): Observable<string> { return observableOf('Foo'); } }
import { Component } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { map } from 'rxjs/operators'; import { BreadcrumbService } from '../../providers/breadcrumb/breadcrumb.service'; /** * A breadcrumbs component which reads the route config and any route that has a `data.breadcrumb` property will * be displayed in the breadcrumb trail. * * The `breadcrumb` property can be a string or a function. If a function, it will be passed the route's `data` * object (which will include all resolved keys) and any route params, and should return a BreadcrumbValue. * * See the test config to get an idea of allowable configs for breadcrumbs. */ @Component({ selector: 'vdr-breadcrumb', templateUrl: './breadcrumb.component.html', styleUrls: ['./breadcrumb.component.scss'], }) export class BreadcrumbComponent { breadcrumbs$: Observable<Array<{ link: string | any[]; label: string }>>; parentBreadcrumb$: Observable<{ link: string | any[]; label: string } | undefined>; private destroy$ = new Subject<void>(); constructor(private breadcrumbService: BreadcrumbService) { this.breadcrumbs$ = this.breadcrumbService.breadcrumbs$; this.parentBreadcrumb$ = this.breadcrumbService.breadcrumbs$.pipe( map(breadcrumbs => (1 < breadcrumbs.length ? breadcrumbs[breadcrumbs.length - 2] : undefined)), ); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { combineLatest, Observable } from 'rxjs'; import { filter, map, startWith } from 'rxjs/operators'; import { CurrentUserChannel } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; import { ChannelService } from '../../providers/channel/channel.service'; @Component({ selector: 'vdr-channel-switcher', templateUrl: './channel-switcher.component.html', styleUrls: ['./channel-switcher.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChannelSwitcherComponent implements OnInit { readonly displayFilterThreshold = 10; channels$: Observable<CurrentUserChannel[]>; channelCount$: Observable<number>; filterControl = new UntypedFormControl(''); activeChannelCode$: Observable<string>; constructor(private dataService: DataService, private channelService: ChannelService) {} ngOnInit() { const channels$ = this.dataService.client.userStatus().mapStream(data => data.userStatus.channels); const filterTerm$ = this.filterControl.valueChanges.pipe<string>(startWith('')); this.channels$ = combineLatest(channels$, filterTerm$).pipe( map(([channels, filterTerm]) => filterTerm ? channels.filter(c => c.code.toLocaleLowerCase().includes(filterTerm.toLocaleLowerCase()), ) : channels), ); this.channelCount$ = channels$.pipe(map(channels => channels.length)); const activeChannel$ = this.dataService.client .userStatus() .mapStream(data => data.userStatus.channels.find(c => c.id === data.userStatus.activeChannelId)) .pipe(filter(notNullOrUndefined)); this.activeChannelCode$ = activeChannel$.pipe(map(channel => channel.code)); } setActiveChannel(channelId: string) { this.channelService.setActiveChannel(channelId).subscribe(() => this.filterControl.patchValue('')); } }
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { NavMenuItem, NavMenuSection } from '../../providers/nav-builder/nav-builder-types'; import { BaseNavComponent } from '../base-nav/base-nav.component'; @Component({ selector: 'vdr-main-nav', templateUrl: './main-nav.component.html', styleUrls: ['./main-nav.component.scss'], }) export class MainNavComponent extends BaseNavComponent implements OnInit { @Input() displayMode: string | undefined; @Output() itemClick = new EventEmitter<NavMenuItem>(); mainMenuConfig$: Observable<NavMenuSection[]>; expandedSections: string[] = []; override ngOnInit(): void { super.ngOnInit(); this.mainMenuConfig$ = this.navBuilderService.menuConfig$.pipe( map(sections => sections.filter(s => this.displayMode ? s.displayMode === this.displayMode : !s.displayMode, ), ), ); } toggleExpand(section: NavMenuSection) { if (this.expandedSections.includes(section.id)) { this.expandedSections = this.expandedSections.filter(id => id !== section.id); } else { this.expandedSections.push(section.id); } } setExpanded(section: NavMenuSection, expanded: boolean) { if (expanded) { this.expandedSections.push(section.id); } else { this.expandedSections = this.expandedSections.filter(id => id !== section.id); } } getStyleForSection(section: NavMenuSection) { if (section.collapsible) { if (this.expandedSections.includes(section.id)) { return { maxHeight: `${section.items.length * 33}px`, opacity: 1, visibility: 'visible' }; } else { return { maxHeight: '0px', opacity: 0, visibility: 'hidden' }; } } } onItemClick(item: NavMenuItem, event: MouseEvent) { item.onClick?.(event); this.itemClick.emit(item); } }
import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core'; import { NotificationType } from '../../providers/notification/notification.service'; import { LocalizationDirectionType, LocalizationService, } from '../../providers/localization/localization.service'; @Component({ selector: 'vdr-notification', templateUrl: './notification.component.html', styleUrls: ['./notification.component.scss'], }) export class NotificationComponent implements OnInit { direction$: LocalizationDirectionType; @ViewChild('wrapper', { static: true }) wrapper: ElementRef; offsetTop = 0; message = ''; translationVars: { [key: string]: string | number } = {}; type: NotificationType = 'info'; isVisible = true; private onClickFn: () => void = () => { /* */ }; /** * */ constructor(private localizationService: LocalizationService) {} ngOnInit(): void { this.direction$ = this.localizationService.direction$; } registerOnClickFn(fn: () => void): void { this.onClickFn = fn; } @HostListener('click') onClick(): void { if (this.isVisible) { this.onClickFn(); } } /** * Fade out the toast. When promise resolves, toast is invisible and * can be removed. */ fadeOut(): Promise<any> { this.isVisible = false; return new Promise(resolve => setTimeout(resolve, 1000)); } /** * Returns the height of the toast element in px. */ getHeight(): number { if (!this.wrapper) { return 0; } const el: HTMLElement = this.wrapper.nativeElement; return el.getBoundingClientRect().height; } getIcon(): string { switch (this.type) { case 'info': return 'info-circle'; case 'success': return 'check-circle'; case 'error': return 'exclamation-circle'; case 'warning': return 'exclamation-triangle'; } } stringifyMessage(message: unknown) { if (typeof message === 'string') { return message; } else { return JSON.stringify(message, null, 2); } } }
import { Component, ViewContainerRef } from '@angular/core'; import { OverlayHostService } from '../../providers/overlay-host/overlay-host.service'; /** * The OverlayHostComponent is a placeholder component which provides a location in the DOM into which overlay * elements (modals, notify notifications etc) may be injected dynamically. */ @Component({ selector: 'vdr-overlay-host', template: '<!-- -->', }) export class OverlayHostComponent { constructor(viewContainerRef: ViewContainerRef, overlayHostService: OverlayHostService) { overlayHostService.registerHostView(viewContainerRef); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { NavMenuSection } from '../../providers/nav-builder/nav-builder-types'; import { BaseNavComponent } from '../base-nav/base-nav.component'; @Component({ selector: 'vdr-settings-nav', templateUrl: './settings-nav.component.html', styleUrls: ['./settings-nav.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SettingsNavComponent extends BaseNavComponent implements OnInit { settingsMenuConfig$: Observable<NavMenuSection[]>; override ngOnInit(): void { super.ngOnInit(); this.settingsMenuConfig$ = this.navBuilderService.menuConfig$.pipe( map(sections => sections.filter(s => s.displayMode === 'settings')), ); } }
import { ChangeDetectionStrategy, Component, HostListener, Input, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { take } from 'rxjs/operators'; import { DataService } from '../../data/providers/data.service'; import { LocalStorageService } from '../../providers/local-storage/local-storage.service'; @Component({ selector: 'vdr-theme-switcher', templateUrl: './theme-switcher.component.html', styleUrls: ['./theme-switcher.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ThemeSwitcherComponent implements OnInit { activeTheme$: Observable<string>; constructor(private dataService: DataService, private localStorageService: LocalStorageService) {} ngOnInit() { this.activeTheme$ = this.dataService.client.uiState().mapStream(data => data.uiState.theme); } @HostListener('click', ['$event']) @HostListener('keydown.enter', ['$event']) onHostClick() { this.activeTheme$.pipe(take(1)).subscribe(current => this.toggleTheme(current)); } toggleTheme(current: string) { const newTheme = current === 'default' ? 'dark' : 'default'; this.dataService.client.setUiTheme(newTheme).subscribe(() => { this.localStorageService.set('activeTheme', newTheme); }); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { Subject, finalize, take, takeUntil } from 'rxjs'; import { CurrencyCode, LanguageCode } from '../../common/generated-types'; import { Dialog } from '../../providers/modal/modal.types'; import { DataService } from '../../data/providers/data.service'; import { getAppConfig } from '../../app.config'; @Component({ selector: 'vdr-ui-language-switcher', templateUrl: './ui-language-switcher-dialog.component.html', styleUrls: ['./ui-language-switcher-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class UiLanguageSwitcherDialogComponent implements Dialog<[LanguageCode, string | undefined]>, OnInit, OnDestroy { isLoading = true; private destroy$ = new Subject<void>(); resolveWith: (result?: [LanguageCode, string | undefined]) => void; currentLanguage: LanguageCode; availableLanguages: LanguageCode[] = []; currentLocale: string | undefined; availableLocales: string[] = []; availableCurrencyCodes = Object.values(CurrencyCode); selectedCurrencyCode: string; previewLocale: string; readonly browserDefaultLocale: string | undefined; readonly now = new Date().toISOString(); constructor(private dataService: DataService, private changeDetector: ChangeDetectorRef) { const browserLanguage = navigator.language.split('-'); this.browserDefaultLocale = browserLanguage.length === 1 ? undefined : browserLanguage[1]; } ngOnInit() { this.updatePreviewLocale(); this.dataService.settings .getActiveChannel() .mapStream(data => data.activeChannel.defaultCurrencyCode) .pipe( take(1), takeUntil(this.destroy$), finalize(() => { this.isLoading = false; this.changeDetector.markForCheck(); }), ) .subscribe(x => { this.selectedCurrencyCode = x; }); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } updatePreviewLocale() { if (!this.currentLocale || this.currentLocale.length === 0 || this.currentLocale.length === 2) { this.previewLocale = this.createLocaleString(this.currentLanguage, this.currentLocale); } } setLanguage() { this.resolveWith([this.currentLanguage, this.currentLocale?.toUpperCase()]); } cancel() { this.resolveWith(); } private createLocaleString(languageCode: LanguageCode, region?: string | null): string { if (!region) { return languageCode; } return [languageCode, region.toUpperCase()].join('-'); } }
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { LanguageCode } from '../../common/generated-types'; @Component({ selector: 'vdr-user-menu', templateUrl: './user-menu.component.html', styleUrls: ['./user-menu.component.scss'], }) export class UserMenuComponent { @Input() userName = ''; @Input() availableLanguages: LanguageCode[] = []; @Input() uiLanguageAndLocale: [LanguageCode, string | undefined]; @Output() logOut = new EventEmitter<void>(); @Output() selectUiLanguage = new EventEmitter<void>(); }
import { Injector } from '@angular/core'; import { ApolloLink, Operation } from '@apollo/client/core'; import { JobQueueService } from '../providers/job-queue/job-queue.service'; /** * This link checks each operation and if it is a mutation, it tells the JobQueueService * to poll for active jobs. This is because certain mutations trigger background jobs * which should be made known in the UI. */ export class CheckJobsLink extends ApolloLink { private _jobQueueService: JobQueueService; get jobQueueService(): JobQueueService { if (!this._jobQueueService) { this._jobQueueService = this.injector.get(JobQueueService); } return this._jobQueueService; } /** * We inject the Injector rather than the JobQueueService directly in order * to avoid a circular dependency error. */ constructor(private injector: Injector) { super((operation, forward) => { if (this.isMutation(operation)) { this.jobQueueService.checkForJobs(); } return forward ? forward(operation) : null; }); } private isMutation(operation: Operation): boolean { return !!operation.query.definitions.find( d => d.kind === 'OperationDefinition' && d.operation === 'mutation', ); } }
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { APP_INITIALIZER, Injector, NgModule } from '@angular/core'; import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core'; import { setContext } from '@apollo/client/link/context'; import { ApolloLink } from '@apollo/client/link/core'; import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular'; import createUploadLink from 'apollo-upload-client/createUploadLink.mjs'; import { getAppConfig } from '../app.config'; import { introspectionResult } from '../common/introspection-result-wrapper'; import { LocalStorageService } from '../providers/local-storage/local-storage.service'; import { CheckJobsLink } from './check-jobs-link'; import { getClientDefaults } from './client-state/client-defaults'; import { clientResolvers } from './client-state/client-resolvers'; import { GET_CLIENT_STATE } from './definitions/client-definitions'; import { OmitTypenameLink } from './omit-typename-link'; import { BaseDataService } from './providers/base-data.service'; import { DataService } from './providers/data.service'; import { FetchAdapter } from './providers/fetch-adapter'; import { DefaultInterceptor } from './providers/interceptor'; import { initializeServerConfigService, ServerConfigService } from './server-config'; import { getServerLocation } from './utils/get-server-location'; export function createApollo( localStorageService: LocalStorageService, fetchAdapter: FetchAdapter, injector: Injector, ): ApolloClientOptions<any> { const { adminApiPath, tokenMethod, channelTokenKey } = getAppConfig(); const serverLocation = getServerLocation(); const apolloCache = new InMemoryCache({ possibleTypes: introspectionResult.possibleTypes, typePolicies: { GlobalSettings: { fields: { serverConfig: { merge: (existing, incoming) => ({ ...existing, ...incoming }), }, }, }, Facet: { fields: { values: { merge: (existing, incoming) => incoming, }, }, }, }, }); apolloCache.writeQuery({ query: GET_CLIENT_STATE, data: getClientDefaults(localStorageService), }); if (!false) { // TODO: enable only for dev mode // make the Apollo Cache inspectable in the console for debug purposes (window as any)['apolloCache'] = apolloCache; } return { link: ApolloLink.from([ new OmitTypenameLink(), new CheckJobsLink(injector), setContext(() => { const headers: Record<string, string> = {}; const channelToken = localStorageService.get('activeChannelToken'); if (channelToken) { headers[channelTokenKey ?? 'vendure-token'] = channelToken; } if (tokenMethod === 'bearer') { const authToken = localStorageService.get('authToken'); if (authToken) { headers.authorization = `Bearer ${authToken}`; } } headers['Apollo-Require-Preflight'] = 'true'; return { headers }; }), createUploadLink({ uri: `${serverLocation}/${adminApiPath}`, fetch: fetchAdapter.fetch, }), ]), cache: apolloCache, resolvers: clientResolvers, }; } // List of all EU countries /** * The DataModule is responsible for all API calls *and* serves as the source of truth for global app * state via the apollo-link-state package. */ @NgModule({ imports: [HttpClientModule, ApolloModule], exports: [], declarations: [], providers: [ BaseDataService, DataService, FetchAdapter, ServerConfigService, { provide: APOLLO_OPTIONS, useFactory: createApollo, deps: [LocalStorageService, FetchAdapter, Injector], }, { provide: HTTP_INTERCEPTORS, useClass: DefaultInterceptor, multi: true }, { provide: APP_INITIALIZER, multi: true, useFactory: initializeServerConfigService, deps: [ServerConfigService], }, ], }) export class DataModule {}
import { ApolloLink } from '@apollo/client/core'; import { omit } from '@vendure/common/lib/omit'; /** * The "__typename" property added by Apollo Client causes errors when posting the entity * back in a mutation. Therefore this link will remove all such keys before the object * reaches the API layer. * * See: https://github.com/apollographql/apollo-client/issues/1913#issuecomment-393721604 */ export class OmitTypenameLink extends ApolloLink { constructor() { super((operation, forward) => { if (operation.variables) { operation.variables = omit(operation.variables, ['__typename'], true); } return forward ? forward(operation) : null; }); } }
import { ApolloQueryResult, NetworkStatus } from '@apollo/client/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { Apollo, QueryRef } from 'apollo-angular'; import { merge, Observable, Subject } from 'rxjs'; import { distinctUntilChanged, filter, finalize, map, skip, take, takeUntil, tap } from 'rxjs/operators'; import { GetUserStatusQuery } from '../common/generated-types'; import { GET_USER_STATUS } from './definitions/client-definitions'; /** * @description * This class wraps the Apollo Angular QueryRef object and exposes some getters * for convenience. * * @docsCategory services * @docsPage DataService */ export class QueryResult<T, V extends Record<string, any> = Record<string, any>> { constructor(private queryRef: QueryRef<T, V>, private apollo: Apollo) { this.valueChanges = queryRef.valueChanges; } completed$ = new Subject<void>(); private valueChanges: Observable<ApolloQueryResult<T>>; /** * @description * Re-fetch this query whenever the active Channel changes. */ refetchOnChannelChange(): QueryResult<T, V> { const userStatus$ = this.apollo.watchQuery<GetUserStatusQuery>({ query: GET_USER_STATUS, }).valueChanges; const activeChannelId$ = userStatus$.pipe( map(data => data.data.userStatus.activeChannelId), filter(notNullOrUndefined), distinctUntilChanged(), skip(1), takeUntil(this.completed$), ); const loggedOut$ = userStatus$.pipe( map(data => data.data.userStatus.isLoggedIn), distinctUntilChanged(), skip(1), filter(isLoggedIn => !isLoggedIn), takeUntil(this.completed$), ); this.valueChanges = merge(activeChannelId$, this.queryRef.valueChanges).pipe( tap(val => { if (typeof val === 'string') { new Promise(resolve => setTimeout(resolve, 50)).then(() => this.queryRef.refetch()); } }), filter<any>(val => typeof val !== 'string'), takeUntil(loggedOut$), takeUntil(this.completed$), ); this.queryRef.valueChanges = this.valueChanges; return this; } /** * @description * Returns an Observable which emits a single result and then completes. */ get single$(): Observable<T> { return this.valueChanges.pipe( filter(result => result.networkStatus === NetworkStatus.ready), take(1), map(result => result.data), finalize(() => { this.completed$.next(); this.completed$.complete(); }), ); } /** * @description * Returns an Observable which emits until unsubscribed. */ get stream$(): Observable<T> { return this.valueChanges.pipe( filter(result => result.networkStatus === NetworkStatus.ready), map(result => result.data), finalize(() => { this.completed$.next(); this.completed$.complete(); }), ); } get ref(): QueryRef<T, V> { return this.queryRef; } /** * @description * Returns a single-result Observable after applying the map function. */ mapSingle<R>(mapFn: (item: T) => R): Observable<R> { return this.single$.pipe(map(mapFn)); } /** * @description * Returns a multiple-result Observable after applying the map function. */ mapStream<R>(mapFn: (item: T) => R): Observable<R> { return this.stream$.pipe(map(mapFn)); } }
import { Injectable, Injector } from '@angular/core'; import { lastValueFrom } from 'rxjs'; import { CustomFieldConfig, CustomFields, GetGlobalSettingsQuery, GetServerConfigQuery, OrderProcessState, PermissionDefinition, } from '../common/generated-types'; import { GET_GLOBAL_SETTINGS, GET_SERVER_CONFIG } from './definitions/settings-definitions'; import { BaseDataService } from './providers/base-data.service'; export function initializeServerConfigService(serverConfigService: ServerConfigService): () => Promise<any> { return serverConfigService.init(); } /** * A service which fetches the config from the server upon initialization, and then provides that config * to the components which require it. */ @Injectable() export class ServerConfigService { private _serverConfig: GetServerConfigQuery['globalSettings']['serverConfig'] = {} as any; customFieldsMap: Map<string, CustomFieldConfig[]> = new Map(); private get baseDataService() { return this.injector.get<BaseDataService>(BaseDataService); } constructor(private injector: Injector) {} /** * Fetches the ServerConfig. Should be run as part of the app bootstrap process by attaching * to the Angular APP_INITIALIZER token. */ init(): () => Promise<any> { return () => this.getServerConfig(); } /** * Fetch the ServerConfig. Should be run on app init (in case user is already logged in) and on successful login. */ getServerConfig() { return lastValueFrom( this.baseDataService.query<GetServerConfigQuery>(GET_SERVER_CONFIG).single$, ).then( result => { this._serverConfig = result.globalSettings.serverConfig; for (const entityCustomFields of this._serverConfig.entityCustomFields) { this.customFieldsMap.set(entityCustomFields.entityName, entityCustomFields.customFields); } }, err => { // Let the error fall through to be caught by the http interceptor. }, ); } getAvailableLanguages() { return this.baseDataService .query<GetGlobalSettingsQuery>(GET_GLOBAL_SETTINGS, {}, 'cache-first') .mapSingle(res => res.globalSettings.availableLanguages); } /** * When any of the GlobalSettings are modified, this method should be called to update the Apollo cache. */ refreshGlobalSettings() { return this.baseDataService.query<GetGlobalSettingsQuery>(GET_GLOBAL_SETTINGS, {}, 'network-only') .single$; } /** * Retrieves the custom field configs for the given entity type. */ getCustomFieldsFor(type: Exclude<keyof CustomFields, '__typename'> | string): CustomFieldConfig[] { return this.customFieldsMap.get(type) || []; } getOrderProcessStates(): OrderProcessState[] { return this.serverConfig.orderProcess; } getPermittedAssetTypes(): string[] { return this.serverConfig.permittedAssetTypes; } getPermissionDefinitions(): PermissionDefinition[] { return this.serverConfig.permissions; } get serverConfig(): GetServerConfigQuery['globalSettings']['serverConfig'] { return this._serverConfig; } }
import { getAppConfig } from '../../app.config'; import { GetNetworkStatusQuery, GetUiStateQuery, GetUserStatusQuery } from '../../common/generated-types'; import { getDefaultUiLanguage, getDefaultUiLocale } from '../../common/utilities/get-default-ui-language'; import { LocalStorageService } from '../../providers/local-storage/local-storage.service'; export function getClientDefaults(localStorageService: LocalStorageService) { const currentLanguage = localStorageService.get('uiLanguageCode') || getDefaultUiLanguage(); const currentLocale = localStorageService.get('uiLocale') || getDefaultUiLocale(); const currentContentLanguage = localStorageService.get('contentLanguageCode') || getDefaultUiLanguage(); const activeTheme = localStorageService.get('activeTheme') || 'default'; return { networkStatus: { inFlightRequests: 0, __typename: 'NetworkStatus', } as GetNetworkStatusQuery['networkStatus'], userStatus: { administratorId: null, username: '', isLoggedIn: false, loginTime: '', activeChannelId: null, permissions: [], channels: [], __typename: 'UserStatus', } as GetUserStatusQuery['userStatus'], uiState: { language: currentLanguage, locale: currentLocale || '', contentLanguage: currentContentLanguage, theme: activeTheme, displayUiExtensionPoints: false, mainNavExpanded: false, __typename: 'UiState', } as GetUiStateQuery['uiState'], }; }
import { InMemoryCache } from '@apollo/client/core'; import * as Codegen from '../../common/generated-types'; import { GetUserStatusQuery, LanguageCode, UserStatus } from '../../common/generated-types'; import { GET_NEWTORK_STATUS, GET_UI_STATE, GET_USER_STATUS } from '../definitions/client-definitions'; export type ResolverContext = { cache: InMemoryCache; optimisticResponse: any; getCacheKey: (storeObj: any) => string; }; export type ResolverDefinition = { Mutation: { [name: string]: (rootValue: any, args: any, context: ResolverContext, info?: any) => any; }; }; export const clientResolvers: ResolverDefinition = { Mutation: { requestStarted: (_, args, { cache }): number => updateRequestsInFlight(cache, 1), requestCompleted: (_, args, { cache }): number => updateRequestsInFlight(cache, -1), setAsLoggedIn: (_, args: Codegen.SetAsLoggedInMutationVariables, { cache }): UserStatus => { const { input: { username, loginTime, channels, activeChannelId, administratorId }, } = args; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const permissions = channels.find(c => c.id === activeChannelId)!.permissions; const data: { userStatus: UserStatus } = { userStatus: { __typename: 'UserStatus', administratorId, username, loginTime, isLoggedIn: true, permissions, channels, activeChannelId, }, }; cache.writeQuery({ query: GET_USER_STATUS, data }); return data.userStatus; }, setAsLoggedOut: (_, args, { cache }): UserStatus => { const data: GetUserStatusQuery = { userStatus: { __typename: 'UserStatus', administratorId: null, username: '', loginTime: '', isLoggedIn: false, permissions: [], channels: [], activeChannelId: null, }, }; cache.writeQuery({ query: GET_USER_STATUS, data }); return data.userStatus; }, setUiLanguage: (_, args: Codegen.SetUiLanguageMutationVariables, { cache }): LanguageCode => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<Codegen.GetUiStateQuery>({ query: GET_UI_STATE })!; const data = updateUiState(previous, 'language', args.languageCode); cache.writeQuery({ query: GET_UI_STATE, data }); return args.languageCode; }, setUiLocale: (_, args: Codegen.SetUiLocaleMutationVariables, { cache }): string | undefined => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<Codegen.GetUiStateQuery>({ query: GET_UI_STATE })!; const data = updateUiState(previous, 'locale', args.locale); cache.writeQuery({ query: GET_UI_STATE, data }); return args.locale ?? undefined; }, setContentLanguage: ( _, args: Codegen.SetContentLanguageMutationVariables, { cache }, ): LanguageCode => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<Codegen.GetUiStateQuery>({ query: GET_UI_STATE })!; const data = updateUiState(previous, 'contentLanguage', args.languageCode); cache.writeQuery({ query: GET_UI_STATE, data }); return args.languageCode; }, setUiTheme: (_, args: Codegen.SetUiThemeMutationVariables, { cache }): string => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<Codegen.GetUiStateQuery>({ query: GET_UI_STATE })!; const data = updateUiState(previous, 'theme', args.theme); cache.writeQuery({ query: GET_UI_STATE, data }); return args.theme; }, setDisplayUiExtensionPoints: ( _, args: Codegen.SetDisplayUiExtensionPointsMutationVariables, { cache }, ): boolean => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<Codegen.GetUiStateQuery>({ query: GET_UI_STATE })!; const data = updateUiState(previous, 'displayUiExtensionPoints', args.display); cache.writeQuery({ query: GET_UI_STATE, data }); return args.display; }, setMainNavExpanded: (_, args: Codegen.SetMainNavExpandedMutationVariables, { cache }): boolean => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<Codegen.GetUiStateQuery>({ query: GET_UI_STATE })!; const data = updateUiState(previous, 'mainNavExpanded', args.expanded); cache.writeQuery({ query: GET_UI_STATE, data }); return args.expanded; }, setActiveChannel: (_, args: Codegen.SetActiveChannelMutationVariables, { cache }): UserStatus => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<GetUserStatusQuery>({ query: GET_USER_STATUS })!; const activeChannel = previous.userStatus.channels.find(c => c.id === args.channelId); if (!activeChannel) { throw new Error('setActiveChannel: Could not find Channel with ID ' + args.channelId); } const permissions = activeChannel.permissions; const data: { userStatus: UserStatus } = { userStatus: { ...previous.userStatus, permissions, activeChannelId: activeChannel.id, }, }; cache.writeQuery({ query: GET_USER_STATUS, data }); return data.userStatus; }, updateUserChannels: (_, args: Codegen.UpdateUserChannelsMutationVariables, { cache }): UserStatus => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const previous = cache.readQuery<GetUserStatusQuery>({ query: GET_USER_STATUS })!; const data = { userStatus: { ...previous.userStatus, channels: Array.isArray(args.channels) ? args.channels : [args.channels], }, }; cache.writeQuery({ query: GET_USER_STATUS, data }); return data.userStatus; }, }, }; function updateUiState<K extends keyof Codegen.GetUiStateQuery['uiState']>( previous: Codegen.GetUiStateQuery, key: K, value: Codegen.GetUiStateQuery['uiState'][K], ): Codegen.GetUiStateQuery { return { uiState: { ...previous.uiState, [key]: value, __typename: 'UiState', }, }; } function updateRequestsInFlight(cache: InMemoryCache, increment: 1 | -1): number { const previous = cache.readQuery<Codegen.GetNetworkStatusQuery>({ query: GET_NEWTORK_STATUS }); const inFlightRequests = previous ? previous.networkStatus.inFlightRequests + increment : increment; const data: Codegen.GetNetworkStatusQuery = { networkStatus: { __typename: 'NetworkStatus', inFlightRequests, }, }; cache.writeQuery({ query: GET_NEWTORK_STATUS, data }); return inFlightRequests; }
import { gql } from 'apollo-angular'; export const ROLE_FRAGMENT = gql` fragment Role on Role { id createdAt updatedAt code description permissions channels { id code token } } `; export const ADMINISTRATOR_FRAGMENT = gql` fragment Administrator on Administrator { id createdAt updatedAt firstName lastName emailAddress user { id identifier lastLogin roles { ...Role } } } ${ROLE_FRAGMENT} `; export const GET_ACTIVE_ADMINISTRATOR = gql` query GetActiveAdministrator { activeAdministrator { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const CREATE_ADMINISTRATOR = gql` mutation CreateAdministrator($input: CreateAdministratorInput!) { createAdministrator(input: $input) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const UPDATE_ADMINISTRATOR = gql` mutation UpdateAdministrator($input: UpdateAdministratorInput!) { updateAdministrator(input: $input) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const UPDATE_ACTIVE_ADMINISTRATOR = gql` mutation UpdateActiveAdministrator($input: UpdateActiveAdministratorInput!) { updateActiveAdministrator(input: $input) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `; export const DELETE_ADMINISTRATOR = gql` mutation DeleteAdministrator($id: ID!) { deleteAdministrator(id: $id) { result message } } `; export const DELETE_ADMINISTRATORS = gql` mutation DeleteAdministrators($ids: [ID!]!) { deleteAdministrators(ids: $ids) { result message } } `; export const GET_ROLES = gql` query GetRoles($options: RoleListOptions) { roles(options: $options) { items { ...Role } totalItems } } ${ROLE_FRAGMENT} `; export const CREATE_ROLE = gql` mutation CreateRole($input: CreateRoleInput!) { createRole(input: $input) { ...Role } } ${ROLE_FRAGMENT} `; export const UPDATE_ROLE = gql` mutation UpdateRole($input: UpdateRoleInput!) { updateRole(input: $input) { ...Role } } ${ROLE_FRAGMENT} `; export const DELETE_ROLE = gql` mutation DeleteRole($id: ID!) { deleteRole(id: $id) { result message } } `; export const DELETE_ROLES = gql` mutation DeleteRoles($ids: [ID!]!) { deleteRoles(ids: $ids) { result message } } `; export const ASSIGN_ROLE_TO_ADMINISTRATOR = gql` mutation AssignRoleToAdministrator($administratorId: ID!, $roleId: ID!) { assignRoleToAdministrator(administratorId: $administratorId, roleId: $roleId) { ...Administrator } } ${ADMINISTRATOR_FRAGMENT} `;
import { gql } from 'apollo-angular'; import { ERROR_RESULT_FRAGMENT } from './shared-definitions'; export const CURRENT_USER_FRAGMENT = gql` fragment CurrentUser on CurrentUser { id identifier channels { id code token permissions } } `; export const ATTEMPT_LOGIN = gql` mutation AttemptLogin($username: String!, $password: String!, $rememberMe: Boolean!) { login(username: $username, password: $password, rememberMe: $rememberMe) { ...CurrentUser ...ErrorResult } } ${CURRENT_USER_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const LOG_OUT = gql` mutation LogOut { logout { success } } `; export const GET_CURRENT_USER = gql` query GetCurrentUser { me { ...CurrentUser } } ${CURRENT_USER_FRAGMENT} `;
import { gql } from 'apollo-angular'; export const REQUEST_STARTED = gql` mutation RequestStarted { requestStarted @client } `; export const REQUEST_COMPLETED = gql` mutation RequestCompleted { requestCompleted @client } `; export const USER_STATUS_FRAGMENT = gql` fragment UserStatus on UserStatus { administratorId username isLoggedIn loginTime activeChannelId permissions channels { id code token permissions } } `; export const SET_AS_LOGGED_IN = gql` mutation SetAsLoggedIn($input: UserStatusInput!) { setAsLoggedIn(input: $input) @client { ...UserStatus } } ${USER_STATUS_FRAGMENT} `; export const SET_AS_LOGGED_OUT = gql` mutation SetAsLoggedOut { setAsLoggedOut @client { ...UserStatus } } ${USER_STATUS_FRAGMENT} `; export const SET_UI_LANGUAGE_AND_LOCALE = gql` mutation SetUiLanguage($languageCode: LanguageCode!, $locale: String) { setUiLanguage(languageCode: $languageCode) @client setUiLocale(locale: $locale) @client } `; export const SET_UI_LOCALE = gql` mutation SetUiLocale($locale: String) { setUiLocale(locale: $locale) @client } `; export const SET_DISPLAY_UI_EXTENSION_POINTS = gql` mutation SetDisplayUiExtensionPoints($display: Boolean!) { setDisplayUiExtensionPoints(display: $display) @client } `; export const SET_MAIN_NAV_EXPANDED = gql` mutation SetMainNavExpanded($expanded: Boolean!) { setMainNavExpanded(expanded: $expanded) @client } `; export const SET_CONTENT_LANGUAGE = gql` mutation SetContentLanguage($languageCode: LanguageCode!) { setContentLanguage(languageCode: $languageCode) @client } `; export const SET_UI_THEME = gql` mutation SetUiTheme($theme: String!) { setUiTheme(theme: $theme) @client } `; export const GET_NEWTORK_STATUS = gql` query GetNetworkStatus { networkStatus @client { inFlightRequests } } `; export const GET_USER_STATUS = gql` query GetUserStatus { userStatus @client { ...UserStatus } } ${USER_STATUS_FRAGMENT} `; export const GET_UI_STATE = gql` query GetUiState { uiState @client { language locale contentLanguage theme displayUiExtensionPoints mainNavExpanded } } `; export const GET_CLIENT_STATE = gql` query GetClientState { networkStatus @client { inFlightRequests } userStatus @client { ...UserStatus } uiState @client { language locale contentLanguage theme displayUiExtensionPoints mainNavExpanded } } ${USER_STATUS_FRAGMENT} `; export const SET_ACTIVE_CHANNEL = gql` mutation SetActiveChannel($channelId: ID!) { setActiveChannel(channelId: $channelId) @client { ...UserStatus } } ${USER_STATUS_FRAGMENT} `; export const UPDATE_USER_CHANNELS = gql` mutation UpdateUserChannels($channels: [CurrentUserChannelInput!]!) { updateUserChannels(channels: $channels) @client { ...UserStatus } } ${USER_STATUS_FRAGMENT} `;
import { gql } from 'apollo-angular'; import { ASSET_FRAGMENT } from './product-definitions'; import { CONFIGURABLE_OPERATION_DEF_FRAGMENT, CONFIGURABLE_OPERATION_FRAGMENT } from './shared-definitions'; export const GET_COLLECTION_FILTERS = gql` query GetCollectionFilters { collectionFilters { ...ConfigurableOperationDef } } ${CONFIGURABLE_OPERATION_DEF_FRAGMENT} `; export const COLLECTION_FRAGMENT = gql` fragment Collection on Collection { id createdAt updatedAt name slug description isPrivate languageCode breadcrumbs { id name slug } featuredAsset { ...Asset } assets { ...Asset } inheritFilters filters { ...ConfigurableOperation } translations { id languageCode name slug description } parent { id name } children { id name } } ${ASSET_FRAGMENT} ${CONFIGURABLE_OPERATION_FRAGMENT} `; export const COLLECTION_FOR_LIST_FRAGMENT = gql` fragment CollectionForList on Collection { id createdAt updatedAt name slug position isPrivate breadcrumbs { id name slug } featuredAsset { ...Asset } parentId children { id } } ${ASSET_FRAGMENT} `; export const GET_COLLECTION_LIST = gql` query GetCollectionList($options: CollectionListOptions) { collections(options: $options) { items { ...CollectionForList } totalItems } } ${COLLECTION_FOR_LIST_FRAGMENT} `; export const CREATE_COLLECTION = gql` mutation CreateCollection($input: CreateCollectionInput!) { createCollection(input: $input) { ...Collection } } ${COLLECTION_FRAGMENT} `; export const UPDATE_COLLECTION = gql` mutation UpdateCollection($input: UpdateCollectionInput!) { updateCollection(input: $input) { ...Collection } } ${COLLECTION_FRAGMENT} `; export const MOVE_COLLECTION = gql` mutation MoveCollection($input: MoveCollectionInput!) { moveCollection(input: $input) { ...Collection } } ${COLLECTION_FRAGMENT} `; export const DELETE_COLLECTION = gql` mutation DeleteCollection($id: ID!) { deleteCollection(id: $id) { result message } } `; export const DELETE_COLLECTIONS = gql` mutation DeleteCollections($ids: [ID!]!) { deleteCollections(ids: $ids) { result message } } `; export const GET_COLLECTION_CONTENTS = gql` query GetCollectionContents($id: ID!, $options: ProductVariantListOptions) { collection(id: $id) { id name productVariants(options: $options) { items { id createdAt updatedAt productId name sku } totalItems } } } `; export const PREVIEW_COLLECTION_CONTENTS = gql` query PreviewCollectionContents( $input: PreviewCollectionVariantsInput! $options: ProductVariantListOptions ) { previewCollectionVariants(input: $input, options: $options) { items { id createdAt updatedAt productId name sku } totalItems } } `; export const ASSIGN_COLLECTIONS_TO_CHANNEL = gql` mutation AssignCollectionsToChannel($input: AssignCollectionsToChannelInput!) { assignCollectionsToChannel(input: $input) { id name } } `; export const REMOVE_COLLECTIONS_FROM_CHANNEL = gql` mutation RemoveCollectionsFromChannel($input: RemoveCollectionsFromChannelInput!) { removeCollectionsFromChannel(input: $input) { id name } } `;
import { gql } from 'apollo-angular'; import { ERROR_RESULT_FRAGMENT } from './shared-definitions'; export const ADDRESS_FRAGMENT = gql` fragment Address on Address { id createdAt updatedAt fullName company streetLine1 streetLine2 city province postalCode country { id code name } phoneNumber defaultShippingAddress defaultBillingAddress } `; export const CUSTOMER_FRAGMENT = gql` fragment Customer on Customer { id createdAt updatedAt title firstName lastName phoneNumber emailAddress user { id identifier verified lastLogin } addresses { ...Address } } ${ADDRESS_FRAGMENT} `; export const CUSTOMER_GROUP_FRAGMENT = gql` fragment CustomerGroup on CustomerGroup { id createdAt updatedAt name } `; export const GET_CUSTOMER_LIST = gql` query GetCustomerList($options: CustomerListOptions) { customers(options: $options) { items { id createdAt updatedAt title firstName lastName emailAddress user { id verified } } totalItems } } `; export const CREATE_CUSTOMER = gql` mutation CreateCustomer($input: CreateCustomerInput!, $password: String) { createCustomer(input: $input, password: $password) { ...Customer ...ErrorResult } } ${CUSTOMER_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const UPDATE_CUSTOMER = gql` mutation UpdateCustomer($input: UpdateCustomerInput!) { updateCustomer(input: $input) { ...Customer ...ErrorResult } } ${CUSTOMER_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const DELETE_CUSTOMER = gql` mutation DeleteCustomer($id: ID!) { deleteCustomer(id: $id) { result message } } `; export const DELETE_CUSTOMERS = gql` mutation DeleteCustomers($ids: [ID!]!) { deleteCustomers(ids: $ids) { result message } } `; export const CREATE_CUSTOMER_ADDRESS = gql` mutation CreateCustomerAddress($customerId: ID!, $input: CreateAddressInput!) { createCustomerAddress(customerId: $customerId, input: $input) { ...Address } } ${ADDRESS_FRAGMENT} `; export const UPDATE_CUSTOMER_ADDRESS = gql` mutation UpdateCustomerAddress($input: UpdateAddressInput!) { updateCustomerAddress(input: $input) { ...Address } } ${ADDRESS_FRAGMENT} `; export const DELETE_CUSTOMER_ADDRESS = gql` mutation DeleteCustomerAddress($id: ID!) { deleteCustomerAddress(id: $id) { success } } `; export const CREATE_CUSTOMER_GROUP = gql` mutation CreateCustomerGroup($input: CreateCustomerGroupInput!) { createCustomerGroup(input: $input) { ...CustomerGroup } } ${CUSTOMER_GROUP_FRAGMENT} `; export const UPDATE_CUSTOMER_GROUP = gql` mutation UpdateCustomerGroup($input: UpdateCustomerGroupInput!) { updateCustomerGroup(input: $input) { ...CustomerGroup } } ${CUSTOMER_GROUP_FRAGMENT} `; export const DELETE_CUSTOMER_GROUP = gql` mutation DeleteCustomerGroup($id: ID!) { deleteCustomerGroup(id: $id) { result message } } `; export const DELETE_CUSTOMER_GROUPS = gql` mutation DeleteCustomerGroups($ids: [ID!]!) { deleteCustomerGroups(ids: $ids) { result message } } `; export const GET_CUSTOMER_GROUPS = gql` query GetCustomerGroups($options: CustomerGroupListOptions) { customerGroups(options: $options) { items { ...CustomerGroup } totalItems } } ${CUSTOMER_GROUP_FRAGMENT} `; export const GET_CUSTOMER_GROUP_WITH_CUSTOMERS = gql` query GetCustomerGroupWithCustomers($id: ID!, $options: CustomerListOptions) { customerGroup(id: $id) { ...CustomerGroup customers(options: $options) { items { id createdAt updatedAt emailAddress firstName lastName user { id } } totalItems } } } ${CUSTOMER_GROUP_FRAGMENT} `; export const ADD_CUSTOMERS_TO_GROUP = gql` mutation AddCustomersToGroup($groupId: ID!, $customerIds: [ID!]!) { addCustomersToGroup(customerGroupId: $groupId, customerIds: $customerIds) { ...CustomerGroup } } ${CUSTOMER_GROUP_FRAGMENT} `; export const REMOVE_CUSTOMERS_FROM_GROUP = gql` mutation RemoveCustomersFromGroup($groupId: ID!, $customerIds: [ID!]!) { removeCustomersFromGroup(customerGroupId: $groupId, customerIds: $customerIds) { ...CustomerGroup } } ${CUSTOMER_GROUP_FRAGMENT} `; export const GET_CUSTOMER_HISTORY = gql` query GetCustomerHistory($id: ID!, $options: HistoryEntryListOptions) { customer(id: $id) { id history(options: $options) { totalItems items { id type createdAt isPublic administrator { id firstName lastName } data } } } } `; export const ADD_NOTE_TO_CUSTOMER = gql` mutation AddNoteToCustomer($input: AddNoteToCustomerInput!) { addNoteToCustomer(input: $input) { id } } `; export const UPDATE_CUSTOMER_NOTE = gql` mutation UpdateCustomerNote($input: UpdateCustomerNoteInput!) { updateCustomerNote(input: $input) { id data isPublic } } `; export const DELETE_CUSTOMER_NOTE = gql` mutation DeleteCustomerNote($id: ID!) { deleteCustomerNote(id: $id) { result message } } `;
import { gql } from 'apollo-angular'; export const FACET_VALUE_FRAGMENT = gql` fragment FacetValue on FacetValue { id createdAt updatedAt languageCode code name translations { id languageCode name } facet { id createdAt updatedAt name } } `; export const FACET_WITH_VALUES_FRAGMENT = gql` fragment FacetWithValues on Facet { id createdAt updatedAt languageCode isPrivate code name translations { id languageCode name } values { ...FacetValue } } ${FACET_VALUE_FRAGMENT} `; export const FACET_WITH_VALUE_LIST_FRAGMENT = gql` fragment FacetWithValueList on Facet { id createdAt updatedAt languageCode isPrivate code name translations { id languageCode name } valueList(options: $facetValueListOptions) { totalItems items { ...FacetValue } } } ${FACET_VALUE_FRAGMENT} `; export const CREATE_FACET = gql` mutation CreateFacet($input: CreateFacetInput!) { createFacet(input: $input) { ...FacetWithValues } } ${FACET_WITH_VALUES_FRAGMENT} `; export const UPDATE_FACET = gql` mutation UpdateFacet($input: UpdateFacetInput!) { updateFacet(input: $input) { ...FacetWithValues } } ${FACET_WITH_VALUES_FRAGMENT} `; export const DELETE_FACET = gql` mutation DeleteFacet($id: ID!, $force: Boolean) { deleteFacet(id: $id, force: $force) { result message } } `; export const DELETE_FACETS = gql` mutation DeleteFacets($ids: [ID!]!, $force: Boolean) { deleteFacets(ids: $ids, force: $force) { result message } } `; export const CREATE_FACET_VALUES = gql` mutation CreateFacetValues($input: [CreateFacetValueInput!]!) { createFacetValues(input: $input) { ...FacetValue } } ${FACET_VALUE_FRAGMENT} `; export const UPDATE_FACET_VALUES = gql` mutation UpdateFacetValues($input: [UpdateFacetValueInput!]!) { updateFacetValues(input: $input) { ...FacetValue } } ${FACET_VALUE_FRAGMENT} `; export const DELETE_FACET_VALUES = gql` mutation DeleteFacetValues($ids: [ID!]!, $force: Boolean) { deleteFacetValues(ids: $ids, force: $force) { result message } } `; export const GET_FACET_VALUE_LIST = gql` query GetFacetValueList($options: FacetValueListOptions) { facetValues(options: $options) { items { ...FacetValue } totalItems } } ${FACET_VALUE_FRAGMENT} `; export const ASSIGN_FACETS_TO_CHANNEL = gql` mutation AssignFacetsToChannel($input: AssignFacetsToChannelInput!) { assignFacetsToChannel(input: $input) { id } } `; export const REMOVE_FACETS_FROM_CHANNEL = gql` mutation RemoveFacetsFromChannel($input: RemoveFacetsFromChannelInput!) { removeFacetsFromChannel(input: $input) { ... on Facet { id } ... on FacetInUseError { errorCode message variantCount productCount } } } `;
import { gql } from 'apollo-angular'; import { ERROR_RESULT_FRAGMENT } from './shared-definitions'; export const DISCOUNT_FRAGMENT = gql` fragment Discount on Discount { adjustmentSource amount amountWithTax description type } `; export const PAYMENT_FRAGMENT = gql` fragment Payment on Payment { id transactionId amount method state metadata } `; export const REFUND_FRAGMENT = gql` fragment Refund on Refund { id state items shipping adjustment transactionId paymentId } `; export const ORDER_ADDRESS_FRAGMENT = gql` fragment OrderAddress on OrderAddress { fullName company streetLine1 streetLine2 city province postalCode country countryCode phoneNumber } `; export const ORDER_FRAGMENT = gql` fragment Order on Order { id createdAt updatedAt type orderPlacedAt code state nextStates total totalWithTax currencyCode customer { id firstName lastName } shippingLines { shippingMethod { name } } } `; export const FULFILLMENT_FRAGMENT = gql` fragment Fulfillment on Fulfillment { id state nextStates createdAt updatedAt method lines { orderLineId quantity } trackingCode } `; export const PAYMENT_WITH_REFUNDS_FRAGMENT = gql` fragment PaymentWithRefunds on Payment { id createdAt transactionId amount method state nextStates errorMessage metadata refunds { id createdAt state items adjustment total paymentId reason transactionId method metadata lines { orderLineId quantity } } } `; export const ORDER_LINE_FRAGMENT = gql` fragment OrderLine on OrderLine { id createdAt updatedAt featuredAsset { preview } productVariant { id name sku trackInventory stockOnHand } discounts { ...Discount } fulfillmentLines { fulfillmentId quantity } unitPrice unitPriceWithTax proratedUnitPrice proratedUnitPriceWithTax quantity orderPlacedQuantity linePrice lineTax linePriceWithTax discountedLinePrice discountedLinePriceWithTax } `; export const ORDER_DETAIL_FRAGMENT = gql` fragment OrderDetail on Order { id createdAt updatedAt type aggregateOrder { id code } sellerOrders { id code channels { id code } } code state nextStates active couponCodes customer { id firstName lastName } lines { ...OrderLine } surcharges { id sku description price priceWithTax taxRate } discounts { ...Discount } promotions { id couponCode } subTotal subTotalWithTax total totalWithTax currencyCode shipping shippingWithTax shippingLines { id discountedPriceWithTax shippingMethod { id code name fulfillmentHandlerCode description } } taxSummary { description taxBase taxRate taxTotal } shippingAddress { ...OrderAddress } billingAddress { ...OrderAddress } payments { ...PaymentWithRefunds } fulfillments { ...Fulfillment } modifications { id createdAt isSettled priceChange note payment { id amount } lines { orderLineId quantity } refund { id paymentId total } surcharges { id } } } ${DISCOUNT_FRAGMENT} ${ORDER_ADDRESS_FRAGMENT} ${FULFILLMENT_FRAGMENT} ${ORDER_LINE_FRAGMENT} ${PAYMENT_WITH_REFUNDS_FRAGMENT} `; export const GET_ORDERS_LIST = gql` query GetOrderList($options: OrderListOptions) { orders(options: $options) { items { ...Order } totalItems } } ${ORDER_FRAGMENT} `; export const GET_ORDER = gql` query GetOrder($id: ID!) { order(id: $id) { ...OrderDetail } } ${ORDER_DETAIL_FRAGMENT} `; export const SETTLE_PAYMENT = gql` mutation SettlePayment($id: ID!) { settlePayment(id: $id) { ...Payment ...ErrorResult ... on SettlePaymentError { paymentErrorMessage } ... on PaymentStateTransitionError { transitionError } ... on OrderStateTransitionError { transitionError } } } ${ERROR_RESULT_FRAGMENT} ${PAYMENT_FRAGMENT} `; export const CANCEL_PAYMENT = gql` mutation CancelPayment($id: ID!) { cancelPayment(id: $id) { ...Payment ...ErrorResult ... on CancelPaymentError { paymentErrorMessage } ... on PaymentStateTransitionError { transitionError } } } ${ERROR_RESULT_FRAGMENT} ${PAYMENT_FRAGMENT} `; export const TRANSITION_PAYMENT_TO_STATE = gql` mutation TransitionPaymentToState($id: ID!, $state: String!) { transitionPaymentToState(id: $id, state: $state) { ...Payment ...ErrorResult ... on PaymentStateTransitionError { transitionError } } } ${PAYMENT_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const CREATE_FULFILLMENT = gql` mutation CreateFulfillment($input: FulfillOrderInput!) { addFulfillmentToOrder(input: $input) { ...Fulfillment ... on CreateFulfillmentError { errorCode message fulfillmentHandlerError } ... on FulfillmentStateTransitionError { errorCode message transitionError } ...ErrorResult } } ${FULFILLMENT_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const CANCEL_ORDER = gql` mutation CancelOrder($input: CancelOrderInput!) { cancelOrder(input: $input) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const REFUND_ORDER = gql` mutation RefundOrder($input: RefundOrderInput!) { refundOrder(input: $input) { ...Refund ...ErrorResult } } ${REFUND_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const SETTLE_REFUND = gql` mutation SettleRefund($input: SettleRefundInput!) { settleRefund(input: $input) { ...Refund ...ErrorResult } } ${REFUND_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const GET_ORDER_HISTORY = gql` query GetOrderHistory($id: ID!, $options: HistoryEntryListOptions) { order(id: $id) { id history(options: $options) { totalItems items { id type createdAt isPublic administrator { id firstName lastName } data } } } } `; export const ADD_NOTE_TO_ORDER = gql` mutation AddNoteToOrder($input: AddNoteToOrderInput!) { addNoteToOrder(input: $input) { id } } `; export const UPDATE_ORDER_NOTE = gql` mutation UpdateOrderNote($input: UpdateOrderNoteInput!) { updateOrderNote(input: $input) { id data isPublic } } `; export const DELETE_ORDER_NOTE = gql` mutation DeleteOrderNote($id: ID!) { deleteOrderNote(id: $id) { result message } } `; export const TRANSITION_ORDER_TO_STATE = gql` mutation TransitionOrderToState($id: ID!, $state: String!) { transitionOrderToState(id: $id, state: $state) { ...Order ...ErrorResult ... on OrderStateTransitionError { transitionError } } } ${ORDER_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const UPDATE_ORDER_CUSTOM_FIELDS = gql` mutation UpdateOrderCustomFields($input: UpdateOrderInput!) { setOrderCustomFields(input: $input) { ...Order } } ${ORDER_FRAGMENT} `; export const TRANSITION_FULFILLMENT_TO_STATE = gql` mutation TransitionFulfillmentToState($id: ID!, $state: String!) { transitionFulfillmentToState(id: $id, state: $state) { ...Fulfillment ...ErrorResult ... on FulfillmentStateTransitionError { transitionError } } } ${FULFILLMENT_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const MODIFY_ORDER = gql` mutation ModifyOrder($input: ModifyOrderInput!) { modifyOrder(input: $input) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const ADD_MANUAL_PAYMENT_TO_ORDER = gql` mutation AddManualPayment($input: ManualPaymentInput!) { addManualPaymentToOrder(input: $input) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const CREATE_DRAFT_ORDER = gql` mutation CreateDraftOrder { createDraftOrder { ...OrderDetail } } ${ORDER_DETAIL_FRAGMENT} `; export const DELETE_DRAFT_ORDER = gql` mutation DeleteDraftOrder($orderId: ID!) { deleteDraftOrder(orderId: $orderId) { result message } } `; export const ADD_ITEM_TO_DRAFT_ORDER = gql` mutation AddItemToDraftOrder($orderId: ID!, $input: AddItemToDraftOrderInput!) { addItemToDraftOrder(orderId: $orderId, input: $input) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const ADJUST_DRAFT_ORDER_LINE = gql` mutation AdjustDraftOrderLine($orderId: ID!, $input: AdjustDraftOrderLineInput!) { adjustDraftOrderLine(orderId: $orderId, input: $input) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const REMOVE_DRAFT_ORDER_LINE = gql` mutation RemoveDraftOrderLine($orderId: ID!, $orderLineId: ID!) { removeDraftOrderLine(orderId: $orderId, orderLineId: $orderLineId) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const SET_CUSTOMER_FOR_DRAFT_ORDER = gql` mutation SetCustomerForDraftOrder($orderId: ID!, $customerId: ID, $input: CreateCustomerInput) { setCustomerForDraftOrder(orderId: $orderId, customerId: $customerId, input: $input) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const SET_SHIPPING_ADDRESS_FOR_DRAFT_ORDER = gql` mutation SetDraftOrderShippingAddress($orderId: ID!, $input: CreateAddressInput!) { setDraftOrderShippingAddress(orderId: $orderId, input: $input) { ...OrderDetail } } ${ORDER_DETAIL_FRAGMENT} `; export const SET_BILLING_ADDRESS_FOR_DRAFT_ORDER = gql` mutation SetDraftOrderBillingAddress($orderId: ID!, $input: CreateAddressInput!) { setDraftOrderBillingAddress(orderId: $orderId, input: $input) { ...OrderDetail } } ${ORDER_DETAIL_FRAGMENT} `; export const APPLY_COUPON_CODE_TO_DRAFT_ORDER = gql` mutation ApplyCouponCodeToDraftOrder($orderId: ID!, $couponCode: String!) { applyCouponCodeToDraftOrder(orderId: $orderId, couponCode: $couponCode) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const REMOVE_COUPON_CODE_FROM_DRAFT_ORDER = gql` mutation RemoveCouponCodeFromDraftOrder($orderId: ID!, $couponCode: String!) { removeCouponCodeFromDraftOrder(orderId: $orderId, couponCode: $couponCode) { ...OrderDetail } } ${ORDER_DETAIL_FRAGMENT} `; export const DRAFT_ORDER_ELIGIBLE_SHIPPING_METHODS = gql` query DraftOrderEligibleShippingMethods($orderId: ID!) { eligibleShippingMethodsForDraftOrder(orderId: $orderId) { id name code description price priceWithTax metadata } } `; export const SET_DRAFT_ORDER_SHIPPING_METHOD = gql` mutation SetDraftOrderShippingMethod($orderId: ID!, $shippingMethodId: ID!) { setDraftOrderShippingMethod(orderId: $orderId, shippingMethodId: $shippingMethodId) { ...OrderDetail ...ErrorResult } } ${ORDER_DETAIL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `;
import { gql } from 'apollo-angular'; import { ERROR_RESULT_FRAGMENT } from './shared-definitions'; export const ASSET_FRAGMENT = gql` fragment Asset on Asset { id createdAt updatedAt name fileSize mimeType type preview source width height focalPoint { x y } } `; export const TAG_FRAGMENT = gql` fragment Tag on Tag { id value } `; export const PRODUCT_OPTION_GROUP_FRAGMENT = gql` fragment ProductOptionGroup on ProductOptionGroup { id createdAt updatedAt code languageCode name translations { id languageCode name } } `; export const PRODUCT_OPTION_FRAGMENT = gql` fragment ProductOption on ProductOption { id createdAt updatedAt code languageCode name groupId translations { id languageCode name } } `; export const PRODUCT_VARIANT_FRAGMENT = gql` fragment ProductVariant on ProductVariant { id createdAt updatedAt enabled languageCode name price currencyCode priceWithTax stockOnHand stockAllocated trackInventory outOfStockThreshold useGlobalOutOfStockThreshold taxRateApplied { id name value } taxCategory { id name } sku options { ...ProductOption } facetValues { id code name facet { id name } } featuredAsset { ...Asset } assets { ...Asset } translations { id languageCode name } channels { id code } } ${PRODUCT_OPTION_FRAGMENT} ${ASSET_FRAGMENT} `; export const PRODUCT_DETAIL_FRAGMENT = gql` fragment ProductDetail on Product { id createdAt updatedAt enabled languageCode name slug description featuredAsset { ...Asset } assets { ...Asset } translations { id languageCode name slug description } optionGroups { ...ProductOptionGroup } facetValues { id code name facet { id name } } channels { id code } } ${PRODUCT_OPTION_GROUP_FRAGMENT} ${ASSET_FRAGMENT} `; export const PRODUCT_OPTION_GROUP_WITH_OPTIONS_FRAGMENT = gql` fragment ProductOptionGroupWithOptions on ProductOptionGroup { id createdAt updatedAt languageCode code name translations { id name } options { id languageCode name code translations { name } } } `; export const UPDATE_PRODUCT = gql` mutation UpdateProduct($input: UpdateProductInput!, $variantListOptions: ProductVariantListOptions) { updateProduct(input: $input) { ...ProductDetail variantList(options: $variantListOptions) { items { ...ProductVariant } totalItems } } } ${PRODUCT_DETAIL_FRAGMENT} ${PRODUCT_VARIANT_FRAGMENT} `; export const CREATE_PRODUCT = gql` mutation CreateProduct($input: CreateProductInput!, $variantListOptions: ProductVariantListOptions) { createProduct(input: $input) { ...ProductDetail variantList(options: $variantListOptions) { items { ...ProductVariant } totalItems } } } ${PRODUCT_DETAIL_FRAGMENT} ${PRODUCT_VARIANT_FRAGMENT} `; export const DELETE_PRODUCT = gql` mutation DeleteProduct($id: ID!) { deleteProduct(id: $id) { result message } } `; export const DELETE_PRODUCTS = gql` mutation DeleteProducts($ids: [ID!]!) { deleteProducts(ids: $ids) { result message } } `; export const CREATE_PRODUCT_VARIANTS = gql` mutation CreateProductVariants($input: [CreateProductVariantInput!]!) { createProductVariants(input: $input) { ...ProductVariant } } ${PRODUCT_VARIANT_FRAGMENT} `; export const UPDATE_PRODUCT_VARIANTS = gql` mutation UpdateProductVariants($input: [UpdateProductVariantInput!]!) { updateProductVariants(input: $input) { ...ProductVariant } } ${PRODUCT_VARIANT_FRAGMENT} `; export const CREATE_PRODUCT_OPTION_GROUP = gql` mutation CreateProductOptionGroup($input: CreateProductOptionGroupInput!) { createProductOptionGroup(input: $input) { ...ProductOptionGroupWithOptions } } ${PRODUCT_OPTION_GROUP_WITH_OPTIONS_FRAGMENT} `; export const GET_PRODUCT_OPTION_GROUP = gql` query GetProductOptionGroup($id: ID!) { productOptionGroup(id: $id) { ...ProductOptionGroupWithOptions } } ${PRODUCT_OPTION_GROUP_WITH_OPTIONS_FRAGMENT} `; export const ADD_OPTION_TO_GROUP = gql` mutation AddOptionToGroup($input: CreateProductOptionInput!) { createProductOption(input: $input) { id createdAt updatedAt name code groupId } } `; export const ADD_OPTION_GROUP_TO_PRODUCT = gql` mutation AddOptionGroupToProduct($productId: ID!, $optionGroupId: ID!) { addOptionGroupToProduct(productId: $productId, optionGroupId: $optionGroupId) { id createdAt updatedAt optionGroups { id createdAt updatedAt code options { id createdAt updatedAt code } } } } `; export const REMOVE_OPTION_GROUP_FROM_PRODUCT = gql` mutation RemoveOptionGroupFromProduct($productId: ID!, $optionGroupId: ID!, $force: Boolean) { removeOptionGroupFromProduct(productId: $productId, optionGroupId: $optionGroupId, force: $force) { ... on Product { id createdAt updatedAt optionGroups { id createdAt updatedAt code options { id createdAt updatedAt code } } } ...ErrorResult } } ${ERROR_RESULT_FRAGMENT} `; export const GET_PRODUCT_WITH_VARIANTS = gql` query GetProductWithVariants($id: ID!, $variantListOptions: ProductVariantListOptions) { product(id: $id) { ...ProductDetail variantList(options: $variantListOptions) { items { ...ProductVariant } totalItems } } } ${PRODUCT_DETAIL_FRAGMENT} ${PRODUCT_VARIANT_FRAGMENT} `; export const GET_PRODUCT_SIMPLE = gql` query GetProductSimple($id: ID!) { product(id: $id) { id name featuredAsset { ...Asset } } } ${ASSET_FRAGMENT} `; export const PRODUCT_FOR_LIST_FRAGMENT = gql` fragment ProductForList on Product { id createdAt updatedAt enabled languageCode name slug featuredAsset { id createdAt updatedAt preview focalPoint { x y } } variantList { totalItems } } `; export const GET_PRODUCT_LIST = gql` query GetProductList($options: ProductListOptions) { products(options: $options) { items { ...ProductForList } totalItems } } ${PRODUCT_FOR_LIST_FRAGMENT} `; export const GET_PRODUCT_OPTION_GROUPS = gql` query GetProductOptionGroups($filterTerm: String) { productOptionGroups(filterTerm: $filterTerm) { id createdAt updatedAt languageCode code name options { id createdAt updatedAt languageCode code name } } } `; export const GET_ASSET_LIST = gql` query GetAssetList($options: AssetListOptions) { assets(options: $options) { items { ...Asset tags { ...Tag } } totalItems } } ${ASSET_FRAGMENT} ${TAG_FRAGMENT} `; export const GET_ASSET = gql` query GetAsset($id: ID!) { asset(id: $id) { ...Asset tags { ...Tag } } } ${ASSET_FRAGMENT} ${TAG_FRAGMENT} `; export const CREATE_ASSETS = gql` mutation CreateAssets($input: [CreateAssetInput!]!) { createAssets(input: $input) { ...Asset ... on Asset { tags { ...Tag } } ... on ErrorResult { message } } } ${ASSET_FRAGMENT} ${TAG_FRAGMENT} `; export const UPDATE_ASSET = gql` mutation UpdateAsset($input: UpdateAssetInput!) { updateAsset(input: $input) { ...Asset tags { ...Tag } } } ${ASSET_FRAGMENT} ${TAG_FRAGMENT} `; export const DELETE_ASSETS = gql` mutation DeleteAssets($input: DeleteAssetsInput!) { deleteAssets(input: $input) { result message } } `; export const SEARCH_PRODUCTS = gql` query SearchProducts($input: SearchInput!) { search(input: $input) { totalItems items { enabled productId productName slug priceWithTax { ... on PriceRange { min max } ... on SinglePrice { value } } productAsset { id preview focalPoint { x y } } currencyCode productVariantId productVariantName productVariantAsset { id preview focalPoint { x y } } sku channelIds } facetValues { count facetValue { id createdAt updatedAt name facet { id createdAt updatedAt name } } } } } `; export const PRODUCT_SELECTOR_SEARCH = gql` query ProductSelectorSearch($term: String!, $take: Int!) { search(input: { groupByProduct: false, term: $term, take: $take }) { items { productVariantId productVariantName productAsset { id preview focalPoint { x y } } price { ... on SinglePrice { value } } priceWithTax { ... on SinglePrice { value } } sku } } } `; export const UPDATE_PRODUCT_OPTION_GROUP = gql` mutation UpdateProductOptionGroup($input: UpdateProductOptionGroupInput!) { updateProductOptionGroup(input: $input) { ...ProductOptionGroup } } ${PRODUCT_OPTION_GROUP_FRAGMENT} `; export const UPDATE_PRODUCT_OPTION = gql` mutation UpdateProductOption($input: UpdateProductOptionInput!) { updateProductOption(input: $input) { ...ProductOption } } ${PRODUCT_OPTION_FRAGMENT} `; export const DELETE_PRODUCT_OPTION = gql` mutation DeleteProductOption($id: ID!) { deleteProductOption(id: $id) { result message } } `; export const DELETE_PRODUCT_VARIANT = gql` mutation DeleteProductVariant($id: ID!) { deleteProductVariant(id: $id) { result message } } `; export const DELETE_PRODUCT_VARIANTS = gql` mutation DeleteProductVariants($ids: [ID!]!) { deleteProductVariants(ids: $ids) { result message } } `; export const GET_PRODUCT_VARIANT_OPTIONS = gql` query GetProductVariantOptions($id: ID!) { product(id: $id) { id createdAt updatedAt name languageCode optionGroups { ...ProductOptionGroup options { ...ProductOption } } variants { id createdAt updatedAt enabled name sku price priceWithTax currencyCode stockOnHand enabled options { id createdAt updatedAt name code groupId } } } } ${PRODUCT_OPTION_GROUP_FRAGMENT} ${PRODUCT_OPTION_FRAGMENT} `; export const ASSIGN_PRODUCTS_TO_CHANNEL = gql` mutation AssignProductsToChannel($input: AssignProductsToChannelInput!) { assignProductsToChannel(input: $input) { id channels { id code } } } `; export const ASSIGN_VARIANTS_TO_CHANNEL = gql` mutation AssignVariantsToChannel($input: AssignProductVariantsToChannelInput!) { assignProductVariantsToChannel(input: $input) { id channels { id code } } } `; export const REMOVE_PRODUCTS_FROM_CHANNEL = gql` mutation RemoveProductsFromChannel($input: RemoveProductsFromChannelInput!) { removeProductsFromChannel(input: $input) { id channels { id code } } } `; export const REMOVE_VARIANTS_FROM_CHANNEL = gql` mutation RemoveVariantsFromChannel($input: RemoveProductVariantsFromChannelInput!) { removeProductVariantsFromChannel(input: $input) { id channels { id code } } } `; export const GET_PRODUCT_VARIANT = gql` query GetProductVariant($id: ID!) { productVariant(id: $id) { id name sku stockOnHand stockAllocated stockLevel useGlobalOutOfStockThreshold featuredAsset { id preview focalPoint { x y } } price priceWithTax product { id featuredAsset { id preview focalPoint { x y } } } } } `; export const GET_PRODUCT_VARIANT_LIST_SIMPLE = gql` query GetProductVariantListSimple($options: ProductVariantListOptions!, $productId: ID) { productVariants(options: $options, productId: $productId) { items { id name sku featuredAsset { id preview focalPoint { x y } } product { id featuredAsset { id preview focalPoint { x y } } } } totalItems } } `; export const GET_PRODUCT_VARIANT_LIST_FOR_PRODUCT = gql` query GetProductVariantListForProduct($options: ProductVariantListOptions!, $productId: ID) { productVariants(options: $options, productId: $productId) { items { ...ProductVariant } totalItems } } ${PRODUCT_VARIANT_FRAGMENT} `; export const GET_PRODUCT_VARIANT_LIST = gql` query GetProductVariantList($options: ProductVariantListOptions!) { productVariants(options: $options) { items { id createdAt updatedAt enabled languageCode name price currencyCode priceWithTax trackInventory outOfStockThreshold stockLevels { id createdAt updatedAt stockLocationId stockOnHand stockAllocated stockLocation { id createdAt updatedAt name } } useGlobalOutOfStockThreshold sku featuredAsset { ...Asset } } totalItems } } ${ASSET_FRAGMENT} `; export const GET_TAG_LIST = gql` query GetTagList($options: TagListOptions) { tags(options: $options) { items { ...Tag } totalItems } } ${TAG_FRAGMENT} `; export const GET_TAG = gql` query GetTag($id: ID!) { tag(id: $id) { ...Tag } } ${TAG_FRAGMENT} `; export const CREATE_TAG = gql` mutation CreateTag($input: CreateTagInput!) { createTag(input: $input) { ...Tag } } ${TAG_FRAGMENT} `; export const UPDATE_TAG = gql` mutation UpdateTag($input: UpdateTagInput!) { updateTag(input: $input) { ...Tag } } ${TAG_FRAGMENT} `; export const DELETE_TAG = gql` mutation DeleteTag($id: ID!) { deleteTag(id: $id) { message result } } `;
import { gql } from 'apollo-angular'; import { CONFIGURABLE_OPERATION_DEF_FRAGMENT, CONFIGURABLE_OPERATION_FRAGMENT, ERROR_RESULT_FRAGMENT, } from './shared-definitions'; export const PROMOTION_FRAGMENT = gql` fragment Promotion on Promotion { id createdAt updatedAt name description enabled couponCode perCustomerUsageLimit usageLimit startsAt endsAt conditions { ...ConfigurableOperation } actions { ...ConfigurableOperation } translations { id languageCode name description } } ${CONFIGURABLE_OPERATION_FRAGMENT} `; export const GET_ADJUSTMENT_OPERATIONS = gql` query GetAdjustmentOperations { promotionConditions { ...ConfigurableOperationDef } promotionActions { ...ConfigurableOperationDef } } ${CONFIGURABLE_OPERATION_DEF_FRAGMENT} `; export const CREATE_PROMOTION = gql` mutation CreatePromotion($input: CreatePromotionInput!) { createPromotion(input: $input) { ...Promotion ...ErrorResult } } ${PROMOTION_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const UPDATE_PROMOTION = gql` mutation UpdatePromotion($input: UpdatePromotionInput!) { updatePromotion(input: $input) { ...Promotion } } ${PROMOTION_FRAGMENT} `; export const DELETE_PROMOTION = gql` mutation DeletePromotion($id: ID!) { deletePromotion(id: $id) { result message } } `; export const DELETE_PROMOTIONS = gql` mutation DeletePromotions($ids: [ID!]!) { deletePromotions(ids: $ids) { result message } } `;
import { gql } from 'apollo-angular'; import { CONFIGURABLE_OPERATION_DEF_FRAGMENT, CONFIGURABLE_OPERATION_FRAGMENT, ERROR_RESULT_FRAGMENT, } from './shared-definitions'; export const COUNTRY_FRAGMENT = gql` fragment Country on Country { id createdAt updatedAt code name enabled translations { id languageCode name } } `; export const GET_AVAILABLE_COUNTRIES = gql` query GetAvailableCountries { countries(options: { filter: { enabled: { eq: true } } }) { items { id code name enabled } } } `; export const CREATE_COUNTRY = gql` mutation CreateCountry($input: CreateCountryInput!) { createCountry(input: $input) { ...Country } } ${COUNTRY_FRAGMENT} `; export const UPDATE_COUNTRY = gql` mutation UpdateCountry($input: UpdateCountryInput!) { updateCountry(input: $input) { ...Country } } ${COUNTRY_FRAGMENT} `; export const DELETE_COUNTRY = gql` mutation DeleteCountry($id: ID!) { deleteCountry(id: $id) { result message } } `; export const DELETE_COUNTRIES = gql` mutation DeleteCountries($ids: [ID!]!) { deleteCountries(ids: $ids) { result message } } `; export const ZONE_FRAGMENT = gql` fragment Zone on Zone { id createdAt updatedAt name members { ...Country } } ${COUNTRY_FRAGMENT} `; export const GET_ZONE = gql` query GetZone($id: ID!) { zone(id: $id) { ...Zone } } ${ZONE_FRAGMENT} `; export const CREATE_ZONE = gql` mutation CreateZone($input: CreateZoneInput!) { createZone(input: $input) { ...Zone } } ${ZONE_FRAGMENT} `; export const UPDATE_ZONE = gql` mutation UpdateZone($input: UpdateZoneInput!) { updateZone(input: $input) { ...Zone } } ${ZONE_FRAGMENT} `; export const DELETE_ZONE = gql` mutation DeleteZone($id: ID!) { deleteZone(id: $id) { message result } } `; export const DELETE_ZONES = gql` mutation DeleteZones($ids: [ID!]!) { deleteZones(ids: $ids) { message result } } `; export const ADD_MEMBERS_TO_ZONE = gql` mutation AddMembersToZone($zoneId: ID!, $memberIds: [ID!]!) { addMembersToZone(zoneId: $zoneId, memberIds: $memberIds) { ...Zone } } ${ZONE_FRAGMENT} `; export const REMOVE_MEMBERS_FROM_ZONE = gql` mutation RemoveMembersFromZone($zoneId: ID!, $memberIds: [ID!]!) { removeMembersFromZone(zoneId: $zoneId, memberIds: $memberIds) { ...Zone } } ${ZONE_FRAGMENT} `; export const TAX_CATEGORY_FRAGMENT = gql` fragment TaxCategory on TaxCategory { id createdAt updatedAt name isDefault } `; export const GET_TAX_CATEGORIES = gql` query GetTaxCategories($options: TaxCategoryListOptions) { taxCategories(options: $options) { items { ...TaxCategory } totalItems } } ${TAX_CATEGORY_FRAGMENT} `; export const CREATE_TAX_CATEGORY = gql` mutation CreateTaxCategory($input: CreateTaxCategoryInput!) { createTaxCategory(input: $input) { ...TaxCategory } } ${TAX_CATEGORY_FRAGMENT} `; export const UPDATE_TAX_CATEGORY = gql` mutation UpdateTaxCategory($input: UpdateTaxCategoryInput!) { updateTaxCategory(input: $input) { ...TaxCategory } } ${TAX_CATEGORY_FRAGMENT} `; export const DELETE_TAX_CATEGORY = gql` mutation DeleteTaxCategory($id: ID!) { deleteTaxCategory(id: $id) { result message } } `; export const DELETE_TAX_CATEGORIES = gql` mutation DeleteTaxCategories($ids: [ID!]!) { deleteTaxCategories(ids: $ids) { result message } } `; export const TAX_RATE_FRAGMENT = gql` fragment TaxRate on TaxRate { id createdAt updatedAt name enabled value category { id name } zone { id name } customerGroup { id name } } `; export const GET_TAX_RATE_LIST_SIMPLE = gql` query GetTaxRateListSimple($options: TaxRateListOptions) { taxRates(options: $options) { items { id createdAt updatedAt name enabled value category { id name } zone { id name } } totalItems } } `; export const CREATE_TAX_RATE = gql` mutation CreateTaxRate($input: CreateTaxRateInput!) { createTaxRate(input: $input) { ...TaxRate } } ${TAX_RATE_FRAGMENT} `; export const UPDATE_TAX_RATE = gql` mutation UpdateTaxRate($input: UpdateTaxRateInput!) { updateTaxRate(input: $input) { ...TaxRate } } ${TAX_RATE_FRAGMENT} `; export const DELETE_TAX_RATE = gql` mutation DeleteTaxRate($id: ID!) { deleteTaxRate(id: $id) { result message } } `; export const DELETE_TAX_RATES = gql` mutation DeleteTaxRates($ids: [ID!]!) { deleteTaxRates(ids: $ids) { result message } } `; export const CHANNEL_FRAGMENT = gql` fragment Channel on Channel { id createdAt updatedAt code token pricesIncludeTax availableCurrencyCodes availableLanguageCodes defaultCurrencyCode defaultLanguageCode defaultShippingZone { id name } defaultTaxZone { id name } seller { id name } } `; export const SELLER_FRAGMENT = gql` fragment Seller on Seller { id createdAt updatedAt name } `; export const GET_CHANNELS = gql` query GetChannels($options: ChannelListOptions) { channels(options: $options) { items { ...Channel } totalItems } } ${CHANNEL_FRAGMENT} `; export const GET_SELLERS = gql` query GetSellers($options: SellerListOptions) { sellers(options: $options) { items { ...Seller } totalItems } } ${SELLER_FRAGMENT} `; export const CREATE_SELLER = gql` mutation CreateSeller($input: CreateSellerInput!) { createSeller(input: $input) { ...Seller } } ${SELLER_FRAGMENT} `; export const UPDATE_SELLER = gql` mutation UpdateSeller($input: UpdateSellerInput!) { updateSeller(input: $input) { ...Seller } } ${SELLER_FRAGMENT} `; export const DELETE_SELLER = gql` mutation DeleteSeller($id: ID!) { deleteSeller(id: $id) { result message } } `; export const DELETE_SELLERS = gql` mutation DeleteSellers($ids: [ID!]!) { deleteSellers(ids: $ids) { result message } } `; export const GET_ACTIVE_CHANNEL = gql` query GetActiveChannel { activeChannel { ...Channel } } ${CHANNEL_FRAGMENT} `; export const CREATE_CHANNEL = gql` mutation CreateChannel($input: CreateChannelInput!) { createChannel(input: $input) { ...Channel ...ErrorResult } } ${CHANNEL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const UPDATE_CHANNEL = gql` mutation UpdateChannel($input: UpdateChannelInput!) { updateChannel(input: $input) { ...Channel ...ErrorResult } } ${CHANNEL_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const DELETE_CHANNEL = gql` mutation DeleteChannel($id: ID!) { deleteChannel(id: $id) { result message } } `; export const DELETE_CHANNELS = gql` mutation DeleteChannels($ids: [ID!]!) { deleteChannels(ids: $ids) { result message } } `; export const PAYMENT_METHOD_FRAGMENT = gql` fragment PaymentMethod on PaymentMethod { id createdAt updatedAt name code description enabled translations { id languageCode name description } checker { ...ConfigurableOperation } handler { ...ConfigurableOperation } } ${CONFIGURABLE_OPERATION_FRAGMENT} `; export const GET_PAYMENT_METHOD_OPERATIONS = gql` query GetPaymentMethodOperations { paymentMethodEligibilityCheckers { ...ConfigurableOperationDef } paymentMethodHandlers { ...ConfigurableOperationDef } } ${CONFIGURABLE_OPERATION_DEF_FRAGMENT} `; export const CREATE_PAYMENT_METHOD = gql` mutation CreatePaymentMethod($input: CreatePaymentMethodInput!) { createPaymentMethod(input: $input) { ...PaymentMethod } } ${PAYMENT_METHOD_FRAGMENT} `; export const UPDATE_PAYMENT_METHOD = gql` mutation UpdatePaymentMethod($input: UpdatePaymentMethodInput!) { updatePaymentMethod(input: $input) { ...PaymentMethod } } ${PAYMENT_METHOD_FRAGMENT} `; export const DELETE_PAYMENT_METHOD = gql` mutation DeletePaymentMethod($id: ID!, $force: Boolean) { deletePaymentMethod(id: $id, force: $force) { result message } } `; export const DELETE_PAYMENT_METHODS = gql` mutation DeletePaymentMethods($ids: [ID!]!, $force: Boolean) { deletePaymentMethods(ids: $ids, force: $force) { result message } } `; export const GLOBAL_SETTINGS_FRAGMENT = gql` fragment GlobalSettings on GlobalSettings { id availableLanguages trackInventory outOfStockThreshold serverConfig { permissions { name description assignable } orderProcess { name } } } `; export const GET_GLOBAL_SETTINGS = gql` query GetGlobalSettings { globalSettings { ...GlobalSettings } } ${GLOBAL_SETTINGS_FRAGMENT} `; export const UPDATE_GLOBAL_SETTINGS = gql` mutation UpdateGlobalSettings($input: UpdateGlobalSettingsInput!) { updateGlobalSettings(input: $input) { ...GlobalSettings ...ErrorResult } } ${GLOBAL_SETTINGS_FRAGMENT} ${ERROR_RESULT_FRAGMENT} `; export const CUSTOM_FIELD_CONFIG_FRAGMENT = gql` fragment CustomFieldConfig on CustomField { name type list description { languageCode value } label { languageCode value } readonly nullable requiresPermission ui } `; export const STRING_CUSTOM_FIELD_FRAGMENT = gql` fragment StringCustomField on StringCustomFieldConfig { ...CustomFieldConfig pattern options { label { languageCode value } value } } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const LOCALE_STRING_CUSTOM_FIELD_FRAGMENT = gql` fragment LocaleStringCustomField on LocaleStringCustomFieldConfig { ...CustomFieldConfig pattern } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const TEXT_CUSTOM_FIELD_FRAGMENT = gql` fragment TextCustomField on TextCustomFieldConfig { ...CustomFieldConfig } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const LOCALE_TEXT_CUSTOM_FIELD_FRAGMENT = gql` fragment LocaleTextCustomField on LocaleTextCustomFieldConfig { ...CustomFieldConfig } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const BOOLEAN_CUSTOM_FIELD_FRAGMENT = gql` fragment BooleanCustomField on BooleanCustomFieldConfig { ...CustomFieldConfig } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const INT_CUSTOM_FIELD_FRAGMENT = gql` fragment IntCustomField on IntCustomFieldConfig { ...CustomFieldConfig intMin: min intMax: max intStep: step } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const FLOAT_CUSTOM_FIELD_FRAGMENT = gql` fragment FloatCustomField on FloatCustomFieldConfig { ...CustomFieldConfig floatMin: min floatMax: max floatStep: step } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const DATE_TIME_CUSTOM_FIELD_FRAGMENT = gql` fragment DateTimeCustomField on DateTimeCustomFieldConfig { ...CustomFieldConfig datetimeMin: min datetimeMax: max datetimeStep: step } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const RELATION_CUSTOM_FIELD_FRAGMENT = gql` fragment RelationCustomField on RelationCustomFieldConfig { ...CustomFieldConfig entity scalarFields } ${CUSTOM_FIELD_CONFIG_FRAGMENT} `; export const ALL_CUSTOM_FIELDS_FRAGMENT = gql` fragment CustomFields on CustomField { ... on StringCustomFieldConfig { ...StringCustomField } ... on LocaleStringCustomFieldConfig { ...LocaleStringCustomField } ... on TextCustomFieldConfig { ...TextCustomField } ... on LocaleTextCustomFieldConfig { ...LocaleTextCustomField } ... on BooleanCustomFieldConfig { ...BooleanCustomField } ... on IntCustomFieldConfig { ...IntCustomField } ... on FloatCustomFieldConfig { ...FloatCustomField } ... on DateTimeCustomFieldConfig { ...DateTimeCustomField } ... on RelationCustomFieldConfig { ...RelationCustomField } } ${STRING_CUSTOM_FIELD_FRAGMENT} ${LOCALE_STRING_CUSTOM_FIELD_FRAGMENT} ${TEXT_CUSTOM_FIELD_FRAGMENT} ${BOOLEAN_CUSTOM_FIELD_FRAGMENT} ${INT_CUSTOM_FIELD_FRAGMENT} ${FLOAT_CUSTOM_FIELD_FRAGMENT} ${DATE_TIME_CUSTOM_FIELD_FRAGMENT} ${RELATION_CUSTOM_FIELD_FRAGMENT} ${LOCALE_TEXT_CUSTOM_FIELD_FRAGMENT} `; export const GET_SERVER_CONFIG = gql` query GetServerConfig { globalSettings { id serverConfig { moneyStrategyPrecision orderProcess { name to } permittedAssetTypes permissions { name description assignable } entityCustomFields { entityName customFields { ...CustomFields } } } } } ${ALL_CUSTOM_FIELDS_FRAGMENT} `; export const JOB_INFO_FRAGMENT = gql` fragment JobInfo on Job { id createdAt startedAt settledAt queueName state isSettled progress duration data result error retries attempts } `; export const GET_JOB_INFO = gql` query GetJobInfo($id: ID!) { job(jobId: $id) { ...JobInfo } } ${JOB_INFO_FRAGMENT} `; export const GET_JOBS_LIST = gql` query GetAllJobs($options: JobListOptions) { jobs(options: $options) { items { ...JobInfo } totalItems } } ${JOB_INFO_FRAGMENT} `; export const GET_JOBS_BY_ID = gql` query GetJobsById($ids: [ID!]!) { jobsById(jobIds: $ids) { ...JobInfo } } ${JOB_INFO_FRAGMENT} `; export const GET_JOB_QUEUE_LIST = gql` query GetJobQueueList { jobQueues { name running } } `; export const CANCEL_JOB = gql` mutation CancelJob($id: ID!) { cancelJob(jobId: $id) { ...JobInfo } } ${JOB_INFO_FRAGMENT} `; export const REINDEX = gql` mutation Reindex { reindex { ...JobInfo } } ${JOB_INFO_FRAGMENT} `; export const GET_PENDING_SEARCH_INDEX_UPDATES = gql` query GetPendingSearchIndexUpdates { pendingSearchIndexUpdates } `; export const RUN_PENDING_SEARCH_INDEX_UPDATES = gql` mutation RunPendingSearchIndexUpdates { runPendingSearchIndexUpdates { success } } `;
import { gql } from 'apollo-angular'; export const CONFIGURABLE_OPERATION_FRAGMENT = gql` fragment ConfigurableOperation on ConfigurableOperation { args { name value } code } `; export const CONFIGURABLE_OPERATION_DEF_FRAGMENT = gql` fragment ConfigurableOperationDef on ConfigurableOperationDefinition { args { name type required defaultValue list ui label description } code description } `; export const ERROR_RESULT_FRAGMENT = gql` fragment ErrorResult on ErrorResult { errorCode message } `;
import { gql } from 'apollo-angular'; import { CONFIGURABLE_OPERATION_DEF_FRAGMENT, CONFIGURABLE_OPERATION_FRAGMENT } from './shared-definitions'; export const SHIPPING_METHOD_FRAGMENT = gql` fragment ShippingMethod on ShippingMethod { id createdAt updatedAt code name description fulfillmentHandlerCode checker { ...ConfigurableOperation } calculator { ...ConfigurableOperation } translations { id languageCode name description } } ${CONFIGURABLE_OPERATION_FRAGMENT} `; export const GET_SHIPPING_METHOD_OPERATIONS = gql` query GetShippingMethodOperations { shippingEligibilityCheckers { ...ConfigurableOperationDef } shippingCalculators { ...ConfigurableOperationDef } fulfillmentHandlers { ...ConfigurableOperationDef } } ${CONFIGURABLE_OPERATION_DEF_FRAGMENT} `; export const CREATE_SHIPPING_METHOD = gql` mutation CreateShippingMethod($input: CreateShippingMethodInput!) { createShippingMethod(input: $input) { ...ShippingMethod } } ${SHIPPING_METHOD_FRAGMENT} `; export const UPDATE_SHIPPING_METHOD = gql` mutation UpdateShippingMethod($input: UpdateShippingMethodInput!) { updateShippingMethod(input: $input) { ...ShippingMethod } } ${SHIPPING_METHOD_FRAGMENT} `; export const DELETE_SHIPPING_METHOD = gql` mutation DeleteShippingMethod($id: ID!) { deleteShippingMethod(id: $id) { result message } } `; export const DELETE_SHIPPING_METHODS = gql` mutation DeleteShippingMethods($ids: [ID!]!) { deleteShippingMethods(ids: $ids) { result message } } `; export const TEST_SHIPPING_METHOD = gql` query TestShippingMethod($input: TestShippingMethodInput!) { testShippingMethod(input: $input) { eligible quote { price priceWithTax metadata } } } `; export const TEST_ELIGIBLE_SHIPPING_METHODS = gql` query TestEligibleShippingMethods($input: TestEligibleShippingMethodsInput!) { testEligibleShippingMethods(input: $input) { id name code description price priceWithTax metadata } } `;
import * as Codegen from '../../common/generated-types'; import { CREATE_ADMINISTRATOR, CREATE_ROLE, DELETE_ADMINISTRATOR, DELETE_ADMINISTRATORS, DELETE_ROLE, DELETE_ROLES, GET_ACTIVE_ADMINISTRATOR, GET_ROLES, UPDATE_ACTIVE_ADMINISTRATOR, UPDATE_ADMINISTRATOR, UPDATE_ROLE, } from '../definitions/administrator-definitions'; import { BaseDataService } from './base-data.service'; export class AdministratorDataService { constructor(private baseDataService: BaseDataService) {} getActiveAdministrator() { return this.baseDataService.query<Codegen.GetActiveAdministratorQuery>(GET_ACTIVE_ADMINISTRATOR, {}); } createAdministrator(input: Codegen.CreateAdministratorInput) { return this.baseDataService.mutate< Codegen.CreateAdministratorMutation, Codegen.CreateAdministratorMutationVariables >(CREATE_ADMINISTRATOR, { input }); } updateAdministrator(input: Codegen.UpdateAdministratorInput) { return this.baseDataService.mutate< Codegen.UpdateAdministratorMutation, Codegen.UpdateAdministratorMutationVariables >(UPDATE_ADMINISTRATOR, { input }); } updateActiveAdministrator(input: Codegen.UpdateActiveAdministratorInput) { return this.baseDataService.mutate< Codegen.UpdateActiveAdministratorMutation, Codegen.UpdateActiveAdministratorMutationVariables >(UPDATE_ACTIVE_ADMINISTRATOR, { input }); } deleteAdministrator(id: string) { return this.baseDataService.mutate< Codegen.DeleteAdministratorMutation, Codegen.DeleteAdministratorMutationVariables >(DELETE_ADMINISTRATOR, { id }); } deleteAdministrators(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteAdministratorsMutation, Codegen.DeleteAdministratorsMutationVariables >(DELETE_ADMINISTRATORS, { ids }); } getRoles(take = 10, skip = 0) { return this.baseDataService.query<Codegen.GetRolesQuery, Codegen.GetRolesQueryVariables>(GET_ROLES, { options: { take, skip, }, }); } createRole(input: Codegen.CreateRoleInput) { return this.baseDataService.mutate<Codegen.CreateRoleMutation, Codegen.CreateRoleMutationVariables>( CREATE_ROLE, { input, }, ); } updateRole(input: Codegen.UpdateRoleInput) { return this.baseDataService.mutate<Codegen.UpdateRoleMutation, Codegen.UpdateRoleMutationVariables>( UPDATE_ROLE, { input, }, ); } deleteRole(id: string) { return this.baseDataService.mutate<Codegen.DeleteRoleMutation, Codegen.DeleteRoleMutationVariables>( DELETE_ROLE, { id, }, ); } deleteRoles(ids: string[]) { return this.baseDataService.mutate<Codegen.DeleteRolesMutation, Codegen.DeleteRolesMutationVariables>( DELETE_ROLES, { ids, }, ); } }
import * as Codegen from '../../common/generated-types'; import { ATTEMPT_LOGIN, GET_CURRENT_USER, LOG_OUT } from '../definitions/auth-definitions'; import { BaseDataService } from './base-data.service'; export class AuthDataService { constructor(private baseDataService: BaseDataService) {} currentUser() { return this.baseDataService.query<Codegen.GetCurrentUserQuery>(GET_CURRENT_USER); } attemptLogin(username: string, password: string, rememberMe: boolean) { return this.baseDataService.mutate< Codegen.AttemptLoginMutation, Codegen.AttemptLoginMutationVariables >(ATTEMPT_LOGIN, { username, password, rememberMe, }); } logOut() { return this.baseDataService.mutate<Codegen.LogOutMutation>(LOG_OUT); } }
import { Injectable } from '@angular/core'; import { MutationUpdaterFn, SingleExecutionResult, WatchQueryFetchPolicy } from '@apollo/client/core'; import { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { simpleDeepClone } from '@vendure/common/lib/simple-deep-clone'; import { Apollo } from 'apollo-angular'; import { DocumentNode } from 'graphql/language/ast'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { CustomFieldConfig } from '../../common/generated-types'; import { QueryResult } from '../query-result'; import { ServerConfigService } from '../server-config'; import { addCustomFields } from '../utils/add-custom-fields'; import { removeReadonlyCustomFields } from '../utils/remove-readonly-custom-fields'; import { transformRelationCustomFieldInputs } from '../utils/transform-relation-custom-field-inputs'; import { isEntityCreateOrUpdateMutation } from '../utils/is-entity-create-or-update-mutation'; @Injectable() export class BaseDataService { constructor( private apollo: Apollo, private serverConfigService: ServerConfigService, ) {} private get customFields(): Map<string, CustomFieldConfig[]> { return this.serverConfigService.customFieldsMap; } /** * Performs a GraphQL watch query */ query<T, V extends Record<string, any> = Record<string, any>>( query: DocumentNode | TypedDocumentNode<T, V>, variables?: V, fetchPolicy: WatchQueryFetchPolicy = 'cache-and-network', ): QueryResult<T, V> { const withCustomFields = addCustomFields(query, this.customFields); const queryRef = this.apollo.watchQuery<T, V>({ query: withCustomFields, variables, fetchPolicy, }); const queryResult = new QueryResult<T, any>(queryRef, this.apollo); return queryResult; } /** * Performs a GraphQL mutation */ mutate<T, V extends Record<string, any> = Record<string, any>>( mutation: DocumentNode | TypedDocumentNode<T, V>, variables?: V, update?: MutationUpdaterFn<T>, ): Observable<T> { const withCustomFields = addCustomFields(mutation, this.customFields); const withoutReadonlyFields = this.prepareCustomFields(mutation, variables); return this.apollo .mutate<T, V>({ mutation: withCustomFields, variables: withoutReadonlyFields, update, }) .pipe(map(result => (result as SingleExecutionResult).data as T)); } private prepareCustomFields<V>(mutation: DocumentNode, variables: V): V { const entity = isEntityCreateOrUpdateMutation(mutation); if (entity) { const customFieldConfig = this.customFields.get(entity); if (variables && customFieldConfig) { let variablesClone = simpleDeepClone(variables as any); variablesClone = removeReadonlyCustomFields(variablesClone, customFieldConfig); variablesClone = transformRelationCustomFieldInputs(variablesClone, customFieldConfig); return variablesClone; } } return variables; } }
import * as Codegen from '../../common/generated-types'; import { CurrentUserChannel, LanguageCode, SetMainNavExpandedDocument } from '../../common/generated-types'; import { GET_NEWTORK_STATUS, GET_UI_STATE, GET_USER_STATUS, REQUEST_COMPLETED, REQUEST_STARTED, SET_ACTIVE_CHANNEL, SET_AS_LOGGED_IN, SET_AS_LOGGED_OUT, SET_CONTENT_LANGUAGE, SET_DISPLAY_UI_EXTENSION_POINTS, SET_UI_LANGUAGE_AND_LOCALE, SET_UI_LOCALE, SET_UI_THEME, UPDATE_USER_CHANNELS, } from '../definitions/client-definitions'; import { BaseDataService } from './base-data.service'; /** * Note: local queries all have a fetch-policy of "cache-first" explicitly specified due to: * https://github.com/apollographql/apollo-link-state/issues/236 */ export class ClientDataService { constructor(private baseDataService: BaseDataService) {} startRequest() { return this.baseDataService.mutate<Codegen.RequestStartedMutation>(REQUEST_STARTED); } completeRequest() { return this.baseDataService.mutate<Codegen.RequestCompletedMutation>(REQUEST_COMPLETED); } getNetworkStatus() { return this.baseDataService.query<Codegen.GetNetworkStatusQuery>( GET_NEWTORK_STATUS, {}, 'cache-first', ); } loginSuccess( administratorId: string, username: string, activeChannelId: string, channels: CurrentUserChannel[], ) { return this.baseDataService.mutate< Codegen.SetAsLoggedInMutation, Codegen.SetAsLoggedInMutationVariables >(SET_AS_LOGGED_IN, { input: { administratorId, username, loginTime: Date.now().toString(), activeChannelId, channels, }, }); } logOut() { return this.baseDataService.mutate(SET_AS_LOGGED_OUT); } userStatus() { return this.baseDataService.query<Codegen.GetUserStatusQuery>(GET_USER_STATUS, {}, 'cache-first'); } uiState() { return this.baseDataService.query<Codegen.GetUiStateQuery>(GET_UI_STATE, {}, 'cache-first'); } setUiLanguage(languageCode: LanguageCode, locale?: string) { return this.baseDataService.mutate< Codegen.SetUiLanguageMutation, Codegen.SetUiLanguageMutationVariables >(SET_UI_LANGUAGE_AND_LOCALE, { languageCode, locale, }); } setUiLocale(locale: string | undefined) { return this.baseDataService.mutate<Codegen.SetUiLocaleMutation, Codegen.SetUiLocaleMutationVariables>( SET_UI_LOCALE, { locale, }, ); } setContentLanguage(languageCode: LanguageCode) { return this.baseDataService.mutate< Codegen.SetContentLanguageMutation, Codegen.SetContentLanguageMutationVariables >(SET_CONTENT_LANGUAGE, { languageCode, }); } setUiTheme(theme: string) { return this.baseDataService.mutate<Codegen.SetUiThemeMutation, Codegen.SetUiThemeMutationVariables>( SET_UI_THEME, { theme, }, ); } setDisplayUiExtensionPoints(display: boolean) { return this.baseDataService.mutate< Codegen.SetDisplayUiExtensionPointsMutation, Codegen.SetDisplayUiExtensionPointsMutationVariables >(SET_DISPLAY_UI_EXTENSION_POINTS, { display, }); } setMainNavExpanded(expanded: boolean) { return this.baseDataService.mutate(SetMainNavExpandedDocument, { expanded, }); } setActiveChannel(channelId: string) { return this.baseDataService.mutate< Codegen.SetActiveChannelMutation, Codegen.SetActiveChannelMutationVariables >(SET_ACTIVE_CHANNEL, { channelId, }); } updateUserChannels(channels: Codegen.CurrentUserChannelInput[]) { return this.baseDataService.mutate< Codegen.UpdateUserChannelsMutation, Codegen.UpdateUserChannelsMutationVariables >(UPDATE_USER_CHANNELS, { channels, }); } }
import { pick } from '@vendure/common/lib/pick'; import { from } from 'rxjs'; import { bufferCount, concatMap } from 'rxjs/operators'; import * as Codegen from '../../common/generated-types'; import { ASSIGN_COLLECTIONS_TO_CHANNEL, CREATE_COLLECTION, DELETE_COLLECTION, DELETE_COLLECTIONS, GET_COLLECTION_CONTENTS, GET_COLLECTION_FILTERS, GET_COLLECTION_LIST, MOVE_COLLECTION, PREVIEW_COLLECTION_CONTENTS, REMOVE_COLLECTIONS_FROM_CHANNEL, UPDATE_COLLECTION, } from '../definitions/collection-definitions'; import { BaseDataService } from './base-data.service'; export class CollectionDataService { constructor(private baseDataService: BaseDataService) {} getCollectionFilters() { return this.baseDataService.query<Codegen.GetCollectionFiltersQuery>(GET_COLLECTION_FILTERS); } getCollections(options?: Codegen.CollectionListOptions) { return this.baseDataService.query< Codegen.GetCollectionListQuery, Codegen.GetCollectionListQueryVariables >(GET_COLLECTION_LIST, { options, }); } createCollection(input: Codegen.CreateCollectionInput) { return this.baseDataService.mutate< Codegen.CreateCollectionMutation, Codegen.CreateCollectionMutationVariables >(CREATE_COLLECTION, { input: pick(input, [ 'translations', 'parentId', 'assetIds', 'featuredAssetId', 'inheritFilters', 'filters', 'customFields', ]), }); } updateCollection(input: Codegen.UpdateCollectionInput) { return this.baseDataService.mutate< Codegen.UpdateCollectionMutation, Codegen.UpdateCollectionMutationVariables >(UPDATE_COLLECTION, { input: pick(input, [ 'id', 'isPrivate', 'translations', 'assetIds', 'featuredAssetId', 'inheritFilters', 'filters', 'customFields', ]), }); } moveCollection(inputs: Codegen.MoveCollectionInput[]) { return from(inputs).pipe( concatMap(input => this.baseDataService.mutate< Codegen.MoveCollectionMutation, Codegen.MoveCollectionMutationVariables >(MOVE_COLLECTION, { input }), ), bufferCount(inputs.length), ); } deleteCollection(id: string) { return this.baseDataService.mutate< Codegen.DeleteCollectionMutation, Codegen.DeleteCollectionMutationVariables >(DELETE_COLLECTION, { id, }); } deleteCollections(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteCollectionsMutation, Codegen.DeleteCollectionsMutationVariables >(DELETE_COLLECTIONS, { ids, }); } previewCollectionVariants( input: Codegen.PreviewCollectionVariantsInput, options: Codegen.ProductVariantListOptions, ) { return this.baseDataService.query< Codegen.PreviewCollectionContentsQuery, Codegen.PreviewCollectionContentsQueryVariables >(PREVIEW_COLLECTION_CONTENTS, { input, options }); } getCollectionContents(id: string, take = 10, skip = 0, filterTerm?: string) { const filter = filterTerm ? ({ name: { contains: filterTerm } } as Codegen.CollectionFilterParameter) : undefined; return this.baseDataService.query< Codegen.GetCollectionContentsQuery, Codegen.GetCollectionContentsQueryVariables >(GET_COLLECTION_CONTENTS, { id, options: { skip, take, filter, }, }); } assignCollectionsToChannel(input: Codegen.AssignCollectionsToChannelInput) { return this.baseDataService.mutate< Codegen.AssignCollectionsToChannelMutation, Codegen.AssignCollectionsToChannelMutationVariables >(ASSIGN_COLLECTIONS_TO_CHANNEL, { input, }); } removeCollectionsFromChannel(input: Codegen.RemoveCollectionsFromChannelInput) { return this.baseDataService.mutate< Codegen.RemoveCollectionsFromChannelMutation, Codegen.RemoveCollectionsFromChannelMutationVariables >(REMOVE_COLLECTIONS_FROM_CHANNEL, { input, }); } }
import * as Codegen from '../../common/generated-types'; import { LogicalOperator } from '../../common/generated-types'; import { ADD_CUSTOMERS_TO_GROUP, ADD_NOTE_TO_CUSTOMER, CREATE_CUSTOMER, CREATE_CUSTOMER_ADDRESS, CREATE_CUSTOMER_GROUP, DELETE_CUSTOMER, DELETE_CUSTOMER_ADDRESS, DELETE_CUSTOMER_GROUP, DELETE_CUSTOMER_GROUPS, DELETE_CUSTOMER_NOTE, DELETE_CUSTOMERS, GET_CUSTOMER_GROUP_WITH_CUSTOMERS, GET_CUSTOMER_GROUPS, GET_CUSTOMER_HISTORY, GET_CUSTOMER_LIST, REMOVE_CUSTOMERS_FROM_GROUP, UPDATE_CUSTOMER, UPDATE_CUSTOMER_ADDRESS, UPDATE_CUSTOMER_GROUP, UPDATE_CUSTOMER_NOTE, } from '../definitions/customer-definitions'; import { BaseDataService } from './base-data.service'; export class CustomerDataService { constructor(private baseDataService: BaseDataService) {} getCustomerList(take = 10, skip = 0, filterTerm?: string) { const filter = filterTerm ? { filter: { emailAddress: { contains: filterTerm, }, lastName: { contains: filterTerm, }, }, } : {}; return this.baseDataService.query< Codegen.GetCustomerListQuery, Codegen.GetCustomerListQueryVariables >(GET_CUSTOMER_LIST, { options: { take, skip, ...filter, filterOperator: LogicalOperator.OR, }, }); } createCustomer(input: Codegen.CreateCustomerInput, password?: string | null) { return this.baseDataService.mutate< Codegen.CreateCustomerMutation, Codegen.CreateCustomerMutationVariables >(CREATE_CUSTOMER, { input, password, }); } updateCustomer(input: Codegen.UpdateCustomerInput) { return this.baseDataService.mutate< Codegen.UpdateCustomerMutation, Codegen.UpdateCustomerMutationVariables >(UPDATE_CUSTOMER, { input, }); } deleteCustomer(id: string) { return this.baseDataService.mutate< Codegen.DeleteCustomerMutation, Codegen.DeleteCustomerMutationVariables >(DELETE_CUSTOMER, { id }); } deleteCustomers(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteCustomersMutation, Codegen.DeleteCustomersMutationVariables >(DELETE_CUSTOMERS, { ids }); } createCustomerAddress(customerId: string, input: Codegen.CreateAddressInput) { return this.baseDataService.mutate< Codegen.CreateCustomerAddressMutation, Codegen.CreateCustomerAddressMutationVariables >(CREATE_CUSTOMER_ADDRESS, { customerId, input, }); } updateCustomerAddress(input: Codegen.UpdateAddressInput) { return this.baseDataService.mutate< Codegen.UpdateCustomerAddressMutation, Codegen.UpdateCustomerAddressMutationVariables >(UPDATE_CUSTOMER_ADDRESS, { input, }); } deleteCustomerAddress(id: string) { return this.baseDataService.mutate< Codegen.DeleteCustomerAddressMutation, Codegen.DeleteCustomerAddressMutationVariables >(DELETE_CUSTOMER_ADDRESS, { id }); } createCustomerGroup(input: Codegen.CreateCustomerGroupInput) { return this.baseDataService.mutate< Codegen.CreateCustomerGroupMutation, Codegen.CreateCustomerGroupMutationVariables >(CREATE_CUSTOMER_GROUP, { input, }); } updateCustomerGroup(input: Codegen.UpdateCustomerGroupInput) { return this.baseDataService.mutate< Codegen.UpdateCustomerGroupMutation, Codegen.UpdateCustomerGroupMutationVariables >(UPDATE_CUSTOMER_GROUP, { input, }); } deleteCustomerGroup(id: string) { return this.baseDataService.mutate< Codegen.DeleteCustomerGroupMutation, Codegen.DeleteCustomerGroupMutationVariables >(DELETE_CUSTOMER_GROUP, { id }); } deleteCustomerGroups(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteCustomerGroupsMutation, Codegen.DeleteCustomerGroupsMutationVariables >(DELETE_CUSTOMER_GROUPS, { ids }); } getCustomerGroupList(options?: Codegen.CustomerGroupListOptions) { return this.baseDataService.query< Codegen.GetCustomerGroupsQuery, Codegen.GetCustomerGroupsQueryVariables >(GET_CUSTOMER_GROUPS, { options, }); } getCustomerGroupWithCustomers(id: string, options: Codegen.CustomerListOptions) { return this.baseDataService.query< Codegen.GetCustomerGroupWithCustomersQuery, Codegen.GetCustomerGroupWithCustomersQueryVariables >(GET_CUSTOMER_GROUP_WITH_CUSTOMERS, { id, options, }); } addCustomersToGroup(groupId: string, customerIds: string[]) { return this.baseDataService.mutate< Codegen.AddCustomersToGroupMutation, Codegen.AddCustomersToGroupMutationVariables >(ADD_CUSTOMERS_TO_GROUP, { groupId, customerIds, }); } removeCustomersFromGroup(groupId: string, customerIds: string[]) { return this.baseDataService.mutate< Codegen.RemoveCustomersFromGroupMutation, Codegen.RemoveCustomersFromGroupMutationVariables >(REMOVE_CUSTOMERS_FROM_GROUP, { groupId, customerIds, }); } getCustomerHistory(id: string, options?: Codegen.HistoryEntryListOptions) { return this.baseDataService.query< Codegen.GetCustomerHistoryQuery, Codegen.GetCustomerHistoryQueryVariables >(GET_CUSTOMER_HISTORY, { id, options, }); } addNoteToCustomer(customerId: string, note: string) { return this.baseDataService.mutate< Codegen.AddNoteToCustomerMutation, Codegen.AddNoteToCustomerMutationVariables >(ADD_NOTE_TO_CUSTOMER, { input: { note, isPublic: false, id: customerId, }, }); } updateCustomerNote(input: Codegen.UpdateCustomerNoteInput) { return this.baseDataService.mutate< Codegen.UpdateCustomerNoteMutation, Codegen.UpdateCustomerNoteMutationVariables >(UPDATE_CUSTOMER_NOTE, { input, }); } deleteCustomerNote(id: string) { return this.baseDataService.mutate< Codegen.DeleteCustomerNoteMutation, Codegen.DeleteCustomerNoteMutationVariables >(DELETE_CUSTOMER_NOTE, { id, }); } }
import { Injectable } from '@angular/core'; import { MutationUpdaterFn, WatchQueryFetchPolicy } from '@apollo/client/core'; import { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { DocumentNode } from 'graphql'; import { Observable } from 'rxjs'; import { QueryResult } from '../query-result'; import { AdministratorDataService } from './administrator-data.service'; import { AuthDataService } from './auth-data.service'; import { BaseDataService } from './base-data.service'; import { ClientDataService } from './client-data.service'; import { CollectionDataService } from './collection-data.service'; import { CustomerDataService } from './customer-data.service'; import { FacetDataService } from './facet-data.service'; import { OrderDataService } from './order-data.service'; import { ProductDataService } from './product-data.service'; import { PromotionDataService } from './promotion-data.service'; import { SettingsDataService } from './settings-data.service'; import { ShippingMethodDataService } from './shipping-method-data.service'; /** * @description * Used to interact with the Admin API via GraphQL queries. Internally this service uses the * Apollo Client, which means it maintains a normalized entity cache. For this reason, it is * advisable to always select the `id` field of any entity, which will allow the returned data * to be effectively cached. * * @docsCategory services * @docsPage DataService * @docsWeight 0 */ @Injectable() export class DataService { /** @internal */ promotion: PromotionDataService; /** @internal */ administrator: AdministratorDataService; /** @internal */ auth: AuthDataService; /** @internal */ collection: CollectionDataService; /** @internal */ product: ProductDataService; /** @internal */ client: ClientDataService; /** @internal */ facet: FacetDataService; /** @internal */ order: OrderDataService; /** @internal */ settings: SettingsDataService; /** @internal */ customer: CustomerDataService; /** @internal */ shippingMethod: ShippingMethodDataService; /** @internal */ constructor(private baseDataService: BaseDataService) { this.promotion = new PromotionDataService(baseDataService); this.administrator = new AdministratorDataService(baseDataService); this.auth = new AuthDataService(baseDataService); this.collection = new CollectionDataService(baseDataService); this.product = new ProductDataService(baseDataService); this.client = new ClientDataService(baseDataService); this.facet = new FacetDataService(baseDataService); this.order = new OrderDataService(baseDataService); this.settings = new SettingsDataService(baseDataService); this.customer = new CustomerDataService(baseDataService); this.shippingMethod = new ShippingMethodDataService(baseDataService); } /** * @description * Perform a GraphQL query. Returns a {@link QueryResult} which allows further control over * they type of result returned, e.g. stream of values, single value etc. * * @example * ```ts * const result$ = this.dataService.query(gql` * query MyQuery($id: ID!) { * product(id: $id) { * id * name * slug * } * }, * { id: 123 }, * ).mapSingle(data => data.product); * ``` */ query<T, V extends Record<string, any> = Record<string, any>>( query: DocumentNode | TypedDocumentNode<T, V>, variables?: V, fetchPolicy: WatchQueryFetchPolicy = 'cache-and-network', ): QueryResult<T, V> { return this.baseDataService.query(query, variables, fetchPolicy); } /** * @description * Perform a GraphQL mutation. * * @example * ```ts * const result$ = this.dataService.mutate(gql` * mutation MyMutation($Codegen.UpdateEntityInput!) { * updateEntity(input: $input) { * id * name * } * }, * { Codegen.updateEntityInput }, * ); * ``` */ mutate<T, V extends Record<string, any> = Record<string, any>>( mutation: DocumentNode | TypedDocumentNode<T, V>, variables?: V, update?: MutationUpdaterFn<T>, ): Observable<T> { return this.baseDataService.mutate(mutation, variables, update); } }
import { WatchQueryFetchPolicy } from '@apollo/client/core'; import { pick } from '@vendure/common/lib/pick'; import * as Codegen from '../../common/generated-types'; import { ASSIGN_FACETS_TO_CHANNEL, CREATE_FACET, CREATE_FACET_VALUES, DELETE_FACET, DELETE_FACET_VALUES, DELETE_FACETS, GET_FACET_VALUE_LIST, REMOVE_FACETS_FROM_CHANNEL, UPDATE_FACET, UPDATE_FACET_VALUES, } from '../definitions/facet-definitions'; import { BaseDataService } from './base-data.service'; export class FacetDataService { constructor(private baseDataService: BaseDataService) {} getFacetValues(options: Codegen.FacetValueListOptions, fetchPolicy?: WatchQueryFetchPolicy) { return this.baseDataService.query< Codegen.GetFacetValueListQuery, Codegen.GetFacetValueListQueryVariables >(GET_FACET_VALUE_LIST, { options }, fetchPolicy); } createFacet(facet: Codegen.CreateFacetInput) { const input: Codegen.CreateFacetMutationVariables = { input: pick(facet, ['code', 'isPrivate', 'translations', 'values', 'customFields']), }; return this.baseDataService.mutate<Codegen.CreateFacetMutation, Codegen.CreateFacetMutationVariables>( CREATE_FACET, input, ); } updateFacet(facet: Codegen.UpdateFacetInput) { const input: Codegen.UpdateFacetMutationVariables = { input: pick(facet, ['id', 'code', 'isPrivate', 'translations', 'customFields']), }; return this.baseDataService.mutate<Codegen.UpdateFacetMutation, Codegen.UpdateFacetMutationVariables>( UPDATE_FACET, input, ); } deleteFacet(id: string, force: boolean) { return this.baseDataService.mutate<Codegen.DeleteFacetMutation, Codegen.DeleteFacetMutationVariables>( DELETE_FACET, { id, force, }, ); } deleteFacets(ids: string[], force: boolean) { return this.baseDataService.mutate< Codegen.DeleteFacetsMutation, Codegen.DeleteFacetsMutationVariables >(DELETE_FACETS, { ids, force, }); } createFacetValues(facetValues: Codegen.CreateFacetValueInput[]) { const input: Codegen.CreateFacetValuesMutationVariables = { input: facetValues.map(pick(['facetId', 'code', 'translations', 'customFields'])), }; return this.baseDataService.mutate< Codegen.CreateFacetValuesMutation, Codegen.CreateFacetValuesMutationVariables >(CREATE_FACET_VALUES, input); } updateFacetValues(facetValues: Codegen.UpdateFacetValueInput[]) { const input: Codegen.UpdateFacetValuesMutationVariables = { input: facetValues.map(pick(['id', 'code', 'translations', 'customFields'])), }; return this.baseDataService.mutate< Codegen.UpdateFacetValuesMutation, Codegen.UpdateFacetValuesMutationVariables >(UPDATE_FACET_VALUES, input); } deleteFacetValues(ids: string[], force: boolean) { return this.baseDataService.mutate< Codegen.DeleteFacetValuesMutation, Codegen.DeleteFacetValuesMutationVariables >(DELETE_FACET_VALUES, { ids, force, }); } assignFacetsToChannel(input: Codegen.AssignFacetsToChannelInput) { return this.baseDataService.mutate< Codegen.AssignFacetsToChannelMutation, Codegen.AssignFacetsToChannelMutationVariables >(ASSIGN_FACETS_TO_CHANNEL, { input, }); } removeFacetsFromChannel(input: Codegen.RemoveFacetsFromChannelInput) { return this.baseDataService.mutate< Codegen.RemoveFacetsFromChannelMutation, Codegen.RemoveFacetsFromChannelMutationVariables >(REMOVE_FACETS_FROM_CHANNEL, { input, }); } }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { lastValueFrom } from 'rxjs'; /** * An adapter that allows the Angular HttpClient to be used as a replacement for the global `fetch` function. * This is used to supply a custom fetch function to the apollo-upload-client whilst also allowing the * use of Angular's http infrastructure such as interceptors. */ @Injectable() export class FetchAdapter { constructor(private httpClient: HttpClient) {} fetch = (input: Request | string, init: RequestInit): Promise<Response> => { const url = typeof input === 'string' ? input : input.url; const method = typeof input === 'string' ? (init.method ? init.method : 'GET') : input.method; return lastValueFrom( this.httpClient.request(method, url, { body: init.body, headers: init.headers as any, observe: 'response', responseType: 'json', withCredentials: true, }), ).then(result => new Response(JSON.stringify(result.body), { status: result.status, statusText: result.statusText, })); }; }
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, } from '@angular/common/http'; import { Injectable, Injector } from '@angular/core'; import { Router } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DEFAULT_AUTH_TOKEN_HEADER_KEY } from '@vendure/common/lib/shared-constants'; import { AdminUiConfig } from '@vendure/common/lib/shared-types'; import { Observable } from 'rxjs'; import { switchMap, tap } from 'rxjs/operators'; import { getAppConfig } from '../../app.config'; import { AuthService } from '../../providers/auth/auth.service'; import { LocalStorageService } from '../../providers/local-storage/local-storage.service'; import { NotificationService } from '../../providers/notification/notification.service'; import { DataService } from './data.service'; export const AUTH_REDIRECT_PARAM = 'redirectTo'; /** * The default interceptor examines all HTTP requests & responses and automatically updates the requesting state * and shows error notifications. */ @Injectable() export class DefaultInterceptor implements HttpInterceptor { private readonly tokenMethod: AdminUiConfig['tokenMethod'] = 'cookie'; private readonly authTokenHeaderKey: string; constructor( private dataService: DataService, private injector: Injector, private authService: AuthService, private router: Router, private localStorageService: LocalStorageService, ) { this.tokenMethod = getAppConfig().tokenMethod; this.authTokenHeaderKey = getAppConfig().authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY; } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { this.dataService.client.startRequest().subscribe(); return this.dataService.client.uiState().single$.pipe( switchMap(({ uiState }) => { const request = req.clone({ setParams: { languageCode: uiState?.contentLanguage ?? '', }, }); return next.handle(request); }), tap( event => { if (event instanceof HttpResponse) { this.checkForAuthToken(event); this.notifyOnError(event); this.dataService.client.completeRequest().subscribe(); } }, err => { if (err instanceof HttpErrorResponse) { this.notifyOnError(err); this.dataService.client.completeRequest().subscribe(); } else { this.displayErrorNotification(err.message); } }, ), ); } private notifyOnError(response: HttpResponse<any> | HttpErrorResponse) { if (response instanceof HttpErrorResponse) { if (response.status === 0) { const { apiHost, apiPort } = getAppConfig(); this.displayErrorNotification(_(`error.could-not-connect-to-server`), { url: `${apiHost}:${apiPort}`, }); } else if (response.status === 503 && response.url?.endsWith('/health')) { this.displayErrorNotification(_(`error.health-check-failed`)); } else { this.displayErrorNotification(this.extractErrorFromHttpResponse(response)); } } else { // GraphQL errors still return 200 OK responses, but have the actual error message // inside the body of the response. const graphQLErrors = response.body.errors; if (graphQLErrors && Array.isArray(graphQLErrors)) { const firstCode: string = graphQLErrors[0]?.extensions?.code; if (firstCode === 'FORBIDDEN') { this.authService.logOut().subscribe(() => { const { loginUrl } = getAppConfig(); // If there is a `loginUrl` which is external to the AdminUI, redirect to it (with no query parameters) if (loginUrl && !this.areUrlsOnSameOrigin(loginUrl, window.location.origin)) { window.location.href = loginUrl; return; } // Else, we build the login path from the login url if one is provided or fallback to `/login` const loginPath = loginUrl ? this.getPathFromLoginUrl(loginUrl) : '/login'; if (!window.location.pathname.includes(loginPath)) { const path = graphQLErrors[0].path.join(' > '); this.displayErrorNotification(_(`error.403-forbidden`), { path }); } // Navigate to the `loginPath` route by ensuring the query param in charge of the redirection is provided this.router.navigate([loginPath], { queryParams: { [AUTH_REDIRECT_PARAM]: btoa(this.router.url), }, }); }); } else if (firstCode === 'CHANNEL_NOT_FOUND') { const message = graphQLErrors.map(err => err.message).join('\n'); this.displayErrorNotification(message); this.localStorageService.remove('activeChannelToken'); } else { const message = graphQLErrors.map(err => err.message).join('\n'); this.displayErrorNotification(message); } } } } private extractErrorFromHttpResponse(response: HttpErrorResponse): string { const errors = response.error.errors; if (Array.isArray(errors)) { return errors.map(e => e.message).join('\n'); } else { return response.message; } } /** * We need to lazily inject the NotificationService since it depends on the I18nService which * eventually depends on the HttpClient (used to load messages from json files). If we were to * directly inject NotificationService into the constructor, we get a cyclic dependency. */ private displayErrorNotification(message: string, vars?: Record<string, any>): void { const notificationService = this.injector.get<NotificationService>(NotificationService); notificationService.error(message, vars); } /** * If the server is configured to use the "bearer" tokenMethod, each response should be checked * for the existence of an auth token. */ private checkForAuthToken(response: HttpResponse<any>) { if (this.tokenMethod === 'bearer') { const authToken = response.headers.get(this.authTokenHeaderKey); if (authToken) { this.localStorageService.set('authToken', authToken); } } } /** * Determine if two urls are on the same origin. */ private areUrlsOnSameOrigin(urlA: string, urlB: string): boolean { return new URL(urlA).origin === new URL(urlB).origin; } /** * If the provided `loginUrl` is on the same origin than the AdminUI, return the path * after the `/admin`. * Else, return the whole login url. */ private getPathFromLoginUrl(loginUrl: string): string { if (!this.areUrlsOnSameOrigin(loginUrl, window.location.origin)) { return loginUrl; } return loginUrl.split('/admin')[1]; } }
import * as Codegen from '../../common/generated-types'; import { ADD_ITEM_TO_DRAFT_ORDER, ADD_MANUAL_PAYMENT_TO_ORDER, ADD_NOTE_TO_ORDER, ADJUST_DRAFT_ORDER_LINE, APPLY_COUPON_CODE_TO_DRAFT_ORDER, CANCEL_ORDER, CANCEL_PAYMENT, CREATE_DRAFT_ORDER, CREATE_FULFILLMENT, DELETE_DRAFT_ORDER, DELETE_ORDER_NOTE, DRAFT_ORDER_ELIGIBLE_SHIPPING_METHODS, GET_ORDER, GET_ORDER_HISTORY, GET_ORDERS_LIST, MODIFY_ORDER, REFUND_ORDER, REMOVE_COUPON_CODE_FROM_DRAFT_ORDER, REMOVE_DRAFT_ORDER_LINE, SET_BILLING_ADDRESS_FOR_DRAFT_ORDER, SET_CUSTOMER_FOR_DRAFT_ORDER, SET_DRAFT_ORDER_SHIPPING_METHOD, SET_SHIPPING_ADDRESS_FOR_DRAFT_ORDER, SETTLE_PAYMENT, SETTLE_REFUND, TRANSITION_FULFILLMENT_TO_STATE, TRANSITION_ORDER_TO_STATE, TRANSITION_PAYMENT_TO_STATE, UPDATE_ORDER_CUSTOM_FIELDS, UPDATE_ORDER_NOTE, } from '../definitions/order-definitions'; import { BaseDataService } from './base-data.service'; export class OrderDataService { constructor(private baseDataService: BaseDataService) {} getOrders(options: Codegen.OrderListOptions = { take: 10 }) { return this.baseDataService.query<Codegen.GetOrderListQuery, Codegen.GetOrderListQueryVariables>( GET_ORDERS_LIST, { options, }, ); } getOrder(id: string) { return this.baseDataService.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(GET_ORDER, { id, }); } getOrderHistory(id: string, options?: Codegen.HistoryEntryListOptions) { return this.baseDataService.query< Codegen.GetOrderHistoryQuery, Codegen.GetOrderHistoryQueryVariables >(GET_ORDER_HISTORY, { id, options, }); } settlePayment(id: string) { return this.baseDataService.mutate< Codegen.SettlePaymentMutation, Codegen.SettlePaymentMutationVariables >(SETTLE_PAYMENT, { id, }); } cancelPayment(id: string) { return this.baseDataService.mutate< Codegen.CancelPaymentMutation, Codegen.CancelPaymentMutationVariables >(CANCEL_PAYMENT, { id, }); } transitionPaymentToState(id: string, state: string) { return this.baseDataService.mutate< Codegen.TransitionPaymentToStateMutation, Codegen.TransitionPaymentToStateMutationVariables >(TRANSITION_PAYMENT_TO_STATE, { id, state, }); } createFulfillment(input: Codegen.FulfillOrderInput) { return this.baseDataService.mutate< Codegen.CreateFulfillmentMutation, Codegen.CreateFulfillmentMutationVariables >(CREATE_FULFILLMENT, { input, }); } transitionFulfillmentToState(id: string, state: string) { return this.baseDataService.mutate< Codegen.TransitionFulfillmentToStateMutation, Codegen.TransitionFulfillmentToStateMutationVariables >(TRANSITION_FULFILLMENT_TO_STATE, { id, state, }); } cancelOrder(input: Codegen.CancelOrderInput) { return this.baseDataService.mutate<Codegen.CancelOrderMutation, Codegen.CancelOrderMutationVariables>( CANCEL_ORDER, { input, }, ); } refundOrder(input: Codegen.RefundOrderInput) { return this.baseDataService.mutate<Codegen.RefundOrderMutation, Codegen.RefundOrderMutationVariables>( REFUND_ORDER, { input, }, ); } settleRefund(input: Codegen.SettleRefundInput, orderId: string) { return this.baseDataService.mutate< Codegen.SettleRefundMutation, Codegen.SettleRefundMutationVariables >(SETTLE_REFUND, { input, }); } addNoteToOrder(input: Codegen.AddNoteToOrderInput) { return this.baseDataService.mutate< Codegen.AddNoteToOrderMutation, Codegen.AddNoteToOrderMutationVariables >(ADD_NOTE_TO_ORDER, { input, }); } updateOrderNote(input: Codegen.UpdateOrderNoteInput) { return this.baseDataService.mutate< Codegen.UpdateOrderNoteMutation, Codegen.UpdateOrderNoteMutationVariables >(UPDATE_ORDER_NOTE, { input, }); } deleteOrderNote(id: string) { return this.baseDataService.mutate< Codegen.DeleteOrderNoteMutation, Codegen.DeleteOrderNoteMutationVariables >(DELETE_ORDER_NOTE, { id, }); } transitionToState(id: string, state: string) { return this.baseDataService.mutate< Codegen.TransitionOrderToStateMutation, Codegen.TransitionOrderToStateMutationVariables >(TRANSITION_ORDER_TO_STATE, { id, state, }); } updateOrderCustomFields(input: Codegen.UpdateOrderInput) { return this.baseDataService.mutate< Codegen.UpdateOrderCustomFieldsMutation, Codegen.UpdateOrderCustomFieldsMutationVariables >(UPDATE_ORDER_CUSTOM_FIELDS, { input, }); } modifyOrder(input: Codegen.ModifyOrderInput) { return this.baseDataService.mutate<Codegen.ModifyOrderMutation, Codegen.ModifyOrderMutationVariables>( MODIFY_ORDER, { input, }, ); } addManualPaymentToOrder(input: Codegen.ManualPaymentInput) { return this.baseDataService.mutate< Codegen.AddManualPaymentMutation, Codegen.AddManualPaymentMutationVariables >(ADD_MANUAL_PAYMENT_TO_ORDER, { input }); } createDraftOrder() { return this.baseDataService.mutate<Codegen.CreateDraftOrderMutation>(CREATE_DRAFT_ORDER); } deleteDraftOrder(orderId: string) { return this.baseDataService.mutate< Codegen.DeleteDraftOrderMutation, Codegen.DeleteDraftOrderMutationVariables >(DELETE_DRAFT_ORDER, { orderId }); } addItemToDraftOrder(orderId: string, input: Codegen.AddItemToDraftOrderInput) { return this.baseDataService.mutate< Codegen.AddItemToDraftOrderMutation, Codegen.AddItemToDraftOrderMutationVariables >(ADD_ITEM_TO_DRAFT_ORDER, { orderId, input }); } adjustDraftOrderLine(orderId: string, input: Codegen.AdjustDraftOrderLineInput) { return this.baseDataService.mutate< Codegen.AdjustDraftOrderLineMutation, Codegen.AdjustDraftOrderLineMutationVariables >(ADJUST_DRAFT_ORDER_LINE, { orderId, input }); } removeDraftOrderLine(orderId: string, orderLineId: string) { return this.baseDataService.mutate< Codegen.RemoveDraftOrderLineMutation, Codegen.RemoveDraftOrderLineMutationVariables >(REMOVE_DRAFT_ORDER_LINE, { orderId, orderLineId }); } setCustomerForDraftOrder( orderId: string, { customerId, input }: { customerId?: string; input?: Codegen.CreateCustomerInput }, ) { return this.baseDataService.mutate< Codegen.SetCustomerForDraftOrderMutation, Codegen.SetCustomerForDraftOrderMutationVariables >(SET_CUSTOMER_FOR_DRAFT_ORDER, { orderId, customerId, input }); } setDraftOrderShippingAddress(orderId: string, input: Codegen.CreateAddressInput) { return this.baseDataService.mutate< Codegen.SetDraftOrderShippingAddressMutation, Codegen.SetDraftOrderShippingAddressMutationVariables >(SET_SHIPPING_ADDRESS_FOR_DRAFT_ORDER, { orderId, input }); } setDraftOrderBillingAddress(orderId: string, input: Codegen.CreateAddressInput) { return this.baseDataService.mutate< Codegen.SetDraftOrderBillingAddressMutation, Codegen.SetDraftOrderBillingAddressMutationVariables >(SET_BILLING_ADDRESS_FOR_DRAFT_ORDER, { orderId, input }); } applyCouponCodeToDraftOrder(orderId: string, couponCode: string) { return this.baseDataService.mutate< Codegen.ApplyCouponCodeToDraftOrderMutation, Codegen.ApplyCouponCodeToDraftOrderMutationVariables >(APPLY_COUPON_CODE_TO_DRAFT_ORDER, { orderId, couponCode }); } removeCouponCodeFromDraftOrder(orderId: string, couponCode: string) { return this.baseDataService.mutate< Codegen.RemoveCouponCodeFromDraftOrderMutation, Codegen.RemoveCouponCodeFromDraftOrderMutationVariables >(REMOVE_COUPON_CODE_FROM_DRAFT_ORDER, { orderId, couponCode }); } getDraftOrderEligibleShippingMethods(orderId: string) { return this.baseDataService.query< Codegen.DraftOrderEligibleShippingMethodsQuery, Codegen.DraftOrderEligibleShippingMethodsQueryVariables >(DRAFT_ORDER_ELIGIBLE_SHIPPING_METHODS, { orderId }); } setDraftOrderShippingMethod(orderId: string, shippingMethodId: string) { return this.baseDataService.mutate< Codegen.SetDraftOrderShippingMethodMutation, Codegen.SetDraftOrderShippingMethodMutationVariables >(SET_DRAFT_ORDER_SHIPPING_METHOD, { orderId, shippingMethodId }); } }
import { pick } from '@vendure/common/lib/pick'; import * as Codegen from '../../common/generated-types'; import { SortOrder } from '../../common/generated-types'; import { ADD_OPTION_GROUP_TO_PRODUCT, ADD_OPTION_TO_GROUP, ASSIGN_PRODUCTS_TO_CHANNEL, ASSIGN_VARIANTS_TO_CHANNEL, CREATE_ASSETS, CREATE_PRODUCT, CREATE_PRODUCT_OPTION_GROUP, CREATE_PRODUCT_VARIANTS, CREATE_TAG, DELETE_ASSETS, DELETE_PRODUCT, DELETE_PRODUCT_OPTION, DELETE_PRODUCT_VARIANT, DELETE_PRODUCT_VARIANTS, DELETE_PRODUCTS, DELETE_TAG, GET_ASSET, GET_ASSET_LIST, GET_PRODUCT_LIST, GET_PRODUCT_OPTION_GROUP, GET_PRODUCT_OPTION_GROUPS, GET_PRODUCT_SIMPLE, GET_PRODUCT_VARIANT, GET_PRODUCT_VARIANT_LIST, GET_PRODUCT_VARIANT_LIST_FOR_PRODUCT, GET_PRODUCT_VARIANT_LIST_SIMPLE, GET_PRODUCT_VARIANT_OPTIONS, GET_PRODUCT_WITH_VARIANTS, GET_TAG, GET_TAG_LIST, PRODUCT_SELECTOR_SEARCH, REMOVE_OPTION_GROUP_FROM_PRODUCT, REMOVE_PRODUCTS_FROM_CHANNEL, REMOVE_VARIANTS_FROM_CHANNEL, SEARCH_PRODUCTS, UPDATE_ASSET, UPDATE_PRODUCT, UPDATE_PRODUCT_OPTION, UPDATE_PRODUCT_OPTION_GROUP, UPDATE_PRODUCT_VARIANTS, UPDATE_TAG, } from '../definitions/product-definitions'; import { GET_PENDING_SEARCH_INDEX_UPDATES, REINDEX, RUN_PENDING_SEARCH_INDEX_UPDATES, } from '../definitions/settings-definitions'; import { BaseDataService } from './base-data.service'; export class ProductDataService { constructor(private baseDataService: BaseDataService) {} searchProducts(term: string, take = 10, skip = 0) { return this.baseDataService.query<Codegen.SearchProductsQuery, Codegen.SearchProductsQueryVariables>( SEARCH_PRODUCTS, { input: { term, take, skip, groupByProduct: true, }, }, ); } productSelectorSearch(term: string, take: number) { return this.baseDataService.query< Codegen.ProductSelectorSearchQuery, Codegen.ProductSelectorSearchQueryVariables >(PRODUCT_SELECTOR_SEARCH, { take, term, }); } reindex() { return this.baseDataService.mutate<Codegen.ReindexMutation>(REINDEX); } getPendingSearchIndexUpdates() { return this.baseDataService.query<Codegen.GetPendingSearchIndexUpdatesQuery>( GET_PENDING_SEARCH_INDEX_UPDATES, ); } runPendingSearchIndexUpdates() { return this.baseDataService.mutate<Codegen.RunPendingSearchIndexUpdatesMutation>( RUN_PENDING_SEARCH_INDEX_UPDATES, ); } getProducts(options: Codegen.ProductListOptions) { return this.baseDataService.query<Codegen.GetProductListQuery, Codegen.GetProductListQueryVariables>( GET_PRODUCT_LIST, { options, }, ); } getProduct(id: string, variantListOptions?: Codegen.ProductVariantListOptions) { return this.baseDataService.query< Codegen.GetProductWithVariantsQuery, Codegen.GetProductWithVariantsQueryVariables >(GET_PRODUCT_WITH_VARIANTS, { id, variantListOptions, }); } getProductSimple(id: string) { return this.baseDataService.query< Codegen.GetProductSimpleQuery, Codegen.GetProductSimpleQueryVariables >(GET_PRODUCT_SIMPLE, { id, }); } getProductVariantsSimple(options: Codegen.ProductVariantListOptions, productId?: string) { return this.baseDataService.query< Codegen.GetProductVariantListSimpleQuery, Codegen.GetProductVariantListSimpleQueryVariables >(GET_PRODUCT_VARIANT_LIST_SIMPLE, { options, productId }); } getProductVariants(options: Codegen.ProductVariantListOptions) { return this.baseDataService.query< Codegen.GetProductVariantListQuery, Codegen.GetProductVariantListQueryVariables >(GET_PRODUCT_VARIANT_LIST, { options }); } getProductVariantsForProduct(options: Codegen.ProductVariantListOptions, productId: string) { return this.baseDataService.query< Codegen.GetProductVariantListForProductQuery, Codegen.GetProductVariantListForProductQueryVariables >(GET_PRODUCT_VARIANT_LIST_FOR_PRODUCT, { options, productId }); } getProductVariant(id: string) { return this.baseDataService.query< Codegen.GetProductVariantQuery, Codegen.GetProductVariantQueryVariables >(GET_PRODUCT_VARIANT, { id }); } getProductVariantsOptions(id: string) { return this.baseDataService.query< Codegen.GetProductVariantOptionsQuery, Codegen.GetProductVariantOptionsQueryVariables >(GET_PRODUCT_VARIANT_OPTIONS, { id, }); } getProductOptionGroup(id: string) { return this.baseDataService.query< Codegen.GetProductOptionGroupQuery, Codegen.GetProductOptionGroupQueryVariables >(GET_PRODUCT_OPTION_GROUP, { id, }); } createProduct(product: Codegen.CreateProductInput) { const input: Codegen.CreateProductMutationVariables = { input: pick(product, [ 'enabled', 'translations', 'customFields', 'assetIds', 'featuredAssetId', 'facetValueIds', ]), }; return this.baseDataService.mutate< Codegen.CreateProductMutation, Codegen.CreateProductMutationVariables >(CREATE_PRODUCT, input); } updateProduct(product: Codegen.UpdateProductInput) { const input: Codegen.UpdateProductMutationVariables = { input: pick(product, [ 'id', 'enabled', 'translations', 'customFields', 'assetIds', 'featuredAssetId', 'facetValueIds', ]), }; return this.baseDataService.mutate< Codegen.UpdateProductMutation, Codegen.UpdateProductMutationVariables >(UPDATE_PRODUCT, input); } deleteProduct(id: string) { return this.baseDataService.mutate< Codegen.DeleteProductMutation, Codegen.DeleteProductMutationVariables >(DELETE_PRODUCT, { id, }); } deleteProducts(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteProductsMutation, Codegen.DeleteProductsMutationVariables >(DELETE_PRODUCTS, { ids, }); } createProductVariants(input: Codegen.CreateProductVariantInput[]) { return this.baseDataService.mutate< Codegen.CreateProductVariantsMutation, Codegen.CreateProductVariantsMutationVariables >(CREATE_PRODUCT_VARIANTS, { input, }); } updateProductVariants(variants: Codegen.UpdateProductVariantInput[]) { const input: Codegen.UpdateProductVariantsMutationVariables = { input: variants.map( pick([ 'id', 'enabled', 'translations', 'sku', 'price', 'taxCategoryId', 'facetValueIds', 'featuredAssetId', 'assetIds', 'optionIds', 'trackInventory', 'outOfStockThreshold', 'useGlobalOutOfStockThreshold', 'stockOnHand', 'customFields', ]), ), }; return this.baseDataService.mutate< Codegen.UpdateProductVariantsMutation, Codegen.UpdateProductVariantsMutationVariables >(UPDATE_PRODUCT_VARIANTS, input); } deleteProductVariant(id: string) { return this.baseDataService.mutate< Codegen.DeleteProductVariantMutation, Codegen.DeleteProductVariantMutationVariables >(DELETE_PRODUCT_VARIANT, { id, }); } deleteProductVariants(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteProductVariantsMutation, Codegen.DeleteProductVariantsMutationVariables >(DELETE_PRODUCT_VARIANTS, { ids, }); } createProductOptionGroups(productOptionGroup: Codegen.CreateProductOptionGroupInput) { const input: Codegen.CreateProductOptionGroupMutationVariables = { input: productOptionGroup, }; return this.baseDataService.mutate< Codegen.CreateProductOptionGroupMutation, Codegen.CreateProductOptionGroupMutationVariables >(CREATE_PRODUCT_OPTION_GROUP, input); } addOptionGroupToProduct(variables: Codegen.AddOptionGroupToProductMutationVariables) { return this.baseDataService.mutate< Codegen.AddOptionGroupToProductMutation, Codegen.AddOptionGroupToProductMutationVariables >(ADD_OPTION_GROUP_TO_PRODUCT, variables); } addOptionToGroup(input: Codegen.CreateProductOptionInput) { return this.baseDataService.mutate< Codegen.AddOptionToGroupMutation, Codegen.AddOptionToGroupMutationVariables >(ADD_OPTION_TO_GROUP, { input }); } deleteProductOption(id: string) { return this.baseDataService.mutate< Codegen.DeleteProductOptionMutation, Codegen.DeleteProductOptionMutationVariables >(DELETE_PRODUCT_OPTION, { id }); } removeOptionGroupFromProduct(variables: Codegen.RemoveOptionGroupFromProductMutationVariables) { return this.baseDataService.mutate< Codegen.RemoveOptionGroupFromProductMutation, Codegen.RemoveOptionGroupFromProductMutationVariables >(REMOVE_OPTION_GROUP_FROM_PRODUCT, variables); } updateProductOption(input: Codegen.UpdateProductOptionInput) { return this.baseDataService.mutate< Codegen.UpdateProductOptionMutation, Codegen.UpdateProductOptionMutationVariables >(UPDATE_PRODUCT_OPTION, { input: pick(input, ['id', 'code', 'translations', 'customFields']), }); } updateProductOptionGroup(input: Codegen.UpdateProductOptionGroupInput) { return this.baseDataService.mutate< Codegen.UpdateProductOptionGroupMutation, Codegen.UpdateProductOptionGroupMutationVariables >(UPDATE_PRODUCT_OPTION_GROUP, { input: pick(input, ['id', 'code', 'translations', 'customFields']), }); } getProductOptionGroups(filterTerm?: string) { return this.baseDataService.query< Codegen.GetProductOptionGroupsQuery, Codegen.GetProductOptionGroupsQueryVariables >(GET_PRODUCT_OPTION_GROUPS, { filterTerm, }); } getAssetList(take = 10, skip = 0) { return this.baseDataService.query<Codegen.GetAssetListQuery, Codegen.GetAssetListQueryVariables>( GET_ASSET_LIST, { options: { skip, take, sort: { createdAt: SortOrder.DESC, }, }, }, ); } getAsset(id: string) { return this.baseDataService.query<Codegen.GetAssetQuery, Codegen.GetAssetQueryVariables>(GET_ASSET, { id, }); } createAssets(files: File[]) { return this.baseDataService.mutate< Codegen.CreateAssetsMutation, Codegen.CreateAssetsMutationVariables >(CREATE_ASSETS, { input: files.map(file => ({ file })), }); } updateAsset(input: Codegen.UpdateAssetInput) { return this.baseDataService.mutate<Codegen.UpdateAssetMutation, Codegen.UpdateAssetMutationVariables>( UPDATE_ASSET, { input, }, ); } deleteAssets(ids: string[], force: boolean) { return this.baseDataService.mutate< Codegen.DeleteAssetsMutation, Codegen.DeleteAssetsMutationVariables >(DELETE_ASSETS, { input: { assetIds: ids, force, }, }); } assignProductsToChannel(input: Codegen.AssignProductsToChannelInput) { return this.baseDataService.mutate< Codegen.AssignProductsToChannelMutation, Codegen.AssignProductsToChannelMutationVariables >(ASSIGN_PRODUCTS_TO_CHANNEL, { input, }); } removeProductsFromChannel(input: Codegen.RemoveProductsFromChannelInput) { return this.baseDataService.mutate< Codegen.RemoveProductsFromChannelMutation, Codegen.RemoveProductsFromChannelMutationVariables >(REMOVE_PRODUCTS_FROM_CHANNEL, { input, }); } assignVariantsToChannel(input: Codegen.AssignProductVariantsToChannelInput) { return this.baseDataService.mutate< Codegen.AssignVariantsToChannelMutation, Codegen.AssignVariantsToChannelMutationVariables >(ASSIGN_VARIANTS_TO_CHANNEL, { input, }); } removeVariantsFromChannel(input: Codegen.RemoveProductVariantsFromChannelInput) { return this.baseDataService.mutate< Codegen.RemoveVariantsFromChannelMutation, Codegen.RemoveVariantsFromChannelMutationVariables >(REMOVE_VARIANTS_FROM_CHANNEL, { input, }); } getTag(id: string) { return this.baseDataService.query<Codegen.GetTagQuery, Codegen.GetTagQueryVariables>(GET_TAG, { id }); } getTagList(options?: Codegen.TagListOptions) { return this.baseDataService.query<Codegen.GetTagListQuery, Codegen.GetTagListQueryVariables>( GET_TAG_LIST, { options, }, ); } createTag(input: Codegen.CreateTagInput) { return this.baseDataService.mutate<Codegen.CreateTagMutation, Codegen.CreateTagMutationVariables>( CREATE_TAG, { input, }, ); } updateTag(input: Codegen.UpdateTagInput) { return this.baseDataService.mutate<Codegen.UpdateTagMutation, Codegen.UpdateTagMutationVariables>( UPDATE_TAG, { input, }, ); } deleteTag(id: string) { return this.baseDataService.mutate<Codegen.DeleteTagMutation, Codegen.DeleteTagMutationVariables>( DELETE_TAG, { id, }, ); } }
import { pick } from '@vendure/common/lib/pick'; import * as Codegen from '../../common/generated-types'; import { CREATE_PROMOTION, DELETE_PROMOTION, DELETE_PROMOTIONS, GET_ADJUSTMENT_OPERATIONS, UPDATE_PROMOTION, } from '../definitions/promotion-definitions'; import { BaseDataService } from './base-data.service'; export class PromotionDataService { constructor(private baseDataService: BaseDataService) {} getPromotionActionsAndConditions() { return this.baseDataService.query<Codegen.GetAdjustmentOperationsQuery>(GET_ADJUSTMENT_OPERATIONS); } createPromotion(input: Codegen.CreatePromotionInput) { return this.baseDataService.mutate< Codegen.CreatePromotionMutation, Codegen.CreatePromotionMutationVariables >(CREATE_PROMOTION, { input: pick(input, [ 'conditions', 'actions', 'couponCode', 'startsAt', 'endsAt', 'perCustomerUsageLimit', 'usageLimit', 'enabled', 'translations', 'customFields', ]), }); } updatePromotion(input: Codegen.UpdatePromotionInput) { return this.baseDataService.mutate< Codegen.UpdatePromotionMutation, Codegen.UpdatePromotionMutationVariables >(UPDATE_PROMOTION, { input: pick(input, [ 'id', 'conditions', 'actions', 'couponCode', 'startsAt', 'endsAt', 'perCustomerUsageLimit', 'usageLimit', 'enabled', 'translations', 'customFields', ]), }); } deletePromotion(id: string) { return this.baseDataService.mutate< Codegen.DeletePromotionMutation, Codegen.DeletePromotionMutationVariables >(DELETE_PROMOTION, { id }); } deletePromotions(ids: string[]) { return this.baseDataService.mutate< Codegen.DeletePromotionsMutation, Codegen.DeletePromotionsMutationVariables >(DELETE_PROMOTIONS, { ids }); } }
import { FetchPolicy, WatchQueryFetchPolicy } from '@apollo/client/core'; import { pick } from '@vendure/common/lib/pick'; import * as Codegen from '../../common/generated-types'; import { ChannelListOptions, JobListOptions, JobState, SellerListOptions, TaxCategoryListOptions, } from '../../common/generated-types'; import { ADD_MEMBERS_TO_ZONE, CANCEL_JOB, CREATE_CHANNEL, CREATE_COUNTRY, CREATE_PAYMENT_METHOD, CREATE_SELLER, CREATE_TAX_CATEGORY, CREATE_TAX_RATE, CREATE_ZONE, DELETE_CHANNEL, DELETE_CHANNELS, DELETE_COUNTRIES, DELETE_COUNTRY, DELETE_PAYMENT_METHOD, DELETE_PAYMENT_METHODS, DELETE_SELLER, DELETE_SELLERS, DELETE_TAX_CATEGORIES, DELETE_TAX_CATEGORY, DELETE_TAX_RATE, DELETE_TAX_RATES, DELETE_ZONE, DELETE_ZONES, GET_ACTIVE_CHANNEL, GET_AVAILABLE_COUNTRIES, GET_CHANNELS, GET_GLOBAL_SETTINGS, GET_JOB_INFO, GET_JOB_QUEUE_LIST, GET_JOBS_BY_ID, GET_JOBS_LIST, GET_PAYMENT_METHOD_OPERATIONS, GET_SELLERS, GET_TAX_CATEGORIES, GET_TAX_RATE_LIST_SIMPLE, GET_ZONE, REMOVE_MEMBERS_FROM_ZONE, UPDATE_CHANNEL, UPDATE_COUNTRY, UPDATE_GLOBAL_SETTINGS, UPDATE_PAYMENT_METHOD, UPDATE_SELLER, UPDATE_TAX_CATEGORY, UPDATE_TAX_RATE, UPDATE_ZONE, } from '../definitions/settings-definitions'; import { BaseDataService } from './base-data.service'; export class SettingsDataService { constructor(private baseDataService: BaseDataService) {} getAvailableCountries() { return this.baseDataService.query<Codegen.GetAvailableCountriesQuery>(GET_AVAILABLE_COUNTRIES); } createCountry(input: Codegen.CreateCountryInput) { return this.baseDataService.mutate< Codegen.CreateCountryMutation, Codegen.CreateCountryMutationVariables >(CREATE_COUNTRY, { input: pick(input, ['code', 'enabled', 'translations', 'customFields']), }); } updateCountry(input: Codegen.UpdateCountryInput) { return this.baseDataService.mutate< Codegen.UpdateCountryMutation, Codegen.UpdateCountryMutationVariables >(UPDATE_COUNTRY, { input: pick(input, ['id', 'code', 'enabled', 'translations', 'customFields']), }); } deleteCountry(id: string) { return this.baseDataService.mutate< Codegen.DeleteCountryMutation, Codegen.DeleteCountryMutationVariables >(DELETE_COUNTRY, { id, }); } deleteCountries(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteCountriesMutation, Codegen.DeleteCountriesMutationVariables >(DELETE_COUNTRIES, { ids, }); } getZone(id: string) { return this.baseDataService.query<Codegen.GetZoneQuery, Codegen.GetZoneQueryVariables>(GET_ZONE, { id, }); } createZone(input: Codegen.CreateZoneInput) { return this.baseDataService.mutate<Codegen.CreateZoneMutation, Codegen.CreateZoneMutationVariables>( CREATE_ZONE, { input, }, ); } updateZone(input: Codegen.UpdateZoneInput) { return this.baseDataService.mutate<Codegen.UpdateZoneMutation, Codegen.UpdateZoneMutationVariables>( UPDATE_ZONE, { input, }, ); } deleteZone(id: string) { return this.baseDataService.mutate<Codegen.DeleteZoneMutation, Codegen.DeleteZoneMutationVariables>( DELETE_ZONE, { id, }, ); } deleteZones(ids: string[]) { return this.baseDataService.mutate<Codegen.DeleteZonesMutation, Codegen.DeleteZonesMutationVariables>( DELETE_ZONES, { ids, }, ); } addMembersToZone(zoneId: string, memberIds: string[]) { return this.baseDataService.mutate< Codegen.AddMembersToZoneMutation, Codegen.AddMembersToZoneMutationVariables >(ADD_MEMBERS_TO_ZONE, { zoneId, memberIds, }); } removeMembersFromZone(zoneId: string, memberIds: string[]) { return this.baseDataService.mutate< Codegen.RemoveMembersFromZoneMutation, Codegen.RemoveMembersFromZoneMutationVariables >(REMOVE_MEMBERS_FROM_ZONE, { zoneId, memberIds, }); } getTaxCategories(options: TaxCategoryListOptions = {}) { return this.baseDataService.query< Codegen.GetTaxCategoriesQuery, Codegen.GetTaxCategoriesQueryVariables >(GET_TAX_CATEGORIES, { options, }); } createTaxCategory(input: Codegen.CreateTaxCategoryInput) { return this.baseDataService.mutate< Codegen.CreateTaxCategoryMutation, Codegen.CreateTaxCategoryMutationVariables >(CREATE_TAX_CATEGORY, { input, }); } updateTaxCategory(input: Codegen.UpdateTaxCategoryInput) { return this.baseDataService.mutate< Codegen.UpdateTaxCategoryMutation, Codegen.UpdateTaxCategoryMutationVariables >(UPDATE_TAX_CATEGORY, { input, }); } deleteTaxCategory(id: string) { return this.baseDataService.mutate< Codegen.DeleteTaxCategoryMutation, Codegen.DeleteTaxCategoryMutationVariables >(DELETE_TAX_CATEGORY, { id, }); } deleteTaxCategories(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteTaxCategoriesMutation, Codegen.DeleteTaxCategoriesMutationVariables >(DELETE_TAX_CATEGORIES, { ids, }); } getTaxRatesSimple(take = 10, skip = 0, fetchPolicy?: FetchPolicy) { return this.baseDataService.query< Codegen.GetTaxRateListSimpleQuery, Codegen.GetTaxRateListSimpleQueryVariables >( GET_TAX_RATE_LIST_SIMPLE, { options: { take, skip, }, }, fetchPolicy, ); } createTaxRate(input: Codegen.CreateTaxRateInput) { return this.baseDataService.mutate< Codegen.CreateTaxRateMutation, Codegen.CreateTaxRateMutationVariables >(CREATE_TAX_RATE, { input, }); } updateTaxRate(input: Codegen.UpdateTaxRateInput) { return this.baseDataService.mutate< Codegen.UpdateTaxRateMutation, Codegen.UpdateTaxRateMutationVariables >(UPDATE_TAX_RATE, { input, }); } deleteTaxRate(id: string) { return this.baseDataService.mutate< Codegen.DeleteTaxRateMutation, Codegen.DeleteTaxRateMutationVariables >(DELETE_TAX_RATE, { id, }); } deleteTaxRates(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteTaxRatesMutation, Codegen.DeleteTaxRatesMutationVariables >(DELETE_TAX_RATES, { ids, }); } getChannels(options: ChannelListOptions = {}) { return this.baseDataService.query<Codegen.GetChannelsQuery, Codegen.GetChannelsQueryVariables>( GET_CHANNELS, { options }, ); } getSellerList(options?: SellerListOptions) { return this.baseDataService.query<Codegen.GetSellersQuery, Codegen.GetSellersQueryVariables>( GET_SELLERS, { options }, ); } createSeller(input: Codegen.CreateSellerInput) { return this.baseDataService.mutate< Codegen.CreateSellerMutation, Codegen.CreateSellerMutationVariables >(CREATE_SELLER, { input, }); } updateSeller(input: Codegen.UpdateSellerInput) { return this.baseDataService.mutate< Codegen.UpdateSellerMutation, Codegen.UpdateSellerMutationVariables >(UPDATE_SELLER, { input, }); } deleteSeller(id: string) { return this.baseDataService.mutate< Codegen.DeleteSellerMutation, Codegen.DeleteSellerMutationVariables >(DELETE_SELLER, { id, }); } deleteSellers(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteSellersMutation, Codegen.DeleteSellersMutationVariables >(DELETE_SELLERS, { ids, }); } getActiveChannel(fetchPolicy?: FetchPolicy) { return this.baseDataService.query< Codegen.GetActiveChannelQuery, Codegen.GetActiveChannelQueryVariables >(GET_ACTIVE_CHANNEL, {}, fetchPolicy); } createChannel(input: Codegen.CreateChannelInput) { return this.baseDataService.mutate< Codegen.CreateChannelMutation, Codegen.CreateChannelMutationVariables >(CREATE_CHANNEL, { input, }); } updateChannel(input: Codegen.UpdateChannelInput) { return this.baseDataService.mutate< Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables >(UPDATE_CHANNEL, { input, }); } deleteChannel(id: string) { return this.baseDataService.mutate< Codegen.DeleteChannelMutation, Codegen.DeleteChannelMutationVariables >(DELETE_CHANNEL, { id, }); } deleteChannels(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteChannelsMutation, Codegen.DeleteChannelsMutationVariables >(DELETE_CHANNELS, { ids, }); } createPaymentMethod(input: Codegen.CreatePaymentMethodInput) { return this.baseDataService.mutate< Codegen.CreatePaymentMethodMutation, Codegen.CreatePaymentMethodMutationVariables >(CREATE_PAYMENT_METHOD, { input: pick(input, ['code', 'checker', 'handler', 'enabled', 'translations', 'customFields']), }); } updatePaymentMethod(input: Codegen.UpdatePaymentMethodInput) { return this.baseDataService.mutate< Codegen.UpdatePaymentMethodMutation, Codegen.UpdatePaymentMethodMutationVariables >(UPDATE_PAYMENT_METHOD, { input: pick(input, [ 'id', 'code', 'checker', 'handler', 'enabled', 'translations', 'customFields', ]), }); } deletePaymentMethod(id: string, force: boolean) { return this.baseDataService.mutate< Codegen.DeletePaymentMethodMutation, Codegen.DeletePaymentMethodMutationVariables >(DELETE_PAYMENT_METHOD, { id, force, }); } deletePaymentMethods(ids: string[], force: boolean) { return this.baseDataService.mutate< Codegen.DeletePaymentMethodsMutation, Codegen.DeletePaymentMethodsMutationVariables >(DELETE_PAYMENT_METHODS, { ids, force, }); } getPaymentMethodOperations() { return this.baseDataService.query<Codegen.GetPaymentMethodOperationsQuery>( GET_PAYMENT_METHOD_OPERATIONS, ); } getGlobalSettings(fetchPolicy?: WatchQueryFetchPolicy) { return this.baseDataService.query<Codegen.GetGlobalSettingsQuery>( GET_GLOBAL_SETTINGS, undefined, fetchPolicy, ); } updateGlobalSettings(input: Codegen.UpdateGlobalSettingsInput) { return this.baseDataService.mutate< Codegen.UpdateGlobalSettingsMutation, Codegen.UpdateGlobalSettingsMutationVariables >(UPDATE_GLOBAL_SETTINGS, { input, }); } getJob(id: string) { return this.baseDataService.query<Codegen.GetJobInfoQuery, Codegen.GetJobInfoQueryVariables>( GET_JOB_INFO, { id, }, ); } pollJobs(ids: string[]) { return this.baseDataService.query<Codegen.GetJobsByIdQuery, Codegen.GetJobsByIdQueryVariables>( GET_JOBS_BY_ID, { ids, }, ); } getAllJobs(options?: JobListOptions) { return this.baseDataService.query<Codegen.GetAllJobsQuery, Codegen.GetAllJobsQueryVariables>( GET_JOBS_LIST, { options, }, 'cache-first', ); } getJobQueues() { return this.baseDataService.query<Codegen.GetJobQueueListQuery>(GET_JOB_QUEUE_LIST); } getRunningJobs() { return this.baseDataService.query<Codegen.GetAllJobsQuery, Codegen.GetAllJobsQueryVariables>( GET_JOBS_LIST, { options: { filter: { state: { eq: JobState.RUNNING, }, }, }, }, ); } cancelJob(id: string) { return this.baseDataService.mutate<Codegen.CancelJobMutation, Codegen.CancelJobMutationVariables>( CANCEL_JOB, { id, }, ); } }
import { pick } from '@vendure/common/lib/pick'; import * as Codegen from '../../common/generated-types'; import { CREATE_SHIPPING_METHOD, DELETE_SHIPPING_METHOD, DELETE_SHIPPING_METHODS, GET_SHIPPING_METHOD_OPERATIONS, TEST_ELIGIBLE_SHIPPING_METHODS, TEST_SHIPPING_METHOD, UPDATE_SHIPPING_METHOD, } from '../definitions/shipping-definitions'; import { BaseDataService } from './base-data.service'; export class ShippingMethodDataService { constructor(private baseDataService: BaseDataService) {} getShippingMethodOperations() { return this.baseDataService.query<Codegen.GetShippingMethodOperationsQuery>( GET_SHIPPING_METHOD_OPERATIONS, ); } createShippingMethod(input: Codegen.CreateShippingMethodInput) { const variables: Codegen.CreateShippingMethodMutationVariables = { input: pick(input, [ 'code', 'checker', 'calculator', 'fulfillmentHandler', 'customFields', 'translations', ]), }; return this.baseDataService.mutate< Codegen.CreateShippingMethodMutation, Codegen.CreateShippingMethodMutationVariables >(CREATE_SHIPPING_METHOD, variables); } updateShippingMethod(input: Codegen.UpdateShippingMethodInput) { const variables: Codegen.UpdateShippingMethodMutationVariables = { input: pick(input, [ 'id', 'code', 'checker', 'calculator', 'fulfillmentHandler', 'customFields', 'translations', ]), }; return this.baseDataService.mutate< Codegen.UpdateShippingMethodMutation, Codegen.UpdateShippingMethodMutationVariables >(UPDATE_SHIPPING_METHOD, variables); } deleteShippingMethod(id: string) { return this.baseDataService.mutate< Codegen.DeleteShippingMethodMutation, Codegen.DeleteShippingMethodMutationVariables >(DELETE_SHIPPING_METHOD, { id, }); } deleteShippingMethods(ids: string[]) { return this.baseDataService.mutate< Codegen.DeleteShippingMethodsMutation, Codegen.DeleteShippingMethodsMutationVariables >(DELETE_SHIPPING_METHODS, { ids, }); } testShippingMethod(input: Codegen.TestShippingMethodInput) { return this.baseDataService.query< Codegen.TestShippingMethodQuery, Codegen.TestShippingMethodQueryVariables >(TEST_SHIPPING_METHOD, { input, }); } testEligibleShippingMethods(input: Codegen.TestEligibleShippingMethodsInput) { return this.baseDataService.query< Codegen.TestEligibleShippingMethodsQuery, Codegen.TestEligibleShippingMethodsQueryVariables >(TEST_ELIGIBLE_SHIPPING_METHODS, { input, }); } }
import { DocumentNode, FieldNode, FragmentDefinitionNode, Kind, OperationTypeNode } from 'graphql'; import { CustomFieldConfig, CustomFields } from '../../common/generated-types'; import { addCustomFields } from './add-custom-fields'; /* eslint-disable @typescript-eslint/no-non-null-assertion */ describe('addCustomFields()', () => { let documentNode: DocumentNode; function generateFragmentDefinitionFor(type: keyof CustomFields): FragmentDefinitionNode { return { kind: Kind.FRAGMENT_DEFINITION, name: { kind: Kind.NAME, value: type, }, typeCondition: { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: type, }, }, directives: [], selectionSet: { kind: Kind.SELECTION_SET, selections: [], }, }; } beforeEach(() => { documentNode = { kind: Kind.DOCUMENT, definitions: [ { kind: Kind.OPERATION_DEFINITION, operation: OperationTypeNode.QUERY, name: { kind: Kind.NAME, value: 'GetProductWithVariants', }, variableDefinitions: [], directives: [], selectionSet: { kind: Kind.SELECTION_SET, selections: [ { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'product', }, arguments: [], directives: [], selectionSet: { kind: Kind.SELECTION_SET, selections: [ { kind: Kind.FRAGMENT_SPREAD, name: { kind: Kind.NAME, value: 'ProductWithVariants', }, directives: [], }, ], }, }, ], }, }, { kind: Kind.FRAGMENT_DEFINITION, name: { kind: Kind.NAME, value: 'ProductWithVariants', }, typeCondition: { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: 'Product', }, }, directives: [], selectionSet: { kind: Kind.SELECTION_SET, selections: [ { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'id', }, arguments: [], directives: [], }, { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'translations', }, arguments: [], directives: [], selectionSet: { kind: Kind.SELECTION_SET, selections: [ { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'languageCode', }, arguments: [], directives: [], }, { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'name', }, arguments: [], directives: [], }, ], }, }, ], }, }, generateFragmentDefinitionFor('ProductVariant'), generateFragmentDefinitionFor('ProductOptionGroup'), generateFragmentDefinitionFor('ProductOption'), generateFragmentDefinitionFor('User'), generateFragmentDefinitionFor('Customer'), generateFragmentDefinitionFor('Address'), ], }; }); it('Adds customFields to Product fragment', () => { const customFieldsConfig = new Map<string, CustomFieldConfig[]>(); customFieldsConfig.set('Product', [ { name: 'custom1', type: 'string', list: false }, { name: 'custom2', type: 'boolean', list: false }, ]); const result = addCustomFields(documentNode, customFieldsConfig); const productFragmentDef = result.definitions[1] as FragmentDefinitionNode; const customFieldsDef = productFragmentDef.selectionSet.selections[2] as FieldNode; expect(productFragmentDef.selectionSet.selections.length).toBe(3); expect(customFieldsDef.selectionSet!.selections.length).toBe(2); expect((customFieldsDef.selectionSet!.selections[0] as FieldNode).name.value).toBe('custom1'); expect((customFieldsDef.selectionSet!.selections[1] as FieldNode).name.value).toBe('custom2'); }); it('Adds customFields to Product translations', () => { const customFieldsConfig = new Map<string, CustomFieldConfig[]>(); customFieldsConfig.set('Product', [ { name: 'customLocaleString', type: 'localeString', list: false }, ]); const result = addCustomFields(documentNode, customFieldsConfig); const productFragmentDef = result.definitions[1] as FragmentDefinitionNode; const translationsField = productFragmentDef.selectionSet.selections[1] as FieldNode; const customTranslationFieldsDef = translationsField.selectionSet!.selections[2] as FieldNode; expect(translationsField.selectionSet!.selections.length).toBe(3); expect((customTranslationFieldsDef.selectionSet!.selections[0] as FieldNode).name.value).toBe( 'customLocaleString', ); }); function addsCustomFieldsToType(type: keyof CustomFields, indexOfDefinition: number) { const customFieldsConfig = new Map<string, CustomFieldConfig[]>(); customFieldsConfig.set(type, [{ name: 'custom', type: 'boolean', list: false }]); const result = addCustomFields(documentNode, customFieldsConfig); const fragmentDef = result.definitions[indexOfDefinition] as FragmentDefinitionNode; const customFieldsDef = fragmentDef.selectionSet.selections[0] as FieldNode; expect(fragmentDef.selectionSet.selections.length).toBe(1); expect(customFieldsDef.selectionSet!.selections.length).toBe(1); expect((customFieldsDef.selectionSet!.selections[0] as FieldNode).name.value).toBe('custom'); } it('Adds customFields to ProductVariant fragment', () => { addsCustomFieldsToType('ProductVariant', 2); }); it('Adds customFields to ProductOptionGroup fragment', () => { addsCustomFieldsToType('ProductOptionGroup', 3); }); it('Adds customFields to ProductOption fragment', () => { addsCustomFieldsToType('ProductOption', 4); }); it('Adds customFields to User fragment', () => { addsCustomFieldsToType('User', 5); }); it('Adds customFields to Customer fragment', () => { addsCustomFieldsToType('Customer', 6); }); it('Adds customFields to Address fragment', () => { addsCustomFieldsToType('Address', 7); }); });
import { DefinitionNode, DocumentNode, FieldNode, FragmentDefinitionNode, Kind, SelectionNode, } from 'graphql'; import { CustomFieldConfig, CustomFields, EntityCustomFields, RelationCustomFieldFragment, } from '../../common/generated-types'; /** * Given a GraphQL AST (DocumentNode), this function looks for fragment definitions and adds and configured * custom fields to those fragments. */ export function addCustomFields( documentNode: DocumentNode, customFields: Map<string, CustomFieldConfig[]>, ): DocumentNode { const fragmentDefs = documentNode.definitions.filter(isFragmentDefinition); for (const fragmentDef of fragmentDefs) { let entityType = fragmentDef.typeCondition.name.value as keyof Pick< CustomFields, Exclude<keyof CustomFields, '__typename'> >; if (entityType === ('OrderAddress' as any)) { // OrderAddress is a special case of the Address entity, and shares its custom fields // so we treat it as an alias entityType = 'Address'; } if (entityType === ('Country' as any)) { // Country is an alias of Region entityType = 'Region'; } const customFieldsForType = customFields.get(entityType); if (customFieldsForType && customFieldsForType.length) { (fragmentDef.selectionSet.selections as SelectionNode[]).push({ name: { kind: Kind.NAME, value: 'customFields', }, kind: Kind.FIELD, selectionSet: { kind: Kind.SELECTION_SET, selections: customFieldsForType.map( customField => ({ kind: Kind.FIELD, name: { kind: Kind.NAME, value: customField.name, }, // For "relation" custom fields, we need to also select // all the scalar fields of the related type ...(customField.type === 'relation' ? { selectionSet: { kind: Kind.SELECTION_SET, selections: ( customField as RelationCustomFieldFragment ).scalarFields.map(f => ({ kind: Kind.FIELD, name: { kind: Kind.NAME, value: f }, })), }, } : {}), } as FieldNode), ), }, }); const localizedFields = customFieldsForType.filter( field => field.type === 'localeString' || field.type === 'localeText', ); const translationsField = fragmentDef.selectionSet.selections .filter(isFieldNode) .find(field => field.name.value === 'translations'); if (localizedFields.length && translationsField && translationsField.selectionSet) { (translationsField.selectionSet.selections as SelectionNode[]).push({ name: { kind: Kind.NAME, value: 'customFields', }, kind: Kind.FIELD, selectionSet: { kind: Kind.SELECTION_SET, selections: localizedFields.map( customField => ({ kind: Kind.FIELD, name: { kind: Kind.NAME, value: customField.name, }, } as FieldNode), ), }, }); } } } return documentNode; } function isFragmentDefinition(value: DefinitionNode): value is FragmentDefinitionNode { return value.kind === Kind.FRAGMENT_DEFINITION; } function isFieldNode(value: SelectionNode): value is FieldNode { return value.kind === Kind.FIELD; }
import { getAppConfig } from '../../app.config'; /** * Returns the location of the server, e.g. "http://localhost:3000" */ export function getServerLocation(): string { const { apiHost, apiPort, adminApiPath, tokenMethod } = getAppConfig(); const host = apiHost === 'auto' ? `${location.protocol}//${location.hostname}` : apiHost; const port = apiPort ? apiPort === 'auto' ? location.port === '' ? '' : `:${location.port}` : `:${apiPort}` : ''; return `${host}${port}`; }
import { DocumentNode, getOperationAST, NamedTypeNode, TypeNode } from 'graphql'; const CREATE_ENTITY_REGEX = /Create([A-Za-z]+)Input/; const UPDATE_ENTITY_REGEX = /Update([A-Za-z]+)Input/; /** * Checks the current documentNode for an operation with a variable named "Create<Entity>Input" or "Update<Entity>Input" * and if a match is found, returns the <Entity> name. */ export function isEntityCreateOrUpdateMutation(documentNode: DocumentNode): string | undefined { const operationDef = getOperationAST(documentNode, null); if (operationDef && operationDef.variableDefinitions) { for (const variableDef of operationDef.variableDefinitions) { const namedType = extractInputType(variableDef.type); const inputTypeName = namedType.name.value; // special cases which don't follow the usual pattern if (inputTypeName === 'UpdateActiveAdministratorInput') { return 'Administrator'; } if (inputTypeName === 'ModifyOrderInput') { return 'Order'; } if ( inputTypeName === 'AddItemToDraftOrderInput' || inputTypeName === 'AdjustDraftOrderLineInput' ) { return 'OrderLine'; } const createMatch = inputTypeName.match(CREATE_ENTITY_REGEX); if (createMatch) { return createMatch[1]; } const updateMatch = inputTypeName.match(UPDATE_ENTITY_REGEX); if (updateMatch) { return updateMatch[1]; } } } } function extractInputType(type: TypeNode): NamedTypeNode { if (type.kind === 'NonNullType') { return extractInputType(type.type); } if (type.kind === 'ListType') { return extractInputType(type.type); } return type; }
import { CustomFieldConfig, LanguageCode } from '../../common/generated-types'; import { removeReadonlyCustomFields } from './remove-readonly-custom-fields'; describe('removeReadonlyCustomFields', () => { it('readonly field and writable field', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'rating', type: 'float', readonly: true, list: false }, ]; const entity = { id: 1, name: 'test', customFields: { weight: 500, rating: 123, }, }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ id: 1, name: 'test', customFields: { weight: 500, }, } as any); }); it('single readonly field', () => { const config: CustomFieldConfig[] = [{ name: 'rating', type: 'float', readonly: true, list: false }]; const entity = { id: 1, name: 'test', customFields: { rating: 123, }, }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ id: 1, name: 'test', customFields: {}, } as any); }); it('readonly field and customFields is undefined', () => { const config: CustomFieldConfig[] = [{ name: 'alias', type: 'string', readonly: true, list: false }]; const entity = { id: 1, name: 'test', customFields: undefined, }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ id: 1, name: 'test', customFields: undefined, } as any); }); it('readonly field in translation', () => { const config: CustomFieldConfig[] = [ { name: 'alias', type: 'localeString', readonly: true, list: false }, ]; const entity = { id: 1, name: 'test', translations: [{ id: 1, languageCode: LanguageCode.en, customFields: { alias: 'testy' } }], }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ id: 1, name: 'test', translations: [{ id: 1, languageCode: LanguageCode.en, customFields: {} }], } as any); }); it('readonly field and customFields is undefined in translation', () => { const config: CustomFieldConfig[] = [ { name: 'alias', type: 'localeString', readonly: true, list: false }, ]; const entity = { id: 1, name: 'test', translations: [{ id: 1, languageCode: LanguageCode.en, customFields: undefined }], }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ id: 1, name: 'test', translations: [{ id: 1, languageCode: LanguageCode.en, customFields: undefined }], } as any); }); it('wrapped in an input object', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'rating', type: 'float', readonly: true, list: false }, ]; const entity = { input: { id: 1, name: 'test', customFields: { weight: 500, rating: 123, }, }, }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ input: { id: 1, name: 'test', customFields: { weight: 500, }, }, } as any); }); it('with array of input objects', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'rating', type: 'float', readonly: true, list: false }, ]; const entity = { input: [ { id: 1, name: 'test', customFields: { weight: 500, rating: 123, }, }, ], }; const result = removeReadonlyCustomFields(entity, config); expect(result).toEqual({ input: [ { id: 1, name: 'test', customFields: { weight: 500, }, }, ], } as any); }); });
import { CustomFieldConfig } from '../../common/generated-types'; type InputWithOptionalCustomFields = Record<string, any> & { customFields?: Record<string, any>; }; type EntityInput = InputWithOptionalCustomFields & { translations?: InputWithOptionalCustomFields[]; }; type Variable = EntityInput | EntityInput[]; type WrappedVariable = { input: Variable; }; /** * Removes any `readonly` custom fields from an entity (including its translations). * To be used before submitting the entity for a create or update request. */ export function removeReadonlyCustomFields( variables: Variable | WrappedVariable | WrappedVariable[], customFieldConfig: CustomFieldConfig[], ) { if (Array.isArray(variables)) { return variables.map(variable => removeReadonlyCustomFields(variable, customFieldConfig)); } if ('input' in variables && variables.input) { if (Array.isArray(variables.input)) { variables.input = variables.input.map(variable => removeReadonly(variable, customFieldConfig)); } else { variables.input = removeReadonly(variables.input, customFieldConfig); } return variables; } return removeReadonly(variables, customFieldConfig); } function removeReadonly(input: EntityInput, customFieldConfig: CustomFieldConfig[]) { const readonlyConfigs = customFieldConfig.filter(({ readonly }) => readonly); readonlyConfigs.forEach(({ name }) => { input.translations?.forEach(translation => { delete translation.customFields?.[name]; }); delete input.customFields?.[name]; }); return input; }
import { CustomFieldConfig } from '../../common/generated-types'; import { transformRelationCustomFieldInputs } from './transform-relation-custom-field-inputs'; describe('transformRelationCustomFieldInput()', () => { it('transforms single type', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'avatar', type: 'relation', list: false, entity: 'Asset' }, ]; const entity = { id: 1, name: 'test', customFields: { weight: 500, avatar: { id: 123, preview: '...', }, }, }; const result = transformRelationCustomFieldInputs(entity, config); expect(result).toEqual({ id: 1, name: 'test', customFields: { weight: 500, avatarId: 123, }, } as any); }); it('transforms single type with null value', () => { const config: CustomFieldConfig[] = [ { name: 'avatar', type: 'relation', list: false, entity: 'Asset' }, ]; const entity = { id: 1, name: 'test', customFields: { avatar: null, }, }; const result = transformRelationCustomFieldInputs(entity, config); expect(result).toEqual({ id: 1, name: 'test', customFields: { avatarId: null }, } as any); }); it('transforms list type', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'avatars', type: 'relation', list: true, entity: 'Asset' }, ]; const entity = { id: 1, name: 'test', customFields: { weight: 500, avatars: [ { id: 123, preview: '...', }, { id: 456, preview: '...', }, { id: 789, preview: '...', }, ], }, }; const result = transformRelationCustomFieldInputs(entity, config); expect(result).toEqual({ id: 1, name: 'test', customFields: { weight: 500, avatarsIds: [123, 456, 789], }, } as any); }); it('transforms input object', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'avatar', type: 'relation', list: false, entity: 'Asset' }, ]; const entity = { id: 1, name: 'test', customFields: { weight: 500, avatar: { id: 123, preview: '...', }, }, }; const result = transformRelationCustomFieldInputs({ input: entity }, config); expect(result).toEqual({ input: { id: 1, name: 'test', customFields: { weight: 500, avatarId: 123, }, }, } as any); }); it('transforms input array (as in UpdateProductVariantsInput)', () => { const config: CustomFieldConfig[] = [ { name: 'weight', type: 'int', list: false }, { name: 'avatar', type: 'relation', list: false, entity: 'Asset' }, ]; const entity = { id: 1, name: 'test', customFields: { weight: 500, avatar: { id: 123, preview: '...', }, }, }; const result = transformRelationCustomFieldInputs({ input: [entity] }, config); expect(result).toEqual({ input: [ { id: 1, name: 'test', customFields: { weight: 500, avatarId: 123, }, }, ], } as any); }); });
import { getGraphQlInputName } from '@vendure/common/lib/shared-utils'; import { simpleDeepClone } from '@vendure/common/lib/simple-deep-clone'; import { CustomFieldConfig } from '../../common/generated-types'; /** * Transforms any custom field "relation" type inputs into the corresponding `<name>Id` format, * as expected by the server. */ export function transformRelationCustomFieldInputs< T extends { input?: Record<string, any> | Array<Record<string, any>> } & Record<string, any> = any, >(variables: T, customFieldConfig: CustomFieldConfig[]): T { if (variables.input) { if (Array.isArray(variables.input)) { for (const item of variables.input) { transformRelations(item, customFieldConfig); } } else { transformRelations(variables.input, customFieldConfig); } } return transformRelations(variables, customFieldConfig); } /** * @description * When persisting custom fields, we need to send just the IDs of the relations, * rather than the objects themselves. */ function transformRelations<T>(input: T, customFieldConfig: CustomFieldConfig[]) { for (const field of customFieldConfig) { if (field.type === 'relation') { if (hasCustomFields(input)) { const entityValue = input.customFields[field.name]; if (input.customFields.hasOwnProperty(field.name)) { delete input.customFields[field.name]; input.customFields[getGraphQlInputName(field)] = field.list && Array.isArray(entityValue) ? entityValue.map(v => (typeof v === 'string' ? v : v?.id)) : entityValue === null ? null : entityValue?.id; } } } } return input; } function hasCustomFields(input: any): input is { customFields: { [key: string]: any } } { return input != null && input.hasOwnProperty('customFields') && typeof input.customFields === 'object'; }
import { APP_INITIALIZER, Provider } from '@angular/core'; import { ActionBarDropdownMenuItem } from '../providers/nav-builder/nav-builder-types'; import { NavBuilderService } from '../providers/nav-builder/nav-builder.service'; /** * @description * Adds a dropdown menu item to the ActionBar at the top right of each list or detail view. The locationId can * be determined by pressing `ctrl + u` when running the Admin UI in dev mode. * * @example * ```ts title="providers.ts" * import { addActionBarDropdownMenuItem } from '\@vendure/admin-ui/core'; * * export default [ * addActionBarDropdownMenuItem({ * id: 'print-invoice', * label: 'Print Invoice', * locationId: 'order-detail', * routerLink: ['/extensions/invoicing'], * }), * ]; * ``` * * @since 2.2.0 * @docsCategory action-bar */ export function addActionBarDropdownMenuItem(config: ActionBarDropdownMenuItem): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (navBuilderService: NavBuilderService) => () => { navBuilderService.addActionBarDropdownMenuItem(config); }, deps: [NavBuilderService], }; }
import { APP_INITIALIZER, Provider } from '@angular/core'; import { ActionBarItem } from '../providers/nav-builder/nav-builder-types'; import { NavBuilderService } from '../providers/nav-builder/nav-builder.service'; /** * @description * Adds a button to the ActionBar at the top right of each list or detail view. The locationId can * be determined by pressing `ctrl + u` when running the Admin UI in dev mode. * * @example * ```ts title="providers.ts" * export default [ * addActionBarItem({ * id: 'print-invoice', * label: 'Print Invoice', * locationId: 'order-detail', * routerLink: ['/extensions/invoicing'], * }), * ]; * ``` * @docsCategory action-bar */ export function addActionBarItem(config: ActionBarItem): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (navBuilderService: NavBuilderService) => () => { navBuilderService.addActionBarItem(config); }, deps: [NavBuilderService], }; }
import { APP_INITIALIZER, Provider } from '@angular/core'; import { NavMenuItem, NavMenuSection } from '../providers/nav-builder/nav-builder-types'; import { NavBuilderService } from '../providers/nav-builder/nav-builder.service'; /** * @description * Add a section to the main nav menu. Providing the `before` argument will * move the section before any existing section with the specified id. If * omitted (or if the id is not found) the section will be appended to the * existing set of sections. * This should be used in the NgModule `providers` array of your ui extension module. * * @example * ```ts title="providers.ts" * import { addNavMenuSection } from '\@vendure/admin-ui/core'; * * export default [ * addNavMenuSection({ * id: 'reports', * label: 'Reports', * items: [{ * // ... * }], * }, * 'settings'), * ]; * ``` * @docsCategory nav-menu */ export function addNavMenuSection(config: NavMenuSection, before?: string): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (navBuilderService: NavBuilderService) => () => { navBuilderService.addNavMenuSection(config, before); }, deps: [NavBuilderService], }; } /** * @description * Add a menu item to an existing section specified by `sectionId`. The id of the section * can be found by inspecting the DOM and finding the `data-section-id` attribute. * Providing the `before` argument will move the item before any existing item with the specified id. * If omitted (or if the name is not found) the item will be appended to the * end of the section. * * This should be used in the NgModule `providers` array of your ui extension module. * * @example * ```ts title="providers.ts" * import { addNavMenuItem } from '\@vendure/admin-ui/core'; * * export default [ * addNavMenuItem({ * id: 'reviews', * label: 'Product Reviews', * routerLink: ['/extensions/reviews'], * icon: 'star', * }, * 'marketing'), * ]; * ``` * * @docsCategory nav-menu */ export function addNavMenuItem(config: NavMenuItem, sectionId: string, before?: string): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (navBuilderService: NavBuilderService) => () => { navBuilderService.addNavMenuItem(config, sectionId, before); }, deps: [NavBuilderService], }; }
import { APP_INITIALIZER, FactoryProvider } from '@angular/core'; import { AlertConfig, AlertsService } from '../providers/alerts/alerts.service'; /** * @description * Registers an alert which can be displayed in the Admin UI alert dropdown in the top bar. * The alert is configured using the {@link AlertConfig} object. * * @since 2.2.0 * @docsCategory alerts */ export function registerAlert(config: AlertConfig): FactoryProvider { return { provide: APP_INITIALIZER, multi: true, useFactory: (alertsService: AlertsService) => () => { alertsService.configureAlert(config); alertsService.refresh(config.id); }, deps: [AlertsService], }; }
import { APP_INITIALIZER, FactoryProvider } from '@angular/core'; import { BulkActionRegistryService } from '../providers/bulk-action-registry/bulk-action-registry.service'; import { BulkAction } from '../providers/bulk-action-registry/bulk-action-types'; /** * @description * Registers a custom {@link BulkAction} which can be invoked from the bulk action menu * of any supported list view. * * This allows you to provide custom functionality that can operate on any of the selected * items in the list view. * * In this example, imagine we have an integration with a 3rd-party text translation service. This * bulk action allows us to select multiple products from the product list view, and send them for * translation via a custom service which integrates with the translation service's API. * * @example * ```ts title="providers.ts" * import { ModalService, registerBulkAction, SharedModule } from '\@vendure/admin-ui/core'; * import { ProductDataTranslationService } from './product-data-translation.service'; * * export default [ * ProductDataTranslationService, * registerBulkAction({ * location: 'product-list', * label: 'Send to translation service', * icon: 'language', * onClick: ({ injector, selection }) => { * const modalService = injector.get(ModalService); * const translationService = injector.get(ProductDataTranslationService); * modalService * .dialog({ * title: `Send ${selection.length} products for translation?`, * buttons: [ * { type: 'secondary', label: 'cancel' }, * { type: 'primary', label: 'send', returnValue: true }, * ], * }) * .subscribe(response => { * if (response) { * translationService.sendForTranslation(selection.map(item => item.productId)); * } * }); * }, * }), * ]; * ``` * @since 1.8.0 * @docsCategory bulk-actions */ export function registerBulkAction(bulkAction: BulkAction): FactoryProvider { return { provide: APP_INITIALIZER, multi: true, useFactory: (registry: BulkActionRegistryService) => () => { registry.registerBulkAction(bulkAction); }, deps: [BulkActionRegistryService], }; }
import { APP_INITIALIZER, Provider } from '@angular/core'; import { CustomDetailComponentConfig } from '../providers/custom-detail-component/custom-detail-component-types'; import { CustomDetailComponentService } from '../providers/custom-detail-component/custom-detail-component.service'; /** * @description * Registers a {@link CustomDetailComponent} to be placed in a given location. This allows you * to embed any type of custom Angular component in the entity detail pages of the Admin UI. * * @example * ```ts * import { Component, OnInit } from '\@angular/core'; * import { switchMap } from 'rxjs'; * import { FormGroup } from '\@angular/forms'; * import { CustomFieldConfig } from '\@vendure/common/lib/generated-types'; * import { * DataService, * SharedModule, * CustomDetailComponent, * registerCustomDetailComponent, * GetProductWithVariants * } from '\@vendure/admin-ui/core'; * * \@Component({ * template: `{{ extraInfo$ | async | json }}`, * standalone: true, * imports: [SharedModule], * }) * export class ProductInfoComponent implements CustomDetailComponent, OnInit { * // These two properties are provided by Vendure and will vary * // depending on the particular detail page you are embedding this * // component into. * entity$: Observable<GetProductWithVariants.Product> * detailForm: FormGroup; * * extraInfo$: Observable<any>; * * constructor(private cmsDataService: CmsDataService) {} * * ngOnInit() { * this.extraInfo$ = this.entity$.pipe( * switchMap(entity => this.cmsDataService.getDataFor(entity.id)) * ); * } * } * * export default [ * registerCustomDetailComponent({ * locationId: 'product-detail', * component: ProductInfoComponent, * }), * ]; * ``` * * @docsCategory custom-detail-components */ export function registerCustomDetailComponent(config: CustomDetailComponentConfig): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (customDetailComponentService: CustomDetailComponentService) => () => { customDetailComponentService.registerCustomDetailComponent(config); }, deps: [CustomDetailComponentService], }; }
import { APP_INITIALIZER, FactoryProvider } from '@angular/core'; import { DashboardWidgetConfig, WidgetLayoutDefinition, } from '../providers/dashboard-widget/dashboard-widget-types'; import { DashboardWidgetService } from '../providers/dashboard-widget/dashboard-widget.service'; /** * @description * Registers a dashboard widget. Once registered, the widget can be set as part of the default * (using {@link setDashboardWidgetLayout}). * * @docsCategory dashboard-widgets */ export function registerDashboardWidget(id: string, config: DashboardWidgetConfig): FactoryProvider { return { provide: APP_INITIALIZER, multi: true, useFactory: (dashboardWidgetService: DashboardWidgetService) => () => { dashboardWidgetService.registerWidget(id, config); }, deps: [DashboardWidgetService], }; } /** * @description * Sets the default widget layout for the Admin UI dashboard. * * @docsCategory dashboard-widgets */ export function setDashboardWidgetLayout(layoutDef: WidgetLayoutDefinition): FactoryProvider { return { provide: APP_INITIALIZER, multi: true, useFactory: (dashboardWidgetService: DashboardWidgetService) => () => { dashboardWidgetService.setDefaultLayout(layoutDef); }, deps: [DashboardWidgetService], }; }
import { APP_INITIALIZER } from '@angular/core'; import { DataTableComponentConfig, DataTableCustomComponentService, } from '../shared/components/data-table-2/data-table-custom-component.service'; /** * @description * Allows you to override the default component used to render the data of a particular column in a DataTable. * The component should implement the {@link CustomDataTableColumnComponent} interface. The tableId and columnId can * be determined by pressing `ctrl + u` when running the Admin UI in dev mode. * * @example * ```ts title="components/custom-table.component.ts" * import { Component, Input } from '\@angular/core'; * import { CustomColumnComponent } from '\@vendure/admin-ui/core'; * * \@Component({ * selector: 'custom-slug-component', * template: ` * <a [href]="'https://example.com/products/' + rowItem.slug" target="_blank">{{ rowItem.slug }}</a> * `, * standalone: true, * }) * export class CustomTableComponent implements CustomColumnComponent { * \@Input() rowItem: any; * } * ``` * * ```ts title="providers.ts" * import { registerDataTableComponent } from '\@vendure/admin-ui/core'; * import { CustomTableComponent } from './components/custom-table.component'; * * export default [ * registerDataTableComponent({ * component: CustomTableComponent, * tableId: 'product-list', * columnId: 'slug', * }), * ]; * ``` * * @docsCategory custom-table-components */ export function registerDataTableComponent(config: DataTableComponentConfig) { return { provide: APP_INITIALIZER, multi: true, useFactory: (dataTableCustomComponentService: DataTableCustomComponentService) => () => { dataTableCustomComponentService.registerCustomComponent(config); }, deps: [DataTableCustomComponentService], }; }
import { APP_INITIALIZER, FactoryProvider, Type } from '@angular/core'; import { FormInputComponent } from '../common/component-registry-types'; import { ComponentRegistryService } from '../providers/component-registry/component-registry.service'; /** * @description * Registers a custom FormInputComponent which can be used to control the argument inputs * of a {@link ConfigurableOperationDef} (e.g. CollectionFilter, ShippingMethod etc.) or for * a custom field. * * @example * ```ts title="providers.ts" * import { registerFormInputComponent } from '\@vendure/admin-ui/core'; * * export default [ * // highlight-next-line * registerFormInputComponent('my-custom-input', MyCustomFieldControl), * ]; * ``` * * This input component can then be used in a custom field: * * @example * ```ts title="src/vendure-config.ts" * import { VendureConfig } from '\@vendure/core'; * * const config: VendureConfig = { * // ... * customFields: { * ProductVariant: [ * { * name: 'rrp', * type: 'int', * // highlight-next-line * ui: { component: 'my-custom-input' }, * }, * ] * } * } * ``` * * or with an argument of a {@link ConfigurableOperationDef}: * * @example * ```ts * args: { * rrp: { type: 'int', ui: { component: 'my-custom-input' } }, * } * ``` * * @docsCategory custom-input-components */ export function registerFormInputComponent(id: string, component: Type<FormInputComponent>): FactoryProvider { return { provide: APP_INITIALIZER, multi: true, useFactory: (registry: ComponentRegistryService) => () => { registry.registerInputComponent(id, component); }, deps: [ComponentRegistryService], }; }
import { APP_INITIALIZER, Provider } from '@angular/core'; import { HistoryEntryConfig } from '../providers/custom-history-entry-component/history-entry-component-types'; import { HistoryEntryComponentService } from '../providers/custom-history-entry-component/history-entry-component.service'; /** * @description * Registers a {@link HistoryEntryComponent} for displaying history entries in the Order/Customer * history timeline. * * @example * ```ts * import { Component } from '\@angular/core'; * import { * CustomerFragment, * CustomerHistoryEntryComponent, * registerHistoryEntryComponent, * SharedModule, * TimelineDisplayType, * TimelineHistoryEntry, * } from '\@vendure/admin-ui/core'; * * \@Component({ * selector: 'tax-id-verification-component', * template: ` * <div *ngIf="entry.data.valid"> * Tax ID <strong>{{ entry.data.taxId }}</strong> was verified * <vdr-history-entry-detail *ngIf="entry.data"> * <vdr-object-tree [value]="entry.data"></vdr-object-tree> * </vdr-history-entry-detail> * </div> * <div *ngIf="entry.data.valid">Tax ID {{ entry.data.taxId }} could not be verified</div> * `, * standalone: true, * imports: [SharedModule], * }) * class TaxIdHistoryEntryComponent implements CustomerHistoryEntryComponent { * entry: TimelineHistoryEntry; * customer: CustomerFragment; * * getDisplayType(entry: TimelineHistoryEntry): TimelineDisplayType { * return entry.data.valid ? 'success' : 'error'; * } * * getName(entry: TimelineHistoryEntry): string { * return 'Tax ID Verification Plugin'; * } * * isFeatured(entry: TimelineHistoryEntry): boolean { * return true; * } * * getIconShape(entry: TimelineHistoryEntry) { * return entry.data.valid ? 'check-circle' : 'exclamation-circle'; * } * } * * export default [ * registerHistoryEntryComponent({ * type: 'CUSTOMER_TAX_ID_VERIFICATION', * component: TaxIdHistoryEntryComponent, * }), * ]; * ``` * * @since 1.9.0 * @docsCategory custom-history-entry-components */ export function registerHistoryEntryComponent(config: HistoryEntryConfig): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (customHistoryEntryComponentService: HistoryEntryComponentService) => () => { customHistoryEntryComponentService.registerComponent(config); }, deps: [HistoryEntryComponentService], }; }
import { APP_INITIALIZER, Provider } from '@angular/core'; import { PageService, PageTabConfig } from '../providers/page/page.service'; /** * @description * Add a tab to an existing list or detail page. * * @example * ```ts title="providers.ts" * import { registerPageTab } from '@vendure/admin-ui/core'; * import { DeletedProductListComponent } from './components/deleted-product-list/deleted-product-list.component'; * * export default [ * registerPageTab({ * location: 'product-list', * tab: 'Deleted Products', * route: 'deleted', * component: DeletedProductListComponent, * }), * ]; * ``` * @docsCategory tabs */ export function registerPageTab(config: PageTabConfig): Provider { return { provide: APP_INITIALIZER, multi: true, useFactory: (pageService: PageService) => () => { pageService.registerPageTab({ ...config, priority: config.priority || 1, }); }, deps: [PageService], }; }
import { Type } from '@angular/core'; import { ResolveFn, Route } from '@angular/router'; import { ResultOf, TypedDocumentNode } from '@graphql-typed-document-node/core'; import { DocumentNode } from 'graphql'; import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { BaseDetailComponent, createBaseDetailResolveFn } from '../common/base-detail.component'; import { BreadcrumbValue } from '../providers/breadcrumb/breadcrumb.service'; import { AngularRouteComponent } from './components/angular-route.component'; import { ROUTE_COMPONENT_OPTIONS } from './components/route.component'; import { RouteComponentOptions } from './types'; /** * @description * Configuration for a route component. * * @docsCategory routes */ export type RegisterRouteComponentOptions< Component extends any | BaseDetailComponent<Entity>, Entity extends { id: string; updatedAt?: string }, T extends DocumentNode | TypedDocumentNode<any, { id: string }>, Field extends keyof ResultOf<T>, R extends Field, > = { component: Type<Component> | Component; title?: string; breadcrumb?: BreadcrumbValue; path?: string; query?: T; getBreadcrumbs?: (entity: Exclude<ResultOf<T>[R], 'Query'>) => BreadcrumbValue; entityKey?: Component extends BaseDetailComponent<any> ? R : string; variables?: T extends TypedDocumentNode<any, infer V> ? Omit<V, 'id'> : never; routeConfig?: Route; } & (Component extends BaseDetailComponent<any> ? { entityKey: R } : unknown); /** * @description * Registers an Angular standalone component to be rendered in a route. * * @example * ```ts title="routes.ts" * import { registerRouteComponent } from '\@vendure/admin-ui/core'; * import { registerReactRouteComponent } from '\@vendure/admin-ui/react'; * * import { ProductReviewDetailComponent } from './components/product-review-detail/product-review-detail.component'; * import { AllProductReviewsList } from './components/all-product-reviews-list/all-product-reviews-list.component'; * import { GetReviewDetailDocument } from './generated-types'; * * export default [ * registerRouteComponent({ * path: '', * component: AllProductReviewsList, * breadcrumb: 'Product reviews', * }), * registerRouteComponent({ * path: ':id', * component: ProductReviewDetailComponent, * query: GetReviewDetailDocument, * entityKey: 'productReview', * getBreadcrumbs: entity => [ * { * label: 'Product reviews', * link: ['/extensions', 'product-reviews'], * }, * { * label: `#${entity?.id} (${entity?.product.name})`, * link: [], * }, * ], * }), * ]; * ``` * * @docsCategory routes */ export function registerRouteComponent< Component extends any | BaseDetailComponent<Entity>, Entity extends { id: string; updatedAt?: string }, T extends DocumentNode | TypedDocumentNode<any, { id: string }>, Field extends keyof ResultOf<T>, R extends Field, >(options: RegisterRouteComponentOptions<Component, Entity, T, Field, R>) { const { query, entityKey, variables, getBreadcrumbs } = options; const breadcrumbSubject$ = new BehaviorSubject<BreadcrumbValue>(options.breadcrumb ?? ''); const titleSubject$ = new BehaviorSubject<string | undefined>(options.title); if (getBreadcrumbs != null && (query == null || entityKey == null)) { console.error( [ `[${ options.path ?? 'custom' } route] When using the "getBreadcrumbs" option, the "query" and "entityKey" options must also be provided.`, ``, `Alternatively, use the "breadcrumb" option instead, or use the "PageMetadataService" inside your Angular component`, `or the "usePageMetadata" React hook to set the breadcrumb.`, ].join('\n'), ); } const resolveFn: | ResolveFn<{ entity: Observable<ResultOf<T>[Field] | null>; result?: ResultOf<T>; }> | undefined = query && entityKey ? createBaseDetailResolveFn({ query, entityKey, variables, }) : undefined; return { path: options.path ?? '', providers: [ { provide: ROUTE_COMPONENT_OPTIONS, useValue: { component: options.component, title$: titleSubject$, breadcrumb$: breadcrumbSubject$, } satisfies RouteComponentOptions, }, ...(options.routeConfig?.providers ?? []), ], ...(options.routeConfig ?? {}), resolve: { ...(resolveFn ? { detail: resolveFn } : {}), ...(options.routeConfig?.resolve ?? {}) }, data: { breadcrumb: breadcrumbSubject$, ...(options.routeConfig?.data ?? {}), ...(getBreadcrumbs && query && entityKey ? { breadcrumb: data => data.detail.entity.pipe(map((entity: any) => getBreadcrumbs(entity))), } : {}), ...(options.routeConfig?.data ?? {}), }, component: AngularRouteComponent, } satisfies Route; }
import { Type } from '@angular/core'; import { Subject } from 'rxjs'; import { BreadcrumbValue } from '../providers/breadcrumb/breadcrumb.service'; export interface RouteComponentOptions { component: any; title$: Subject<string | undefined>; breadcrumb$: Subject<BreadcrumbValue>; } export interface AngularRouteComponentOptions extends RouteComponentOptions { component: Type<any>; }
import { Component, inject } from '@angular/core'; import { SharedModule } from '../../shared/shared.module'; import { ROUTE_COMPONENT_OPTIONS, RouteComponent } from './route.component'; @Component({ selector: 'vdr-angular-route-component', template: ` <vdr-route-component><ng-container *ngComponentOutlet="component" /></vdr-route-component> `, standalone: true, imports: [SharedModule, RouteComponent], }) export class AngularRouteComponent { protected component = inject(ROUTE_COMPONENT_OPTIONS).component; }
import { Component, inject, InjectionToken } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { combineLatest, Observable, of, switchMap } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { BreadcrumbValue } from '../../providers/breadcrumb/breadcrumb.service'; import { SharedModule } from '../../shared/shared.module'; import { PageMetadataService } from '../providers/page-metadata.service'; import { AngularRouteComponentOptions } from '../types'; export const ROUTE_COMPONENT_OPTIONS = new InjectionToken<AngularRouteComponentOptions>( 'ROUTE_COMPONENT_OPTIONS', ); @Component({ selector: 'vdr-route-component', template: ` <vdr-page-header> <vdr-page-title *ngIf="title$ | async as title" [title]="title"></vdr-page-title> </vdr-page-header> <vdr-page-body><ng-content /></vdr-page-body> `, standalone: true, imports: [SharedModule], providers: [PageMetadataService], }) export class RouteComponent { protected title$: Observable<string | undefined>; constructor(private route: ActivatedRoute) { const breadcrumbLabel$ = this.route.data.pipe( switchMap(data => { if (data.breadcrumb instanceof Observable) { return data.breadcrumb as Observable<BreadcrumbValue>; } if (typeof data.breadcrumb === 'function') { return data.breadcrumb(data) as Observable<BreadcrumbValue>; } return of(undefined); }), filter(notNullOrUndefined), map(breadcrumb => { if (typeof breadcrumb === 'string') { return breadcrumb; } if (Array.isArray(breadcrumb)) { return breadcrumb[breadcrumb.length - 1].label; } return breadcrumb.label; }), ); this.title$ = combineLatest([inject(ROUTE_COMPONENT_OPTIONS).title$, breadcrumbLabel$]).pipe( map(([title, breadcrumbLabel]) => title ?? breadcrumbLabel), ); } }
import { inject, Injectable } from '@angular/core'; import { BreadcrumbValue } from '../../providers/breadcrumb/breadcrumb.service'; import { ROUTE_COMPONENT_OPTIONS } from '../components/route.component'; @Injectable() export class PageMetadataService { private readonly routeComponentOptions = inject(ROUTE_COMPONENT_OPTIONS); setTitle(title: string) { this.routeComponentOptions.title$.next(title); } setBreadcrumbs(value: BreadcrumbValue) { this.routeComponentOptions.breadcrumb$.next(value); } }
import { Injectable, Injector } from '@angular/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { BehaviorSubject, combineLatest, first, isObservable, Observable, of, Subject, switchMap, } from 'rxjs'; import { filter, map, startWith, take } from 'rxjs/operators'; import { Permission } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; import { ModalService } from '../modal/modal.service'; import { NotificationService } from '../notification/notification.service'; import { PermissionsService } from '../permissions/permissions.service'; /** * @description * The context object which is passed to the `check`, `isAlert`, `label` and `action` functions of an * {@link AlertConfig} object. * * @since 2.2.0 * @docsCategory alerts */ export interface AlertContext { /** * @description * The Angular [Injector](https://angular.dev/api/core/Injector) which can be used to get instances * of services and other providers available in the application. */ injector: Injector; /** * @description * The [DataService](/reference/admin-ui-api/services/data-service), which provides methods for querying the * server-side data. */ dataService: DataService; /** * @description * The [NotificationService](/reference/admin-ui-api/services/notification-service), which provides methods for * displaying notifications to the user. */ notificationService: NotificationService; /** * @description * The [ModalService](/reference/admin-ui-api/services/modal-service), which provides methods for * opening modal dialogs. */ modalService: ModalService; } /** * @description * A configuration object for an Admin UI alert. * * @since 2.2.0 * @docsCategory alerts */ export interface AlertConfig<T = any> { /** * @description * A unique identifier for the alert. */ id: string; /** * @description * A function which is gets the data used to determine whether the alert should be shown. * Typically, this function will query the server or some other remote data source. * * This function will be called once when the Admin UI app bootstraps, and can be also * set to run at regular intervals by setting the `recheckIntervalMs` property. */ check: (context: AlertContext) => T | Promise<T> | Observable<T>; /** * @description * A function which returns an Observable which is used to determine when to re-run the `check` * function. Whenever the observable emits, the `check` function will be called again. * * A basic time-interval-based recheck can be achieved by using the `interval` function from RxJS. * * @example * ```ts * import { interval } from 'rxjs'; * * // ... * recheck: () => interval(60_000) * ``` * * If this is not set, the `check` function will only be called once when the Admin UI app bootstraps. * * @default undefined */ recheck?: (context: AlertContext) => Observable<any>; /** * @description * A function which determines whether the alert should be shown based on the data returned by the `check` * function. */ isAlert: (data: T, context: AlertContext) => boolean; /** * @description * A function which is called when the alert is clicked in the Admin UI. */ action: (data: T, context: AlertContext) => void; /** * @description * A function which returns the text used in the UI to describe the alert. */ label: ( data: T, context: AlertContext, ) => { text: string; translationVars?: { [key: string]: string | number } }; /** * @description * A list of permissions which the current Administrator must have in order. If the current * Administrator does not have these permissions, none of the other alert functions will be called. */ requiredPermissions?: Permission[]; } export interface ActiveAlert { id: string; runAction: () => void; hasRun: boolean; label: { text: string; translationVars?: { [key: string]: string | number } }; } export class Alert<T> { activeAlert$: Observable<ActiveAlert | undefined>; private hasRun$ = new BehaviorSubject(false); private data$ = new BehaviorSubject<T | undefined>(undefined); constructor( private config: AlertConfig<T>, private context: AlertContext, ) { if (this.config.recheck) { this.config.recheck(this.context).subscribe(() => this.runCheck()); } this.activeAlert$ = combineLatest(this.data$, this.hasRun$).pipe( map(([data, hasRun]) => { if (!data) { return; } const isAlert = this.config.isAlert(data, this.context); if (!isAlert) { return; } return { id: this.config.id, runAction: () => { if (!hasRun) { this.config.action(data, this.context); this.hasRun$.next(true); } }, hasRun, label: this.config.label(data, this.context), }; }), ); } get id() { return this.config.id; } runCheck() { const result = this.config.check(this.context); if (result instanceof Promise) { result.then(data => this.data$.next(data)); } else if (isObservable(result)) { result.pipe(take(1)).subscribe(data => this.data$.next(data)); } else { this.data$.next(result); } this.hasRun$.next(false); } } @Injectable({ providedIn: 'root', }) export class AlertsService { activeAlerts$: Observable<ActiveAlert[]>; private alertsMap = new Map<string, Alert<any>>(); private configUpdated = new Subject<void>(); constructor( private permissionsService: PermissionsService, private injector: Injector, private dataService: DataService, private notificationService: NotificationService, private modalService: ModalService, ) { const alerts$ = this.configUpdated.pipe( map(() => [...this.alertsMap.values()]), startWith([...this.alertsMap.values()]), ); this.activeAlerts$ = alerts$.pipe( switchMap(() => { const alerts = [...this.alertsMap.values()]; const isAlertStreams = alerts.map(alert => alert.activeAlert$); return combineLatest(isAlertStreams); }), map(alertStates => alertStates.filter(notNullOrUndefined)), ); } configureAlert<T>(config: AlertConfig<T>) { this.hasSufficientPermissions(config.requiredPermissions) .pipe(first()) .subscribe(hasPermissions => { if (hasPermissions) { this.alertsMap.set(config.id, new Alert(config, this.createContext())); this.configUpdated.next(); } }); } hasSufficientPermissions(permissions?: Permission[]) { if (!permissions || permissions.length === 0) { return of(true); } return this.permissionsService.currentUserPermissions$.pipe( filter(permissions => permissions.length > 0), map(() => this.permissionsService.userHasPermissions(permissions)), ); } refresh(id?: string) { if (id) { this.alertsMap.get(id)?.runCheck(); } else { this.alertsMap.forEach(config => config.runCheck()); } } protected createContext(): AlertContext { return { injector: this.injector, dataService: this.dataService, notificationService: this.notificationService, modalService: this.modalService, }; } }
import { Injectable } from '@angular/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { Observable, of } from 'rxjs'; import { catchError, map, mapTo, mergeMap, switchMap } from 'rxjs/operators'; import { AttemptLoginMutation, CurrentUserFragment } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; import { ServerConfigService } from '../../data/server-config'; import { LocalStorageService } from '../local-storage/local-storage.service'; import { PermissionsService } from '../permissions/permissions.service'; /** * This service handles logic relating to authentication of the current user. */ @Injectable({ providedIn: 'root', }) export class AuthService { constructor( private localStorageService: LocalStorageService, private dataService: DataService, private serverConfigService: ServerConfigService, private permissionsService: PermissionsService, ) {} /** * Attempts to log in via the REST login endpoint and updates the app * state on success. */ logIn( username: string, password: string, rememberMe: boolean, ): Observable<AttemptLoginMutation['login']> { return this.dataService.auth.attemptLogin(username, password, rememberMe).pipe( switchMap(response => { if (response.login.__typename === 'CurrentUser') { this.setChannelToken(response.login.channels); } return this.serverConfigService.getServerConfig().then(() => response.login); }), switchMap(login => { if (login.__typename === 'CurrentUser') { const activeChannel = this.getActiveChannel(login.channels); this.permissionsService.setCurrentUserPermissions(activeChannel.permissions); return this.dataService.administrator.getActiveAdministrator().single$.pipe( switchMap(({ activeAdministrator }) => { if (activeAdministrator) { return this.dataService.client .loginSuccess( activeAdministrator.id, `${activeAdministrator.firstName} ${activeAdministrator.lastName}`, activeChannel.id, login.channels, ) .pipe(map(() => login)); } else { return of(login); } }), ); } return of(login); }), ); } /** * Update the user status to being logged out. */ logOut(): Observable<boolean> { return this.dataService.client.userStatus().single$.pipe( switchMap(status => { if (status.userStatus.isLoggedIn) { return this.dataService.client .logOut() .pipe(mergeMap(() => this.dataService.auth.logOut())); } else { return []; } }), mapTo(true), ); } /** * Checks the app state to see if the user is already logged in, * and if not, attempts to validate any auth token found. */ checkAuthenticatedStatus(): Observable<boolean> { return this.dataService.client.userStatus().single$.pipe( mergeMap(data => { if (!data.userStatus.isLoggedIn) { return this.validateAuthToken(); } else { return of(true); } }), ); } /** * Checks for an auth token and if found, attempts to validate * that token against the API. */ validateAuthToken(): Observable<boolean> { return this.dataService.auth.currentUser().single$.pipe( mergeMap(({ me }) => { if (!me) { return of(false) as any; } this.setChannelToken(me.channels); const activeChannel = this.getActiveChannel(me.channels); this.permissionsService.setCurrentUserPermissions(activeChannel.permissions); return this.dataService.administrator.getActiveAdministrator().single$.pipe( switchMap(({ activeAdministrator }) => { if (activeAdministrator) { return this.dataService.client .loginSuccess( activeAdministrator.id, `${activeAdministrator.firstName} ${activeAdministrator.lastName}`, activeChannel.id, me.channels, ) .pipe(map(() => true)); } else { return of(false); } }), ); }), mapTo(true), catchError(err => of(false)), ); } private getActiveChannel(userChannels: CurrentUserFragment['channels']) { const lastActiveChannelToken = this.localStorageService.get('activeChannelToken'); if (lastActiveChannelToken) { const lastActiveChannel = userChannels.find(c => c.token === lastActiveChannelToken); if (lastActiveChannel) { return lastActiveChannel; } } const defaultChannel = userChannels.find(c => c.code === DEFAULT_CHANNEL_CODE); return defaultChannel || userChannels[0]; } private setChannelToken(userChannels: CurrentUserFragment['channels']) { this.localStorageService.set('activeChannelToken', this.getActiveChannel(userChannels).token); } }
import { Injectable, OnDestroy } from '@angular/core'; import { ActivatedRoute, Data, NavigationEnd, Params, PRIMARY_OUTLET, Router } from '@angular/router'; import { flatten } from 'lodash'; import { combineLatest as observableCombineLatest, isObservable, Observable, of as observableOf, Subject, } from 'rxjs'; import { filter, map, shareReplay, startWith, switchMap, takeUntil } from 'rxjs/operators'; import { DataService } from '../../data/providers/data.service'; export type BreadcrumbString = string; export interface BreadcrumbLabelLinkPair { label: string; link: any[]; } export type BreadcrumbValue = BreadcrumbString | BreadcrumbLabelLinkPair | BreadcrumbLabelLinkPair[]; export type BreadcrumbFunction = ( data: Data, params: Params, dataService: DataService, ) => BreadcrumbValue | Observable<BreadcrumbValue>; export type BreadcrumbDefinition = BreadcrumbValue | BreadcrumbFunction | Observable<BreadcrumbValue>; @Injectable({ providedIn: 'root', }) export class BreadcrumbService implements OnDestroy { breadcrumbs$: Observable<Array<{ link: string | any[]; label: string }>>; private destroy$ = new Subject<void>(); constructor(private router: Router, private route: ActivatedRoute, private dataService: DataService) { this.breadcrumbs$ = this.router.events.pipe( filter(event => event instanceof NavigationEnd), takeUntil(this.destroy$), startWith(true), switchMap(() => this.generateBreadcrumbs(this.route.root)), shareReplay(1), ); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } private generateBreadcrumbs( rootRoute: ActivatedRoute, ): Observable<Array<{ link: Array<string | any>; label: string }>> { const breadcrumbParts = this.assembleBreadcrumbParts(rootRoute); const breadcrumbObservables$ = breadcrumbParts.map( ({ value$, path }) => value$.pipe( map(value => { if (isBreadcrumbLabelLinkPair(value)) { return { label: value.label, link: this.normalizeRelativeLinks(value.link, path), }; } else if (isBreadcrumbPairArray(value)) { return value.map(val => ({ label: val.label, link: this.normalizeRelativeLinks(val.link, path), })); } else { return { label: value, link: '/' + path.join('/'), }; } }), ) as Observable<BreadcrumbLabelLinkPair | BreadcrumbLabelLinkPair[]>, ); return observableCombineLatest(breadcrumbObservables$).pipe(map(links => flatten(links))); } /** * Walks the route definition tree to assemble an array from which the breadcrumbs can be derived. */ private assembleBreadcrumbParts( rootRoute: ActivatedRoute, ): Array<{ value$: Observable<BreadcrumbValue>; path: string[] }> { const breadcrumbParts: Array<{ value$: Observable<BreadcrumbValue>; path: string[] }> = []; const segmentPaths: string[] = []; let currentRoute: ActivatedRoute | null = rootRoute; do { const childRoutes = currentRoute.children; currentRoute = null; childRoutes.forEach((route: ActivatedRoute) => { if (route.outlet === PRIMARY_OUTLET) { const routeSnapshot = route.snapshot; let breadcrumbDef: BreadcrumbDefinition | undefined = route.routeConfig && route.routeConfig.data && route.routeConfig.data['breadcrumb']; segmentPaths.push(routeSnapshot.url.map(segment => segment.path).join('/')); if (breadcrumbDef) { if (isBreadcrumbFunction(breadcrumbDef)) { breadcrumbDef = breadcrumbDef( routeSnapshot.data, routeSnapshot.params, this.dataService, ); } const observableValue = isObservable(breadcrumbDef) ? breadcrumbDef : observableOf(breadcrumbDef); breadcrumbParts.push({ value$: observableValue, path: segmentPaths.slice() }); } currentRoute = route; } }); } while (currentRoute); return breadcrumbParts; } /** * Accounts for relative routes in the link array, i.e. arrays whose first element is either: * * `./` - this appends the rest of the link segments to the current active route * * `../` - this removes the last segment of the current active route, and appends the link segments * to the parent route. */ private normalizeRelativeLinks(link: any[], segmentPaths: string[]): any[] { const clone = link.slice(); if (clone[0] === './') { clone[0] = segmentPaths.join('/'); } if (clone[0] === '../') { clone[0] = segmentPaths.slice(0, -1).join('/'); } return clone.filter(segment => segment !== ''); } } function isBreadcrumbFunction(value: BreadcrumbDefinition): value is BreadcrumbFunction { return typeof value === 'function'; } function isBreadcrumbLabelLinkPair(value: BreadcrumbValue): value is BreadcrumbLabelLinkPair { return value.hasOwnProperty('label') && value.hasOwnProperty('link'); } function isBreadcrumbPairArray(value: BreadcrumbValue): value is BreadcrumbLabelLinkPair[] { return Array.isArray(value) && isBreadcrumbLabelLinkPair(value[0]); }
import { Injectable } from '@angular/core'; import { BulkAction, BulkActionLocationId } from './bulk-action-types'; @Injectable({ providedIn: 'root', }) export class BulkActionRegistryService { private locationBulActionMap = new Map<BulkActionLocationId, Set<BulkAction>>(); registerBulkAction(bulkAction: BulkAction) { if (!this.locationBulActionMap.has(bulkAction.location)) { this.locationBulActionMap.set(bulkAction.location, new Set([bulkAction])); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.locationBulActionMap.get(bulkAction.location)!.add(bulkAction); } } getBulkActionsForLocation(id: BulkActionLocationId): BulkAction[] { return [...(this.locationBulActionMap.get(id)?.values() ?? [])]; } }
import { Injector } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; /** * @description * A valid location of a list view that supports the bulk actions API. * * @since 1.8.0 * @docsCategory bulk-actions * @docsPage BulkAction */ export type BulkActionLocationId = | 'product-list' | 'facet-list' | 'collection-list' | 'customer-list' | 'customer-group-list' | 'customer-group-members-list' | 'customer-group-members-picker-list' | 'promotion-list' | 'seller-list' | 'channel-list' | 'administrator-list' | 'role-list' | 'shipping-method-list' | 'stock-location-list' | 'payment-method-list' | 'tax-category-list' | 'tax-rate-list' | 'zone-list' | 'zone-members-list' | string; /** * @description * This is the argument which gets passed to the `getTranslationVars` and `isVisible` functions * of the BulkAction definition. * * @since 1.8.0 * @docsCategory bulk-actions * @docsPage BulkAction */ export interface BulkActionFunctionContext<ItemType, ComponentType> { /** * @description * An array of the selected items from the list. */ selection: ItemType[]; /** * @description * The component instance that is hosting the list view. For instance, * `ProductListComponent`. This can be used to call methods on the instance, * e.g. calling `hostComponent.refresh()` to force a list refresh after * deleting the selected items. */ hostComponent: ComponentType; /** * @description * The Angular [Injector](https://angular.io/api/core/Injector) which can be used * to get service instances which might be needed in the click handler. */ injector: Injector; route: ActivatedRoute; } /** * @description * This is the argument which gets passed to the `onClick` function of a BulkAction. * * @since 1.8.0 * @docsCategory bulk-actions * @docsPage BulkAction */ export interface BulkActionClickContext<ItemType, ComponentType> extends BulkActionFunctionContext<ItemType, ComponentType> { /** * @description * Clears the selection in the active list view. */ clearSelection: () => void; /** * @description * The click event itself. */ event: MouseEvent; } /** * @description * Configures a bulk action which can be performed on all selected items in a list view. * * For a full example, see the {@link registerBulkAction} docs. * * @since 1.8.0 * @docsCategory bulk-actions * @docsPage BulkAction * @docsWeight 0 */ export interface BulkAction<ItemType = any, ComponentType = any> { location: BulkActionLocationId; label: string; /** * @description * An optional function that should resolve to a map of translation variables which can be * used when translating the `label` string. */ getTranslationVars?: ( context: BulkActionFunctionContext<ItemType, ComponentType>, ) => Record<string, string | number> | Promise<Record<string, string | number>>; /** * @description * A valid [Clarity Icons](https://core.clarity.design/foundation/icons/shapes/) icon shape, e.g. * "cog", "user", "info-standard". */ icon?: string; /** * @description * A class to be added to the icon element. Examples: * * - is-success * - is-danger * - is-warning * - is-info * - is-highlight */ iconClass?: string; /** * @description * Defines the logic that executes when the bulk action button is clicked. */ onClick: (context: BulkActionClickContext<ItemType, ComponentType>) => void; /** * @description * A function that determines whether this bulk action item should be displayed in the menu. * If not defined, the item will always be displayed. * * This function will be invoked each time the selection is changed, so try to avoid expensive code * running here. * * @example * ```ts * import { registerBulkAction, DataService } from '\@vendure/admin-ui/core'; * * registerBulkAction({ * location: 'product-list', * label: 'Assign to channel', * // Only display this action if there are multiple channels * isVisible: ({ injector }) => injector.get(DataService).client * .userStatus() * .mapSingle(({ userStatus }) => 1 < userStatus.channels.length) * .toPromise(), * // ... * }); * ``` */ isVisible?: (context: BulkActionFunctionContext<ItemType, ComponentType>) => boolean | Promise<boolean>; /** * @description * Control the display of this item based on the user permissions. * * @example * ```ts * registerBulkAction({ * // Can be specified as a simple string * requiresPermission: Permission.UpdateProduct, * * // Or as a function that returns a boolean if permissions are satisfied * requiresPermission: userPermissions => * userPermissions.includes(Permission.UpdateCatalog) || * userPermissions.includes(Permission.UpdateProduct), * // ... * }) * ``` */ requiresPermission?: string | ((userPermissions: string[]) => boolean); }
import { Injectable } from '@angular/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { Observable } from 'rxjs'; import { map, shareReplay, tap } from 'rxjs/operators'; import { UserStatusFragment } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; import { LocalStorageService } from '../local-storage/local-storage.service'; import { PermissionsService } from '../permissions/permissions.service'; @Injectable({ providedIn: 'root', }) export class ChannelService { defaultChannelIsActive$: Observable<boolean>; constructor( private dataService: DataService, private localStorageService: LocalStorageService, private permissionsService: PermissionsService, ) { this.defaultChannelIsActive$ = this.dataService.client .userStatus() .mapStream(({ userStatus }) => { const activeChannel = userStatus.channels.find(c => c.id === userStatus.activeChannelId); return activeChannel ? activeChannel.code === DEFAULT_CHANNEL_CODE : false; }) .pipe(shareReplay(1)); } setActiveChannel(channelId: string): Observable<UserStatusFragment> { return this.dataService.client.setActiveChannel(channelId).pipe( map(({ setActiveChannel }) => setActiveChannel), tap(userStatus => { const activeChannel = userStatus.channels.find(c => c.id === channelId); if (activeChannel) { this.localStorageService.set('activeChannelToken', activeChannel.token); this.permissionsService.setCurrentUserPermissions(activeChannel.permissions); } }), ); } }
import { TestBed } from '@angular/core/testing'; import { ComponentRegistryService } from './component-registry.service'; describe('ComponentRegistryService', () => { let service: ComponentRegistryService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(ComponentRegistryService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
import { Injectable, Provider, Type } from '@angular/core'; import { FormInputComponent } from '../../common/component-registry-types'; @Injectable({ providedIn: 'root', }) export class ComponentRegistryService { private inputComponentMap = new Map< string, { type: Type<FormInputComponent<any>>; providers: Provider[] } >(); registerInputComponent(id: string, component: Type<FormInputComponent<any>>, providers?: Provider[]) { if (this.inputComponentMap.has(id)) { throw new Error( `Cannot register an InputComponent with the id "${id}", as one with that id already exists`, ); } this.inputComponentMap.set(id, { type: component, providers: providers || [] }); } getInputComponent( id: string, ): { type: Type<FormInputComponent<any>>; providers: Provider[] } | undefined { return this.inputComponentMap.get(id); } }
import { Injectable } from '@angular/core'; import { ServerConfigService } from '../../data/server-config'; @Injectable({ providedIn: 'root', }) export class CurrencyService { readonly precision: number; readonly precisionFactor: number; constructor(serverConfigService: ServerConfigService) { this.precision = serverConfigService.serverConfig.moneyStrategyPrecision; this.precisionFactor = Math.pow(10, this.precision); } toMajorUnits(value: number): number { return value / this.precisionFactor; } }
import { Provider, Type } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { Observable } from 'rxjs'; import { CustomDetailComponentLocationId } from '../../common/component-registry-types'; /** * @description * CustomDetailComponents allow any arbitrary Angular components to be embedded in entity detail * pages of the Admin UI. * * @docsCategory custom-detail-components */ export interface CustomDetailComponent { entity$: Observable<any>; detailForm: UntypedFormGroup; } /** * @description * Configures a {@link CustomDetailComponent} to be placed in the given location. * * @docsCategory custom-detail-components */ export interface CustomDetailComponentConfig { locationId: CustomDetailComponentLocationId; component: Type<CustomDetailComponent>; providers?: Provider[]; }
import { Injectable } from '@angular/core'; import { CustomDetailComponentConfig } from './custom-detail-component-types'; @Injectable({ providedIn: 'root', }) export class CustomDetailComponentService { private customDetailComponents = new Map<string, CustomDetailComponentConfig[]>(); registerCustomDetailComponent(config: CustomDetailComponentConfig) { if (this.customDetailComponents.has(config.locationId)) { this.customDetailComponents.get(config.locationId)?.push(config); } else { this.customDetailComponents.set(config.locationId, [config]); } } getCustomDetailComponentsFor(locationId: string): CustomDetailComponentConfig[] { return this.customDetailComponents.get(locationId) ?? []; } }
import { Injectable } from '@angular/core'; import { FormInputComponent } from '../../common/component-registry-types'; import { CustomFields, CustomFieldsFragment } from '../../common/generated-types'; import { ComponentRegistryService } from '../component-registry/component-registry.service'; export type CustomFieldConfigType = CustomFieldsFragment; export interface CustomFieldControl extends FormInputComponent<CustomFieldConfigType> {} export type CustomFieldEntityName = Exclude<keyof CustomFields, '__typename'>; /** * This service allows the registration of custom controls for customFields. * * @deprecated The ComponentRegistryService now handles custom field components directly. */ @Injectable({ providedIn: 'root', }) export class CustomFieldComponentService { constructor(private componentRegistryService: ComponentRegistryService) {} /** * Checks whether a custom component is registered for the given entity custom field, * and if so returns the ID of that component. */ customFieldComponentExists(entity: CustomFieldEntityName, fieldName: string): string | undefined { const id = this.generateId(entity, fieldName, true); return this.componentRegistryService.getInputComponent(id) ? id : undefined; } private generateId(entity: CustomFieldEntityName, fieldName: string, isCustomField: boolean) { let id = entity; if (isCustomField) { id += '-customFields'; } id += '-' + fieldName; return id; } }
import { Type } from '@angular/core'; import { CustomerFragment, GetOrderHistoryQuery, OrderDetailFragment } from '../../common/generated-types'; import { TimelineDisplayType } from '../../shared/components/timeline-entry/timeline-entry.component'; export type TimelineHistoryEntry = NonNullable<GetOrderHistoryQuery['order']>['history']['items'][number]; /** * @description * This interface should be implemented by components intended to display a history entry in the * Order or Customer history timeline. If the component needs access to the Order or Customer object itself, * you should implement {@link OrderHistoryEntryComponent} or {@link CustomerHistoryEntryComponent} respectively. * * @since 1.9.0 * @docsCategory custom-history-entry-components */ export interface HistoryEntryComponent { /** * @description * The HistoryEntry data. */ entry: TimelineHistoryEntry; /** * @description * Defines whether this entry is highlighted with a "success", "error" etc. color. */ getDisplayType: (entry: TimelineHistoryEntry) => TimelineDisplayType; /** * @description * Featured entries are always expanded. Non-featured entries start of collapsed and can be clicked * to expand. */ isFeatured: (entry: TimelineHistoryEntry) => boolean; /** * @description * Returns the name of the person who did this action. For example, it could be the Customer's name * or "Administrator". */ getName?: (entry: TimelineHistoryEntry) => string | undefined; /** * @description * Optional Clarity icon shape to display with the entry. Examples: `'note'`, `['success-standard', 'is-solid']` */ getIconShape?: (entry: TimelineHistoryEntry) => string | string[] | undefined; } /** * @description * Used to implement a {@link HistoryEntryComponent} which requires access to the Order object. * * @since 1.9.0 * @docsCategory custom-history-entry-components */ export interface OrderHistoryEntryComponent extends HistoryEntryComponent { order: OrderDetailFragment; } /** * @description * Used to implement a {@link HistoryEntryComponent} which requires access to the Customer object. * * @since 1.9.0 * @docsCategory custom-history-entry-components */ export interface CustomerHistoryEntryComponent extends HistoryEntryComponent { customer: CustomerFragment; } /** * @description * Configuration for registering a custom {@link HistoryEntryComponent}. * * @since 1.9.0 * @docsCategory custom-history-entry-components */ export interface HistoryEntryConfig { /** * @description * The type should correspond to the custom HistoryEntryType string. */ type: string; /** * @description * The component to be rendered for this history entry type. */ component: Type<HistoryEntryComponent>; }
import { Injectable, Type } from '@angular/core'; import { HistoryEntryComponent, HistoryEntryConfig } from './history-entry-component-types'; @Injectable({ providedIn: 'root', }) export class HistoryEntryComponentService { private customEntryComponents = new Map<string, HistoryEntryConfig>(); registerComponent(config: HistoryEntryConfig) { this.customEntryComponents.set(config.type, config); } getComponent(type: string): Type<HistoryEntryComponent> | undefined { return this.customEntryComponents.get(type)?.component; } }
import { Type } from '@angular/core'; export type DashboardWidgetWidth = 3 | 4 | 6 | 8 | 12; /** * @description * A configuration object for a dashboard widget. * * @docsCategory dashboard-widgets */ export interface DashboardWidgetConfig { /** * @description * Used to specify the widget component. Supports both eager- and lazy-loading. * @example * ```ts * // eager-loading * loadComponent: () => MyWidgetComponent, * * // lazy-loading * loadComponent: () => import('./path-to/widget.component').then(m => m.MyWidgetComponent), * ``` */ loadComponent: () => Promise<Type<any>> | Type<any>; /** * @description * The title of the widget. Can be a translation token as it will get passed * through the `translate` pipe. */ title?: string; /** * @description * The supported widths of the widget, in terms of a Bootstrap-style 12-column grid. * If omitted, then it is assumed the widget supports all widths. */ supportedWidths?: DashboardWidgetWidth[]; /** * @description * If set, the widget will only be displayed if the current user has all the * specified permissions. */ requiresPermissions?: string[]; } /** * @description * A configuration object for the default dashboard widget layout. * * @docsCategory dashboard-widgets */ export type WidgetLayoutDefinition = Array<{ id: string; width: DashboardWidgetWidth }>; export type WidgetLayout = Array< Array<{ id: string; config: DashboardWidgetConfig; width: DashboardWidgetWidth }> >;
import { Injectable } from '@angular/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { Permission } from '../../common/generated-types'; import { DashboardWidgetConfig, DashboardWidgetWidth, WidgetLayout, WidgetLayoutDefinition, } from './dashboard-widget-types'; /** * Responsible for registering dashboard widget components and querying for layouts. */ @Injectable({ providedIn: 'root', }) export class DashboardWidgetService { private registry = new Map<string, DashboardWidgetConfig>(); private layoutDef: WidgetLayoutDefinition = []; registerWidget(id: string, config: DashboardWidgetConfig) { if (this.registry.has(id)) { throw new Error(`A dashboard widget with the id "${id}" already exists`); } this.registry.set(id, config); } getAvailableWidgets( currentUserPermissions: Permission[], ): Array<{ id: string; config: DashboardWidgetConfig }> { const hasAllPermissions = (requiredPerms: string[], userPerms: string[]): boolean => requiredPerms.every(p => userPerms.includes(p)); return [...this.registry.entries()] .filter( ([id, config]) => !config.requiresPermissions || hasAllPermissions(config.requiresPermissions, currentUserPermissions), ) .map(([id, config]) => ({ id, config })); } getWidgetById(id: string) { return this.registry.get(id); } setDefaultLayout(layout: WidgetLayoutDefinition) { this.layoutDef = layout; } getDefaultLayout(): WidgetLayoutDefinition { return this.layoutDef; } getWidgetLayout(layoutDef?: WidgetLayoutDefinition): WidgetLayout { const intermediateLayout = (layoutDef || this.layoutDef) .map(({ id, width }) => { const config = this.registry.get(id); if (!config) { return this.idNotFound(id); } return { id, config, width: this.getValidWidth(id, config, width) }; }) .filter(notNullOrUndefined); return this.buildLayout(intermediateLayout); } private idNotFound(id: string): undefined { // eslint-disable-next-line no-console console.error( `No dashboard widget was found with the id "${id}"\nAvailable ids: ${[...this.registry.keys()] .map(_id => `"${_id}"`) .join(', ')}`, ); return; } private getValidWidth( id: string, config: DashboardWidgetConfig, targetWidth: DashboardWidgetWidth, ): DashboardWidgetWidth { let adjustedWidth = targetWidth; const supportedWidths = config.supportedWidths?.length ? config.supportedWidths : ([3, 4, 6, 8, 12] as DashboardWidgetWidth[]); if (!supportedWidths.includes(targetWidth)) { // Fall back to the largest supported width const sortedWidths = supportedWidths.sort((a, b) => a - b); const fallbackWidth = supportedWidths[sortedWidths.length - 1]; // eslint-disable-next-line no-console console.error( `The "${id}" widget does not support the specified width (${targetWidth}).\nSupported widths are: [${sortedWidths.join( ', ', )}].\nUsing (${fallbackWidth}) instead.`, ); adjustedWidth = fallbackWidth; } return adjustedWidth; } private buildLayout(intermediateLayout: WidgetLayout[number]): WidgetLayout { const layout: WidgetLayout = []; let row: WidgetLayout[number] = []; for (const { id, config, width } of intermediateLayout) { const rowSize = row.reduce((size, c) => size + c.width, 0); if (12 < rowSize + width) { layout.push(row); row = []; } row.push({ id, config, width }); } layout.push(row); return layout; } }
import { ActivatedRoute, Router } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CustomFieldType } from '@vendure/common/lib/shared-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import extend from 'just-extend'; import { Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, startWith, takeUntil } from 'rxjs/operators'; import { CustomFieldConfig, DateOperators, IdOperators, NumberOperators, StringOperators, } from '../../common/generated-types'; import { DataTableFilter, DataTableFilterBooleanType, DataTableFilterCustomType, DataTableFilterDateRangeType, DataTableFilterIDType, DataTableFilterNumberType, DataTableFilterOptions, DataTableFilterSelectType, DataTableFilterTextType, DataTableFilterType, DataTableFilterValue, } from './data-table-filter'; export class FilterWithValue<Type extends DataTableFilterType = DataTableFilterType> { private onUpdateFns = new Set<(value: DataTableFilterValue<Type>) => void>(); constructor( public readonly filter: DataTableFilter<any, Type>, public value: DataTableFilterValue<Type>, onUpdate?: (value: DataTableFilterValue<Type>) => void, ) { if (onUpdate) { this.onUpdateFns.add(onUpdate); } } onUpdate(fn: (value: DataTableFilterValue<Type>) => void) { this.onUpdateFns.add(fn); } updateValue(value: DataTableFilterValue<Type>) { this.value = value; for (const fn of this.onUpdateFns) { fn(value); } } isId(): this is FilterWithValue<DataTableFilterIDType> { return this.filter.type.kind === 'id'; } isText(): this is FilterWithValue<DataTableFilterTextType> { return this.filter.type.kind === 'text'; } isNumber(): this is FilterWithValue<DataTableFilterNumberType> { return this.filter.type.kind === 'number'; } isBoolean(): this is FilterWithValue<DataTableFilterBooleanType> { return this.filter.type.kind === 'boolean'; } isSelect(): this is FilterWithValue<DataTableFilterSelectType> { return this.filter.type.kind === 'select'; } isDateRange(): this is FilterWithValue<DataTableFilterDateRangeType> { return this.filter.type.kind === 'dateRange'; } isCustom(): this is FilterWithValue<DataTableFilterCustomType> { return this.filter.type.kind === 'custom'; } } export class DataTableFilterCollection<FilterInput extends Record<string, any> = Record<string, any>> { readonly #filters: Array<DataTableFilter<FilterInput, any>> = []; #activeFilters: FilterWithValue[] = []; #valueChanges$ = new Subject<FilterWithValue[]>(); #connectedToRouter = false; valueChanges = this.#valueChanges$.asObservable().pipe(debounceTime(10)); readonly #filtersQueryParamName = 'filters'; private readonly destroy$ = new Subject<void>(); constructor(private router: Router) {} get length(): number { return this.#filters.length; } get activeFilters(): FilterWithValue[] { return this.#activeFilters; } destroy() { this.destroy$.next(); this.destroy$.complete(); } addFilter<FilterType extends DataTableFilterType>( config: DataTableFilterOptions<FilterInput, FilterType>, ): DataTableFilterCollection<FilterInput> { if (this.#connectedToRouter) { throw new Error( 'Cannot add filter after connecting to router. Make sure to call addFilter() before connectToRoute()', ); } this.#filters.push( new DataTableFilter(config, (filter, value) => this.onActivateFilter(filter, value)), ); return this; } addFilters<FilterType extends DataTableFilterType>( configs: Array<DataTableFilterOptions<FilterInput, FilterType>>, ): DataTableFilterCollection<FilterInput> { for (const config of configs) { this.addFilter(config); } return this; } addIdFilter(): FilterInput extends { id?: IdOperators | null; } ? DataTableFilterCollection<FilterInput> : never { this.addFilter({ name: 'id', type: { kind: 'id' }, label: _('common.id'), filterField: 'id', }); return this as any; } addDateFilters(): FilterInput extends { createdAt?: DateOperators | null; updatedAt?: DateOperators | null; } ? DataTableFilterCollection<FilterInput> : never { this.addFilter({ name: 'createdAt', type: { kind: 'dateRange' }, label: _('common.created-at'), filterField: 'createdAt', }); this.addFilter({ name: 'updatedAt', type: { kind: 'dateRange' }, label: _('common.updated-at'), filterField: 'updatedAt', }); return this as any; } addCustomFieldFilters(customFields: CustomFieldConfig[]) { for (const config of customFields) { const type = config.type as CustomFieldType; if (config.list) { continue; } let filterType: DataTableFilterType | undefined; switch (type) { case 'boolean': filterType = { kind: 'boolean' }; break; case 'int': case 'float': filterType = { kind: 'number' }; break; case 'datetime': filterType = { kind: 'dateRange' }; break; case 'string': case 'localeString': case 'localeText': case 'text': filterType = { kind: 'text' }; break; case 'relation': // Cannot sort relations break; default: assertNever(type); } if (filterType) { this.addFilter({ name: config.name, type: filterType, label: config.label ?? config.name, filterField: config.name, }); } } return this; } getFilter(name: string): DataTableFilter<FilterInput> | undefined { return this.#filters.find(f => f.name === name); } getFilters(): Array<DataTableFilter<FilterInput>> { return this.#filters; } removeActiveFilterAtIndex(index: number) { this.#activeFilters.splice(index, 1); this.#valueChanges$.next(this.#activeFilters); } createFilterInput(): FilterInput { return this.#activeFilters.reduce((acc, { filter, value }) => { const newValue = value != null ? filter.toFilterInput(value) : {}; const result = extend(true, acc, newValue); return result as FilterInput; }, {} as FilterInput); } connectToRoute(route: ActivatedRoute) { this.valueChanges.pipe(takeUntil(this.destroy$)).subscribe(val => { const currentFilters = route.snapshot.queryParamMap.get(this.#filtersQueryParamName); if (val.length === 0 && !currentFilters) { return; } this.router.navigate(['./'], { queryParams: { [this.#filtersQueryParamName]: this.serialize(), page: 1 }, relativeTo: route, queryParamsHandling: 'merge', }); }); route.queryParamMap .pipe( map(params => params.get(this.#filtersQueryParamName)), distinctUntilChanged(), startWith(route.snapshot.queryParamMap.get(this.#filtersQueryParamName) ?? ''), takeUntil(this.destroy$), ) .subscribe(value => { this.#activeFilters = []; if (value === '' || value === null) { this.#valueChanges$.next(this.#activeFilters); return; } const filterQueryParams = (value ?? '') .split(';') .map(value => value.split(':')) .map(([name, value]) => ({ name, value })); for (const { name, value } of filterQueryParams) { const filter = this.getFilter(name); if (filter) { const val = this.deserializeValue(filter, value); filter.activate(val); } } }); this.#connectedToRouter = true; return this; } serialize(): string { return this.#activeFilters .map( (filterWithValue, i) => `${filterWithValue.filter.name}:${this.serializeValue(filterWithValue)}`, ) .join(';'); } private serializeValue<Type extends DataTableFilterType>( filterWithValue: FilterWithValue<Type>, ): string | undefined { if (filterWithValue.isId()) { const val = filterWithValue.value; return `${val?.operator},${val?.term}`; } if (filterWithValue.isText()) { const val = filterWithValue.value; return `${val?.operator},${val?.term}`; } else if (filterWithValue.isNumber()) { const val = filterWithValue.value; return `${val.operator},${val.amount}`; } else if (filterWithValue.isSelect()) { const val = filterWithValue.value; return val.join(','); } else if (filterWithValue.isBoolean()) { const val = filterWithValue.value; return val ? '1' : '0'; } else if (filterWithValue.isDateRange()) { const val = filterWithValue.value; if (val.mode === 'relative') { return `${val.mode},${val.relativeValue},${val.relativeUnit}`; } else { const start = val.start ? new Date(val.start).getTime() : ''; const end = val.end ? new Date(val.end).getTime() : ''; return `${start},${end}`; } } else if (filterWithValue.isCustom()) { return filterWithValue.filter.type.serializeValue(filterWithValue.value); } } private deserializeValue( filter: DataTableFilter, value: string, ): DataTableFilterValue<DataTableFilterType> { switch (filter.type.kind) { case 'id': { const [operator, term] = value.split(',') as [keyof StringOperators, string]; return { operator, term }; } case 'text': { const [operator, term] = value.split(',') as [keyof StringOperators, string]; return { operator, term }; } case 'number': { const [operator, amount] = value.split(',') as [keyof NumberOperators, string]; return { operator, amount: +amount }; } case 'select': return value.split(','); case 'boolean': return value === '1'; case 'dateRange': let mode = 'relative'; let relativeValue: number | undefined; let relativeUnit: 'day' | 'month' | 'year' | undefined; let start: string | undefined; let end: string | undefined; if (value.startsWith('relative')) { mode = 'relative'; const [_, relativeValueStr, relativeUnitStr] = value.split(','); relativeValue = Number(relativeValueStr); relativeUnit = relativeUnitStr as 'day' | 'month' | 'year'; } else { mode = 'range'; const [startTimestamp, endTimestamp] = value.split(','); start = startTimestamp ? new Date(Number(startTimestamp)).toISOString() : ''; end = endTimestamp ? new Date(Number(endTimestamp)).toISOString() : ''; } return { mode, relativeValue, relativeUnit, start, end }; case 'custom': return filter.type.deserializeValue(value); default: assertNever(filter.type); } } private onActivateFilter(filter: DataTableFilter<any, any>, value: DataTableFilterValue<any>) { this.#activeFilters.push(this.createFilterWithValue(filter, value)); this.#valueChanges$.next(this.#activeFilters); } private createFilterWithValue( filter: DataTableFilter<any, any>, value: DataTableFilterValue<DataTableFilterType>, ) { return new FilterWithValue(filter, value, v => this.#valueChanges$.next(v)); } }
import { Type as ComponentType } from '@angular/core'; import { LocalizedString } from '@vendure/common/lib/generated-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import dayjs from 'dayjs'; import { FormInputComponent } from '../../common/component-registry-types'; import { BooleanOperators, DateOperators, IdOperators, NumberOperators, StringOperators, } from '../../common/generated-types'; export interface DataTableFilterIDType { kind: 'id'; } export interface DataTableFilterTextType { kind: 'text'; placeholder?: string; } export interface DataTableFilterSelectType { kind: 'select'; options: Array<{ value: any; label: string }>; } export interface DataTableFilterBooleanType { kind: 'boolean'; } export interface DataTableFilterNumberType { kind: 'number'; inputType?: 'number' | 'currency'; } export interface DataTableFilterDateRangeType { kind: 'dateRange'; } export interface DataTableFilterCustomType { kind: 'custom'; component: ComponentType<FormInputComponent>; serializeValue: (value: any) => string; deserializeValue: (serialized: string) => any; getLabel(value: any): string | Promise<string>; } export type KindValueMap = { id: { raw: { operator: keyof IdOperators; term: string; }; input: IdOperators; }; text: { raw: { operator: keyof StringOperators; term: string; }; input: StringOperators; }; select: { raw: string[]; input: StringOperators }; boolean: { raw: boolean; input: BooleanOperators }; dateRange: { raw: { mode: 'relative' | 'range'; relativeValue: number; relativeUnit: 'day' | 'month' | 'year'; start?: string; end?: string; }; input: DateOperators; }; number: { raw: { operator: keyof NumberOperators; amount: number }; input: NumberOperators }; custom: { raw: any; input: any }; }; export type DataTableFilterType = | DataTableFilterIDType | DataTableFilterTextType | DataTableFilterSelectType | DataTableFilterBooleanType | DataTableFilterDateRangeType | DataTableFilterNumberType | DataTableFilterCustomType; export interface DataTableFilterOptions< FilterInput extends Record<string, any> = any, Type extends DataTableFilterType = DataTableFilterType, > { readonly name: string; readonly type: Type; readonly label: string | LocalizedString[]; readonly filterField?: keyof FilterInput; readonly toFilterInput?: (value: DataTableFilterValue<Type>) => Partial<FilterInput>; } export type DataTableFilterValue<Type extends DataTableFilterType> = KindValueMap[Type['kind']]['raw']; export type DataTableFilterOperator<Type extends DataTableFilterType> = KindValueMap[Type['kind']]['input']; export class DataTableFilter< FilterInput extends Record<string, any> = any, Type extends DataTableFilterType = DataTableFilterType, > { constructor( private readonly options: DataTableFilterOptions<FilterInput, Type>, private onActivate?: ( filter: DataTableFilter<FilterInput, Type>, value: DataTableFilterValue<Type> | undefined, ) => void, ) {} get name(): string { return this.options.name; } get type(): Type { return this.options.type; } get label(): string | LocalizedString[] { return this.options.label; } getFilterOperator(value: any): DataTableFilterOperator<Type> { const type = this.options.type; switch (type.kind) { case 'boolean': return { eq: !!value, }; case 'dateRange': { let dateOperators: DateOperators; const mode = value.mode ?? 'relative'; if (mode === 'relative') { const relativeValue = value.relativeValue ?? 30; const relativeUnit = value.relativeUnit ?? 'day'; dateOperators = { after: dayjs().subtract(relativeValue, relativeUnit).startOf('day').toISOString(), }; } else { const start = value.start ?? undefined; const end = value.end ?? undefined; if (start && end) { dateOperators = { between: { start, end }, }; } else if (start) { dateOperators = { after: start, }; } else { dateOperators = { before: end, }; } } return dateOperators; } case 'number': return { [value.operator]: Number(value.amount), }; case 'select': return { in: value }; case 'text': return { [value.operator]: value.term, }; case 'id': return { [value.operator]: value.term, }; case 'custom': { return value; } default: assertNever(type); } } toFilterInput(value: DataTableFilterValue<Type>): Partial<FilterInput> { if (this.options.toFilterInput) { return this.options.toFilterInput(value); } if (this.options.filterField) { return { [this.options.filterField]: this.getFilterOperator(value) } as Partial<FilterInput>; } else { throw new Error( `Either "filterField" or "toFilterInput" must be provided (for filter "${this.name}"))`, ); } } activate(value: DataTableFilterValue<Type>) { if (this.onActivate) { this.onActivate(this, value); } } isId(): this is DataTableFilter<FilterInput, DataTableFilterIDType> { return this.type.kind === 'id'; } isText(): this is DataTableFilter<FilterInput, DataTableFilterTextType> { return this.type.kind === 'text'; } isNumber(): this is DataTableFilter<FilterInput, DataTableFilterNumberType> { return this.type.kind === 'number'; } isBoolean(): this is DataTableFilter<FilterInput, DataTableFilterBooleanType> { return this.type.kind === 'boolean'; } isSelect(): this is DataTableFilter<FilterInput, DataTableFilterSelectType> { return this.type.kind === 'select'; } isDateRange(): this is DataTableFilter<FilterInput, DataTableFilterDateRangeType> { return this.type.kind === 'dateRange'; } isCustom(): this is DataTableFilter<FilterInput, DataTableFilterCustomType> { return this.type.kind === 'custom'; } }
import { ActivatedRoute, Router } from '@angular/router'; import { CustomFieldType } from '@vendure/common/lib/shared-types'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { CustomFieldConfig } from '../../common/generated-types'; import { DataTableSort, DataTableSortOptions, DataTableSortOrder } from './data-table-sort'; export class DataTableSortCollection< SortInput extends Record<string, 'ASC' | 'DESC'>, Names extends [...Array<keyof SortInput>] = [], > { readonly #sorts: Array<DataTableSort<SortInput>> = []; #valueChanges$ = new Subject<Array<{ name: string; sortOrder: DataTableSortOrder | undefined }>>(); #connectedToRouter = false; valueChanges = this.#valueChanges$.asObservable(); readonly #sortQueryParamName = 'sort'; #defaultSort: { name: keyof SortInput; sortOrder: DataTableSortOrder } | undefined; private readonly destroy$ = new Subject<void>(); constructor(private router: Router) {} get length(): number { return this.#sorts.length; } destroy() { this.destroy$.next(); this.destroy$.complete(); } addSort<Name extends keyof SortInput>( config: DataTableSortOptions<SortInput, Name>, ): DataTableSortCollection<SortInput, [...Names, Name]> { if (this.#connectedToRouter) { throw new Error( 'Cannot add sort after connecting to router. Make sure to call addSort() before connectToRoute()', ); } this.#sorts.push(new DataTableSort<SortInput>(config, () => this.onSetValue())); return this as unknown as DataTableSortCollection<SortInput, [...Names, Name]>; } addSorts<Name extends keyof SortInput>( configs: Array<DataTableSortOptions<SortInput, Name>>, ): DataTableSortCollection<SortInput, [...Names, Name]> { for (const config of configs) { this.addSort(config); } return this as unknown as DataTableSortCollection<SortInput, [...Names, Name]>; } addCustomFieldSorts(customFields: CustomFieldConfig[]) { for (const config of customFields) { const type = config.type as CustomFieldType; if (config.list) { continue; } switch (type) { case 'string': case 'localeString': case 'boolean': case 'int': case 'float': case 'datetime': case 'localeText': case 'text': this.addSort({ name: config.name }); break; case 'relation': // Cannot sort relations break; default: assertNever(type); } } return this; } defaultSort(name: keyof SortInput, sortOrder: DataTableSortOrder) { this.#defaultSort = { name, sortOrder }; return this; } get(name: Names[number]): DataTableSort<SortInput> | undefined { return this.#sorts.find(s => s.name === name); } connectToRoute(route: ActivatedRoute) { this.valueChanges.pipe(takeUntil(this.destroy$)).subscribe(() => { this.router.navigate(['./'], { queryParams: { [this.#sortQueryParamName]: this.serialize() }, relativeTo: route, queryParamsHandling: 'merge', }); }); const filterQueryParams = (route.snapshot.queryParamMap.get(this.#sortQueryParamName) ?? '') .split(';') .map(value => value.split(':')) .map(([name, value]) => ({ name, value })); for (const { name, value } of filterQueryParams) { const sort = this.get(name); if (sort) { sort.setSortOrder(value as any); } } this.#connectedToRouter = true; return this; } createSortInput(): SortInput { const activeSorts = this.#sorts.filter(s => s.sortOrder !== undefined); let sortInput = {} as SortInput; if (activeSorts.length === 0 && this.#defaultSort) { return { [this.#defaultSort.name]: this.#defaultSort.sortOrder } as SortInput; } for (const sort of activeSorts) { sortInput = { ...sortInput, [sort.name]: sort.sortOrder }; } return sortInput; } private serialize(): string { const activeSorts = this.#sorts.filter(s => s.sortOrder !== undefined); return activeSorts.map(s => `${s.name as string}:${s.sortOrder}`).join(';'); } private onSetValue() { this.#valueChanges$.next( this.#sorts .filter(f => f.sortOrder !== undefined) .map(s => ({ name: s.name as any, sortOrder: s.sortOrder })), ); } }
import { DataTableFilterOptions, KindValueMap } from './data-table-filter'; export type DataTableSortOrder = 'ASC' | 'DESC'; export interface DataTableSortOptions< SortInput extends Record<string, DataTableSortOrder>, Name extends keyof SortInput, > { name: Name; } export class DataTableSort<SortInput extends Record<string, DataTableSortOrder>> { constructor( private readonly options: DataTableSortOptions<SortInput, any>, private onSetValue?: (name: keyof SortInput, state: DataTableSortOrder | undefined) => void, ) {} #sortOrder: DataTableSortOrder | undefined; get sortOrder(): DataTableSortOrder | undefined { return this.#sortOrder; } get name(): keyof SortInput { return this.options.name as string; } toggleSortOrder(): void { if (this.#sortOrder === undefined) { this.#sortOrder = 'ASC'; } else if (this.#sortOrder === 'ASC') { this.#sortOrder = 'DESC'; } else { this.#sortOrder = undefined; } if (this.onSetValue) { this.onSetValue(this.name, this.#sortOrder); } } setSortOrder(sortOrder: DataTableSortOrder | undefined): void { this.#sortOrder = sortOrder; if (this.onSetValue) { this.onSetValue(this.name, this.#sortOrder); } } }
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { getAppConfig } from '../../app.config'; import { AuthService } from '../auth/auth.service'; /** * This guard prevents unauthorized users from accessing any routes which require * authorization. */ @Injectable({ providedIn: 'root', }) export class AuthGuard { private readonly externalLoginUrl: string | undefined; constructor(private router: Router, private authService: AuthService) { this.externalLoginUrl = getAppConfig().loginUrl; } canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { return this.authService.checkAuthenticatedStatus().pipe( tap(authenticated => { if (!authenticated) { if (this.externalLoginUrl) { window.location.href = this.externalLoginUrl; } else { this.router.navigate(['/login']); } } }), ); } }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { merge, Observable, of, Subject, timer } from 'rxjs'; import { catchError, map, shareReplay, switchMap, throttleTime } from 'rxjs/operators'; import { getServerLocation } from '../../data/utils/get-server-location'; export type SystemStatus = 'ok' | 'error'; export interface HealthCheckResult { status: SystemStatus; info: { [name: string]: HealthCheckSuccessResult }; details: { [name: string]: HealthCheckSuccessResult | HealthCheckErrorResult }; error: { [name: string]: HealthCheckErrorResult }; } export interface HealthCheckSuccessResult { status: 'up'; } export interface HealthCheckErrorResult { status: 'down'; message: string; } @Injectable({ providedIn: 'root', }) export class HealthCheckService { status$: Observable<SystemStatus>; details$: Observable<Array<{ key: string; result: HealthCheckSuccessResult | HealthCheckErrorResult }>>; lastCheck$: Observable<Date>; private readonly pollingDelayMs = 60 * 1000; private readonly healthCheckEndpoint: string; private readonly _refresh = new Subject<void>(); constructor(private httpClient: HttpClient) { this.healthCheckEndpoint = getServerLocation() + '/health'; const refresh$ = this._refresh.pipe(throttleTime(1000)); const result$ = merge(timer(0, this.pollingDelayMs), refresh$).pipe( switchMap(() => this.checkHealth()), shareReplay(1), ); this.status$ = result$.pipe(map(res => res.status)); this.details$ = result$.pipe( map(res => Object.keys(res.details).map(key => ({ key, result: res.details[key] })), ), ); this.lastCheck$ = result$.pipe(map(res => res.lastChecked)); } refresh() { this._refresh.next(); } private checkHealth() { return this.httpClient.get<HealthCheckResult>(this.healthCheckEndpoint).pipe( catchError(err => of(err.error)), map(res => ({ ...res, lastChecked: new Date() })), ); } }
import { HttpClient } from '@angular/common/http'; import { TranslateLoader } from '@ngx-translate/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export type Dictionary = { [key: string]: string | Dictionary; }; /** * A loader for ngx-translate which extends the HttpLoader functionality by stripping out any * values which are empty strings. This means that during development, translation keys which have * been extracted but not yet defined will fall back to the raw key text rather than displaying nothing. * * Originally from https://github.com/ngx-translate/core/issues/662#issuecomment-377010232 */ export class CustomHttpTranslationLoader implements TranslateLoader { constructor( private http: HttpClient, private prefix: string = '/assets/i18n/', private suffix: string = '.json', ) {} public getTranslation(lang: string): Observable<any> { return this.http .get(`${this.prefix}${lang}${this.suffix}`) .pipe(map((res: any) => this.process(res))); } private process(object: Dictionary): Dictionary { const newObject: Dictionary = {}; for (const key in object) { if (object.hasOwnProperty(key)) { const value = object[key]; if (typeof value !== 'string') { newObject[key] = this.process(value); } else if (typeof value === 'string' && value === '') { // do not copy empty strings } else { newObject[key] = object[key]; } } } return newObject; } }
/* eslint-disable no-console */ import { Injectable } from '@angular/core'; import { TranslateMessageFormatCompiler, TranslateMessageFormatDebugCompiler, } from 'ngx-translate-messageformat-compiler'; /** * Work-around for Angular 9 compat. * See https://github.com/lephyrus/ngx-translate-messageformat-compiler/issues/53#issuecomment-583677994 * * Also logs errors which would otherwise get swallowed by ngx-translate. This is important * because it is quite easy to make errors in messageformat syntax, and without clear * error messages it's very hard to debug. */ @Injectable({ providedIn: 'root' }) export class InjectableTranslateMessageFormatCompiler extends TranslateMessageFormatCompiler { compileTranslations(value: any, lang: string): any { try { return super.compileTranslations(value, lang); } catch (e: any) { console.error(`There was an error with the ${lang} translations:`); console.log(e); console.log( `Check the messageformat docs: https://messageformat.github.io/messageformat/page-guide`, ); } } }
import { TranslateService } from '@ngx-translate/core'; import { MockOf } from '../../../../../testing/testing-types'; import { LanguageCode } from '../../common/generated-types'; import { I18nService } from './i18n.service'; export class MockI18nService implements MockOf<I18nService> { setDefaultLanguage(languageCode: LanguageCode) { // blank } setLanguage(language: LanguageCode) { // blank } translate(key: string | string[], params?: any) { return key as string; } isRTL(): boolean { return false; } availableLanguages: LanguageCode[]; availableLocales: string[] = []; setAvailableLocales: (locales: string[]) => void; setAvailableLanguages: (languages: LanguageCode[]) => void; _availableLanguages: LanguageCode[]; _availableLocales: string[] = []; ngxTranslate: TranslateService; }
import { DOCUMENT } from '@angular/common'; import { Inject, Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { LanguageCode } from '../../common/generated-types'; /** @dynamic */ @Injectable({ providedIn: 'root', }) export class I18nService { _availableLocales: string[] = []; _availableLanguages: LanguageCode[] = []; get availableLanguages(): LanguageCode[] { return [...this._availableLanguages]; } get availableLocales(): string[] { return [...this._availableLocales]; } constructor(private ngxTranslate: TranslateService, @Inject(DOCUMENT) private document: Document) {} /** * Set the default language */ setDefaultLanguage(languageCode: LanguageCode) { this.ngxTranslate.setDefaultLang(languageCode); } /** * Set the UI language */ setLanguage(language: LanguageCode): void { this.ngxTranslate.use(language); if (this.document?.documentElement) { this.document.documentElement.lang = language; } } /** * Set the available UI languages */ setAvailableLanguages(languages: LanguageCode[]) { this._availableLanguages = languages; } /** * Set the available UI locales */ setAvailableLocales(locales: string[]) { this._availableLocales = locales; } /** * Translate the given key. */ translate(key: string | string[], params?: any): string { return this.ngxTranslate.instant(key, params); } /** * Returns true if the given language code is a right-to-left language. */ isRTL(languageCode: LanguageCode): boolean { const rtlLanguageCodes = [ LanguageCode.ar, LanguageCode.he, LanguageCode.fa, LanguageCode.ur, LanguageCode.ps, ]; return rtlLanguageCodes.includes(languageCode); } }
import { Injectable, OnDestroy } from '@angular/core'; import { EMPTY, interval, Observable, of, Subject, Subscription, timer } from 'rxjs'; import { debounceTime, map, mapTo, scan, shareReplay, switchMap } from 'rxjs/operators'; import { JobInfoFragment, JobState, Permission } from '../../common/generated-types'; import { DataService } from '../../data/providers/data.service'; @Injectable({ providedIn: 'root', }) export class JobQueueService implements OnDestroy { activeJobs$: Observable<JobInfoFragment[]>; private updateJob$ = new Subject<JobInfoFragment>(); private onCompleteHandlers = new Map<string, (job: JobInfoFragment) => void>(); private readonly subscription: Subscription; constructor(private dataService: DataService) { this.checkForJobs(); this.activeJobs$ = this.updateJob$.pipe( scan<JobInfoFragment, Map<string, JobInfoFragment>>( (jobMap, job) => this.handleJob(jobMap, job), new Map<string, JobInfoFragment>(), ), map(jobMap => Array.from(jobMap.values())), debounceTime(500), shareReplay(1), ); this.subscription = this.activeJobs$ .pipe( switchMap(jobs => { if (jobs.length) { return interval(2500).pipe(mapTo(jobs)); } else { return of([]); } }), ) .subscribe(jobs => { if (jobs.length) { this.dataService.settings.pollJobs(jobs.map(j => j.id)).single$.subscribe(data => { data.jobsById.forEach(job => { this.updateJob$.next(job); }); }); } }); } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } /** * After a given delay, checks the server for any active jobs. */ checkForJobs(delay = 1000) { timer(delay) .pipe( switchMap(() => this.dataService.client.userStatus().mapSingle(data => data.userStatus)), switchMap(userStatus => { if (userStatus.permissions.includes(Permission.ReadSettings) && userStatus.isLoggedIn) { return this.dataService.settings.getRunningJobs().single$; } else { return EMPTY; } }), ) .subscribe(data => data.jobs.items.forEach(job => this.updateJob$.next(job))); } addJob(jobId: string, onComplete?: (job: JobInfoFragment) => void) { this.dataService.settings.getJob(jobId).single$.subscribe(({ job }) => { if (job) { this.updateJob$.next(job); if (onComplete) { this.onCompleteHandlers.set(jobId, onComplete); } } }); } private handleJob(jobMap: Map<string, JobInfoFragment>, job: JobInfoFragment) { switch (job.state) { case JobState.RUNNING: case JobState.PENDING: jobMap.set(job.id, job); break; case JobState.COMPLETED: case JobState.FAILED: case JobState.CANCELLED: jobMap.delete(job.id); const handler = this.onCompleteHandlers.get(job.id); if (handler) { handler(job); this.onCompleteHandlers.delete(job.id); } break; } return jobMap; } }
import { Location } from '@angular/common'; import { Injectable } from '@angular/core'; import { LanguageCode } from '../../common/generated-types'; import { WidgetLayoutDefinition } from '../dashboard-widget/dashboard-widget-types'; export type DataTableConfig = { [id: string]: { visibility: string[]; order: { [id: string]: number }; showSearchFilterRow: boolean; filterPresets: Array<{ name: string; value: string }>; }; }; export type LocalStorageTypeMap = { activeChannelToken: string; authToken: string; uiLanguageCode: LanguageCode; uiLocale: string | undefined; contentLanguageCode: LanguageCode; dashboardWidgetLayout: WidgetLayoutDefinition; activeTheme: string; livePreviewCollectionContents: boolean; dataTableConfig: DataTableConfig; }; export type LocalStorageLocationBasedTypeMap = { shippingTestOrder: any; shippingTestAddress: any; }; /** * These keys are stored specific to a particular AdminId, so that multiple * admins can use the same browser without interfering with each other's data. */ const ADMIN_SPECIFIC_KEYS: Array<keyof LocalStorageTypeMap> = [ 'activeTheme', 'dashboardWidgetLayout', 'activeTheme', 'livePreviewCollectionContents', 'dataTableConfig', ]; const PREFIX = 'vnd_'; /** * Wrapper around the browser's LocalStorage / SessionStorage object, for persisting data to the browser. */ @Injectable({ providedIn: 'root', }) export class LocalStorageService { private adminId = '__global__'; constructor(private location: Location) {} public setAdminId(adminId?: string | null) { this.adminId = adminId ?? '__global__'; } /** * Set a key-value pair in the browser's LocalStorage */ public set<K extends keyof LocalStorageTypeMap>(key: K, value: LocalStorageTypeMap[K]): void { const keyName = this.keyName(key); localStorage.setItem(keyName, JSON.stringify(value)); } /** * Set a key-value pair specific to the current location (url) */ public setForCurrentLocation<K extends keyof LocalStorageLocationBasedTypeMap>( key: K, value: LocalStorageLocationBasedTypeMap[K], ) { const compositeKey = this.getLocationBasedKey(key); this.set(compositeKey as any, value); } /** * Set a key-value pair in the browser's SessionStorage */ public setForSession<K extends keyof LocalStorageTypeMap>(key: K, value: LocalStorageTypeMap[K]): void { const keyName = this.keyName(key); sessionStorage.setItem(keyName, JSON.stringify(value)); } /** * Get the value of the given key from the SessionStorage or LocalStorage. */ public get<K extends keyof LocalStorageTypeMap>(key: K): LocalStorageTypeMap[K] | null { const keyName = this.keyName(key); const item = sessionStorage.getItem(keyName) || localStorage.getItem(keyName); let result: any; try { result = JSON.parse(item || 'null'); } catch (e: any) { // eslint-disable-next-line no-console console.error(`Could not parse the localStorage value for "${key}" (${item})`); } return result; } /** * Get the value of the given key for the current location (url) */ public getForCurrentLocation<K extends keyof LocalStorageLocationBasedTypeMap>( key: K, ): LocalStorageLocationBasedTypeMap[K] { const compositeKey = this.getLocationBasedKey(key); return this.get(compositeKey as any); } public remove(key: keyof LocalStorageTypeMap): void { const keyName = this.keyName(key); sessionStorage.removeItem(keyName); localStorage.removeItem(keyName); } private getLocationBasedKey(key: string) { const path = this.location.path(); return key + path; } private keyName(key: keyof LocalStorageTypeMap): string { if (ADMIN_SPECIFIC_KEYS.includes(key)) { return `${PREFIX}_${this.adminId}_${key}`; } else { return `${PREFIX}_${key}`; } } }
import { TestBed } from '@angular/core/testing'; import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { TestingCommonModule } from '../../../../../testing/testing-common.module'; import { MockI18nService } from '../i18n/i18n.service.mock'; import { DataService } from '../../data/providers/data.service'; import { I18nService } from '../../providers/i18n/i18n.service'; import { LocalizationService } from './localization.service'; describe('LocalizationService', () => { let service: LocalizationService; beforeEach(() => { TestBed.configureTestingModule({ imports: [TestingCommonModule], providers: [ LocalizationService, { provide: I18nService, useClass: MockI18nService }, { provide: DataService, useClass: class {} }, ], schemas: [CUSTOM_ELEMENTS_SCHEMA], }); service = TestBed.inject(LocalizationService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
import { Injectable } from '@angular/core'; import { Observable, map } from 'rxjs'; import { DataService } from '../../data/providers/data.service'; import { I18nService } from '../../providers/i18n/i18n.service'; import { LanguageCode } from '../../common/generated-types'; export type LocalizationDirectionType = Observable<'ltr' | 'rtl'>; export type LocalizationLanguageCodeType = Observable<[LanguageCode, string | undefined]>; /** * @description * Provides localization helper functionality. * */ @Injectable({ providedIn: 'root', }) export class LocalizationService { uiLanguageAndLocale$: LocalizationLanguageCodeType; direction$: LocalizationDirectionType; constructor(private i18nService: I18nService, private dataService: DataService) { this.uiLanguageAndLocale$ = this.dataService.client?.uiState()?.stream$?.pipe( map(({ uiState }) => { return [uiState.language, uiState.locale ?? undefined]; }), ); this.direction$ = this.uiLanguageAndLocale$?.pipe( map(([languageCode]) => { return this.i18nService.isRTL(languageCode) ? 'rtl' : 'ltr'; }), ); } }