content
stringlengths
28
1.34M
import { SentenceCasePipe } from './sentence-case.pipe'; describe('SentenceCasePipe:', () => { let sentenceCasePipe: SentenceCasePipe; beforeEach(() => (sentenceCasePipe = new SentenceCasePipe())); it('works with multiple words', () => { expect(sentenceCasePipe.transform('foo bar baz')).toBe('Foo bar baz'); expect(sentenceCasePipe.transform('fOo BAR baZ')).toBe('Foo bar baz'); }); it('splits camelCase', () => { expect(sentenceCasePipe.transform('fooBarBaz')).toBe('Foo bar baz'); expect(sentenceCasePipe.transform('FooBarbaz')).toBe('Foo barbaz'); }); it('unexpected input', () => { expect(sentenceCasePipe.transform(null as any)).toBe(null); expect(sentenceCasePipe.transform(undefined as any)).toBe(undefined); expect(sentenceCasePipe.transform([] as any)).toEqual([]); expect(sentenceCasePipe.transform(123 as any)).toEqual(123); }); });
import { Pipe, PipeTransform } from '@angular/core'; /** * Formats a string into sentence case (first letter of first word uppercase). */ @Pipe({ name: 'sentenceCase' }) export class SentenceCasePipe implements PipeTransform { transform(value: any): any { if (typeof value === 'string') { let lower: string; if (isCamelCase(value)) { lower = value.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase(); } else { lower = value.toLowerCase(); } return lower.charAt(0).toUpperCase() + lower.slice(1); } return value; } } function isCamelCase(value: string): boolean { return /^[a-zA-Z]+[A-Z][a-zA-Z]+$/.test(value); }
import { SortPipe } from './sort.pipe'; describe('SortPipe', () => { const sortPipe = new SortPipe(); it('sorts a primitive array', () => { const input = [5, 4, 2, 3, 2, 7, 1]; expect(sortPipe.transform(input)).toEqual([1, 2, 2, 3, 4, 5, 7]); }); it('sorts an array of objects', () => { const input = [{ id: 3 }, { id: 1 }, { id: 9 }, { id: 2 }, { id: 4 }]; expect(sortPipe.transform(input, 'id')).toEqual([ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 9 }, ]); }); it('sorts a frozen array', () => { const input = Object.freeze([5, 4, 2, 3, 2, 7, 1]); expect(sortPipe.transform(input)).toEqual([1, 2, 2, 3, 4, 5, 7]); }); });
import { Pipe, PipeTransform } from '@angular/core'; /** * A pipe for sorting elements of an array. Should be used with caution due to the * potential for perf degredation. Ideally should only be used on small arrays (< 10s of items) * and in components using OnPush change detection. */ @Pipe({ name: 'sort', }) export class SortPipe implements PipeTransform { transform<T>(value: T[] | readonly T[], orderByProp?: keyof T) { return value.slice().sort((a, b) => { const aProp = orderByProp ? a[orderByProp] : a; const bProp = orderByProp ? b[orderByProp] : b; if (aProp === bProp) { return 0; } if (aProp == null) { return 1; } if (bProp == null) { return -1; } return aProp > bProp ? 1 : -1; }); } }
import { StateI18nTokenPipe } from './state-i18n-token.pipe'; describe('StateI18nTokenPipe', () => { const pipe = new StateI18nTokenPipe(); it('works with default states', () => { const result = pipe.transform('AddingItems'); expect(result).toBe('state.adding-items'); }); it('works with unknown states', () => { const result = pipe.transform('ValidatingCustomer'); expect(result).toBe('state.validating-customer'); }); it('works with unknown states with various formatting', () => { const result1 = pipe.transform('validating-Customer'); expect(result1).toBe('state.validating-customer'); const result2 = pipe.transform('validating-Customer'); expect(result2).toBe('state.validating-customer'); const result3 = pipe.transform('Validating Customer'); expect(result3).toBe('state.validating-customer'); }); it('passes through non-string values', () => { expect(pipe.transform(null)).toBeNull(); expect(pipe.transform(1)).toBe(1); expect(pipe.transform({})).toEqual({}); }); });
import { Pipe, PipeTransform } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; @Pipe({ name: 'stateI18nToken', }) export class StateI18nTokenPipe implements PipeTransform { private readonly stateI18nTokens = { Created: _('state.created'), Draft: _('state.draft'), AddingItems: _('state.adding-items'), ArrangingPayment: _('state.arranging-payment'), PaymentAuthorized: _('state.payment-authorized'), PaymentSettled: _('state.payment-settled'), PartiallyShipped: _('state.partially-shipped'), Shipped: _('state.shipped'), PartiallyDelivered: _('state.partially-delivered'), Authorized: _('state.authorized'), Delivered: _('state.delivered'), Cancelled: _('state.cancelled'), Pending: _('state.pending'), Settled: _('state.settled'), Failed: _('state.failed'), Error: _('state.error'), Declined: _('state.declined'), Modifying: _('state.modifying'), ArrangingAdditionalPayment: _('state.arranging-additional-payment'), }; transform<T>(value: T): T { if (typeof value === 'string' && value.length) { const defaultStateToken = this.stateI18nTokens[value as any]; if (defaultStateToken) { return defaultStateToken; } return getOrderStateTranslationToken(value as string) as T; } return value; } } export function getOrderStateTranslationToken(state: string): string { return ( 'state.' + state .replace(/([a-z])([A-Z])/g, '$1-$2') .replace(/ +/g, '-') .toLowerCase() ); }
import { Pipe, PipeTransform } from '@angular/core'; import { stringToColor } from '../../common/utilities/string-to-color'; @Pipe({ name: 'stringToColor', pure: true, }) export class StringToColorPipe implements PipeTransform { transform(value: any): string { return stringToColor(value); } }
import { TimeAgoPipe } from './time-ago.pipe'; describe('TimeAgoPipe', () => { let mockI18nService: any; beforeEach(() => { mockI18nService = { translate: jasmine.createSpy('translate'), }; }); it('seconds ago', () => { const pipe = new TimeAgoPipe(mockI18nService); pipe.transform('2020-02-04T16:15:10.100Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(0)).toEqual(['datetime.ago-seconds', { count: 0 }]); pipe.transform('2020-02-04T16:15:07.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(1)).toEqual(['datetime.ago-seconds', { count: 3 }]); pipe.transform('2020-02-04T16:14:20.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(2)).toEqual(['datetime.ago-seconds', { count: 50 }]); }); it('minutes ago', () => { const pipe = new TimeAgoPipe(mockI18nService); pipe.transform('2020-02-04T16:13:10.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(0)).toEqual( ['datetime.ago-minutes', { count: 2 }], 'a', ); pipe.transform('2020-02-04T16:12:10.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(1)).toEqual( ['datetime.ago-minutes', { count: 3 }], 'b', ); pipe.transform('2020-02-04T15:20:10.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(2)).toEqual( ['datetime.ago-minutes', { count: 55 }], 'c', ); }); it('hours ago', () => { const pipe = new TimeAgoPipe(mockI18nService); pipe.transform('2020-02-04T14:15:10.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(0)).toEqual(['datetime.ago-hours', { count: 2 }]); pipe.transform('2020-02-04T02:15:07.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(1)).toEqual(['datetime.ago-hours', { count: 14 }]); pipe.transform('2020-02-03T17:14:20.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(2)).toEqual(['datetime.ago-hours', { count: 23 }]); }); it('days ago', () => { const pipe = new TimeAgoPipe(mockI18nService); pipe.transform('2020-02-03T16:15:10.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(0)).toEqual(['datetime.ago-days', { count: 1 }]); pipe.transform('2020-02-01T02:15:07.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(1)).toEqual(['datetime.ago-days', { count: 3 }]); pipe.transform('2020-01-03T17:14:20.500Z', '2020-02-04T16:15:10.500Z'); expect(mockI18nService.translate.calls.argsFor(2)).toEqual(['datetime.ago-days', { count: 31 }]); }); it('years ago', () => { const pipe = new TimeAgoPipe(mockI18nService); pipe.transform('2019-02-04T12:00:00.000Z', '2020-02-04T12:00:00.000Z'); expect(mockI18nService.translate.calls.argsFor(0)).toEqual(['datetime.ago-years', { count: 1 }]); pipe.transform('2018-02-04T12:00:01.000Z', '2020-02-04T12:00:00.000Z'); expect(mockI18nService.translate.calls.argsFor(1)).toEqual(['datetime.ago-years', { count: 1 }]); pipe.transform('2018-02-04T12:00:00.000Z', '2020-02-04T12:00:00.000Z'); expect(mockI18nService.translate.calls.argsFor(2)).toEqual(['datetime.ago-years', { count: 2 }]); pipe.transform('2010-01-04T12:00:00.000Z', '2020-02-04T12:00:00.000Z'); expect(mockI18nService.translate.calls.argsFor(3)).toEqual(['datetime.ago-years', { count: 10 }]); }); });
import { Pipe, PipeTransform } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import dayjs from 'dayjs'; import { I18nService } from '../../providers/i18n/i18n.service'; /** * @description * Converts a date into the format "3 minutes ago", "5 hours ago" etc. * * @example * ```HTML * {{ order.orderPlacedAt | timeAgo }} * ``` * * @docsCategory pipes */ @Pipe({ name: 'timeAgo', pure: false, }) export class TimeAgoPipe implements PipeTransform { constructor(private i18nService: I18nService) {} transform(value: string | Date, nowVal?: string | Date): string { const then = dayjs(value); const now = dayjs(nowVal || new Date()); const secondsDiff = now.diff(then, 'second'); const durations: Array<[number, string]> = [ [60, _('datetime.ago-seconds')], [3600, _('datetime.ago-minutes')], [86400, _('datetime.ago-hours')], [31536000, _('datetime.ago-days')], [Number.MAX_SAFE_INTEGER, _('datetime.ago-years')], ]; let lastUpperBound = 1; for (const [upperBound, translationToken] of durations) { if (secondsDiff < upperBound) { const count = Math.max(0, Math.floor(secondsDiff / lastUpperBound)); return this.i18nService.translate(translationToken, { count }); } lastUpperBound = upperBound; } return then.format(); } }
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { DeactivateAware } from '../../../common/deactivate-aware'; import { ModalService } from '../../../providers/modal/modal.service'; @Injectable() export class CanDeactivateDetailGuard { constructor(private modalService: ModalService, private router: Router) {} canDeactivate( component: DeactivateAware, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot, ): boolean | Observable<boolean> { if (!component.canDeactivate()) { return this.modalService .dialog({ title: _('common.confirm-navigation'), body: _('common.there-are-unsaved-changes'), buttons: [ { type: 'danger', label: _('common.discard-changes'), returnValue: true }, { type: 'primary', label: _('common.cancel-navigation'), returnValue: false }, ], }) .pipe(map(result => !!result)); } else { return true; } } }
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function unicodePatternValidator(patternRe: RegExp): ValidatorFn { const unicodeRe = patternRe.unicode ? patternRe : new RegExp(patternRe, 'u'); return (control: AbstractControl): ValidationErrors | null => { const valid = unicodeRe.test(control.value); return valid ? null : { pattern: { value: control.value } }; }; }
import { NgModule } from '@angular/core'; import { RouterModule, ROUTES } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { BulkActionRegistryService, CustomerDetailQueryDocument, detailComponentWithResolver, GetCustomerGroupDetailDocument, PageService, SharedModule, SortOrder, } from '@vendure/admin-ui/core'; import { AddCustomerToGroupDialogComponent } from './components/add-customer-to-group-dialog/add-customer-to-group-dialog.component'; import { AddressCardComponent } from './components/address-card/address-card.component'; import { AddressDetailDialogComponent } from './components/address-detail-dialog/address-detail-dialog.component'; import { CustomerDetailComponent } from './components/customer-detail/customer-detail.component'; import { CustomerGroupDetailDialogComponent } from './components/customer-group-detail-dialog/customer-group-detail-dialog.component'; import { deleteCustomerGroupsBulkAction } from './components/customer-group-list/customer-group-list-bulk-actions'; import { CustomerGroupListComponent } from './components/customer-group-list/customer-group-list.component'; import { removeCustomerGroupMembersBulkAction } from './components/customer-group-member-list/customer-group-member-list-bulk-actions'; import { CustomerGroupMemberListComponent } from './components/customer-group-member-list/customer-group-member-list.component'; import { CustomerHistoryEntryHostComponent } from './components/customer-history/customer-history-entry-host.component'; import { CustomerHistoryComponent } from './components/customer-history/customer-history.component'; import { deleteCustomersBulkAction } from './components/customer-list/customer-list-bulk-actions'; import { CustomerListComponent } from './components/customer-list/customer-list.component'; import { CustomerStatusLabelComponent } from './components/customer-status-label/customer-status-label.component'; import { SelectCustomerGroupDialogComponent } from './components/select-customer-group-dialog/select-customer-group-dialog.component'; import { createRoutes } from './customer.routes'; import { CustomerGroupDetailComponent } from './components/customer-group-detail/customer-group-detail.component'; @NgModule({ imports: [SharedModule, RouterModule.forChild([])], providers: [ { provide: ROUTES, useFactory: (pageService: PageService) => createRoutes(pageService), multi: true, deps: [PageService], }, ], declarations: [ CustomerListComponent, CustomerDetailComponent, CustomerStatusLabelComponent, AddressCardComponent, CustomerGroupListComponent, CustomerGroupDetailDialogComponent, AddCustomerToGroupDialogComponent, CustomerGroupMemberListComponent, SelectCustomerGroupDialogComponent, CustomerHistoryComponent, AddressDetailDialogComponent, CustomerHistoryEntryHostComponent, CustomerGroupDetailComponent, ], exports: [AddressCardComponent], }) export class CustomerModule { private static hasRegisteredTabsAndBulkActions = false; constructor(bulkActionRegistryService: BulkActionRegistryService, pageService: PageService) { if (CustomerModule.hasRegisteredTabsAndBulkActions) { return; } bulkActionRegistryService.registerBulkAction(deleteCustomersBulkAction); bulkActionRegistryService.registerBulkAction(deleteCustomerGroupsBulkAction); bulkActionRegistryService.registerBulkAction(removeCustomerGroupMembersBulkAction); pageService.registerPageTab({ priority: 0, location: 'customer-list', tab: _('customer.customers'), route: '', component: CustomerListComponent, }); pageService.registerPageTab({ priority: 0, location: 'customer-detail', tab: _('customer.customer'), route: '', component: detailComponentWithResolver({ component: CustomerDetailComponent, query: CustomerDetailQueryDocument, entityKey: 'customer', variables: { orderListOptions: { sort: { orderPlacedAt: SortOrder.DESC, }, }, }, getBreadcrumbs: entity => [ { label: entity ? `${entity?.firstName} ${entity?.lastName}` : _('customer.create-new-customer'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'customer-group-list', tab: _('customer.customer-groups'), route: '', component: CustomerGroupListComponent, }); pageService.registerPageTab({ priority: 0, location: 'customer-group-detail', tab: _('customer.customer-group'), route: '', component: detailComponentWithResolver({ component: CustomerGroupDetailComponent, query: GetCustomerGroupDetailDocument, entityKey: 'customerGroup', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('customer.create-new-customer-group'), link: [entity?.id], }, ], }), }); CustomerModule.hasRegisteredTabsAndBulkActions = true; } }
import { Route } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CustomerFragment, detailBreadcrumb, PageComponent, PageService } from '@vendure/admin-ui/core'; export const createRoutes = (pageService: PageService): Route[] => [ { path: 'customers', component: PageComponent, data: { locationId: 'customer-list', breadcrumb: _('breadcrumb.customers'), }, children: pageService.getPageTabRoutes('customer-list'), }, { path: 'customers/:id', component: PageComponent, data: { locationId: 'customer-detail', breadcrumb: { label: _('breadcrumb.customers'), link: ['../', 'customers'] }, }, children: pageService.getPageTabRoutes('customer-detail'), }, { path: 'groups', component: PageComponent, data: { locationId: 'customer-detail', breadcrumb: _('breadcrumb.customer-groups'), }, children: pageService.getPageTabRoutes('customer-group-list'), }, { path: 'groups/:id', component: PageComponent, data: { locationId: 'customer-group-detail', breadcrumb: { label: _('breadcrumb.customer-groups'), link: ['../', 'groups'] }, }, children: pageService.getPageTabRoutes('customer-group-detail'), }, ]; export function customerBreadcrumb(data: any, params: any) { return detailBreadcrumb<CustomerFragment>({ entity: data.entity, id: params.id, breadcrumbKey: 'breadcrumb.customers', getName: customer => `${customer.firstName} ${customer.lastName}`, route: 'customers', }); }
// This file was generated by the build-public-api.ts script export * from './components/add-customer-to-group-dialog/add-customer-to-group-dialog.component'; export * from './components/address-card/address-card.component'; export * from './components/address-detail-dialog/address-detail-dialog.component'; export * from './components/customer-detail/customer-detail.component'; export * from './components/customer-group-detail/customer-group-detail.component'; export * from './components/customer-group-detail-dialog/customer-group-detail-dialog.component'; export * from './components/customer-group-list/customer-group-list-bulk-actions'; export * from './components/customer-group-list/customer-group-list.component'; export * from './components/customer-group-member-list/customer-group-member-list-bulk-actions'; export * from './components/customer-group-member-list/customer-group-member-list.component'; export * from './components/customer-history/customer-history-entry-host.component'; export * from './components/customer-history/customer-history.component'; export * from './components/customer-list/customer-list-bulk-actions'; export * from './components/customer-list/customer-list.component'; export * from './components/customer-status-label/customer-status-label.component'; export * from './components/select-customer-group-dialog/select-customer-group-dialog.component'; export * from './customer.module'; export * from './customer.routes';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { DataService, Dialog, GetCustomerGroupsQuery, GetCustomerListQuery, ItemOf, } from '@vendure/admin-ui/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; import { CustomerGroupMemberFetchParams } from '../customer-group-member-list/customer-group-member-list.component'; @Component({ selector: 'vdr-add-customer-to-group-dialog', templateUrl: './add-customer-to-group-dialog.component.html', styleUrls: ['./add-customer-to-group-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddCustomerToGroupDialogComponent implements Dialog<string[]>, OnInit { resolveWith: (result?: string[]) => void; group: ItemOf<GetCustomerGroupsQuery, 'customerGroups'>; route: ActivatedRoute; selectedCustomerIds: string[] = []; customers$: Observable<GetCustomerListQuery['customers']['items']>; customersTotal$: Observable<number>; fetchGroupMembers$ = new BehaviorSubject<CustomerGroupMemberFetchParams>({ skip: 0, take: 10, filterTerm: '', }); constructor(private dataService: DataService) {} ngOnInit() { const customerResult$ = this.fetchGroupMembers$.pipe( switchMap(({ skip, take, filterTerm }) => this.dataService.customer .getCustomerList(take, skip, filterTerm) .mapStream(res => res.customers), ), ); this.customers$ = customerResult$.pipe(map(res => res.items)); this.customersTotal$ = customerResult$.pipe(map(res => res.totalItems)); } cancel() { this.resolveWith(); } add() { this.resolveWith(this.selectedCustomerIds); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { CustomFieldConfig, GetAvailableCountriesQuery, ModalService } from '@vendure/admin-ui/core'; import { BehaviorSubject } from 'rxjs'; import { filter, take } from 'rxjs/operators'; import { AddressDetailDialogComponent } from '../address-detail-dialog/address-detail-dialog.component'; @Component({ selector: 'vdr-address-card', templateUrl: './address-card.component.html', styleUrls: ['./address-card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddressCardComponent implements OnInit, OnChanges { @Input() addressForm: UntypedFormGroup; @Input() customFields: CustomFieldConfig; @Input() availableCountries: GetAvailableCountriesQuery['countries']['items'] = []; @Input() isDefaultBilling: string; @Input() isDefaultShipping: string; @Input() editable = true; @Output() setAsDefaultShipping = new EventEmitter<string>(); @Output() setAsDefaultBilling = new EventEmitter<string>(); @Output() deleteAddress = new EventEmitter<string>(); private dataDependenciesPopulated = new BehaviorSubject<boolean>(false); constructor(private modalService: ModalService, private changeDetector: ChangeDetectorRef) {} ngOnInit(): void { const streetLine1 = this.addressForm.get('streetLine1') as UntypedFormControl; // Make the address dialog display automatically if there is no address line // as is the case when adding a new address. if (!streetLine1.value) { this.dataDependenciesPopulated .pipe( filter(value => value), take(1), ) .subscribe(() => { this.editAddress(); }); } } ngOnChanges(changes: SimpleChanges) { if (this.customFields != null && this.availableCountries != null) { this.dataDependenciesPopulated.next(true); } } getCountryName(countryCode: string) { if (!this.availableCountries) { return ''; } const match = this.availableCountries.find(c => c.code === countryCode); return match ? match.name : ''; } setAsDefaultBillingAddress() { this.setAsDefaultBilling.emit(this.addressForm.value.id); this.addressForm.markAsDirty(); } setAsDefaultShippingAddress() { this.setAsDefaultShipping.emit(this.addressForm.value.id); this.addressForm.markAsDirty(); } delete() { this.deleteAddress.emit(this.addressForm.value.id); this.addressForm.markAsDirty(); } editAddress() { this.modalService .fromComponent(AddressDetailDialogComponent, { locals: { addressForm: this.addressForm, customFields: this.customFields, availableCountries: this.availableCountries, }, size: 'md', closable: true, }) .subscribe(() => { this.changeDetector.markForCheck(); }); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { CustomFieldConfig, Dialog, GetAvailableCountriesQuery } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-address-detail-dialog', templateUrl: './address-detail-dialog.component.html', styleUrls: ['./address-detail-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddressDetailDialogComponent implements Dialog<UntypedFormGroup>, OnInit { addressForm: UntypedFormGroup; customFields: CustomFieldConfig; availableCountries: GetAvailableCountriesQuery['countries']['items'] = []; resolveWith: (result?: UntypedFormGroup) => void; constructor(private changeDetector: ChangeDetectorRef) {} ngOnInit() { this.addressForm.valueChanges.subscribe(() => this.changeDetector.markForCheck()); } cancel() { this.resolveWith(); } save() { this.resolveWith(this.addressForm); } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, UntypedFormArray, UntypedFormControl, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CreateAddressInput, CreateCustomerAddressMutation, CreateCustomerInput, CUSTOMER_FRAGMENT, CustomerDetailQueryDocument, CustomerDetailQueryQuery, DataService, DeleteCustomerAddressMutation, EditNoteDialogComponent, GetAvailableCountriesQuery, GetCustomerHistoryQuery, getCustomFieldsDefaults, ModalService, NotificationService, SortOrder, TimelineHistoryEntry, TypedBaseDetailComponent, UpdateCustomerAddressMutation, UpdateCustomerInput, UpdateCustomerMutation, } from '@vendure/admin-ui/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { gql } from 'apollo-angular'; import { EMPTY, forkJoin, from, Observable, Subject } from 'rxjs'; import { concatMap, filter, map, merge, mergeMap, shareReplay, startWith, switchMap, take, } from 'rxjs/operators'; import { SelectCustomerGroupDialogComponent } from '../select-customer-group-dialog/select-customer-group-dialog.component'; type CustomerWithOrders = NonNullable<CustomerDetailQueryQuery['customer']>; export const CUSTOMER_DETAIL_QUERY = gql` query CustomerDetailQuery($id: ID!, $orderListOptions: OrderListOptions) { customer(id: $id) { ...Customer groups { id name } orders(options: $orderListOptions) { items { id code type state total totalWithTax currencyCode createdAt updatedAt orderPlacedAt } totalItems } } } ${CUSTOMER_FRAGMENT} `; @Component({ selector: 'vdr-customer-detail', templateUrl: './customer-detail.component.html', styleUrls: ['./customer-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerDetailComponent extends TypedBaseDetailComponent<typeof CustomerDetailQueryDocument, 'customer'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Customer'); addressCustomFields = this.getCustomFieldConfig('Address'); detailForm = this.formBuilder.group({ customer: this.formBuilder.group({ title: '', firstName: ['', Validators.required], lastName: ['', Validators.required], phoneNumber: '', emailAddress: ['', [Validators.required, Validators.email]], password: '', customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }), addresses: new UntypedFormArray([]), }); availableCountries$: Observable<GetAvailableCountriesQuery['countries']['items']>; orders$: Observable<CustomerWithOrders['orders']['items']>; ordersCount$: Observable<number>; history$: Observable<NonNullable<GetCustomerHistoryQuery['customer']>['history']['items'] | undefined>; fetchHistory = new Subject<void>(); defaultShippingAddressId: string; defaultBillingAddressId: string; addressesToDeleteIds = new Set<string>(); addressDefaultsUpdated = false; ordersPerPage = 10; currentOrdersPage = 1; private orderListUpdates$ = new Subject<CustomerWithOrders>(); constructor( private changeDetector: ChangeDetectorRef, private formBuilder: FormBuilder, protected dataService: DataService, private modalService: ModalService, private notificationService: NotificationService, ) { super(); } ngOnInit() { this.init(); this.availableCountries$ = this.dataService.settings .getAvailableCountries() .mapSingle(result => result.countries.items) .pipe(shareReplay(1)); const customerWithUpdates$ = this.entity$.pipe(merge(this.orderListUpdates$)); this.orders$ = customerWithUpdates$.pipe(map(customer => customer.orders.items)); this.ordersCount$ = this.entity$.pipe(map(customer => customer.orders.totalItems)); this.history$ = this.fetchHistory.pipe( startWith(null), switchMap(() => this.dataService.customer .getCustomerHistory(this.id, { sort: { createdAt: SortOrder.DESC, }, }) .mapStream(data => data.customer?.history.items), ), ); } ngOnDestroy() { this.destroy(); this.orderListUpdates$.complete(); } getAddressFormControls(): UntypedFormControl[] { const formArray = this.detailForm.get(['addresses']) as UntypedFormArray; return formArray.controls as UntypedFormControl[]; } setDefaultBillingAddressId(id: string) { this.defaultBillingAddressId = id; this.addressDefaultsUpdated = true; } setDefaultShippingAddressId(id: string) { this.defaultShippingAddressId = id; this.addressDefaultsUpdated = true; } toggleDeleteAddress(id: string) { if (this.addressesToDeleteIds.has(id)) { this.addressesToDeleteIds.delete(id); } else { this.addressesToDeleteIds.add(id); } } addAddress() { const addressFormArray = this.detailForm.get('addresses') as UntypedFormArray; const newAddress = this.formBuilder.group({ fullName: '', company: '', streetLine1: ['', Validators.required], streetLine2: '', city: '', province: '', postalCode: '', countryCode: ['', Validators.required], phoneNumber: '', defaultShippingAddress: false, defaultBillingAddress: false, customFields: this.formBuilder.group( this.addressCustomFields.reduce((hash, field) => ({ ...hash, [field.name]: '' }), {}), ), }); addressFormArray.push(newAddress); } setOrderItemsPerPage(itemsPerPage: number) { this.ordersPerPage = +itemsPerPage; this.fetchOrdersList(); } setOrderCurrentPage(page: number) { this.currentOrdersPage = +page; this.fetchOrdersList(); } create() { const customerForm = this.detailForm.get('customer'); if (!customerForm) { return; } const { title, emailAddress, firstName, lastName, phoneNumber, password } = customerForm.value; const customFields = customerForm.get('customFields')?.value; if (!emailAddress || !firstName || !lastName) { return; } const customer: CreateCustomerInput = { title, emailAddress, firstName, lastName, phoneNumber, customFields, }; this.dataService.customer.createCustomer(customer, password).subscribe(({ createCustomer }) => { switch (createCustomer.__typename) { case 'Customer': this.notificationService.success(_('common.notify-create-success'), { entity: 'Customer', }); if (createCustomer.emailAddress && !password) { this.notificationService.notify({ message: _('customer.email-verification-sent'), translationVars: { emailAddress }, type: 'info', duration: 10000, }); } this.detailForm.markAsPristine(); this.addressDefaultsUpdated = false; this.changeDetector.markForCheck(); this.router.navigate(['../', createCustomer.id], { relativeTo: this.route }); break; case 'EmailAddressConflictError': this.notificationService.error(createCustomer.message); } }); } save() { this.entity$ .pipe( take(1), mergeMap(({ id }) => { const saveOperations: Array< Observable< | UpdateCustomerMutation['updateCustomer'] | CreateCustomerAddressMutation['createCustomerAddress'] | UpdateCustomerAddressMutation['updateCustomerAddress'] | DeleteCustomerAddressMutation['deleteCustomerAddress'] > > = []; const customerForm = this.detailForm.get('customer'); if (customerForm && customerForm.dirty) { const formValue = customerForm.value; const customFields = customerForm.get('customFields')?.value; const customer: UpdateCustomerInput = { id, title: formValue.title, emailAddress: formValue.emailAddress, firstName: formValue.firstName, lastName: formValue.lastName, phoneNumber: formValue.phoneNumber, customFields, }; saveOperations.push( this.dataService.customer .updateCustomer(customer) .pipe(map(res => res.updateCustomer)), ); } const addressFormArray = this.detailForm.get('addresses') as UntypedFormArray; if ((addressFormArray && addressFormArray.dirty) || this.addressDefaultsUpdated) { for (const addressControl of addressFormArray.controls) { if (addressControl.dirty || this.addressDefaultsUpdated) { const address = addressControl.value; const input: CreateAddressInput = { fullName: address.fullName, company: address.company, streetLine1: address.streetLine1, streetLine2: address.streetLine2, city: address.city, province: address.province, postalCode: address.postalCode, countryCode: address.countryCode, phoneNumber: address.phoneNumber, defaultShippingAddress: this.defaultShippingAddressId === address.id, defaultBillingAddress: this.defaultBillingAddressId === address.id, customFields: address.customFields, }; if (!address.id) { saveOperations.push( this.dataService.customer .createCustomerAddress(id, input) .pipe(map(res => res.createCustomerAddress)), ); } else { if (this.addressesToDeleteIds.has(address.id)) { saveOperations.push( this.dataService.customer .deleteCustomerAddress(address.id) .pipe(map(res => res.deleteCustomerAddress)), ); } else { saveOperations.push( this.dataService.customer .updateCustomerAddress({ ...input, id: address.id, }) .pipe(map(res => res.updateCustomerAddress)), ); } } } } } return forkJoin(saveOperations); }), ) .subscribe( data => { let notified = false; for (const result of data) { switch (result.__typename) { case 'Customer': case 'Address': case 'Success': if (!notified) { this.notificationService.success(_('common.notify-update-success'), { entity: 'Customer', }); notified = true; this.detailForm.markAsPristine(); this.addressDefaultsUpdated = false; this.changeDetector.markForCheck(); this.fetchHistory.next(); this.refreshCustomer().subscribe(); } break; case 'EmailAddressConflictError': this.notificationService.error(result.message); break; } } }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Customer', }); }, ); } addToGroup() { this.modalService .fromComponent(SelectCustomerGroupDialogComponent, { size: 'md', }) .pipe( switchMap(groupIds => (groupIds ? from(groupIds) : EMPTY)), concatMap(groupId => this.dataService.customer.addCustomersToGroup(groupId, [this.id])), ) .subscribe({ next: res => { this.notificationService.success(_(`customer.add-customers-to-group-success`), { customerCount: 1, groupName: res.addCustomersToGroup.name, }); }, complete: () => { this.refreshCustomer().subscribe(); this.fetchHistory.next(); }, }); } removeFromGroup(group: CustomerWithOrders['groups'][number]) { this.modalService .dialog({ title: _('customer.confirm-remove-customer-from-group'), buttons: [ { type: 'secondary', label: _('common.cancel') }, { type: 'danger', label: _('common.delete'), returnValue: true }, ], }) .pipe( switchMap(response => response ? this.dataService.customer.removeCustomersFromGroup(group.id, [this.id]) : EMPTY, ), switchMap(() => this.refreshCustomer()), ) .subscribe(result => { this.notificationService.success(_(`customer.remove-customers-from-group-success`), { customerCount: 1, groupName: group.name, }); this.fetchHistory.next(); }); } addNoteToCustomer({ note }: { note: string }) { this.dataService.customer.addNoteToCustomer(this.id, note).subscribe(() => { this.fetchHistory.next(); this.notificationService.success(_('common.notify-create-success'), { entity: 'Note', }); }); } updateNote(entry: TimelineHistoryEntry) { this.modalService .fromComponent(EditNoteDialogComponent, { closable: true, locals: { displayPrivacyControls: false, note: entry.data.note, }, }) .pipe( switchMap(result => { if (result) { return this.dataService.customer.updateCustomerNote({ noteId: entry.id, note: result.note, }); } else { return EMPTY; } }), ) .subscribe(result => { this.fetchHistory.next(); this.notificationService.success(_('common.notify-update-success'), { entity: 'Note', }); }); } deleteNote(entry: TimelineHistoryEntry) { return this.modalService .dialog({ title: _('common.confirm-delete-note'), body: entry.data.note, buttons: [ { type: 'secondary', label: _('common.cancel') }, { type: 'danger', label: _('common.delete'), returnValue: true }, ], }) .pipe(switchMap(res => (res ? this.dataService.customer.deleteCustomerNote(entry.id) : EMPTY))) .subscribe(() => { this.fetchHistory.next(); this.notificationService.success(_('common.notify-delete-success'), { entity: 'Note', }); }); } protected setFormValues(entity: CustomerWithOrders): void { const customerGroup = this.detailForm.get('customer'); if (customerGroup) { customerGroup.patchValue({ title: entity.title ?? null, firstName: entity.firstName, lastName: entity.lastName, phoneNumber: entity.phoneNumber ?? null, emailAddress: entity.emailAddress, password: '', customFields: {}, }); } if (entity.addresses) { const addressesArray = new UntypedFormArray([]); for (const address of entity.addresses) { const { customFields, ...rest } = address as typeof address & { customFields: any }; const addressGroup = this.formBuilder.group({ ...rest, countryCode: address.country.code, customFields: this.formBuilder.group( this.addressCustomFields.reduce( (hash, field) => ({ ...hash, [field.name]: address['customFields'][field.name], }), {}, ), ), }); addressesArray.push(addressGroup); if (address.defaultShippingAddress) { this.defaultShippingAddressId = address.id; } if (address.defaultBillingAddress) { this.defaultBillingAddressId = address.id; } } this.detailForm.setControl('addresses', addressesArray); } if (this.customFields.length) { this.setCustomFieldFormValues( this.customFields, this.detailForm.get(['customer', 'customFields']), entity, ); } this.changeDetector.markForCheck(); } /** * Refetch the customer with the current order list settings. */ private fetchOrdersList() { this.dataService .query(CustomerDetailQueryDocument, { id: this.id, orderListOptions: { take: this.ordersPerPage, skip: (this.currentOrdersPage - 1) * this.ordersPerPage, sort: { orderPlacedAt: SortOrder.DESC }, }, }) .single$.pipe( map(data => data.customer), filter(notNullOrUndefined), ) .subscribe(result => this.orderListUpdates$.next(result)); } private refreshCustomer() { return this.dataService.query(CustomerDetailQueryDocument, { id: this.id, orderListOptions: { take: 0 }, }).single$; } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { CreateCustomerGroupInput, CustomFieldConfig, Dialog, getCustomFieldsDefaults, ServerConfigService, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-customer-group-detail-dialog', templateUrl: './customer-group-detail-dialog.component.html', styleUrls: ['./customer-group-detail-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerGroupDetailDialogComponent implements Dialog<CreateCustomerGroupInput>, OnInit { group: { id?: string; name: string; customFields?: { [name: string]: any } }; resolveWith: (result?: CreateCustomerGroupInput) => void; customFields: CustomFieldConfig[]; form: UntypedFormGroup; constructor(private serverConfigService: ServerConfigService, private formBuilder: UntypedFormBuilder) { this.customFields = this.serverConfigService.getCustomFieldsFor('CustomerGroup'); } ngOnInit() { this.form = this.formBuilder.group({ name: [this.group.name, Validators.required], customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); if (this.customFields.length) { const customFieldsGroup = this.form.get('customFields') as UntypedFormGroup; for (const fieldDef of this.customFields) { const key = fieldDef.name; const value = this.group.customFields?.[key]; const control = customFieldsGroup.get(key); if (control) { control.patchValue(value); } } } } cancel() { this.resolveWith(); } save() { this.resolveWith(this.form.value); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { FormBuilder, UntypedFormGroup } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { ResultOf } from '@graphql-typed-document-node/core'; import { DataService, GetCustomerGroupDetailDocument, getCustomFieldsDefaults, ModalService, NotificationService, TypedBaseDetailComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const CUSTOMER_GROUP_DETAIL_QUERY = gql` query GetCustomerGroupDetail($id: ID!) { customerGroup(id: $id) { ...CustomerGroupDetail } } fragment CustomerGroupDetail on CustomerGroup { id createdAt updatedAt name } `; @Component({ selector: 'vdr-customer-group-detail', templateUrl: './customer-group-detail.component.html', styleUrls: ['./customer-group-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerGroupDetailComponent extends TypedBaseDetailComponent<typeof GetCustomerGroupDetailDocument, 'customerGroup'> implements OnInit { customFields = this.getCustomFieldConfig('CustomerGroup'); detailForm = this.formBuilder.group({ name: '', customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); constructor( private formBuilder: FormBuilder, protected dataService: DataService, private modalService: ModalService, private notificationService: NotificationService, ) { super(); } ngOnInit() { super.init(); } create() { const formvalue = this.detailForm.value; if (formvalue.name) { this.dataService.customer .createCustomerGroup({ name: formvalue.name, customFields: formvalue.customFields, customerIds: [], }) .subscribe( ({ createCustomerGroup }) => { this.notificationService.success(_('common.notify-create-success'), { entity: 'CustomerGroup', }); this.detailForm.markAsPristine(); this.router.navigate(['../', createCustomerGroup.id], { relativeTo: this.route }); }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'CustomerGroup', }); }, ); } } save() { const formValue = this.detailForm.value; this.dataService.customer.updateCustomerGroup({ id: this.id, ...formValue }).subscribe( () => { this.notificationService.success(_('common.notify-update-success'), { entity: 'CustomerGroup', }); this.detailForm.markAsPristine(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'CustomerGroup', }); }, ); } protected setFormValues( entity: NonNullable<ResultOf<typeof GetCustomerGroupDetailDocument>['customerGroup']>, ) { this.detailForm.patchValue({ name: entity.name, }); if (this.customFields.length) { const customFieldsGroup = this.detailForm.get(['customFields']) as UntypedFormGroup; this.setCustomFieldFormValues(this.customFields, this.detailForm.get('customFields'), entity); } } }
import { createBulkDeleteAction, GetCustomerGroupsQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteCustomerGroupsBulkAction = createBulkDeleteAction< ItemOf<GetCustomerGroupsQuery, 'customerGroups'> >({ location: 'customer-group-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteCustomerGroup), getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.customer.deleteCustomerGroups(ids).pipe(map(res => res.deleteCustomerGroups)), });
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CUSTOMER_GROUP_FRAGMENT, DataService, GetCustomerGroupListDocument, GetCustomerGroupsQuery, GetCustomerGroupWithCustomersQuery, ItemOf, ModalService, NotificationService, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { BehaviorSubject, combineLatest, EMPTY, Observable, of } from 'rxjs'; import { distinctUntilChanged, map, mapTo, switchMap } from 'rxjs/operators'; import { AddCustomerToGroupDialogComponent } from '../add-customer-to-group-dialog/add-customer-to-group-dialog.component'; import { CustomerGroupMemberFetchParams } from '../customer-group-member-list/customer-group-member-list.component'; export const GET_CUSTOMER_GROUP_LIST = gql` query GetCustomerGroupList($options: CustomerGroupListOptions) { customerGroups(options: $options) { items { ...CustomerGroup } totalItems } } ${CUSTOMER_GROUP_FRAGMENT} `; @Component({ selector: 'vdr-customer-group-list', templateUrl: './customer-group-list.component.html', styleUrls: ['./customer-group-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerGroupListComponent extends TypedBaseListComponent<typeof GetCustomerGroupListDocument, 'customerGroups'> implements OnInit { activeGroup$: Observable<ItemOf<GetCustomerGroupsQuery, 'customerGroups'> | undefined>; activeIndex$: Observable<number>; listIsEmpty$: Observable<boolean>; members$: Observable< NonNullable<GetCustomerGroupWithCustomersQuery['customerGroup']>['customers']['items'] >; membersTotal$: Observable<number>; fetchGroupMembers$ = new BehaviorSubject<CustomerGroupMemberFetchParams>({ skip: 0, take: 0, filterTerm: '', }); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'name' }) .connectToRoute(this.route); private refreshActiveGroupMembers$ = new BehaviorSubject<void>(undefined); constructor( protected dataService: DataService, private notificationService: NotificationService, private modalService: ModalService, public route: ActivatedRoute, protected router: Router, ) { super(); super.configure({ document: GetCustomerGroupListDocument, getItems: data => data.customerGroups, setVariables: (skip, take) => ({ options: { skip, take, filter: { name: { contains: this.searchTermControl.value }, ...this.filters.createFilterInput(), }, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } ngOnInit(): void { super.ngOnInit(); const activeGroupId$ = this.route.paramMap.pipe( map(pm => pm.get('contents')), distinctUntilChanged(), ); this.listIsEmpty$ = this.items$.pipe(map(groups => groups.length === 0)); this.activeGroup$ = combineLatest(this.items$, activeGroupId$).pipe( map(([groups, activeGroupId]) => { if (activeGroupId) { return groups.find(g => g.id === activeGroupId); } }), ); this.activeIndex$ = combineLatest(this.items$, activeGroupId$).pipe( map(([groups, activeGroupId]) => { if (activeGroupId) { return groups.findIndex(g => g.id === activeGroupId); } else { return -1; } }), ); const membersResult$ = combineLatest( this.activeGroup$, this.fetchGroupMembers$, this.refreshActiveGroupMembers$, ).pipe( switchMap(([activeGroup, { skip, take, filterTerm }]) => { if (activeGroup) { return this.dataService.customer .getCustomerGroupWithCustomers(activeGroup.id, { skip, take, filter: { emailAddress: { contains: filterTerm, }, }, }) .mapStream(res => res.customerGroup?.customers); } else { return of(undefined); } }), ); this.members$ = membersResult$.pipe(map(res => res?.items ?? [])); this.membersTotal$ = membersResult$.pipe(map(res => res?.totalItems ?? 0)); } closeMembers() { const params = { ...this.route.snapshot.params }; delete params.contents; this.router.navigate(['./', params], { relativeTo: this.route, queryParamsHandling: 'preserve' }); } addToGroup(group: NonNullable<GetCustomerGroupWithCustomersQuery['customerGroup']>) { this.modalService .fromComponent(AddCustomerToGroupDialogComponent, { locals: { group, route: this.route, }, size: 'md', verticalAlign: 'top', }) .pipe( switchMap(customerIds => customerIds ? this.dataService.customer .addCustomersToGroup(group.id, customerIds) .pipe(mapTo(customerIds)) : EMPTY, ), ) .subscribe({ next: result => { this.notificationService.success(_(`customer.add-customers-to-group-success`), { customerCount: result.length, groupName: group.name, }); this.refreshActiveGroupMembers$.next(); }, }); } }
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { BulkAction, DataService, ModalService, NotificationService, Permission, } from '@vendure/admin-ui/core'; import { CustomerGroupMember, CustomerGroupMemberListComponent, } from './customer-group-member-list.component'; export const removeCustomerGroupMembersBulkAction: BulkAction< CustomerGroupMember, CustomerGroupMemberListComponent > = { location: 'customer-group-members-list', label: _('customer.remove-from-group'), icon: 'trash', iconClass: 'is-danger', requiresPermission: Permission.UpdateCustomerGroup, onClick: ({ injector, selection, hostComponent, clearSelection }) => { const modalService = injector.get(ModalService); const dataService = injector.get(DataService); const notificationService = injector.get(NotificationService); const group = hostComponent.activeGroup; const customerIds = selection.map(s => s.id); dataService.customer.removeCustomersFromGroup(group.id, customerIds).subscribe({ complete: () => { notificationService.success(_(`customer.remove-customers-from-group-success`), { customerCount: customerIds.length, groupName: group.name, }); clearSelection(); hostComponent.refresh(); }, }); }, };
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnDestroy, OnInit, Output, } from '@angular/core'; import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { BulkActionLocationId, Customer, DataService, GetCustomerGroupsQuery, ItemOf, SelectionManager, } from '@vendure/admin-ui/core'; import { BehaviorSubject, combineLatest, Observable, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, startWith, takeUntil, tap } from 'rxjs/operators'; export interface CustomerGroupMemberFetchParams { skip: number; take: number; filterTerm: string; } export type CustomerGroupMember = Pick< Customer, 'id' | 'createdAt' | 'updatedAt' | 'title' | 'firstName' | 'lastName' | 'emailAddress' >; @Component({ selector: 'vdr-customer-group-member-list', templateUrl: './customer-group-member-list.component.html', styleUrls: ['./customer-group-member-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerGroupMemberListComponent implements OnInit, OnDestroy { @Input() locationId: BulkActionLocationId; @Input() members: CustomerGroupMember[]; @Input() totalItems: number; @Input() route: ActivatedRoute; @Input() selectedMemberIds: string[] = []; @Input() activeGroup: ItemOf<GetCustomerGroupsQuery, 'customerGroups'>; @Output() selectionChange = new EventEmitter<string[]>(); @Output() fetchParamsChange = new EventEmitter<CustomerGroupMemberFetchParams>(); membersItemsPerPage$: Observable<number>; membersCurrentPage$: Observable<number>; filterTermControl = new FormControl(''); selectionManager = new SelectionManager<CustomerGroupMember>({ multiSelect: true, itemsAreEqual: (a, b) => a.id === b.id, additiveMode: true, }); private refresh$ = new BehaviorSubject<boolean>(true); private destroy$ = new Subject<void>(); constructor(private router: Router, private dataService: DataService) {} ngOnInit() { this.membersCurrentPage$ = this.route.paramMap.pipe( map(qpm => qpm.get('membersPage')), map(page => (!page ? 1 : +page)), startWith(1), distinctUntilChanged(), ); this.membersItemsPerPage$ = this.route.paramMap.pipe( map(qpm => qpm.get('membersPerPage')), map(perPage => (!perPage ? 10 : +perPage)), startWith(10), distinctUntilChanged(), ); const filterTerm$ = this.filterTermControl.valueChanges.pipe( debounceTime(250), tap(() => this.setContentsPageNumber(1)), startWith(''), ); combineLatest(this.membersCurrentPage$, this.membersItemsPerPage$, filterTerm$, this.refresh$) .pipe(takeUntil(this.destroy$)) .subscribe(([currentPage, itemsPerPage, filterTerm]) => { const take = itemsPerPage; const skip = (currentPage - 1) * itemsPerPage; this.fetchParamsChange.emit({ filterTerm: filterTerm ?? '', skip, take, }); }); this.selectionManager.setCurrentItems( this.members?.filter(m => this.selectedMemberIds.includes(m.id)) ?? [], ); this.selectionManager.selectionChanges$.pipe(takeUntil(this.destroy$)).subscribe(selection => { this.selectionChange.emit(selection.map(s => s.id)); }); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } setContentsPageNumber(page: number) { this.setParam('membersPage', page); } setContentsItemsPerPage(perPage: number) { this.setParam('membersPerPage', perPage); } refresh() { this.refresh$.next(true); } private setParam(key: string, value: any) { this.router.navigate(['./', { ...this.route.snapshot.params, [key]: value }], { relativeTo: this.route, queryParamsHandling: 'merge', }); } }
import { Component, ComponentRef, EventEmitter, Input, OnDestroy, OnInit, Output, Type, ViewChild, ViewContainerRef, } from '@angular/core'; import { CustomerFragment, CustomerHistoryEntryComponent, HistoryEntryComponentService, TimelineHistoryEntry, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-customer-history-entry-host', template: ` <vdr-timeline-entry [displayType]="instance.getDisplayType(entry)" [iconShape]="instance.getIconShape && instance.getIconShape(entry)" [createdAt]="entry.createdAt" [name]="instance.getName && instance.getName(entry)" [featured]="instance.isFeatured(entry)" [collapsed]="!expanded && !instance.isFeatured(entry)" (expandClick)="expandClick.emit()" > <div #portal></div> </vdr-timeline-entry>`, exportAs: 'historyEntry', }) export class CustomerHistoryEntryHostComponent implements OnInit, OnDestroy { @Input() entry: TimelineHistoryEntry; @Input() customer: CustomerFragment; @Input() expanded: boolean; @Output() expandClick = new EventEmitter<void>(); @ViewChild('portal', { static: true, read: ViewContainerRef }) portalRef: ViewContainerRef; instance: CustomerHistoryEntryComponent; private componentRef: ComponentRef<CustomerHistoryEntryComponent>; constructor(private historyEntryComponentService: HistoryEntryComponentService) {} ngOnInit(): void { const componentType = this.historyEntryComponentService.getComponent( this.entry.type, ) as Type<CustomerHistoryEntryComponent>; const componentRef = this.portalRef.createComponent(componentType); componentRef.instance.entry = this.entry; componentRef.instance.customer = this.customer; this.instance = componentRef.instance; this.componentRef = componentRef; } ngOnDestroy() { this.componentRef?.destroy(); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { CustomerFragment, GetCustomerHistoryQuery, HistoryEntryComponentService, HistoryEntryType, TimelineDisplayType, TimelineHistoryEntry, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-customer-history', templateUrl: './customer-history.component.html', styleUrls: ['./customer-history.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerHistoryComponent { @Input() customer: CustomerFragment; @Input() history: TimelineHistoryEntry[]; @Output() addNote = new EventEmitter<{ note: string }>(); @Output() updateNote = new EventEmitter<TimelineHistoryEntry>(); @Output() deleteNote = new EventEmitter<TimelineHistoryEntry>(); note = ''; expanded = false; readonly type = HistoryEntryType; constructor(private historyEntryComponentService: HistoryEntryComponentService) {} hasCustomComponent(type: string): boolean { return !!this.historyEntryComponentService.getComponent(type); } getDisplayType(entry: TimelineHistoryEntry): TimelineDisplayType { switch (entry.type) { case HistoryEntryType.CUSTOMER_VERIFIED: case HistoryEntryType.CUSTOMER_EMAIL_UPDATE_VERIFIED: case HistoryEntryType.CUSTOMER_PASSWORD_RESET_VERIFIED: return 'success'; case HistoryEntryType.CUSTOMER_REGISTERED: return 'muted'; case HistoryEntryType.CUSTOMER_REMOVED_FROM_GROUP: return 'error'; default: return 'default'; } } getTimelineIcon(entry: TimelineHistoryEntry): string | [string, string] | undefined { switch (entry.type) { case HistoryEntryType.CUSTOMER_REGISTERED: return 'user'; case HistoryEntryType.CUSTOMER_VERIFIED: return ['assign-user', 'is-solid']; case HistoryEntryType.CUSTOMER_NOTE: return 'note'; case HistoryEntryType.CUSTOMER_ADDED_TO_GROUP: case HistoryEntryType.CUSTOMER_REMOVED_FROM_GROUP: return 'users'; } } isFeatured(entry: TimelineHistoryEntry): boolean { switch (entry.type) { case HistoryEntryType.CUSTOMER_REGISTERED: case HistoryEntryType.CUSTOMER_VERIFIED: return true; default: return false; } } getName(entry: TimelineHistoryEntry): string { const { administrator } = entry; if (administrator) { return `${administrator.firstName} ${administrator.lastName}`; } else { return `${this.customer.firstName} ${this.customer.lastName}`; } } addNoteToCustomer() { this.addNote.emit({ note: this.note }); this.note = ''; } }
import { createBulkDeleteAction, GetCustomerListQuery, ItemOf, Permission } from '@vendure/admin-ui/core'; import { map } from 'rxjs/operators'; export const deleteCustomersBulkAction = createBulkDeleteAction<ItemOf<GetCustomerListQuery, 'customers'>>({ location: 'customer-list', requiresPermission: userPermissions => userPermissions.includes(Permission.DeleteCustomer), getItemName: item => item.firstName + ' ' + item.lastName, bulkDelete: (dataService, ids) => dataService.customer.deleteCustomers(ids).pipe(map(res => res.deleteCustomers)), });
import { Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CustomerListQueryDocument, LogicalOperator, TypedBaseListComponent } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const CUSTOMER_LIST_QUERY = gql` query CustomerListQuery($options: CustomerListOptions) { customers(options: $options) { items { ...CustomerListItem } totalItems } } fragment CustomerListItem on Customer { id createdAt updatedAt title firstName lastName emailAddress user { id verified } } `; @Component({ selector: 'vdr-customer-list', templateUrl: './customer-list.component.html', styleUrls: ['./customer-list.component.scss'], }) export class CustomerListComponent extends TypedBaseListComponent<typeof CustomerListQueryDocument, 'customers'> implements OnInit { readonly customFields = this.getCustomFieldConfig('Customer'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'firstName', type: { kind: 'text' }, label: _('customer.first-name'), filterField: 'firstName', }) .addFilter({ name: 'lastName', type: { kind: 'text' }, label: _('customer.last-name'), filterField: 'lastName', }) .addFilter({ name: 'emailAddress', type: { kind: 'text' }, label: _('customer.email-address'), filterField: 'emailAddress', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'lastName' }) .addSort({ name: 'emailAddress' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); this.configure({ document: CustomerListQueryDocument, getItems: data => data.customers, setVariables: (skip, take) => ({ options: { skip, take, filter: { ...(this.searchTermControl.value ? { emailAddress: { contains: this.searchTermControl.value, }, lastName: { contains: this.searchTermControl.value, }, postalCode: { contains: this.searchTermControl.value, }, } : {}), ...this.filters.createFilterInput(), }, filterOperator: this.searchTermControl.value ? LogicalOperator.OR : LogicalOperator.AND, sort: this.sorts.createSortInput(), }, }), refreshListOnChanges: [this.sorts.valueChanges, this.filters.valueChanges], }); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { CustomerFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-customer-status-label', templateUrl: './customer-status-label.component.html', styleUrls: ['./customer-status-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CustomerStatusLabelComponent { @Input() customer: CustomerFragment; }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { DataService, Dialog, GetCustomerGroupsQuery, ItemOf } from '@vendure/admin-ui/core'; import { Observable } from 'rxjs'; @Component({ selector: 'vdr-select-customer-group-dialog', templateUrl: './select-customer-group-dialog.component.html', styleUrls: ['./select-customer-group-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectCustomerGroupDialogComponent implements Dialog<string[]>, OnInit { resolveWith: (result?: string[]) => void; groups$: Observable<Array<ItemOf<GetCustomerGroupsQuery, 'customerGroups'>>>; selectedGroupIds: string[] = []; constructor(private dataService: DataService) {} ngOnInit() { this.groups$ = this.dataService.customer .getCustomerGroupList() .mapStream(res => res.customerGroups.items); } cancel() { this.resolveWith(); } add() { this.resolveWith(this.selectedGroupIds); } }
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { DashboardWidgetService, SharedModule } from '@vendure/admin-ui/core'; import { DashboardWidgetComponent } from './components/dashboard-widget/dashboard-widget.component'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { dashboardRoutes } from './dashboard.routes'; import { DEFAULT_DASHBOARD_WIDGET_LAYOUT, DEFAULT_WIDGETS } from './default-widgets'; import { OrderChartWidgetComponent } from './widgets/order-chart-widget/order-chart-widget.component'; @NgModule({ imports: [SharedModule, RouterModule.forChild(dashboardRoutes)], declarations: [DashboardComponent, DashboardWidgetComponent, OrderChartWidgetComponent], }) export class DashboardModule { constructor(dashboardWidgetService: DashboardWidgetService) { Object.entries(DEFAULT_WIDGETS).map(([id, config]) => { if (!dashboardWidgetService.getWidgetById(id)) { dashboardWidgetService.registerWidget(id, config); } }); if (dashboardWidgetService.getDefaultLayout().length === 0) { dashboardWidgetService.setDefaultLayout(DEFAULT_DASHBOARD_WIDGET_LAYOUT); } } }
import { Routes } from '@angular/router'; import { DashboardComponent } from './components/dashboard/dashboard.component'; export const dashboardRoutes: Routes = [ { path: '', component: DashboardComponent, pathMatch: 'full', }, ];
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DashboardWidgetConfig, Permission, WidgetLayoutDefinition } from '@vendure/admin-ui/core'; import { LatestOrdersWidgetComponent } from './widgets/latest-orders-widget/latest-orders-widget.component'; import { OrderChartWidgetComponent } from './widgets/order-chart-widget/order-chart-widget.component'; import { OrderSummaryWidgetComponent } from './widgets/order-summary-widget/order-summary-widget.component'; export const DEFAULT_DASHBOARD_WIDGET_LAYOUT: WidgetLayoutDefinition = [ { id: 'metrics', width: 12 }, { id: 'orderSummary', width: 6 }, { id: 'latestOrders', width: 6 }, ]; export const DEFAULT_WIDGETS: { [id: string]: DashboardWidgetConfig } = { metrics: { title: _('dashboard.metrics'), supportedWidths: [6, 8, 12], loadComponent: () => OrderChartWidgetComponent, requiresPermissions: [Permission.ReadOrder], }, orderSummary: { title: _('dashboard.orders-summary'), loadComponent: () => OrderSummaryWidgetComponent, supportedWidths: [4, 6, 8, 12], requiresPermissions: [Permission.ReadOrder], }, latestOrders: { title: _('dashboard.latest-orders'), loadComponent: () => LatestOrdersWidgetComponent, supportedWidths: [6, 8, 12], requiresPermissions: [Permission.ReadOrder], }, };
// This file was generated by the build-public-api.ts script export * from './components/dashboard/dashboard.component'; export * from './components/dashboard-widget/dashboard-widget.component'; export * from './dashboard.module'; export * from './dashboard.routes'; export * from './default-widgets'; export * from './widgets/latest-orders-widget/latest-orders-widget.component'; export * from './widgets/order-chart-widget/order-chart-widget.component'; export * from './widgets/order-summary-widget/order-summary-widget.component'; export * from './widgets/test-widget/test-widget.component'; export * from './widgets/welcome-widget/welcome-widget.component';
import { AfterViewInit, ChangeDetectionStrategy, Component, ComponentRef, Input, OnDestroy, ViewChild, ViewContainerRef, } from '@angular/core'; import { DashboardWidgetConfig } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-dashboard-widget', templateUrl: './dashboard-widget.component.html', styleUrls: ['./dashboard-widget.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DashboardWidgetComponent implements AfterViewInit, OnDestroy { @Input() widgetConfig: DashboardWidgetConfig; @ViewChild('portal', { read: ViewContainerRef }) private portal: ViewContainerRef; private componentRef: ComponentRef<any>; ngAfterViewInit(): void { this.loadWidget(); } private async loadWidget() { const loadComponentResult = this.widgetConfig.loadComponent(); const componentType = loadComponentResult instanceof Promise ? await loadComponentResult : loadComponentResult; this.componentRef = this.portal.createComponent(componentType); this.componentRef.changeDetectorRef.detectChanges(); } ngOnDestroy() { if (this.componentRef) { this.componentRef.destroy(); } } }
import { CdkDragDrop } from '@angular/cdk/drag-drop'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { DashboardWidgetConfig, DashboardWidgetService, DashboardWidgetWidth, DataService, LocalStorageService, titleSetter, WidgetLayout, WidgetLayoutDefinition, } from '@vendure/admin-ui/core'; import { assertNever } from '@vendure/common/lib/shared-utils'; import { Observable } from 'rxjs'; import { map, tap } from 'rxjs/operators'; @Component({ selector: 'vdr-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DashboardComponent implements OnInit { widgetLayout: WidgetLayout | undefined; availableWidgets$: Observable<Array<{ id: string; config: DashboardWidgetConfig }>>; private readonly deletionMarker = '__delete__'; private setTitle = titleSetter(); constructor( private dashboardWidgetService: DashboardWidgetService, private localStorageService: LocalStorageService, private changedDetectorRef: ChangeDetectorRef, private dataService: DataService, ) {} ngOnInit() { this.availableWidgets$ = this.dataService.client.userStatus().stream$.pipe( map(({ userStatus }) => userStatus.permissions), map(permissions => this.dashboardWidgetService.getAvailableWidgets(permissions)), tap(widgets => (this.widgetLayout = this.initLayout(widgets.map(w => w.id)))), ); this.setTitle('breadcrumb.dashboard'); } getClassForWidth(width: DashboardWidgetWidth): string { switch (width) { case 3: return `clr-col-12 clr-col-sm-6 clr-col-lg-3`; case 4: return `clr-col-12 clr-col-sm-6 clr-col-lg-4`; case 6: return `clr-col-12 clr-col-lg-6`; case 8: return `clr-col-12 clr-col-lg-8`; case 12: return `clr-col-12`; default: assertNever(width); } } getSupportedWidths(config: DashboardWidgetConfig): DashboardWidgetWidth[] { return config.supportedWidths || [3, 4, 6, 8, 12]; } setWidgetWidth(widget: WidgetLayout[number][number], width: DashboardWidgetWidth) { widget.width = width; this.recalculateLayout(); } trackRow(index: number, row: WidgetLayout[number]) { const id = row.map(item => `${item.id}:${item.width}`).join('|'); return id; } trackRowItem(index: number, item: WidgetLayout[number][number]) { return item.config; } addWidget(id: string) { const config = this.dashboardWidgetService.getWidgetById(id); if (config) { const width = this.getSupportedWidths(config)[0]; const widget: WidgetLayout[number][number] = { id, config, width, }; let targetRow: WidgetLayout[number]; if (this.widgetLayout && this.widgetLayout.length) { targetRow = this.widgetLayout[this.widgetLayout.length - 1]; } else { targetRow = []; this.widgetLayout?.push(targetRow); } targetRow.push(widget); this.recalculateLayout(); } } removeWidget(widget: WidgetLayout[number][number]) { widget.id = this.deletionMarker; this.recalculateLayout(); } drop(event: CdkDragDrop<{ index: number }>) { const { currentIndex, previousIndex, previousContainer, container } = event; if (previousIndex === currentIndex && previousContainer.data.index === container.data.index) { // Nothing changed return; } if (this.widgetLayout) { const previousLayoutRow = this.widgetLayout[previousContainer.data.index]; const newLayoutRow = this.widgetLayout[container.data.index]; previousLayoutRow.splice(previousIndex, 1); newLayoutRow.splice(currentIndex, 0, event.item.data); this.recalculateLayout(); } } private initLayout(availableIds: string[]): WidgetLayout { const savedLayoutDef = this.localStorageService.get('dashboardWidgetLayout'); let layoutDef: WidgetLayoutDefinition | undefined; if (savedLayoutDef) { // validate all the IDs from the saved layout are still available layoutDef = savedLayoutDef.filter(item => availableIds.includes(item.id)); } return this.dashboardWidgetService.getWidgetLayout(layoutDef); } private recalculateLayout() { if (this.widgetLayout) { const flattened = this.widgetLayout .reduce((flat, row) => [...flat, ...row], []) .filter(item => item.id !== this.deletionMarker); const newLayoutDef: WidgetLayoutDefinition = flattened.map(item => ({ id: item.id, width: item.width, })); this.widgetLayout = this.dashboardWidgetService.getWidgetLayout(newLayoutDef); this.localStorageService.set('dashboardWidgetLayout', newLayoutDef); setTimeout(() => this.changedDetectorRef.markForCheck()); } } }
import { ChangeDetectionStrategy, Component, NgModule, OnInit } from '@angular/core'; import { CoreModule, DataService, GetLatestOrdersDocument, GetLatestOrdersQuery, GetOrderListQuery, ItemOf, SharedModule, SortOrder, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; const GET_LATEST_ORDERS = gql` query GetLatestOrders($options: OrderListOptions) { orders(options: $options) { items { id createdAt updatedAt type orderPlacedAt code state total totalWithTax currencyCode customer { id firstName lastName } } } } `; @Component({ selector: 'vdr-latest-orders-widget', templateUrl: './latest-orders-widget.component.html', styleUrls: ['./latest-orders-widget.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LatestOrdersWidgetComponent implements OnInit { latestOrders$: Observable<Array<ItemOf<GetLatestOrdersQuery, 'orders'>>>; constructor(private dataService: DataService) {} ngOnInit(): void { this.latestOrders$ = this.dataService .query(GetLatestOrdersDocument, { options: { take: 10, filter: { active: { eq: false }, state: { notIn: ['Cancelled', 'Draft'] }, }, sort: { orderPlacedAt: SortOrder.DESC, }, }, }) .refetchOnChannelChange() .mapStream(data => data.orders.items); } } @NgModule({ imports: [CoreModule, SharedModule], declarations: [LatestOrdersWidgetComponent], }) export class LatestOrdersWidgetModule {}
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ChartEntry, ChartFormatOptions, DataService, GetOrderChartDataDocument, MetricType, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { BehaviorSubject, combineLatest, Observable, Subject, switchMap } from 'rxjs'; import { distinctUntilChanged, map, startWith } from 'rxjs/operators'; export const GET_ORDER_CHART_DATA = gql` query GetOrderChartData($refresh: Boolean, $types: [MetricType!]!) { metricSummary(input: { interval: Daily, types: $types, refresh: $refresh }) { interval type entries { label value } } } `; @Component({ selector: 'vdr-order-chart-widget', templateUrl: './order-chart-widget.component.html', styleUrls: ['./order-chart-widget.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderChartWidgetComponent implements OnInit { constructor(private dataService: DataService) {} metrics$: Observable<ChartEntry[]>; refresh$ = new Subject<boolean>(); metricType$ = new BehaviorSubject(MetricType.OrderTotal); MetricType = MetricType; ngOnInit() { const currencyCode$ = this.dataService.settings .getActiveChannel() .refetchOnChannelChange() .mapStream(data => data.activeChannel.defaultCurrencyCode || undefined); const uiState$ = this.dataService.client.uiState().mapStream(data => data.uiState); const metricType$ = this.metricType$.pipe(distinctUntilChanged()); this.metrics$ = combineLatest(metricType$, currencyCode$, uiState$).pipe( switchMap(([metricType, currencyCode, uiState]) => this.refresh$.pipe( startWith(false), switchMap(refresh => this.dataService .query(GetOrderChartDataDocument, { types: [metricType], refresh, }) .mapSingle(data => data.metricSummary) .pipe( map(metrics => { const formatValueAs: 'currency' | 'number' = metricType === MetricType.OrderCount ? 'number' : 'currency'; const locale = `${uiState.language}-${uiState.locale}`; const formatOptions: ChartFormatOptions = { formatValueAs, currencyCode, locale, }; return ( metrics .find(m => m.type === metricType) ?.entries.map(entry => ({ ...entry, formatOptions })) ?? [] ); }), ), ), ), ), ); } refresh() { this.refresh$.next(true); } }
import { ChangeDetectionStrategy, Component, NgModule, OnInit } from '@angular/core'; import { CoreModule, DataService, GetOrderSummaryDocument } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import dayjs from 'dayjs'; import { BehaviorSubject, Observable } from 'rxjs'; import { distinctUntilChanged, map, shareReplay, switchMap } from 'rxjs/operators'; export type Timeframe = 'day' | 'week' | 'month'; export const GET_ORDER_SUMMARY = gql` query GetOrderSummary($start: DateTime!, $end: DateTime!) { orders(options: { filter: { orderPlacedAt: { between: { start: $start, end: $end } } } }) { totalItems items { id totalWithTax currencyCode } } } `; @Component({ selector: 'vdr-order-summary-widget', templateUrl: './order-summary-widget.component.html', styleUrls: ['./order-summary-widget.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderSummaryWidgetComponent implements OnInit { today = new Date(); yesterday = new Date(new Date().setDate(this.today.getDate() - 1)); totalOrderCount$: Observable<number>; totalOrderValue$: Observable<number>; currencyCode$: Observable<string | undefined>; selection$ = new BehaviorSubject<{ timeframe: Timeframe; date?: Date }>({ timeframe: 'day', date: this.today, }); dateRange$: Observable<{ start: Date; end: Date }>; constructor(private dataService: DataService) {} ngOnInit(): void { this.dateRange$ = this.selection$.pipe( distinctUntilChanged(), map(selection => ({ start: dayjs(selection.date).startOf(selection.timeframe).toDate(), end: dayjs(selection.date).endOf(selection.timeframe).toDate(), })), shareReplay(1), ); const orderSummary$ = this.dateRange$.pipe( switchMap(({ start, end }) => this.dataService .query(GetOrderSummaryDocument, { start: start.toISOString(), end: end.toISOString() }) .refetchOnChannelChange() .mapStream(data => data.orders), ), shareReplay(1), ); this.totalOrderCount$ = orderSummary$.pipe(map(res => res.totalItems)); this.totalOrderValue$ = orderSummary$.pipe( map(res => res.items.reduce((total, order) => total + order.totalWithTax, 0)), ); this.currencyCode$ = this.dataService.settings .getActiveChannel() .refetchOnChannelChange() .mapStream(data => data.activeChannel.defaultCurrencyCode || undefined); } } @NgModule({ imports: [CoreModule], declarations: [OrderSummaryWidgetComponent], }) export class OrderSummaryWidgetModule {}
import { ChangeDetectionStrategy, Component, NgModule } from '@angular/core'; @Component({ selector: 'vdr-test-widget', templateUrl: './test-widget.component.html', styleUrls: ['./test-widget.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class TestWidgetComponent {} @NgModule({ declarations: [TestWidgetComponent], }) export class TestWidgetModule {}
import { ChangeDetectionStrategy, Component, NgModule, OnInit } from '@angular/core'; import { ADMIN_UI_VERSION, CoreModule, DataService, GetActiveAdministratorQuery, getAppConfig, } from '@vendure/admin-ui/core'; import { Observable } from 'rxjs'; @Component({ selector: 'vdr-welcome-widget', templateUrl: './welcome-widget.component.html', styleUrls: ['./welcome-widget.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class WelcomeWidgetComponent implements OnInit { version = ADMIN_UI_VERSION; administrator$: Observable<GetActiveAdministratorQuery['activeAdministrator']>; brand = getAppConfig().brand; hideVendureBranding = getAppConfig().hideVendureBranding; hideVersion = getAppConfig().hideVersion; constructor(private dataService: DataService) {} ngOnInit(): void { this.administrator$ = this.dataService.administrator .getActiveAdministrator() .mapStream(data => data.activeAdministrator || null); } } @NgModule({ imports: [CoreModule], declarations: [WelcomeWidgetComponent], }) export class WelcomeWidgetModule {}
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { SharedModule } from '@vendure/admin-ui/core'; import { LoginComponent } from './components/login/login.component'; import { loginRoutes } from './login.routes'; @NgModule({ imports: [SharedModule, RouterModule.forChild(loginRoutes)], exports: [], declarations: [LoginComponent], }) export class LoginModule {}
import { Routes } from '@angular/router'; import { LoginComponent } from './components/login/login.component'; import { LoginGuard } from './providers/login.guard'; export const loginRoutes: Routes = [ { path: '', component: LoginComponent, pathMatch: 'full', canActivate: [LoginGuard], }, ];
// This file was generated by the build-public-api.ts script export * from './components/login/login.component'; export * from './login.module'; export * from './login.routes'; export * from './providers/login.guard';
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ADMIN_UI_VERSION, AuthService, AUTH_REDIRECT_PARAM, getAppConfig, LocalizationDirectionType, LocalizationService, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit { direction$: LocalizationDirectionType; username = ''; password = ''; rememberMe = false; version = ADMIN_UI_VERSION; errorMessage: string | undefined; brand = getAppConfig().brand; hideVendureBranding = getAppConfig().hideVendureBranding; customImageUrl = getAppConfig().loginImageUrl; imageUrl = ''; imageUnsplashUrl = ''; imageLocation = ''; imageCreator = ''; imageCreatorUrl = ''; constructor( private authService: AuthService, private router: Router, private httpClient: HttpClient, private localizationService: LocalizationService, ) { if (this.customImageUrl) { this.imageUrl = this.customImageUrl; } else { this.loadImage(); } } ngOnInit(): void { this.direction$ = this.localizationService.direction$; } logIn(): void { this.errorMessage = undefined; this.authService.logIn(this.username, this.password, this.rememberMe).subscribe(result => { switch (result.__typename) { case 'CurrentUser': const redirect = this.getRedirectRoute(); this.router.navigateByUrl(redirect ? redirect : '/'); break; case 'InvalidCredentialsError': case 'NativeAuthStrategyError': this.errorMessage = result.message; break; } }); } loadImage() { this.httpClient .get('https://login-image.vendure.io') .toPromise() .then(res => { this.updateImage(res); }); } updateImage(res: any) { const user: any = (res as any).user; const location: any = (res as any).location; this.imageUrl = res.urls.regular + '?utm_source=Vendure+Login+Image&utm_medium=referral'; this.imageCreator = user.name; this.imageLocation = location.name; this.imageCreatorUrl = user.links.html + '?utm_source=Vendure+Login+Image&utm_medium=referral'; this.imageUnsplashUrl = res.links.html; } /** * Attempts to read a redirect param from the current url and parse it into a * route from which the user was redirected after a 401 error. */ private getRedirectRoute(): string | undefined { let redirectTo: string | undefined; const re = new RegExp(`${AUTH_REDIRECT_PARAM}=(.*)`); try { const redirectToParam = window.location.search.match(re); if (redirectToParam && 1 < redirectToParam.length) { redirectTo = atob(decodeURIComponent(redirectToParam[1])); } } catch (e: any) { // ignore } return redirectTo; } }
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { AuthService } from '@vendure/admin-ui/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; /** * This guard prevents loggen-in users from navigating to the login screen. */ @Injectable({ providedIn: 'root', }) export class LoginGuard { constructor(private router: Router, private authService: AuthService) {} canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { return this.authService.checkAuthenticatedStatus().pipe( map(authenticated => { if (authenticated) { this.router.navigate(['/']); } return !authenticated; }), ); } }
import { AsyncPipe } from '@angular/common'; import { NgModule } from '@angular/core'; import { RouterModule, ROUTES } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { BulkActionRegistryService, detailComponentWithResolver, GetPromotionDetailDocument, PageService, SharedModule, } from '@vendure/admin-ui/core'; import { PromotionDetailComponent } from './components/promotion-detail/promotion-detail.component'; import { assignPromotionsToChannelBulkAction, deletePromotionsBulkAction, duplicatePromotionsBulkAction, removePromotionsFromChannelBulkAction, } from './components/promotion-list/promotion-list-bulk-actions'; import { PromotionListComponent } from './components/promotion-list/promotion-list.component'; import { createRoutes } from './marketing.routes'; @NgModule({ imports: [SharedModule, RouterModule.forChild([]), SharedModule, AsyncPipe, SharedModule], providers: [ { provide: ROUTES, useFactory: (pageService: PageService) => createRoutes(pageService), multi: true, deps: [PageService], }, ], declarations: [PromotionListComponent, PromotionDetailComponent], }) export class MarketingModule { private static hasRegisteredTabsAndBulkActions = false; constructor(bulkActionRegistryService: BulkActionRegistryService, pageService: PageService) { if (MarketingModule.hasRegisteredTabsAndBulkActions) { return; } bulkActionRegistryService.registerBulkAction(assignPromotionsToChannelBulkAction); bulkActionRegistryService.registerBulkAction(removePromotionsFromChannelBulkAction); bulkActionRegistryService.registerBulkAction(duplicatePromotionsBulkAction); bulkActionRegistryService.registerBulkAction(deletePromotionsBulkAction); pageService.registerPageTab({ priority: 0, location: 'promotion-list', tab: _('breadcrumb.promotions'), route: '', component: PromotionListComponent, }); pageService.registerPageTab({ priority: 0, location: 'promotion-detail', tab: _('marketing.promotion'), route: '', component: detailComponentWithResolver({ component: PromotionDetailComponent, query: GetPromotionDetailDocument, entityKey: 'promotion', getBreadcrumbs: entity => [ { label: entity ? entity.name : _('marketing.create-new-promotion'), link: [entity?.id], }, ], }), }); MarketingModule.hasRegisteredTabsAndBulkActions = true; } }
import { Route } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { detailBreadcrumb, PageComponent, PageService, PromotionFragment } from '@vendure/admin-ui/core'; export const createRoutes = (pageService: PageService): Route[] => [ { path: 'promotions', component: PageComponent, data: { locationId: 'promotion-list', breadcrumb: _('breadcrumb.promotions'), }, children: pageService.getPageTabRoutes('promotion-list'), }, { path: 'promotions/:id', component: PageComponent, data: { locationId: 'promotion-detail', breadcrumb: { label: _('breadcrumb.promotions'), link: ['../', 'promotions'] }, }, children: pageService.getPageTabRoutes('promotion-detail'), }, ]; export function promotionBreadcrumb(data: any, params: any) { return detailBreadcrumb<PromotionFragment>({ entity: data.entity, id: params.id, breadcrumbKey: 'breadcrumb.promotions', getName: promotion => promotion.name, route: 'promotions', }); }
// This file was generated by the build-public-api.ts script export * from './components/promotion-detail/promotion-detail.component'; export * from './components/promotion-list/promotion-list-bulk-actions'; export * from './components/promotion-list/promotion-list.component'; export * from './marketing.module'; export * from './marketing.routes';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, UntypedFormArray, UntypedFormGroup, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { ConfigurableOperation, ConfigurableOperationDefinition, ConfigurableOperationInput, CreatePromotionInput, createUpdatedTranslatable, DataService, encodeConfigArgValue, findTranslation, getConfigArgValue, getCustomFieldsDefaults, getDefaultConfigArgValue, GetPromotionDetailDocument, LanguageCode, NotificationService, PROMOTION_FRAGMENT, PromotionFragment, TypedBaseDetailComponent, UpdatePromotionInput, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { combineLatest } from 'rxjs'; import { mergeMap, take } from 'rxjs/operators'; export const GET_PROMOTION_DETAIL = gql` query GetPromotionDetail($id: ID!) { promotion(id: $id) { ...Promotion } } ${PROMOTION_FRAGMENT} `; @Component({ selector: 'vdr-promotion-detail', templateUrl: './promotion-detail.component.html', styleUrls: ['./promotion-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PromotionDetailComponent extends TypedBaseDetailComponent<typeof GetPromotionDetailDocument, 'promotion'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Promotion'); detailForm = this.formBuilder.group({ name: ['', Validators.required], description: '', enabled: true, couponCode: null as string | null, perCustomerUsageLimit: null as number | null, usageLimit: null as number | null, startsAt: null, endsAt: null, conditions: this.formBuilder.array([]), actions: this.formBuilder.array([]), customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); conditions: ConfigurableOperation[] = []; actions: ConfigurableOperation[] = []; private allConditions: ConfigurableOperationDefinition[] = []; private allActions: ConfigurableOperationDefinition[] = []; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private formBuilder: FormBuilder, private notificationService: NotificationService, ) { super(); this.customFields = this.getCustomFieldConfig('Promotion'); } ngOnInit() { this.init(); this.dataService.promotion.getPromotionActionsAndConditions().single$.subscribe(data => { this.allActions = data.promotionActions; this.allConditions = data.promotionConditions; this.changeDetector.markForCheck(); }); } ngOnDestroy() { this.destroy(); } getAvailableConditions(): ConfigurableOperationDefinition[] { return this.allConditions.filter(o => !this.conditions.find(c => c.code === o.code)); } getConditionDefinition(condition: ConfigurableOperation): ConfigurableOperationDefinition | undefined { return this.allConditions.find(c => c.code === condition.code); } getAvailableActions(): ConfigurableOperationDefinition[] { return this.allActions.filter(o => !this.actions.find(a => a.code === o.code)); } getActionDefinition(action: ConfigurableOperation): ConfigurableOperationDefinition | undefined { return this.allActions.find(c => c.code === action.code); } saveButtonEnabled(): boolean { return !!( this.detailForm.dirty && this.detailForm.valid && (this.conditions.length !== 0 || this.detailForm.value.couponCode) && this.actions.length !== 0 ); } addCondition(condition: ConfigurableOperation) { this.addOperation('conditions', condition); this.detailForm.markAsDirty(); } addAction(action: ConfigurableOperation) { this.addOperation('actions', action); this.detailForm.markAsDirty(); } removeCondition(condition: ConfigurableOperation) { this.removeOperation('conditions', condition); this.detailForm.markAsDirty(); } removeAction(action: ConfigurableOperation) { this.removeOperation('actions', action); this.detailForm.markAsDirty(); } formArrayOf(key: 'conditions' | 'actions'): UntypedFormArray { return this.detailForm.get(key) as UntypedFormArray; } create() { if (!this.detailForm.dirty) { return; } const input = this.getUpdatedPromotion( { id: '', createdAt: '', updatedAt: '', startsAt: '', endsAt: '', name: '', description: '', couponCode: null, perCustomerUsageLimit: null, usageLimit: null, enabled: false, conditions: [], actions: [], translations: [], }, this.detailForm, this.languageCode, ) as CreatePromotionInput; this.dataService.promotion.createPromotion(input).subscribe( ({ createPromotion }) => { switch (createPromotion.__typename) { case 'Promotion': this.notificationService.success(_('common.notify-create-success'), { entity: 'Promotion', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); this.router.navigate(['../', createPromotion.id], { relativeTo: this.route }); break; case 'MissingConditionsError': this.notificationService.error(createPromotion.message); break; } }, err => { this.notificationService.error(_('common.notify-create-error'), { entity: 'Promotion', }); }, ); } save() { if (!this.detailForm.dirty) { return; } combineLatest(this.entity$, this.languageCode$) .pipe( take(1), mergeMap(([paymentMethod, languageCode]) => { const input = this.getUpdatedPromotion( paymentMethod, this.detailForm, languageCode, ) as UpdatePromotionInput; return this.dataService.promotion.updatePromotion(input); }), ) .subscribe( data => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Promotion', }); this.detailForm.markAsPristine(); this.changeDetector.markForCheck(); }, err => { this.notificationService.error(_('common.notify-update-error'), { entity: 'Promotion', }); }, ); } /** * Given a PaymentMethod and the value of the detailForm, this method creates an updated copy of it which * can then be persisted to the API. */ private getUpdatedPromotion( promotion: PromotionFragment, formGroup: UntypedFormGroup, languageCode: LanguageCode, ): UpdatePromotionInput | CreatePromotionInput { const formValue = formGroup.value; const input = createUpdatedTranslatable({ translatable: promotion, updatedFields: formValue, customFieldConfig: this.customFields, languageCode, defaultTranslation: { languageCode, name: promotion.name || '', description: promotion.description || '', }, }); return { ...input, conditions: this.mapOperationsToInputs(this.conditions, formValue.conditions), actions: this.mapOperationsToInputs(this.actions, formValue.actions), }; } /** * Update the form values when the entity changes. */ protected setFormValues(entity: PromotionFragment, languageCode: LanguageCode): void { const currentTranslation = findTranslation(entity, languageCode); this.detailForm.patchValue({ name: currentTranslation?.name, description: currentTranslation?.description, enabled: entity.enabled, couponCode: entity.couponCode, perCustomerUsageLimit: entity.perCustomerUsageLimit, usageLimit: entity.usageLimit, startsAt: entity.startsAt, endsAt: entity.endsAt, }); entity.conditions.forEach(o => { this.addOperation('conditions', o); }); entity.actions.forEach(o => this.addOperation('actions', o)); if (this.customFields.length) { this.setCustomFieldFormValues( this.customFields, this.detailForm.get('customFields'), entity, currentTranslation, ); } } /** * Maps an array of conditions or actions to the input format expected by the GraphQL API. */ private mapOperationsToInputs( operations: ConfigurableOperation[], formValueOperations: any, ): ConfigurableOperationInput[] { return operations.map((o, i) => ({ code: o.code, arguments: Object.values<any>(formValueOperations[i].args).map((value, j) => ({ name: o.args[j].name, value: encodeConfigArgValue(value), })), })); } /** * Adds a new condition or action to the promotion. */ private addOperation(key: 'conditions' | 'actions', operation: ConfigurableOperation) { const operationsArray = this.formArrayOf(key); const collection = key === 'conditions' ? this.conditions : this.actions; const index = operationsArray.value.findIndex(o => o.code === operation.code); if (index === -1) { const argsHash = operation.args.reduce( (output, arg) => ({ ...output, [arg.name]: getConfigArgValue(arg.value) ?? this.getDefaultArgValue(key, operation, arg.name), }), {}, ); operationsArray.push( this.formBuilder.control({ code: operation.code, args: argsHash, }), ); collection.push({ code: operation.code, args: operation.args.map(a => ({ name: a.name, value: getConfigArgValue(a.value) })), }); } } private getDefaultArgValue( key: 'conditions' | 'actions', operation: ConfigurableOperation, argName: string, ) { const def = key === 'conditions' ? this.allConditions.find(c => c.code === operation.code) : this.allActions.find(a => a.code === operation.code); if (def) { const argDef = def.args.find(a => a.name === argName); if (argDef) { return getDefaultConfigArgValue(argDef); } } throw new Error(`Could not determine default value for "argName"`); } /** * Removes a condition or action from the promotion. */ private removeOperation(key: 'conditions' | 'actions', operation: ConfigurableOperation) { const operationsArray = this.formArrayOf(key); const collection = key === 'conditions' ? this.conditions : this.actions; const index = operationsArray.value.findIndex(o => o.code === operation.code); if (index !== -1) { operationsArray.removeAt(index); collection.splice(index, 1); } } }
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { AssignPromotionsToChannelDocument, BulkAction, createBulkAssignToChannelAction, createBulkDeleteAction, createBulkRemoveFromChannelAction, DuplicateEntityDialogComponent, GetPromotionListQuery, ItemOf, ModalService, Permission, RemovePromotionsFromChannelDocument, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { map } from 'rxjs/operators'; import { PromotionListComponent } from './promotion-list.component'; const ASSIGN_PROMOTIONS_TO_CHANNEL = gql` mutation AssignPromotionsToChannel($input: AssignPromotionsToChannelInput!) { assignPromotionsToChannel(input: $input) { id name } } `; const REMOVE_PROMOTIONS_FROM_CHANNEL = gql` mutation RemovePromotionsFromChannel($input: RemovePromotionsFromChannelInput!) { removePromotionsFromChannel(input: $input) { id name } } `; export const deletePromotionsBulkAction = createBulkDeleteAction<ItemOf<GetPromotionListQuery, 'promotions'>>( { location: 'promotion-list', requiresPermission: Permission.DeletePromotion, getItemName: item => item.name, bulkDelete: (dataService, ids) => dataService.promotion.deletePromotions(ids).pipe(map(res => res.deletePromotions)), }, ); export const assignPromotionsToChannelBulkAction = createBulkAssignToChannelAction< ItemOf<GetPromotionListQuery, 'promotions'> >({ location: 'promotion-list', requiresPermission: Permission.UpdatePromotion, getItemName: item => item.name, bulkAssignToChannel: (dataService, promotionIds, channelIds) => { return channelIds.map(channelId => dataService .mutate(AssignPromotionsToChannelDocument, { input: { channelId, promotionIds, }, }) .pipe(map(res => res.assignPromotionsToChannel)), ); }, }); export const removePromotionsFromChannelBulkAction = createBulkRemoveFromChannelAction< ItemOf<GetPromotionListQuery, 'promotions'> >({ location: 'promotion-list', requiresPermission: Permission.DeleteCatalog, getItemName: item => item.name, bulkRemoveFromChannel: (dataService, promotionIds, channelId) => dataService .mutate(RemovePromotionsFromChannelDocument, { input: { channelId, promotionIds, }, }) .pipe(map(res => res.removePromotionsFromChannel)), }); export const duplicatePromotionsBulkAction: BulkAction< ItemOf<GetPromotionListQuery, 'promotions'>, PromotionListComponent > = { location: 'promotion-list', label: _('common.duplicate'), icon: 'copy', onClick: ({ injector, selection, hostComponent, clearSelection }) => { const modalService = injector.get(ModalService); modalService .fromComponent(DuplicateEntityDialogComponent<ItemOf<GetPromotionListQuery, 'promotions'>>, { locals: { entities: selection, entityName: 'Promotion', title: _('marketing.duplicate-promotions'), getEntityName: entity => entity.name, }, }) .subscribe(result => { if (result) { clearSelection(); hostComponent.refresh(); } }); }, };
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { GetPromotionListDocument, LogicalOperator, PROMOTION_FRAGMENT, PromotionListOptions, PromotionSortParameter, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_PROMOTION_LIST = gql` query GetPromotionList($options: PromotionListOptions) { promotions(options: $options) { items { ...Promotion } totalItems } } ${PROMOTION_FRAGMENT} `; @Component({ selector: 'vdr-promotion-list', templateUrl: './promotion-list.component.html', styleUrls: ['./promotion-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PromotionListComponent extends TypedBaseListComponent<typeof GetPromotionListDocument, 'promotions'> implements OnInit { readonly customFields = this.getCustomFieldConfig('Promotion'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilters([ { name: 'startsAt', type: { kind: 'dateRange' }, label: _('marketing.starts-at'), filterField: 'startsAt', }, { name: 'endsAt', type: { kind: 'dateRange' }, label: _('marketing.ends-at'), filterField: 'endsAt', }, { name: 'enabled', type: { kind: 'boolean' }, label: _('common.enabled'), filterField: 'enabled', }, { name: 'name', type: { kind: 'text' }, label: _('common.name'), filterField: 'name', }, { name: 'couponCode', type: { kind: 'text' }, label: _('marketing.coupon-code'), filterField: 'couponCode', }, { name: 'desc', type: { kind: 'text' }, label: _('common.description'), filterField: 'description', }, { name: 'perCustomerUsageLimit', type: { kind: 'number' }, label: _('marketing.per-customer-limit'), filterField: 'perCustomerUsageLimit', }, { name: 'usageLimit', type: { kind: 'number' }, label: _('marketing.usage-limit'), filterField: 'usageLimit', }, ]) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('createdAt', 'DESC') .addSorts([ { name: 'createdAt' }, { name: 'updatedAt' }, { name: 'startsAt' }, { name: 'endsAt' }, { name: 'name' }, { name: 'couponCode' }, { name: 'perCustomerUsageLimit' }, { name: 'usageLimit' }, ]) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); constructor() { super(); super.configure({ document: GetPromotionListDocument, getItems: data => data.promotions, setVariables: (skip, take) => this.createQueryOptions(skip, take, this.searchTermControl.value), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); } private createQueryOptions( skip: number, take: number, searchTerm: string | null, ): { options: PromotionListOptions } { const filter = this.filters.createFilterInput(); const sort = this.sorts.createSortInput(); let filterOperator = LogicalOperator.AND; if (searchTerm) { filter.couponCode = { contains: searchTerm }; filter.name = { contains: searchTerm }; filterOperator = LogicalOperator.OR; } return { options: { skip, take, filter, filterOperator, sort, }, }; } }
import { NgModule } from '@angular/core'; import { RouterModule, ROUTES } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { detailComponentWithResolver, OrderDetailQueryDocument, OrderType, PageService, SharedModule, } from '@vendure/admin-ui/core'; import { AddManualPaymentDialogComponent } from './components/add-manual-payment-dialog/add-manual-payment-dialog.component'; import { CancelOrderDialogComponent } from './components/cancel-order-dialog/cancel-order-dialog.component'; import { CouponCodeSelectorComponent } from './components/coupon-code-selector/coupon-code-selector.component'; import { DraftOrderDetailComponent } from './components/draft-order-detail/draft-order-detail.component'; import { DraftOrderVariantSelectorComponent } from './components/draft-order-variant-selector/draft-order-variant-selector.component'; import { FulfillOrderDialogComponent } from './components/fulfill-order-dialog/fulfill-order-dialog.component'; import { FulfillmentCardComponent } from './components/fulfillment-card/fulfillment-card.component'; import { FulfillmentDetailComponent } from './components/fulfillment-detail/fulfillment-detail.component'; import { FulfillmentStateLabelComponent } from './components/fulfillment-state-label/fulfillment-state-label.component'; import { LineFulfillmentComponent } from './components/line-fulfillment/line-fulfillment.component'; import { LineRefundsComponent } from './components/line-refunds/line-refunds.component'; import { ModificationDetailComponent } from './components/modification-detail/modification-detail.component'; import { OrderCustomFieldsCardComponent } from './components/order-custom-fields-card/order-custom-fields-card.component'; import { OrderTotalColumnComponent } from './components/order-data-table/order-total-column.component'; import { OrderDetailComponent } from './components/order-detail/order-detail.component'; import { OrderEditorComponent } from './components/order-editor/order-editor.component'; import { OrderEditsPreviewDialogComponent } from './components/order-edits-preview-dialog/order-edits-preview-dialog.component'; import { OrderHistoryEntryHostComponent } from './components/order-history/order-history-entry-host.component'; import { OrderHistoryComponent } from './components/order-history/order-history.component'; import { OrderListComponent } from './components/order-list/order-list.component'; import { OrderPaymentCardComponent } from './components/order-payment-card/order-payment-card.component'; import { OrderProcessGraphDialogComponent } from './components/order-process-graph-dialog/order-process-graph-dialog.component'; import { OrderProcessEdgeComponent } from './components/order-process-graph/order-process-edge.component'; import { OrderProcessGraphComponent } from './components/order-process-graph/order-process-graph.component'; import { OrderProcessNodeComponent } from './components/order-process-graph/order-process-node.component'; import { OrderStateSelectDialogComponent } from './components/order-state-select-dialog/order-state-select-dialog.component'; import { OrderTableComponent } from './components/order-table/order-table.component'; import { PaymentDetailComponent } from './components/payment-detail/payment-detail.component'; import { PaymentStateLabelComponent } from './components/payment-state-label/payment-state-label.component'; import { RefundDetailComponent } from './components/refund-detail/refund-detail.component'; import { RefundOrderDialogComponent } from './components/refund-order-dialog/refund-order-dialog.component'; import { RefundStateLabelComponent } from './components/refund-state-label/refund-state-label.component'; import { SelectAddressDialogComponent } from './components/select-address-dialog/select-address-dialog.component'; import { SelectCustomerDialogComponent } from './components/select-customer-dialog/select-customer-dialog.component'; import { SelectShippingMethodDialogComponent } from './components/select-shipping-method-dialog/select-shipping-method-dialog.component'; import { SellerOrdersCardComponent } from './components/seller-orders-card/seller-orders-card.component'; import { SettleRefundDialogComponent } from './components/settle-refund-dialog/settle-refund-dialog.component'; import { SimpleItemListComponent } from './components/simple-item-list/simple-item-list.component'; import { createRoutes } from './order.routes'; import { OrderDataTableComponent } from './components/order-data-table/order-data-table.component'; import { PaymentForRefundSelectorComponent } from './components/payment-for-refund-selector/payment-for-refund-selector.component'; import { OrderModificationSummaryComponent } from './components/order-modification-summary/order-modification-summary.component'; @NgModule({ imports: [SharedModule, RouterModule.forChild([])], providers: [ { provide: ROUTES, useFactory: (pageService: PageService) => createRoutes(pageService), multi: true, deps: [PageService], }, ], declarations: [ OrderListComponent, OrderDetailComponent, FulfillOrderDialogComponent, LineFulfillmentComponent, RefundOrderDialogComponent, CancelOrderDialogComponent, PaymentStateLabelComponent, LineRefundsComponent, OrderPaymentCardComponent, RefundStateLabelComponent, SettleRefundDialogComponent, OrderHistoryComponent, FulfillmentDetailComponent, PaymentDetailComponent, SimpleItemListComponent, OrderCustomFieldsCardComponent, OrderProcessGraphComponent, OrderProcessNodeComponent, OrderProcessEdgeComponent, OrderProcessGraphDialogComponent, FulfillmentStateLabelComponent, FulfillmentCardComponent, OrderEditorComponent, OrderTableComponent, OrderEditsPreviewDialogComponent, ModificationDetailComponent, AddManualPaymentDialogComponent, OrderStateSelectDialogComponent, DraftOrderDetailComponent, DraftOrderVariantSelectorComponent, SelectCustomerDialogComponent, SelectAddressDialogComponent, CouponCodeSelectorComponent, SelectShippingMethodDialogComponent, OrderHistoryEntryHostComponent, SellerOrdersCardComponent, OrderDataTableComponent, OrderTotalColumnComponent, PaymentForRefundSelectorComponent, OrderModificationSummaryComponent, RefundDetailComponent, ], exports: [OrderCustomFieldsCardComponent], }) export class OrderModule { private static hasRegisteredTabsAndBulkActions = false; constructor(pageService: PageService) { if (OrderModule.hasRegisteredTabsAndBulkActions) { return; } pageService.registerPageTab({ priority: 0, location: 'order-list', tab: _('order.orders'), route: '', component: OrderListComponent, }); pageService.registerPageTab({ priority: 0, location: 'order-detail', tab: _('order.order'), route: '', component: detailComponentWithResolver({ component: OrderDetailComponent, query: OrderDetailQueryDocument, entityKey: 'order', getBreadcrumbs: entity => entity?.type !== OrderType.Seller || !entity?.aggregateOrder ? [ { label: `${entity?.code}`, link: [entity?.id], }, ] : [ { label: `${entity?.aggregateOrder?.code}`, link: ['/orders/', entity?.aggregateOrder?.id], }, { label: _('breadcrumb.seller-orders'), link: ['/orders/', entity?.aggregateOrder?.id], }, { label: `${entity?.code}`, link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'draft-order-detail', tab: _('order.order'), route: '', component: detailComponentWithResolver({ component: DraftOrderDetailComponent, query: OrderDetailQueryDocument, entityKey: 'order', getBreadcrumbs: entity => [ { label: _('order.draft-order'), link: [entity?.id], }, ], }), }); pageService.registerPageTab({ priority: 0, location: 'modify-order', tab: _('order.order'), route: '', component: detailComponentWithResolver({ component: OrderEditorComponent, query: OrderDetailQueryDocument, entityKey: 'order', getBreadcrumbs: entity => [ { label: entity?.code || 'order', link: ['/orders/', entity?.id], }, { label: _('breadcrumb.modifying-order'), link: [entity?.id], }, ], }), }); OrderModule.hasRegisteredTabsAndBulkActions = true; } }
import { Route } from '@angular/router'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { PageComponent, PageService } from '@vendure/admin-ui/core'; import { OrderGuard } from './providers/routing/order.guard'; export const createRoutes = (pageService: PageService): Route[] => [ { path: '', component: PageComponent, pathMatch: 'full', data: { locationId: 'order-list', breadcrumb: _('breadcrumb.orders'), }, children: pageService.getPageTabRoutes('order-list'), }, { path: 'draft/:id', component: PageComponent, canActivate: [OrderGuard], data: { locationId: 'draft-order-detail', breadcrumb: { label: _('breadcrumb.orders'), link: ['../'] }, }, children: pageService.getPageTabRoutes('draft-order-detail'), }, { path: ':id', component: PageComponent, canActivate: [OrderGuard], data: { locationId: 'order-detail', breadcrumb: { label: _('breadcrumb.orders'), link: ['../'] }, }, children: pageService.getPageTabRoutes('order-detail'), }, { path: ':aggregateOrderId/seller-orders/:id', component: PageComponent, canActivate: [OrderGuard], data: { locationId: 'order-detail', breadcrumb: { label: _('breadcrumb.orders'), link: ['../'] }, }, children: pageService.getPageTabRoutes('order-detail'), }, { path: ':id/modify', component: PageComponent, canActivate: [OrderGuard], data: { locationId: 'modify-order', breadcrumb: { label: _('breadcrumb.orders'), link: ['../'] }, }, children: pageService.getPageTabRoutes('modify-order'), }, ];
// This file was generated by the build-public-api.ts script export * from './common/get-refundable-payments'; export * from './common/modify-order-types'; export * from './components/add-manual-payment-dialog/add-manual-payment-dialog.component'; export * from './components/cancel-order-dialog/cancel-order-dialog.component'; export * from './components/coupon-code-selector/coupon-code-selector.component'; export * from './components/draft-order-detail/draft-order-detail.component'; export * from './components/draft-order-variant-selector/draft-order-variant-selector.component'; export * from './components/fulfill-order-dialog/fulfill-order-dialog.component'; export * from './components/fulfillment-card/fulfillment-card.component'; export * from './components/fulfillment-detail/fulfillment-detail.component'; export * from './components/fulfillment-state-label/fulfillment-state-label.component'; export * from './components/line-fulfillment/line-fulfillment.component'; export * from './components/line-refunds/line-refunds.component'; export * from './components/modification-detail/modification-detail.component'; export * from './components/order-custom-fields-card/order-custom-fields-card.component'; export * from './components/order-data-table/order-data-table.component'; export * from './components/order-data-table/order-total-column.component'; export * from './components/order-detail/order-detail.component'; export * from './components/order-editor/order-editor.component'; export * from './components/order-edits-preview-dialog/order-edits-preview-dialog.component'; export * from './components/order-history/order-history-entry-host.component'; export * from './components/order-history/order-history.component'; export * from './components/order-list/order-list.component'; export * from './components/order-modification-summary/order-modification-summary.component'; export * from './components/order-payment-card/order-payment-card.component'; export * from './components/order-process-graph/constants'; export * from './components/order-process-graph/order-process-edge.component'; export * from './components/order-process-graph/order-process-graph.component'; export * from './components/order-process-graph/order-process-node.component'; export * from './components/order-process-graph/types'; export * from './components/order-process-graph-dialog/order-process-graph-dialog.component'; export * from './components/order-state-select-dialog/order-state-select-dialog.component'; export * from './components/order-table/order-table.component'; export * from './components/payment-detail/payment-detail.component'; export * from './components/payment-for-refund-selector/payment-for-refund-selector.component'; export * from './components/payment-state-label/payment-state-label.component'; export * from './components/refund-detail/refund-detail.component'; export * from './components/refund-order-dialog/refund-order-dialog.component'; export * from './components/refund-state-label/refund-state-label.component'; export * from './components/select-address-dialog/select-address-dialog.component'; export * from './components/select-address-dialog/select-address-dialog.graphql'; export * from './components/select-customer-dialog/select-customer-dialog.component'; export * from './components/select-shipping-method-dialog/select-shipping-method-dialog.component'; export * from './components/seller-orders-card/seller-orders-card.component'; export * from './components/seller-orders-card/seller-orders-card.graphql'; export * from './components/settle-refund-dialog/settle-refund-dialog.component'; export * from './components/simple-item-list/simple-item-list.component'; export * from './order.module'; export * from './order.routes'; export * from './providers/order-transition.service'; export * from './providers/routing/order.guard';
import { FormControl, Validators } from '@angular/forms'; import { OrderDetailFragment } from '@vendure/admin-ui/core'; import { summate } from '@vendure/common/lib/shared-utils'; export type Payment = NonNullable<OrderDetailFragment['payments']>[number]; export type RefundablePayment = Payment & { refundableAmount: number; amountToRefundControl: FormControl<number>; selected: boolean; }; export function getRefundablePayments(payments: OrderDetailFragment['payments']): RefundablePayment[] { const settledPayments = (payments || []).filter(p => p.state === 'Settled'); return settledPayments.map((payment, index) => { const refundableAmount = payment.amount - summate( payment.refunds.filter(r => r.state !== 'Failed'), 'total', ); return { ...payment, refundableAmount, amountToRefundControl: new FormControl(0, { nonNullable: true, validators: [Validators.min(0), Validators.max(refundableAmount)], }), selected: index === 0, }; }); }
import { AddItemInput, CurrencyCode, ModifyOrderInput, OrderDetailFragment, OrderLineInput, ProductSelectorSearchQuery, } from '@vendure/admin-ui/core'; export interface OrderSnapshot { totalWithTax: number; currencyCode: CurrencyCode; couponCodes: string[]; lines: OrderDetailFragment['lines']; shippingLines: OrderDetailFragment['shippingLines']; } export type ProductSelectorItem = ProductSelectorSearchQuery['search']['items'][number]; export interface AddedLine { id: string; featuredAsset?: ProductSelectorItem['productAsset'] | null; productVariant: { id: string; name: string; sku: string; }; unitPrice: number; unitPriceWithTax: number; quantity: number; } export type ModifyOrderData = Omit<ModifyOrderInput, 'addItems' | 'adjustOrderLines'> & { addItems: Array<AddItemInput & { customFields?: any }>; adjustOrderLines: Array<OrderLineInput & { customFields?: any }>; };
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { CurrencyCode, DataService, Dialog, GetAddManualPaymentMethodListDocument, GetAddManualPaymentMethodListQuery, GetPaymentMethodListQuery, ItemOf, ManualPaymentInput, PAYMENT_METHOD_FRAGMENT, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { Observable } from 'rxjs'; const GET_PAYMENT_METHODS_FOR_MANUAL_ADD = gql` query GetAddManualPaymentMethodList($options: PaymentMethodListOptions!) { paymentMethods(options: $options) { items { id createdAt updatedAt name code description enabled } totalItems } } `; @Component({ selector: 'vdr-add-manual-payment-dialog', templateUrl: './add-manual-payment-dialog.component.html', styleUrls: ['./add-manual-payment-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class AddManualPaymentDialogComponent implements OnInit, Dialog<Omit<ManualPaymentInput, 'orderId'>> { // populated by ModalService call outstandingAmount: number; currencyCode: CurrencyCode; resolveWith: (result?: Omit<ManualPaymentInput, 'orderId'>) => void; form = new UntypedFormGroup({ method: new UntypedFormControl('', Validators.required), transactionId: new UntypedFormControl('', Validators.required), }); paymentMethods$: Observable<Array<ItemOf<GetAddManualPaymentMethodListQuery, 'paymentMethods'>>>; constructor(private dataService: DataService) {} ngOnInit(): void { this.paymentMethods$ = this.dataService .query(GetAddManualPaymentMethodListDocument, { options: { take: 999, }, }) .mapSingle(data => data.paymentMethods.items); } submit() { const formValue = this.form.value; this.resolveWith({ method: formValue.method, transactionId: formValue.transactionId, }); } cancel() { this.resolveWith(); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CancelOrderInput, Dialog, getAppConfig, I18nService, OrderDetailFragment, OrderLineInput, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-cancel-order-dialog', templateUrl: './cancel-order-dialog.component.html', styleUrls: ['./cancel-order-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CancelOrderDialogComponent implements OnInit, Dialog<CancelOrderInput> { order: OrderDetailFragment; cancelAll = true; resolveWith: (result?: CancelOrderInput) => void; reason: string; lineQuantities: { [lineId: string]: number } = {}; reasons: string[] = getAppConfig().cancellationReasons ?? [ _('order.cancel-reason-customer-request'), _('order.cancel-reason-not-available'), ]; get selectionCount(): number { return Object.values(this.lineQuantities).reduce((sum, n) => sum + n, 0); } constructor(private i18nService: I18nService) { this.reasons = this.reasons.map(r => this.i18nService.translate(r)); } ngOnInit() { this.lineQuantities = this.order.lines.reduce( (result, line) => ({ ...result, [line.id]: line.quantity }), {}, ); } radioChanged() { if (this.cancelAll) { for (const line of this.order.lines) { this.lineQuantities[line.id] = line.quantity; } } else { for (const line of this.order.lines) { this.lineQuantities[line.id] = 0; } } } checkIfAllSelected() { for (const [lineId, quantity] of Object.entries(this.lineQuantities)) { const quantityInOrder = this.order.lines.find(line => line.id === lineId)?.quantity; if (quantityInOrder && quantity < quantityInOrder) { return; } } // If we got here, all of the selected quantities are equal to the order // line quantities, i.e. everything is selected. this.cancelAll = true; } select() { this.resolveWith({ orderId: this.order.id, lines: this.getLineInputs(), reason: this.reason, cancelShipping: this.cancelAll, }); } cancel() { this.resolveWith(); } private getLineInputs(): OrderLineInput[] | undefined { if (this.order.active) { return; } return Object.entries(this.lineQuantities) .map(([orderLineId, quantity]) => ({ orderLineId, quantity, })) .filter(l => 0 < l.quantity); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { DataService, GetCouponCodeSelectorPromotionListDocument, PROMOTION_FRAGMENT, } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; import { concat, Observable, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, map, skip, startWith, switchMap } from 'rxjs/operators'; export const GET_COUPON_CODE_SELECTOR_PROMOTION_LIST = gql` query GetCouponCodeSelectorPromotionList($options: PromotionListOptions) { promotions(options: $options) { items { id name couponCode } totalItems } } `; @Component({ selector: 'vdr-coupon-code-selector', templateUrl: './coupon-code-selector.component.html', styleUrls: ['./coupon-code-selector.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class CouponCodeSelectorComponent implements OnInit { @Input() couponCodes: string[]; @Input() control: UntypedFormControl | undefined; @Output() addCouponCode = new EventEmitter<string>(); @Output() removeCouponCode = new EventEmitter<string>(); availableCouponCodes$: Observable<Array<{ code: string; promotionName: string }>>; couponCodeInput$ = new Subject<string>(); constructor(private dataService: DataService) {} ngOnInit(): void { this.availableCouponCodes$ = concat( this.couponCodeInput$.pipe( debounceTime(200), distinctUntilChanged(), switchMap( term => this.dataService.query(GetCouponCodeSelectorPromotionListDocument, { options: { take: 10, skip: 0, filter: { couponCode: { contains: term }, }, }, }).single$, ), map(({ promotions }) => // eslint-disable-next-line @typescript-eslint/no-non-null-assertion promotions.items.map(p => ({ code: p.couponCode!, promotionName: p.name })), ), startWith([]), ), ); if (!this.control) { this.control = new UntypedFormControl(this.couponCodes ?? []); } } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { UntypedFormGroup } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DataService, DeletionResult, DraftOrderEligibleShippingMethodsQuery, ModalService, NotificationService, Order, OrderDetailFragment, OrderDetailQueryDocument, TypedBaseDetailComponent, } from '@vendure/admin-ui/core'; import { combineLatest, Observable, Subject } from 'rxjs'; import { switchMap, take } from 'rxjs/operators'; import { OrderTransitionService } from '../../providers/order-transition.service'; import { SelectAddressDialogComponent } from '../select-address-dialog/select-address-dialog.component'; import { SelectCustomerDialogComponent } from '../select-customer-dialog/select-customer-dialog.component'; import { SelectShippingMethodDialogComponent } from '../select-shipping-method-dialog/select-shipping-method-dialog.component'; @Component({ selector: 'vdr-draft-order-detail', templateUrl: './draft-order-detail.component.html', styleUrls: ['./draft-order-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DraftOrderDetailComponent extends TypedBaseDetailComponent<typeof OrderDetailQueryDocument, 'order'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Order'); orderLineCustomFields = this.getCustomFieldConfig('OrderLine'); detailForm = new UntypedFormGroup({}); eligibleShippingMethods$: Observable< DraftOrderEligibleShippingMethodsQuery['eligibleShippingMethodsForDraftOrder'] >; nextStates$: Observable<string[]>; fetchHistory = new Subject<void>(); displayCouponCodeInput = false; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private notificationService: NotificationService, private modalService: ModalService, private orderTransitionService: OrderTransitionService, ) { super(); } ngOnInit() { this.init(); this.orderLineCustomFields = this.getCustomFieldConfig('OrderLine'); this.eligibleShippingMethods$ = this.entity$.pipe( switchMap(order => this.dataService.order .getDraftOrderEligibleShippingMethods(order.id) .mapSingle( ({ eligibleShippingMethodsForDraftOrder }) => eligibleShippingMethodsForDraftOrder, ), ), ); } ngOnDestroy() { this.destroy(); } addItemToOrder(event: { productVariantId: string; quantity: number; customFields: any }) { this.dataService.order.addItemToDraftOrder(this.id, event).subscribe(result => { if (result.addItemToDraftOrder.__typename !== 'Order') { this.notificationService.error((result.addItemToDraftOrder as any).message); } }); } adjustOrderLine(event: { lineId: string; quantity: number }) { this.dataService.order .adjustDraftOrderLine(this.id, { orderLineId: event.lineId, quantity: event.quantity }) .subscribe(result => { if (result.adjustDraftOrderLine.__typename !== 'Order') { this.notificationService.error((result.adjustDraftOrderLine as any).message); } }); } removeOrderLine(event: { lineId: string }) { this.dataService.order.removeDraftOrderLine(this.id, event.lineId).subscribe(result => { if (result.removeDraftOrderLine.__typename !== 'Order') { this.notificationService.error((result.removeDraftOrderLine as any).message); } }); } getOrderAddressLines(orderAddress?: { [key: string]: string }): string[] { if (!orderAddress) { return []; } return Object.values(orderAddress) .filter(val => val !== 'OrderAddress') .filter(line => !!line); } setCustomer() { this.modalService.fromComponent(SelectCustomerDialogComponent).subscribe(result => { if (this.hasId(result)) { this.dataService.order .setCustomerForDraftOrder(this.id, { customerId: result.id }) .subscribe(); } else if (result) { const { note, ...input } = result; this.dataService.order.setCustomerForDraftOrder(this.id, { input }).subscribe(); } }); } setShippingAddress() { this.entity$ .pipe( take(1), switchMap(order => this.modalService.fromComponent(SelectAddressDialogComponent, { locals: { customerId: order.customer?.id, currentAddress: order.shippingAddress ?? undefined, }, }), ), ) .subscribe(result => { if (result) { this.dataService.order.setDraftOrderShippingAddress(this.id, result).subscribe(); } }); } setBillingAddress() { this.entity$ .pipe( take(1), switchMap(order => this.modalService.fromComponent(SelectAddressDialogComponent, { locals: { customerId: order.customer?.id, currentAddress: order.billingAddress ?? undefined, }, }), ), ) .subscribe(result => { if (result) { this.dataService.order.setDraftOrderBillingAddress(this.id, result).subscribe(); } }); } applyCouponCode(couponCode: string) { this.dataService.order.applyCouponCodeToDraftOrder(this.id, couponCode).subscribe(); } removeCouponCode(couponCode: string) { this.dataService.order.removeCouponCodeFromDraftOrder(this.id, couponCode).subscribe(); } setShippingMethod() { combineLatest(this.entity$, this.eligibleShippingMethods$) .pipe( take(1), switchMap(([order, methods]) => this.modalService.fromComponent(SelectShippingMethodDialogComponent, { locals: { eligibleShippingMethods: methods, currencyCode: order.currencyCode, currentSelectionId: order.shippingLines?.[0]?.shippingMethod.id, }, }), ), ) .subscribe(result => { if (result) { this.dataService.order.setDraftOrderShippingMethod(this.id, result).subscribe(); } }); } updateCustomFields(customFieldsValue: any) { this.dataService.order .updateOrderCustomFields({ id: this.id, customFields: customFieldsValue, }) .subscribe(); } deleteOrder() { this.dataService.order.deleteDraftOrder(this.id).subscribe(({ deleteDraftOrder }) => { if (deleteDraftOrder.result === DeletionResult.DELETED) { this.notificationService.success(_('common.notify-delete-success'), { entity: 'Order', }); this.router.navigate(['/orders']); } else if (deleteDraftOrder.message) { this.notificationService.error(deleteDraftOrder.message); } }); } completeOrder() { this.dataService.order .transitionToState(this.id, 'ArrangingPayment') .subscribe(({ transitionOrderToState }) => { if (transitionOrderToState?.__typename === 'Order') { this.router.navigate(['/orders', this.id]); } else if (transitionOrderToState?.__typename === 'OrderStateTransitionError') { this.notificationService.error(transitionOrderToState.transitionError); } }); } private hasId<T extends { id: string }>(input: T | any): input is { id: string } { return typeof input === 'object' && !!input.id; } protected setFormValues(entity: OrderDetailFragment): void { // empty } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { CurrencyCode, CustomFieldConfig, DataService, GetProductVariantQuery } from '@vendure/admin-ui/core'; import { Observable, Subject } from 'rxjs'; import { switchMap } from 'rxjs/operators'; @Component({ selector: 'vdr-draft-order-variant-selector', templateUrl: './draft-order-variant-selector.component.html', styleUrls: ['./draft-order-variant-selector.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DraftOrderVariantSelectorComponent implements OnInit { @Input() currencyCode: CurrencyCode; @Input() orderLineCustomFields: CustomFieldConfig[]; @Output() addItem = new EventEmitter<{ productVariantId: string; quantity: number; customFields: any }>(); customFieldsFormGroup = new UntypedFormGroup({}); selectedVariant$: Observable<GetProductVariantQuery['productVariant']>; selectedVariantId$ = new Subject<string | undefined>(); quantity = 1; constructor(private dataService: DataService) {} ngOnInit(): void { this.selectedVariant$ = this.selectedVariantId$.pipe( switchMap(id => { if (id) { return this.dataService.product .getProductVariant(id) .mapSingle(({ productVariant }) => productVariant); } else { return [undefined]; } }), ); for (const customField of this.orderLineCustomFields) { this.customFieldsFormGroup.addControl(customField.name, new UntypedFormControl('')); } } addItemClick(selectedVariant: GetProductVariantQuery['productVariant']) { if (selectedVariant) { this.addItem.emit({ productVariantId: selectedVariant.id, quantity: this.quantity, customFields: this.orderLineCustomFields.length ? this.customFieldsFormGroup.value : undefined, }); this.selectedVariantId$.next(undefined); this.customFieldsFormGroup.reset(); } } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { UntypedFormControl } from '@angular/forms'; import { configurableDefinitionToInstance, ConfigurableOperation, ConfigurableOperationDefinition, configurableOperationValueIsValid, DataService, Dialog, FulfillOrderInput, GlobalFlag, OrderDetailFragment, toConfigurableOperationInput, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-fulfill-order-dialog', templateUrl: './fulfill-order-dialog.component.html', styleUrls: ['./fulfill-order-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FulfillOrderDialogComponent implements Dialog<FulfillOrderInput>, OnInit { resolveWith: (result?: FulfillOrderInput) => void; fulfillmentHandlerDef: ConfigurableOperationDefinition; fulfillmentHandler: ConfigurableOperation; fulfillmentHandlerControl = new UntypedFormControl(); fulfillmentQuantities: { [lineId: string]: { fulfillCount: number; max: number } } = {}; // Provided by modalService.fromComponent() call order: OrderDetailFragment; constructor(private dataService: DataService, private changeDetector: ChangeDetectorRef) {} ngOnInit(): void { this.dataService.settings.getGlobalSettings().single$.subscribe(({ globalSettings }) => { this.fulfillmentQuantities = this.order.lines.reduce((result, line) => { const fulfillCount = this.getFulfillableCount(line, globalSettings.trackInventory); return { ...result, [line.id]: { fulfillCount, max: fulfillCount }, }; }, {}); this.changeDetector.markForCheck(); }); this.dataService.shippingMethod .getShippingMethodOperations() .mapSingle(data => data.fulfillmentHandlers) .subscribe(handlers => { this.fulfillmentHandlerDef = handlers.find( h => h.code === this.order.shippingLines[0]?.shippingMethod?.fulfillmentHandlerCode, ) || handlers[0]; this.fulfillmentHandler = configurableDefinitionToInstance(this.fulfillmentHandlerDef); this.fulfillmentHandlerControl.patchValue(this.fulfillmentHandler); this.changeDetector.markForCheck(); }); } getFulfillableCount(line: OrderDetailFragment['lines'][number], globalTrackInventory: boolean): number { const { trackInventory, stockOnHand } = line.productVariant; const effectiveTracInventory = trackInventory === GlobalFlag.INHERIT ? globalTrackInventory : trackInventory === GlobalFlag.TRUE; const unfulfilledCount = this.getUnfulfilledCount(line); return effectiveTracInventory ? Math.min(unfulfilledCount, stockOnHand) : unfulfilledCount; } getUnfulfilledCount(line: OrderDetailFragment['lines'][number]): number { const fulfilled = this.order.fulfillments ?.filter(f => f.state !== 'Cancelled') .map(f => f.lines) .flat() .filter(row => row.orderLineId === line.id) .reduce((sum, row) => sum + row.quantity, 0) ?? 0; return line.quantity - fulfilled; } canSubmit(): boolean { const totalCount = Object.values(this.fulfillmentQuantities).reduce( (total, { fulfillCount }) => total + fulfillCount, 0, ); const fulfillmentQuantityIsValid = Object.values(this.fulfillmentQuantities).every( ({ fulfillCount, max }) => fulfillCount <= max, ); const formIsValid = configurableOperationValueIsValid( this.fulfillmentHandlerDef, this.fulfillmentHandlerControl.value, ) && this.fulfillmentHandlerControl.valid; return formIsValid && 0 < totalCount && fulfillmentQuantityIsValid; } select() { const lines = Object.entries(this.fulfillmentQuantities).map(([orderLineId, { fulfillCount }]) => ({ orderLineId, quantity: fulfillCount, })); this.resolveWith({ lines, handler: toConfigurableOperationInput( this.fulfillmentHandler, this.fulfillmentHandlerControl.value, ), }); } cancel() { this.resolveWith(); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { FulfillmentFragment, OrderDetailFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-fulfillment-card', templateUrl: './fulfillment-card.component.html', styleUrls: ['./fulfillment-card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FulfillmentCardComponent { @Input() fulfillment: FulfillmentFragment | undefined; @Input() order: OrderDetailFragment; @Output() transitionState = new EventEmitter<string>(); nextSuggestedState(): string | undefined { if (!this.fulfillment) { return; } const { nextStates } = this.fulfillment; const namedStateOrDefault = (targetState: string) => nextStates.includes(targetState) ? targetState : nextStates[0]; switch (this.fulfillment?.state) { case 'Pending': return namedStateOrDefault('Shipped'); case 'Shipped': return namedStateOrDefault('Delivered'); default: return nextStates.find(s => s !== 'Cancelled'); } } nextOtherStates(): string[] { if (!this.fulfillment) { return []; } const suggested = this.nextSuggestedState(); return this.fulfillment.nextStates.filter(s => s !== suggested); } }
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { CustomFieldConfig, OrderDetailFragment, ServerConfigService } from '@vendure/admin-ui/core'; import { isObject } from '@vendure/common/lib/shared-utils'; @Component({ selector: 'vdr-fulfillment-detail', templateUrl: './fulfillment-detail.component.html', styleUrls: ['./fulfillment-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FulfillmentDetailComponent implements OnInit, OnChanges { @Input() fulfillmentId: string; @Input() order: OrderDetailFragment; customFieldConfig: CustomFieldConfig[] = []; customFieldFormGroup = new UntypedFormGroup({}); constructor(private serverConfigService: ServerConfigService) {} ngOnInit() { this.customFieldConfig = this.serverConfigService.getCustomFieldsFor('Fulfillment'); } ngOnChanges(changes: SimpleChanges) { this.buildCustomFieldsFormGroup(); } get fulfillment(): NonNullable<OrderDetailFragment['fulfillments']>[number] | undefined | null { return this.order.fulfillments && this.order.fulfillments.find(f => f.id === this.fulfillmentId); } get items(): Array<{ name: string; quantity: number }> { return ( this.fulfillment?.lines.map(row => ({ name: this.order.lines.find(line => line.id === row.orderLineId)?.productVariant.name ?? '', quantity: row.quantity, })) ?? [] ); } buildCustomFieldsFormGroup() { const customFields = (this.fulfillment as any).customFields; for (const fieldDef of this.serverConfigService.getCustomFieldsFor('Fulfillment')) { this.customFieldFormGroup.addControl( fieldDef.name, new UntypedFormControl(customFields[fieldDef.name]), ); } } customFieldIsObject(customField: unknown) { return Array.isArray(customField) || isObject(customField); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-fulfillment-state-label', templateUrl: './fulfillment-state-label.component.html', styleUrls: ['./fulfillment-state-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FulfillmentStateLabelComponent { @Input() state: string; get chipColorType() { switch (this.state) { case 'Pending': case 'Shipped': return 'warning'; case 'Delivered': return 'success'; case 'Cancelled': return 'error'; } } }
import { ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { OrderDetailFragment } from '@vendure/admin-ui/core'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { unique } from '@vendure/common/lib/unique'; export type FulfillmentStatus = 'full' | 'partial' | 'none'; type Fulfillment = NonNullable<OrderDetailFragment['fulfillments']>[number]; @Component({ selector: 'vdr-line-fulfillment', templateUrl: './line-fulfillment.component.html', styleUrls: ['./line-fulfillment.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LineFulfillmentComponent implements OnChanges { @Input() line: OrderDetailFragment['lines'][number]; @Input() allOrderFulfillments: OrderDetailFragment['fulfillments']; @Input() orderState: string; fulfilledCount = 0; fulfillmentStatus: FulfillmentStatus; fulfillments: Array<{ count: number; fulfillment: Fulfillment; }> = []; ngOnChanges(changes: SimpleChanges): void { if (this.line) { this.fulfilledCount = this.getDeliveredCount(this.line); this.fulfillmentStatus = this.getFulfillmentStatus(this.fulfilledCount, this.line.quantity); this.fulfillments = this.getFulfillments(this.line); } } /** * Returns the number of items in an OrderLine which are fulfilled. */ private getDeliveredCount(line: OrderDetailFragment['lines'][number]): number { return ( line.fulfillmentLines?.reduce((sum, fulfillmentLine) => sum + fulfillmentLine.quantity, 0) ?? 0 ); } private getFulfillmentStatus(fulfilledCount: number, lineQuantity: number): FulfillmentStatus { if (fulfilledCount === lineQuantity) { return 'full'; } if (0 < fulfilledCount && fulfilledCount < lineQuantity) { return 'partial'; } return 'none'; } private getFulfillments( line: OrderDetailFragment['lines'][number], ): Array<{ count: number; fulfillment: NonNullable<OrderDetailFragment['fulfillments']>[number] }> { return ( line.fulfillmentLines ?.map(fulfillmentLine => { const fulfillment = this.allOrderFulfillments?.find( f => f.id === fulfillmentLine.fulfillmentId, ); if (!fulfillment) { return; } return { count: fulfillmentLine.quantity, fulfillment, }; }) .filter(notNullOrUndefined) ?? [] ); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { OrderDetailFragment, PaymentWithRefundsFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-line-refunds', templateUrl: './line-refunds.component.html', styleUrls: ['./line-refunds.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class LineRefundsComponent { @Input() line: OrderDetailFragment['lines'][number]; @Input() payments: PaymentWithRefundsFragment[]; getRefundedCount(): number { const refundLines = this.payments ?.reduce( (all, payment) => [...all, ...payment.refunds], [] as PaymentWithRefundsFragment['refunds'], ) .filter(refund => refund.state !== 'Failed') .reduce( (all, refund) => [...all, ...refund.lines], [] as Array<{ orderLineId: string; quantity: number }>, ) ?? []; return refundLines .filter(i => i.orderLineId === this.line.id) .reduce((sum, i) => sum + i.quantity, 0); } }
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnInit } from '@angular/core'; import { OrderDetailFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-modification-detail', templateUrl: './modification-detail.component.html', styleUrls: ['./modification-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ModificationDetailComponent implements OnChanges { @Input() order: OrderDetailFragment; @Input() modification: OrderDetailFragment['modifications'][number]; private addedItems = new Map<OrderDetailFragment['lines'][number], number>(); private removedItems = new Map<OrderDetailFragment['lines'][number], number>(); private modifiedItems = new Set<OrderDetailFragment['lines'][number]>(); ngOnChanges(): void { const { added, removed, modified } = this.getModifiedLines(); this.addedItems = added; this.removedItems = removed; this.modifiedItems = modified; } getSurcharge(id: string) { return this.order.surcharges.find(m => m.id === id); } getAddedItems() { return [...this.addedItems.entries()].map(([line, count]) => ({ name: line.productVariant.name, quantity: count, })); } getRemovedItems() { return [...this.removedItems.entries()].map(([line, count]) => ({ name: line.productVariant.name, quantity: count, })); } getModifiedItems() { return [...this.modifiedItems].map(line => ({ name: line.productVariant.name, })); } private getModifiedLines() { const added = new Map<OrderDetailFragment['lines'][number], number>(); const removed = new Map<OrderDetailFragment['lines'][number], number>(); const modified = new Set<OrderDetailFragment['lines'][number]>(); for (const modificationLine of this.modification.lines || []) { const line = this.order.lines.find(l => l.id === modificationLine.orderLineId); if (!line) { continue; } if (modificationLine.quantity === 0) { modified.add(line); } else if (modificationLine.quantity < 0) { removed.set(line, -modificationLine.quantity); } else { added.set(line, modificationLine.quantity); } } return { added, removed, modified }; } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CustomFieldConfig, ModalService } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-order-custom-fields-card', templateUrl: './order-custom-fields-card.component.html', styleUrls: ['./order-custom-fields-card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderCustomFieldsCardComponent implements OnInit { @Input() customFieldsConfig: CustomFieldConfig[] = []; @Input() customFieldValues: { [name: string]: any } = {}; @Output() updateClick = new EventEmitter<any>(); customFieldForm: UntypedFormGroup; editable = false; constructor(private formBuilder: UntypedFormBuilder, private modalService: ModalService) {} ngOnInit() { this.customFieldForm = this.formBuilder.group({}); for (const field of this.customFieldsConfig) { this.customFieldForm.addControl( field.name, this.formBuilder.control(this.customFieldValues[field.name]), ); } } onUpdateClick() { this.updateClick.emit(this.customFieldForm.value); this.customFieldForm.markAsPristine(); this.editable = false; } onCancelClick() { if (this.customFieldForm.dirty) { this.modalService .dialog({ title: _('catalog.confirm-cancel'), buttons: [ { type: 'secondary', label: _('common.keep-editing') }, { type: 'danger', label: _('common.discard-changes'), returnValue: true }, ], }) .subscribe(result => { if (result) { this.customFieldForm.reset(); this.customFieldForm.markAsPristine(); this.editable = false; } }); } else { this.editable = false; } } }
import { ChangeDetectionStrategy, Component, ContentChildren, Input, QueryList } from '@angular/core'; import { DataTable2ColumnComponent, DataTable2Component, OrderDetailFragment } from '@vendure/admin-ui/core'; import { OrderTotalColumnComponent } from './order-total-column.component'; @Component({ selector: 'vdr-order-data-table', templateUrl: './order-data-table.component.html', styleUrls: [ '../../../../core/src/shared/components/data-table-2/data-table2.component.scss', './order-data-table.component.scss', ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderDataTableComponent extends DataTable2Component<OrderDetailFragment> { @ContentChildren(OrderTotalColumnComponent) totalColumns: QueryList<OrderTotalColumnComponent<any>>; @Input() order: OrderDetailFragment; get allColumns() { return [...(this.columns ?? []), ...(this.customFieldColumns ?? []), ...(this.totalColumns ?? [])]; } get sortedColumns() { const columns = this.allColumns; const dataTableConfig = this.getDataTableConfig(); for (const [id, index] of Object.entries(dataTableConfig[this.id].order)) { const column = columns.find(c => c.id === id); const currentIndex = columns.findIndex(c => c.id === id); if (currentIndex !== -1 && column) { columns.splice(currentIndex, 1); columns.splice(index, 0, column); } } return columns; } getPromotionLink(promotion: OrderDetailFragment['discounts'][number]): any[] { const id = promotion.adjustmentSource.split(':')[1]; return ['/marketing', 'promotions', id]; } getCouponCodeForAdjustment( order: OrderDetailFragment, promotionAdjustment: OrderDetailFragment['discounts'][number], ): string | undefined { const id = promotionAdjustment.adjustmentSource.split(':')[1]; const promotion = order.promotions.find(p => p.id === id); if (promotion) { return promotion.couponCode || undefined; } } getShippingNames(order: OrderDetailFragment) { if (order.shippingLines.length) { return order.shippingLines.map(shippingLine => shippingLine.shippingMethod.name).join(', '); } else { return ''; } } }
import { Component } from '@angular/core'; import { DataTable2ColumnComponent } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-order-total-column', template: ``, exportAs: 'row', }) export class OrderTotalColumnComponent<T> extends DataTable2ColumnComponent<T> { orderable = false; }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { DataService, EditNoteDialogComponent, FulfillmentFragment, getCustomFieldsDefaults, GetOrderHistoryQuery, GetOrderQuery, ModalService, NotificationService, ORDER_DETAIL_FRAGMENT, OrderDetailFragment, OrderDetailQueryDocument, Refund, SetOrderCustomerDocument, SortOrder, TimelineHistoryEntry, TypedBaseDetailComponent, } from '@vendure/admin-ui/core'; import { assertNever, summate } from '@vendure/common/lib/shared-utils'; import { gql } from 'apollo-angular'; import { EMPTY, forkJoin, Observable, of, Subject } from 'rxjs'; import { map, mapTo, startWith, switchMap, take } from 'rxjs/operators'; import { OrderTransitionService } from '../../providers/order-transition.service'; import { AddManualPaymentDialogComponent } from '../add-manual-payment-dialog/add-manual-payment-dialog.component'; import { CancelOrderDialogComponent } from '../cancel-order-dialog/cancel-order-dialog.component'; import { FulfillOrderDialogComponent } from '../fulfill-order-dialog/fulfill-order-dialog.component'; import { OrderProcessGraphDialogComponent } from '../order-process-graph-dialog/order-process-graph-dialog.component'; import { RefundOrderDialogComponent } from '../refund-order-dialog/refund-order-dialog.component'; import { SelectCustomerDialogComponent } from '../select-customer-dialog/select-customer-dialog.component'; import { SettleRefundDialogComponent } from '../settle-refund-dialog/settle-refund-dialog.component'; type Payment = NonNullable<OrderDetailFragment['payments']>[number]; export const ORDER_DETAIL_QUERY = gql` query OrderDetailQuery($id: ID!) { order(id: $id) { ...OrderDetail } } ${ORDER_DETAIL_FRAGMENT} `; export const SET_ORDER_CUSTOMER_MUTATION = gql` mutation SetOrderCustomer($input: SetOrderCustomerInput!) { setOrderCustomer(input: $input) { id customer { id firstName lastName emailAddress } } } `; @Component({ selector: 'vdr-order-detail', templateUrl: './order-detail.component.html', styleUrls: ['./order-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderDetailComponent extends TypedBaseDetailComponent<typeof OrderDetailQueryDocument, 'order'> implements OnInit, OnDestroy { customFields = this.getCustomFieldConfig('Order'); orderLineCustomFields = this.getCustomFieldConfig('OrderLine'); detailForm = new FormGroup({ customFields: this.formBuilder.group(getCustomFieldsDefaults(this.customFields)), }); history$: Observable<NonNullable<GetOrderHistoryQuery['order']>['history']['items'] | undefined>; nextStates$: Observable<string[]>; fetchHistory = new Subject<void>(); private readonly defaultStates = [ 'AddingItems', 'ArrangingPayment', 'PaymentAuthorized', 'PaymentSettled', 'PartiallyShipped', 'Shipped', 'PartiallyDelivered', 'Delivered', 'Cancelled', 'Modifying', 'ArrangingAdditionalPayment', ]; constructor( private changeDetector: ChangeDetectorRef, protected dataService: DataService, private notificationService: NotificationService, private modalService: ModalService, private orderTransitionService: OrderTransitionService, private formBuilder: FormBuilder, ) { super(); } ngOnInit() { this.init(); this.entity$.pipe(take(1)).subscribe(order => { if (order.state === 'Modifying') { this.router.navigate(['./', 'modify'], { relativeTo: this.route }); } }); this.history$ = this.fetchHistory.pipe( startWith(null), switchMap(() => this.dataService.order .getOrderHistory(this.id, { sort: { createdAt: SortOrder.DESC, }, }) .mapStream(data => data.order?.history.items), ), ); this.nextStates$ = this.entity$.pipe( map(order => { const isInCustomState = !this.defaultStates.includes(order.state); return isInCustomState ? order.nextStates : order.nextStates.filter(s => !this.defaultStates.includes(s)); }), ); } ngOnDestroy() { this.destroy(); } openStateDiagram() { this.entity$ .pipe( take(1), switchMap(order => this.modalService.fromComponent(OrderProcessGraphDialogComponent, { closable: true, locals: { activeState: order.state, }, }), ), ) .subscribe(); } setOrderCustomer() { this.modalService .fromComponent(SelectCustomerDialogComponent, { locals: { canCreateNew: false, includeNoteInput: true, title: _('order.assign-order-to-another-customer'), }, }) .pipe( switchMap(result => { function isExisting(input: any): input is { id: string } { return typeof input === 'object' && !!input.id; } if (isExisting(result)) { return this.dataService.mutate(SetOrderCustomerDocument, { input: { customerId: result.id, orderId: this.id, note: result.note, }, }); } else { return EMPTY; } }), switchMap(result => this.refetchOrder(result)), ) .subscribe(result => { if (result) { this.notificationService.success(_('order.set-customer-success')); } }); } transitionToState(state: string) { this.dataService.order.transitionToState(this.id, state).subscribe(({ transitionOrderToState }) => { switch (transitionOrderToState?.__typename) { case 'Order': this.notificationService.success(_('order.transitioned-to-state-success'), { state }); this.fetchHistory.next(); break; case 'OrderStateTransitionError': this.notificationService.error(transitionOrderToState.transitionError); } }); } manuallyTransitionToState(order: OrderDetailFragment) { this.orderTransitionService .manuallyTransitionToState({ orderId: order.id, nextStates: order.nextStates, cancellable: true, message: _('order.manually-transition-to-state-message'), retry: 0, }) .subscribe(); } transitionToModifying() { this.dataService.order .transitionToState(this.id, 'Modifying') .subscribe(({ transitionOrderToState }) => { switch (transitionOrderToState?.__typename) { case 'Order': this.router.navigate(['./modify'], { relativeTo: this.route }); break; case 'OrderStateTransitionError': this.notificationService.error(transitionOrderToState.transitionError); } }); } updateCustomFields() { this.dataService.order .updateOrderCustomFields({ id: this.id, customFields: this.detailForm.value.customFields, }) .subscribe(() => { this.notificationService.success(_('common.notify-update-success'), { entity: 'Order' }); }); } getOrderAddressLines(orderAddress?: { [key: string]: string }): string[] { if (!orderAddress) { return []; } return Object.values(orderAddress) .filter(val => val !== 'OrderAddress') .filter(line => !!line); } settlePayment(payment: Payment) { this.dataService.order.settlePayment(payment.id).subscribe(({ settlePayment }) => { switch (settlePayment.__typename) { case 'Payment': if (settlePayment.state === 'Settled') { this.notificationService.success(_('order.settle-payment-success')); } else { this.notificationService.error(_('order.settle-payment-error')); } this.dataService.order.getOrder(this.id).single$.subscribe(); this.fetchHistory.next(); break; case 'OrderStateTransitionError': case 'PaymentStateTransitionError': case 'SettlePaymentError': this.notificationService.error(settlePayment.message); } }); } transitionPaymentState({ payment, state }: { payment: Payment; state: string }) { if (state === 'Cancelled') { this.dataService.order.cancelPayment(payment.id).subscribe(({ cancelPayment }) => { switch (cancelPayment.__typename) { case 'Payment': this.notificationService.success(_('order.transitioned-payment-to-state-success'), { state, }); this.dataService.order.getOrder(this.id).single$.subscribe(); this.fetchHistory.next(); break; case 'PaymentStateTransitionError': this.notificationService.error(cancelPayment.transitionError); break; case 'CancelPaymentError': this.notificationService.error(cancelPayment.paymentErrorMessage); break; } }); } else { this.dataService.order .transitionPaymentToState(payment.id, state) .subscribe(({ transitionPaymentToState }) => { switch (transitionPaymentToState.__typename) { case 'Payment': this.notificationService.success( _('order.transitioned-payment-to-state-success'), { state, }, ); this.dataService.order.getOrder(this.id).single$.subscribe(); this.fetchHistory.next(); break; case 'PaymentStateTransitionError': this.notificationService.error(transitionPaymentToState.message); break; } }); } } canAddFulfillment(order: OrderDetailFragment): boolean { const allFulfillmentLines: FulfillmentFragment['lines'] = (order.fulfillments ?? []) .filter(fulfillment => fulfillment.state !== 'Cancelled') .reduce((all, fulfillment) => [...all, ...fulfillment.lines], [] as FulfillmentFragment['lines']); let allItemsFulfilled = true; for (const line of order.lines) { const totalFulfilledCount = allFulfillmentLines .filter(row => row.orderLineId === line.id) .reduce((sum, row) => sum + row.quantity, 0); if (totalFulfilledCount < line.quantity) { allItemsFulfilled = false; } } return ( !allItemsFulfilled && !this.hasUnsettledModifications(order) && this.outstandingPaymentAmount(order) === 0 && (order.nextStates.includes('Shipped') || order.nextStates.includes('PartiallyShipped') || order.nextStates.includes('Delivered')) ); } hasUnsettledModifications(order: OrderDetailFragment): boolean { return 0 < order.modifications.filter(m => !m.isSettled).length; } getOutstandingModificationAmount(order: OrderDetailFragment): number { return summate( order.modifications.filter(m => !m.isSettled), 'priceChange', ); } outstandingPaymentAmount(order: OrderDetailFragment): number { const paymentIsValid = (p: Payment): boolean => p.state !== 'Cancelled' && p.state !== 'Declined' && p.state !== 'Error'; let amountCovered = 0; for (const payment of order.payments?.filter(paymentIsValid) ?? []) { const refunds = payment.refunds.filter(r => r.state !== 'Failed') ?? []; const refundsTotal = summate(refunds as Array<Required<Refund>>, 'total'); amountCovered += payment.amount - refundsTotal; } return order.totalWithTax - amountCovered; } addManualPayment(order: OrderDetailFragment) { const priorState = order.state; this.modalService .fromComponent(AddManualPaymentDialogComponent, { closable: true, locals: { outstandingAmount: this.outstandingPaymentAmount(order), currencyCode: order.currencyCode, }, }) .pipe( switchMap(result => { if (result) { return this.dataService.order.addManualPaymentToOrder({ orderId: this.id, transactionId: result.transactionId, method: result.method, metadata: result.metadata || {}, }); } else { return EMPTY; } }), switchMap(({ addManualPaymentToOrder }) => { switch (addManualPaymentToOrder.__typename) { case 'Order': this.notificationService.success(_('order.add-payment-to-order-success')); if (priorState === 'ArrangingAdditionalPayment') { return this.orderTransitionService.transitionToPreModifyingState( order.id, order.nextStates, ); } else { return of('PaymentSettled'); } case 'ManualPaymentStateError': this.notificationService.error(addManualPaymentToOrder.message); return EMPTY; default: return EMPTY; } }), ) .subscribe(result => { if (result) { this.refetchOrder({ result }); } }); } fulfillOrder() { this.entity$ .pipe( take(1), switchMap(order => this.modalService.fromComponent(FulfillOrderDialogComponent, { size: 'xl', locals: { order, }, }), ), switchMap(input => { if (input) { return this.dataService.order.createFulfillment(input); } else { return of(undefined); } }), switchMap(result => this.refetchOrder(result).pipe(mapTo(result))), ) .subscribe(result => { if (result) { const { addFulfillmentToOrder } = result; switch (addFulfillmentToOrder.__typename) { case 'Fulfillment': this.notificationService.success(_('order.create-fulfillment-success')); break; case 'EmptyOrderLineSelectionError': case 'InsufficientStockOnHandError': case 'ItemsAlreadyFulfilledError': case 'InvalidFulfillmentHandlerError': this.notificationService.error(addFulfillmentToOrder.message); break; case 'FulfillmentStateTransitionError': this.notificationService.error(addFulfillmentToOrder.transitionError); break; case 'CreateFulfillmentError': this.notificationService.error(addFulfillmentToOrder.fulfillmentHandlerError); break; case undefined: this.notificationService.error(JSON.stringify(addFulfillmentToOrder)); break; default: assertNever(addFulfillmentToOrder); } } }); } transitionFulfillment(id: string, state: string) { this.dataService.order .transitionFulfillmentToState(id, state) .pipe(switchMap(result => this.refetchOrder(result))) .subscribe(() => { this.notificationService.success(_('order.successfully-updated-fulfillment')); }); } cancelOrRefund(order: OrderDetailFragment) { const isRefundable = this.orderHasSettledPayments(order); if (order.state === 'PaymentAuthorized' || order.active === true || !isRefundable) { this.cancelOrder(order); } else { this.refundOrder(order); } } settleRefund(refund: Payment['refunds'][number]) { this.modalService .fromComponent(SettleRefundDialogComponent, { size: 'md', locals: { refund, }, }) .pipe( switchMap(transactionId => { if (transactionId) { return this.dataService.order.settleRefund( { transactionId, id: refund.id, }, this.id, ); } else { return of(undefined); } }), // switchMap(result => this.refetchOrder(result)), ) .subscribe(result => { if (result) { this.notificationService.success(_('order.settle-refund-success')); } }); } addNote(event: { note: string; isPublic: boolean }) { const { note, isPublic } = event; this.dataService.order .addNoteToOrder({ id: this.id, note, isPublic, }) .pipe(switchMap(result => this.refetchOrder(result))) .subscribe(result => { this.notificationService.success(_('common.notify-create-success'), { entity: 'Note', }); }); } updateNote(entry: TimelineHistoryEntry) { this.modalService .fromComponent(EditNoteDialogComponent, { closable: true, locals: { displayPrivacyControls: true, note: entry.data.note, noteIsPrivate: !entry.isPublic, }, }) .pipe( switchMap(result => { if (result) { return this.dataService.order.updateOrderNote({ noteId: entry.id, isPublic: !result.isPrivate, note: result.note, }); } else { return EMPTY; } }), ) .subscribe(result => { this.fetchHistory.next(); this.notificationService.success(_('common.notify-update-success'), { entity: 'Note', }); }); } deleteNote(entry: TimelineHistoryEntry) { return this.modalService .dialog({ title: _('common.confirm-delete-note'), body: entry.data.note, buttons: [ { type: 'secondary', label: _('common.cancel') }, { type: 'danger', label: _('common.delete'), returnValue: true }, ], }) .pipe(switchMap(res => (res ? this.dataService.order.deleteOrderNote(entry.id) : EMPTY))) .subscribe(() => { this.fetchHistory.next(); this.notificationService.success(_('common.notify-delete-success'), { entity: 'Note', }); }); } orderHasSettledPayments(order: OrderDetailFragment): boolean { return !!order.payments?.find(p => p.state === 'Settled'); } private cancelOrder(order: OrderDetailFragment) { this.modalService .fromComponent(CancelOrderDialogComponent, { size: 'xl', locals: { order, }, }) .pipe( switchMap(input => { if (input) { return this.dataService.order.cancelOrder(input); } else { return of(undefined); } }), switchMap(result => this.refetchOrder(result)), ) .subscribe(result => { if (result) { this.notificationService.success(_('order.cancelled-order-success')); } }); } private refundOrder(order: OrderDetailFragment) { this.modalService .fromComponent(RefundOrderDialogComponent, { size: 'xl', locals: { order, }, }) .pipe( switchMap(input => { if (!input) { return of(undefined); } if (input.cancel.lines?.length) { return this.dataService.order.cancelOrder(input.cancel).pipe( map(res => { const result = res.cancelOrder; switch (result.__typename) { case 'Order': this.refetchOrder(result).subscribe(); this.notificationService.success( _('order.cancelled-order-items-success'), { count: summate(input.cancel.lines, 'quantity'), }, ); return input; case 'CancelActiveOrderError': case 'QuantityTooGreatError': case 'MultipleOrderError': case 'OrderStateTransitionError': case 'EmptyOrderLineSelectionError': this.notificationService.error(result.message); return undefined; } }), ); } else { return [input]; } }), switchMap(input => { if (!input) { return of(undefined); } if (input.refunds.length) { return forkJoin( input.refunds.map(refund => this.dataService.order.refundOrder(refund).pipe(map(res => res.refundOrder)), ), ); } else { return [undefined]; } }), ) .subscribe(results => { for (const result of results ?? []) { if (result) { switch (result.__typename) { case 'Refund': if (result.state === 'Failed') { this.notificationService.error(_('order.refund-order-failed')); } else { this.notificationService.success(_('order.refund-order-success')); } break; case 'AlreadyRefundedError': case 'NothingToRefundError': case 'PaymentOrderMismatchError': case 'RefundOrderStateError': case 'RefundStateTransitionError': this.notificationService.error(result.message); break; } } } this.refetchOrder(results?.[0]).subscribe(); }); } private refetchOrder(result: object | undefined): Observable<GetOrderQuery | undefined> { this.fetchHistory.next(); if (result) { return this.dataService.order.getOrder(this.id).single$; } else { return of(undefined); } } protected setFormValues(entity: OrderDetailFragment): void { if (this.customFields.length) { this.setCustomFieldFormValues(this.customFields, this.detailForm.get(['customFields']), entity); } } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup, UntypedFormArray, UntypedFormControl, UntypedFormGroup, Validators, } from '@angular/forms'; import { CustomFieldConfig, DataService, DraftOrderEligibleShippingMethodsQuery, ErrorResult, GetAvailableCountriesQuery, HistoryEntryType, LanguageCode, ModalService, ModifyOrderInput, NotificationService, OrderAddressFragment, OrderDetailFragment, OrderDetailQueryDocument, SortOrder, SurchargeInput, transformRelationCustomFieldInputs, TypedBaseDetailComponent, } from '@vendure/admin-ui/core'; import { assertNever, notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import { simpleDeepClone } from '@vendure/common/lib/simple-deep-clone'; import { EMPTY, Observable, of } from 'rxjs'; import { map, mapTo, shareReplay, switchMap, take, takeUntil } from 'rxjs/operators'; import { AddedLine, ModifyOrderData, OrderSnapshot, ProductSelectorItem, } from '../../common/modify-order-types'; import { OrderTransitionService } from '../../providers/order-transition.service'; import { OrderEditResultType, OrderEditsPreviewDialogComponent, } from '../order-edits-preview-dialog/order-edits-preview-dialog.component'; import { SelectShippingMethodDialogComponent } from '../select-shipping-method-dialog/select-shipping-method-dialog.component'; @Component({ selector: 'vdr-order-editor', templateUrl: './order-editor.component.html', styleUrls: ['./order-editor.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderEditorComponent extends TypedBaseDetailComponent<typeof OrderDetailQueryDocument, 'order'> implements OnInit, OnDestroy { availableCountries$: Observable<GetAvailableCountriesQuery['countries']['items']>; addressCustomFields: CustomFieldConfig[]; uiLanguage$: Observable<LanguageCode>; detailForm = new UntypedFormGroup({}); couponCodesControl = new FormControl<string[]>([]); orderLineCustomFieldsFormArray: UntypedFormArray; addItemCustomFieldsFormArray: UntypedFormArray; addItemCustomFieldsForm: UntypedFormGroup; addItemSelectedVariant: ProductSelectorItem | undefined; orderLineCustomFields: CustomFieldConfig[]; orderSnapshot: OrderSnapshot; modifyOrderInput: ModifyOrderData = { dryRun: true, orderId: '', addItems: [], adjustOrderLines: [], surcharges: [], note: '', refunds: [], updateShippingAddress: {}, updateBillingAddress: {}, }; surchargeForm = new FormGroup({ description: new FormControl('', Validators.minLength(1)), sku: new FormControl(''), price: new FormControl(0), priceIncludesTax: new FormControl(true), taxRate: new FormControl(0), taxDescription: new FormControl(''), }); shippingAddressForm = new FormGroup({ fullName: new FormControl(''), company: new FormControl(''), streetLine1: new FormControl(''), streetLine2: new FormControl(''), city: new FormControl(''), province: new FormControl(''), postalCode: new FormControl(''), countryCode: new FormControl(''), phoneNumber: new FormControl(''), }); billingAddressForm = new FormGroup({ fullName: new FormControl(''), company: new FormControl(''), streetLine1: new FormControl(''), streetLine2: new FormControl(''), city: new FormControl(''), province: new FormControl(''), postalCode: new FormControl(''), countryCode: new FormControl(''), phoneNumber: new FormControl(''), }); note = ''; recalculateShipping = true; previousState: string; editingShippingAddress = false; editingBillingAddress = false; updatedShippingMethods: { [ shippingLineId: string ]: DraftOrderEligibleShippingMethodsQuery['eligibleShippingMethodsForDraftOrder'][number]; } = {}; private addedVariants = new Map<string, ProductSelectorItem>(); constructor( protected dataService: DataService, private notificationService: NotificationService, private modalService: ModalService, private orderTransitionService: OrderTransitionService, private changeDetectorRef: ChangeDetectorRef, ) { super(); } ngOnInit(): void { this.init(); this.addressCustomFields = this.getCustomFieldConfig('Address'); this.modifyOrderInput.orderId = this.route.snapshot.paramMap.get('id') as string; this.orderLineCustomFields = this.getCustomFieldConfig('OrderLine'); this.entity$.pipe(take(1)).subscribe(order => { this.orderSnapshot = this.createOrderSnapshot(order); if (order.couponCodes.length) { this.couponCodesControl.setValue(order.couponCodes); } this.surchargeForm.reset(); for (const [name, control] of Object.entries(this.shippingAddressForm.controls)) { control.setValue(order.shippingAddress?.[name]); } this.addAddressCustomFieldsFormGroup(this.shippingAddressForm, order.shippingAddress); for (const [name, control] of Object.entries(this.billingAddressForm.controls)) { control.setValue(order.billingAddress?.[name]); } this.addAddressCustomFieldsFormGroup(this.billingAddressForm, order.billingAddress); this.orderLineCustomFieldsFormArray = new UntypedFormArray([]); for (const line of order.lines) { const formGroup = new UntypedFormGroup({}); for (const { name } of this.orderLineCustomFields) { formGroup.addControl(name, new UntypedFormControl((line as any).customFields[name])); } formGroup.valueChanges.pipe(takeUntil(this.destroy$)).subscribe(value => { let modifyRow = this.modifyOrderInput.adjustOrderLines.find( l => l.orderLineId === line.id, ); if (!modifyRow) { modifyRow = { orderLineId: line.id, quantity: line.quantity, }; this.modifyOrderInput.adjustOrderLines.push(modifyRow); } if (this.orderLineCustomFields.length) { modifyRow.customFields = value; } }); this.orderLineCustomFieldsFormArray.push(formGroup); } }); this.addItemCustomFieldsFormArray = new UntypedFormArray([]); this.addItemCustomFieldsForm = new UntypedFormGroup({}); for (const customField of this.orderLineCustomFields) { this.addItemCustomFieldsForm.addControl(customField.name, new UntypedFormControl()); } this.availableCountries$ = this.dataService.settings .getAvailableCountries() .mapSingle(result => result.countries.items) .pipe(shareReplay(1)); this.dataService.order .getOrderHistory(this.id, { take: 1, sort: { createdAt: SortOrder.DESC, }, filter: { type: { eq: HistoryEntryType.ORDER_STATE_TRANSITION } }, }) .single$.subscribe(({ order }) => { this.previousState = order?.history.items[0].data.from; }); this.uiLanguage$ = this.dataService.client .uiState() .stream$.pipe(map(({ uiState }) => uiState.language)); } ngOnDestroy(): void { this.destroy(); } get addedLines(): AddedLine[] { const getSinglePriceValue = (price: ProductSelectorItem['price']) => price.__typename === 'SinglePrice' ? price.value : 0; return (this.modifyOrderInput.addItems || []) .map(row => { const variantInfo = this.addedVariants.get(row.productVariantId); if (variantInfo) { return { id: this.getIdForAddedItem(row), featuredAsset: variantInfo.productAsset, productVariant: { id: variantInfo.productVariantId, name: variantInfo.productVariantName, sku: variantInfo.sku, }, unitPrice: getSinglePriceValue(variantInfo.price), unitPriceWithTax: getSinglePriceValue(variantInfo.priceWithTax), quantity: row.quantity, }; } }) .filter(notNullOrUndefined); } private getIdForAddedItem(row: ModifyOrderData['addItems'][number]) { return `added-${row.productVariantId}-${JSON.stringify(row.customFields || {})}`; } transitionToPriorState(order: OrderDetailFragment) { this.orderTransitionService .transitionToPreModifyingState(order.id, order.nextStates) .subscribe(result => { this.router.navigate(['..'], { relativeTo: this.route }); }); } hasModifications(): boolean { const { addItems, adjustOrderLines, surcharges } = this.modifyOrderInput; return ( !!addItems?.length || !!surcharges?.length || !!adjustOrderLines?.length || (this.shippingAddressForm.dirty && this.shippingAddressForm.valid) || (this.billingAddressForm.dirty && this.billingAddressForm.valid) || this.couponCodesControl.dirty || Object.entries(this.updatedShippingMethods).length > 0 ); } isLineModified(line: OrderDetailFragment['lines'][number]): boolean { return !!this.modifyOrderInput.adjustOrderLines?.find( l => l.orderLineId === line.id && l.quantity !== line.quantity, ); } getInitialLineQuantity(lineId: string): number { const adjustedLine = this.modifyOrderInput.adjustOrderLines?.find(l => l.orderLineId === lineId); if (adjustedLine) { return adjustedLine.quantity; } const addedLine = this.modifyOrderInput.addItems?.find(l => this.getIdForAddedItem(l) === lineId); if (addedLine) { return addedLine.quantity ?? 1; } const line = this.orderSnapshot.lines.find(l => l.id === lineId); return line ? line.quantity : 1; } updateLineQuantity(line: OrderDetailFragment['lines'][number] | AddedLine, quantity: string) { const { adjustOrderLines } = this.modifyOrderInput; if (this.isAddedLine(line)) { const row = this.modifyOrderInput.addItems?.find( l => l.productVariantId === line.productVariant.id, ); if (row) { row.quantity = +quantity; } } else { let row = adjustOrderLines?.find(l => l.orderLineId === line.id); if (row && +quantity === line.quantity) { // Remove the modification if the quantity is the same as // the original order adjustOrderLines?.splice(adjustOrderLines?.indexOf(row), 1); } if (!row) { row = { orderLineId: line.id, quantity: +quantity }; adjustOrderLines?.push(row); } row.quantity = +quantity; } } isAddedLine(line: OrderDetailFragment['lines'][number] | AddedLine): line is AddedLine { return (line as AddedLine).id.startsWith('added-'); } updateAddedItemQuantity(item: AddedLine, quantity: string) { const row = this.modifyOrderInput.addItems?.find(l => l.productVariantId === item.productVariant.id); if (row) { row.quantity = +quantity; } } trackByProductVariantId(index: number, item: AddedLine) { return item.productVariant.id; } getSelectedItemPrice(result: ProductSelectorItem | undefined): number { switch (result?.priceWithTax.__typename) { case 'SinglePrice': return result.priceWithTax.value; default: return 0; } } addItemToOrder(result: ProductSelectorItem | undefined) { if (!result) { return; } const customFields = this.orderLineCustomFields.length ? this.addItemCustomFieldsForm.value : undefined; let row = this.modifyOrderInput.addItems?.find(l => this.isMatchingAddItemRow(l, result, customFields), ); if (!row) { row = { productVariantId: result.productVariantId, quantity: 1 }; if (customFields) { row.customFields = customFields; } this.modifyOrderInput.addItems?.push(row); } else { row.quantity++; } if (customFields) { const formGroup = new UntypedFormGroup({}); for (const [key, value] of Object.entries(customFields)) { formGroup.addControl(key, new UntypedFormControl(value)); } this.addItemCustomFieldsFormArray.push(formGroup); formGroup.valueChanges.pipe(takeUntil(this.destroy$)).subscribe(value => { if (row) { row.customFields = value; } }); } this.addItemCustomFieldsForm.reset({}); this.addItemSelectedVariant = undefined; this.addedVariants.set(result.productVariantId, result); } getShippingLineDetails(shippingLine: OrderDetailFragment['shippingLines'][number]): { name: string; price: number; } { const updatedMethod = this.updatedShippingMethods[shippingLine.id]; if (updatedMethod) { return { name: updatedMethod.name || updatedMethod.code, price: updatedMethod.priceWithTax, }; } else { return { name: shippingLine.shippingMethod.name || shippingLine.shippingMethod.code, price: shippingLine.discountedPriceWithTax, }; } } setShippingMethod(shippingLineId: string) { const currentShippingMethod = this.updatedShippingMethods[shippingLineId] ?? this.entity?.shippingLines.find(l => l.id === shippingLineId)?.shippingMethod; if (!currentShippingMethod) { return; } this.dataService.order .getDraftOrderEligibleShippingMethods(this.id) .mapSingle(({ eligibleShippingMethodsForDraftOrder }) => eligibleShippingMethodsForDraftOrder) .pipe( switchMap(methods => this.modalService .fromComponent(SelectShippingMethodDialogComponent, { locals: { eligibleShippingMethods: methods, currencyCode: this.entity?.currencyCode, currentSelectionId: currentShippingMethod.id, }, }) .pipe( map(result => { if (result) { return methods.find(method => method.id === result); } }), ), ), ) .subscribe(result => { if (result) { this.updatedShippingMethods[shippingLineId] = result; this.changeDetectorRef.markForCheck(); } }); } private isMatchingAddItemRow( row: ModifyOrderData['addItems'][number], result: ProductSelectorItem, customFields: any, ): boolean { return ( row.productVariantId === result.productVariantId && JSON.stringify(row.customFields) === JSON.stringify(customFields) ); } removeAddedItem(id: string) { this.modifyOrderInput.addItems = this.modifyOrderInput.addItems?.filter(l => { const itemId = this.getIdForAddedItem(l); return itemId !== id; }); } getSurchargePrices(surcharge: SurchargeInput) { const priceWithTax = surcharge.priceIncludesTax ? surcharge.price : Math.round(surcharge.price * ((100 + (surcharge.taxRate || 0)) / 100)); const price = surcharge.priceIncludesTax ? Math.round(surcharge.price / ((100 + (surcharge.taxRate || 0)) / 100)) : surcharge.price; return { price, priceWithTax, }; } addSurcharge(value: any) { this.modifyOrderInput.surcharges?.push(value); this.surchargeForm.reset({ price: 0, priceIncludesTax: true, taxRate: 0, }); } removeSurcharge(index: number) { this.modifyOrderInput.surcharges?.splice(index, 1); } previewAndModify(order: OrderDetailFragment) { const modifyOrderInput: ModifyOrderData = { ...this.modifyOrderInput, adjustOrderLines: this.modifyOrderInput.adjustOrderLines.map(line => transformRelationCustomFieldInputs(simpleDeepClone(line), this.orderLineCustomFields), ), }; const input: ModifyOrderInput = { ...modifyOrderInput, ...(this.billingAddressForm.dirty ? { updateBillingAddress: this.billingAddressForm.value } : {}), ...(this.shippingAddressForm.dirty ? { updateShippingAddress: this.shippingAddressForm.value } : {}), dryRun: true, couponCodes: this.couponCodesControl.dirty ? this.couponCodesControl.value : undefined, note: this.note ?? '', options: { recalculateShipping: this.recalculateShipping, }, }; if (Object.entries(this.updatedShippingMethods).length) { input.shippingMethodIds = order.shippingLines.map(l => this.updatedShippingMethods[l.id] ? this.updatedShippingMethods[l.id].id : l.shippingMethod.id, ); } this.dataService.order .modifyOrder(input) .pipe( switchMap(({ modifyOrder }) => { switch (modifyOrder.__typename) { case 'Order': return this.modalService.fromComponent(OrderEditsPreviewDialogComponent, { size: 'xl', closable: false, locals: { order: modifyOrder, orderSnapshot: this.orderSnapshot, orderLineCustomFields: this.orderLineCustomFields, modifyOrderInput: input, addedLines: this.addedLines, shippingAddressForm: this.shippingAddressForm, billingAddressForm: this.billingAddressForm, couponCodesControl: this.couponCodesControl, updatedShippingMethods: this.updatedShippingMethods, }, }); case 'InsufficientStockError': case 'NegativeQuantityError': case 'NoChangesSpecifiedError': case 'OrderLimitError': case 'OrderModificationStateError': case 'PaymentMethodMissingError': case 'RefundPaymentIdMissingError': case 'CouponCodeLimitError': case 'CouponCodeExpiredError': case 'IneligibleShippingMethodError': case 'CouponCodeInvalidError': { this.notificationService.error(modifyOrder.message); return of(false as const); } case null: case undefined: return of(false as const); default: assertNever(modifyOrder); } }), switchMap(result => { if (!result || result.result === OrderEditResultType.Cancel) { // re-fetch so that the preview values get overwritten in the cache. return this.dataService.order.getOrder(this.id).mapSingle(() => false); } else { // Do the modification const wetRunInput = { ...input, dryRun: false, }; if (result.result === OrderEditResultType.Refund) { wetRunInput.refunds = result.refunds; } return this.dataService.order.modifyOrder(wetRunInput).pipe( switchMap(({ modifyOrder }) => { if (modifyOrder.__typename === 'Order') { const priceDelta = modifyOrder.totalWithTax - this.orderSnapshot.totalWithTax; const nextState = 0 < priceDelta ? 'ArrangingAdditionalPayment' : this.previousState; return this.dataService.order .transitionToState(order.id, nextState) .pipe(mapTo(true)); } else { this.notificationService.error((modifyOrder as ErrorResult).message); return EMPTY; } }), ); } }), ) .subscribe(result => { if (result) { this.router.navigate(['../'], { relativeTo: this.route }); } }); } private addAddressCustomFieldsFormGroup( parentFormGroup: UntypedFormGroup, address?: OrderAddressFragment | null, ) { if (address && this.addressCustomFields.length) { const addressCustomFieldsFormGroup = new UntypedFormGroup({}); for (const customFieldDef of this.addressCustomFields) { const name = customFieldDef.name; const value = (address as any).customFields?.[name]; addressCustomFieldsFormGroup.addControl(name, new UntypedFormControl(value)); } parentFormGroup.addControl('customFields', addressCustomFieldsFormGroup); } } private createOrderSnapshot(order: OrderDetailFragment): OrderSnapshot { return { totalWithTax: order.totalWithTax, currencyCode: order.currencyCode, couponCodes: order.couponCodes, lines: [...order.lines].map(line => ({ ...line })), shippingLines: [...order.shippingLines].map(line => ({ ...line })), }; } protected setFormValues(entity: OrderDetailFragment, languageCode: LanguageCode): void { /* not used */ } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { AdministratorRefundInput, CustomFieldConfig, Dialog, ModifyOrderInput, OrderDetailFragment, } from '@vendure/admin-ui/core'; import { getRefundablePayments, RefundablePayment } from '../../common/get-refundable-payments'; import { AddedLine, OrderSnapshot } from '../../common/modify-order-types'; import { OrderEditorComponent } from '../order-editor/order-editor.component'; export enum OrderEditResultType { Refund, Payment, PriceUnchanged, Cancel, } interface OrderEditsRefundResult { result: OrderEditResultType.Refund; refunds: AdministratorRefundInput[]; } interface OrderEditsPaymentResult { result: OrderEditResultType.Payment; } interface OrderEditsPriceUnchangedResult { result: OrderEditResultType.PriceUnchanged; } interface OrderEditsCancelResult { result: OrderEditResultType.Cancel; } type OrderEditResult = | OrderEditsRefundResult | OrderEditsPaymentResult | OrderEditsPriceUnchangedResult | OrderEditsCancelResult; @Component({ selector: 'vdr-order-edits-preview-dialog', templateUrl: './order-edits-preview-dialog.component.html', styleUrls: ['./order-edits-preview-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderEditsPreviewDialogComponent implements OnInit, Dialog<OrderEditResult> { // Passed in via the modalService orderLineCustomFields: CustomFieldConfig[]; order: OrderDetailFragment; orderSnapshot: OrderSnapshot; modifyOrderInput: ModifyOrderInput; addedLines: AddedLine[]; shippingAddressForm: OrderEditorComponent['shippingAddressForm']; billingAddressForm: OrderEditorComponent['billingAddressForm']; updatedShippingMethods: OrderEditorComponent['updatedShippingMethods']; couponCodesControl: FormControl<string[] | null>; refundablePayments: RefundablePayment[]; refundNote: string; resolveWith: (result?: OrderEditResult) => void; get priceDifference(): number { return this.order.totalWithTax - this.orderSnapshot.totalWithTax; } get amountToRefundTotal(): number { return this.refundablePayments.reduce( (total, payment) => total + payment.amountToRefundControl.value, 0, ); } ngOnInit() { this.refundNote = this.modifyOrderInput.note || ''; this.refundablePayments = getRefundablePayments(this.order.payments || []); this.refundablePayments.forEach(rp => { rp.amountToRefundControl.addValidators(Validators.max(this.priceDifference * -1)); }); if (this.priceDifference < 0 && this.refundablePayments.length) { this.onPaymentSelected(this.refundablePayments[0], true); } } onPaymentSelected(payment: RefundablePayment, selected: boolean) { if (selected) { const outstandingRefundAmount = this.priceDifference * -1 - this.refundablePayments .filter(p => p.id !== payment.id) .reduce((total, p) => total + p.amountToRefundControl.value, 0); if (0 < outstandingRefundAmount) { payment.amountToRefundControl.setValue( Math.min(outstandingRefundAmount, payment.refundableAmount), ); } } else { payment.amountToRefundControl.setValue(0); } } refundsCoverDifference(): boolean { return this.priceDifference * -1 === this.amountToRefundTotal; } cancel() { this.resolveWith({ result: OrderEditResultType.Cancel, }); } submit() { if (0 < this.priceDifference) { this.resolveWith({ result: OrderEditResultType.Payment, }); } else if (this.priceDifference < 0) { this.resolveWith({ result: OrderEditResultType.Refund, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion refunds: this.refundablePayments .filter(rp => rp.selected && 0 < rp.amountToRefundControl.value) .map(payment => { return { reason: this.refundNote || this.modifyOrderInput.note, paymentId: payment.id, amount: payment.amountToRefundControl.value, }; }), }); } else { this.resolveWith({ result: OrderEditResultType.PriceUnchanged, }); } } }
import { Component, ComponentRef, EventEmitter, Input, OnDestroy, OnInit, Output, Type, ViewChild, ViewContainerRef, } from '@angular/core'; import { HistoryEntryComponentService, OrderDetailFragment, OrderHistoryEntryComponent, TimelineHistoryEntry, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-order-history-entry-host', template: `<vdr-timeline-entry [displayType]="instance.getDisplayType(entry)" [iconShape]="instance.getIconShape && instance.getIconShape(entry)" [createdAt]="entry.createdAt" [name]="instance.getName && instance.getName(entry)" [featured]="instance.isFeatured(entry)" [collapsed]="!expanded && !instance.isFeatured(entry)" (expandClick)="expandClick.emit()" > <div #portal></div> </vdr-timeline-entry>`, exportAs: 'historyEntry', }) export class OrderHistoryEntryHostComponent implements OnInit, OnDestroy { @Input() entry: TimelineHistoryEntry; @Input() order: OrderDetailFragment; @Input() expanded: boolean; @Output() expandClick = new EventEmitter<void>(); @ViewChild('portal', { static: true, read: ViewContainerRef }) portalRef: ViewContainerRef; instance: OrderHistoryEntryComponent; private componentRef: ComponentRef<OrderHistoryEntryComponent>; constructor(private historyEntryComponentService: HistoryEntryComponentService) {} ngOnInit(): void { const componentType = this.historyEntryComponentService.getComponent( this.entry.type, ) as Type<OrderHistoryEntryComponent>; const componentRef = this.portalRef.createComponent(componentType); componentRef.instance.entry = this.entry; componentRef.instance.order = this.order; this.instance = componentRef.instance; this.componentRef = componentRef; } ngOnDestroy() { this.componentRef?.destroy(); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { HistoryEntryComponentService, HistoryEntryType, OrderDetailFragment, TimelineDisplayType, TimelineHistoryEntry, } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-order-history', templateUrl: './order-history.component.html', styleUrls: ['./order-history.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderHistoryComponent { @Input() order: OrderDetailFragment; @Input() history: TimelineHistoryEntry[]; @Output() addNote = new EventEmitter<{ note: string; isPublic: boolean }>(); @Output() updateNote = new EventEmitter<TimelineHistoryEntry>(); @Output() deleteNote = new EventEmitter<TimelineHistoryEntry>(); note = ''; noteIsPrivate = true; expanded = false; readonly type = HistoryEntryType; constructor(private historyEntryComponentService: HistoryEntryComponentService) {} hasCustomComponent(type: string): boolean { return !!this.historyEntryComponentService.getComponent(type); } getDisplayType(entry: TimelineHistoryEntry): TimelineDisplayType { if (entry.type === HistoryEntryType.ORDER_STATE_TRANSITION) { if (entry.data.to === 'Delivered') { return 'success'; } if (entry.data.to === 'Cancelled') { return 'error'; } } if (entry.type === HistoryEntryType.ORDER_FULFILLMENT_TRANSITION) { if (entry.data.to === 'Delivered') { return 'success'; } } if (entry.type === HistoryEntryType.ORDER_PAYMENT_TRANSITION) { if (entry.data.to === 'Declined' || entry.data.to === 'Cancelled') { return 'error'; } } if (entry.type === HistoryEntryType.ORDER_CANCELLATION) { return 'warning'; } if (entry.type === HistoryEntryType.ORDER_REFUND_TRANSITION) { return 'warning'; } return 'default'; } getTimelineIcon(entry: TimelineHistoryEntry) { if (entry.type === HistoryEntryType.ORDER_STATE_TRANSITION) { if (entry.data.to === 'Delivered') { return ['success-standard', 'is-solid']; } if (entry.data.to === 'Cancelled') { return 'ban'; } } if (entry.type === HistoryEntryType.ORDER_PAYMENT_TRANSITION) { if (entry.data.to === 'Settled') { return 'credit-card'; } } if (entry.type === HistoryEntryType.ORDER_REFUND_TRANSITION) { if (entry.data.to === 'Settled') { return 'credit-card'; } } if (entry.type === HistoryEntryType.ORDER_NOTE) { return 'note'; } if (entry.type === HistoryEntryType.ORDER_MODIFIED) { return 'pencil'; } if (entry.type === HistoryEntryType.ORDER_CUSTOMER_UPDATED) { return 'switch'; } if (entry.type === HistoryEntryType.ORDER_FULFILLMENT_TRANSITION) { if (entry.data.to === 'Shipped') { return 'truck'; } if (entry.data.to === 'Delivered') { return 'truck'; } } } isFeatured(entry: TimelineHistoryEntry): boolean { switch (entry.type) { case HistoryEntryType.ORDER_STATE_TRANSITION: { return ( entry.data.to === 'Delivered' || entry.data.to === 'Cancelled' || entry.data.to === 'Settled' ); } case HistoryEntryType.ORDER_REFUND_TRANSITION: return entry.data.to === 'Settled'; case HistoryEntryType.ORDER_PAYMENT_TRANSITION: return entry.data.to === 'Settled' || entry.data.to === 'Cancelled'; case HistoryEntryType.ORDER_FULFILLMENT_TRANSITION: return entry.data.to === 'Delivered' || entry.data.to === 'Shipped'; case HistoryEntryType.ORDER_NOTE: case HistoryEntryType.ORDER_MODIFIED: case HistoryEntryType.ORDER_CUSTOMER_UPDATED: return true; default: return false; } } getFulfillment( entry: TimelineHistoryEntry, ): NonNullable<OrderDetailFragment['fulfillments']>[number] | undefined { if ( (entry.type === HistoryEntryType.ORDER_FULFILLMENT || entry.type === HistoryEntryType.ORDER_FULFILLMENT_TRANSITION) && this.order.fulfillments ) { return this.order.fulfillments.find(f => f.id === entry.data.fulfillmentId); } } getPayment( entry: TimelineHistoryEntry, ): NonNullable<OrderDetailFragment['payments']>[number] | undefined { if (entry.type === HistoryEntryType.ORDER_PAYMENT_TRANSITION && this.order.payments) { return this.order.payments.find(p => p.id === entry.data.paymentId); } } getRefund( entry: TimelineHistoryEntry, ): NonNullable<OrderDetailFragment['payments']>[number]['refunds'][number] | undefined { if (entry.type === HistoryEntryType.ORDER_REFUND_TRANSITION && this.order.payments) { const allRefunds = this.order.payments.reduce( (refunds, payment) => refunds.concat(payment.refunds), [] as NonNullable<OrderDetailFragment['payments']>[number]['refunds'], ); return allRefunds.find(r => r.id === entry.data.refundId); } } getCancelledQuantity(entry: TimelineHistoryEntry): number { return entry.data.lines.reduce((total, line) => total + line.quantity, 0); } getCancelledItems( cancellationLines: Array<{ orderLineId: string; quantity: number }>, ): Array<{ name: string; quantity: number }> { const itemMap = new Map<string, number>(); for (const line of this.order.lines) { const cancellationLine = cancellationLines.find(l => l.orderLineId === line.id); if (cancellationLine) { const count = itemMap.get(line.productVariant.name); itemMap.set(line.productVariant.name, cancellationLine.quantity); } } return Array.from(itemMap.entries()).map(([name, quantity]) => ({ name, quantity })); } getModification(id: string) { return this.order.modifications.find(m => m.id === id); } getName(entry: TimelineHistoryEntry): string { const { administrator } = entry; if (administrator) { return `${administrator.firstName} ${administrator.lastName}`; } else { const customer = this.order.customer; if (customer) { return `${customer.firstName} ${customer.lastName}`; } } return ''; } addNoteToOrder() { this.addNote.emit({ note: this.note, isPublic: !this.noteIsPrivate }); this.note = ''; this.noteIsPrivate = true; } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { ChannelService, GetOrderListDocument, getOrderStateTranslationToken, LogicalOperator, OrderListOptions, OrderType, ServerConfigService, TypedBaseListComponent, } from '@vendure/admin-ui/core'; import { Order } from '@vendure/common/lib/generated-types'; import { tap } from 'rxjs/operators'; @Component({ selector: 'vdr-order-list', templateUrl: './order-list.component.html', styleUrls: ['./order-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderListComponent extends TypedBaseListComponent<typeof GetOrderListDocument, 'orders'> implements OnInit { orderStates = this.serverConfigService.getOrderProcessStates().map(item => item.name); readonly OrderType = OrderType; readonly customFields = this.getCustomFieldConfig('Order'); readonly filters = this.createFilterCollection() .addIdFilter() .addDateFilters() .addFilter({ name: 'active', type: { kind: 'boolean' }, label: _('order.filter-is-active'), filterField: 'active', }) .addFilter({ name: 'totalWithTax', type: { kind: 'number', inputType: 'currency', currencyCode: 'USD' }, label: _('order.total'), filterField: 'totalWithTax', }) .addFilter({ name: 'state', type: { kind: 'select', options: this.orderStates.map(s => ({ value: s, label: getOrderStateTranslationToken(s) })), }, label: _('order.state'), filterField: 'state', }) .addFilter({ name: 'type', type: { kind: 'select', options: [ { value: OrderType.Regular, label: _('order.order-type-regular') }, { value: OrderType.Aggregate, label: _('order.order-type-aggregate') }, { value: OrderType.Seller, label: _('order.order-type-seller') }, ], }, label: _('order.order-type'), filterField: 'type', }) .addFilter({ name: 'orderPlacedAt', type: { kind: 'dateRange' }, label: _('order.placed-at'), filterField: 'orderPlacedAt', }) .addFilter({ name: 'customerLastName', type: { kind: 'text' }, label: _('customer.last-name'), filterField: 'customerLastName', }) .addFilter({ name: 'transactionId', type: { kind: 'text' }, label: _('order.transaction-id'), filterField: 'transactionId', }) .addCustomFieldFilters(this.customFields) .connectToRoute(this.route); readonly sorts = this.createSortCollection() .defaultSort('updatedAt', 'DESC') .addSort({ name: 'id' }) .addSort({ name: 'createdAt' }) .addSort({ name: 'updatedAt' }) .addSort({ name: 'orderPlacedAt' }) .addSort({ name: 'customerLastName' }) .addSort({ name: 'state' }) .addSort({ name: 'totalWithTax' }) .addCustomFieldSorts(this.customFields) .connectToRoute(this.route); canCreateDraftOrder = false; private activeChannelIsDefaultChannel = false; constructor(protected serverConfigService: ServerConfigService, private channelService: ChannelService) { super(); super.configure({ document: GetOrderListDocument, getItems: result => result.orders, setVariables: (skip, take) => this.createQueryOptions(skip, take, this.searchTermControl.value), refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges], }); this.canCreateDraftOrder = !!this.serverConfigService .getOrderProcessStates() .find(state => state.name === 'Created') ?.to.includes('Draft'); } ngOnInit() { super.ngOnInit(); const isDefaultChannel$ = this.channelService.defaultChannelIsActive$.pipe( tap(isDefault => (this.activeChannelIsDefaultChannel = isDefault)), ); super.refreshListOnChanges(this.filters.valueChanges, this.sorts.valueChanges, isDefaultChannel$); } private createQueryOptions( // eslint-disable-next-line @typescript-eslint/no-shadow skip: number, take: number, searchTerm: string | null, ): { options: OrderListOptions } { let filterInput = this.filters.createFilterInput(); if (this.activeChannelIsDefaultChannel) { filterInput = { ...(filterInput ?? {}), }; } if (searchTerm) { filterInput = { code: { contains: searchTerm, }, customerLastName: { contains: searchTerm, }, transactionId: { contains: searchTerm, }, }; } return { options: { skip, take, filter: { ...(filterInput ?? {}), }, filterOperator: searchTerm ? LogicalOperator.OR : LogicalOperator.AND, sort: this.sorts.createSortInput(), }, }; } getShippingNames(order: Order) { if (order.shippingLines.length) { return order.shippingLines.map(shippingLine => shippingLine.shippingMethod.name).join(', '); } else { return ''; } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { notNullOrUndefined } from '@vendure/common/lib/shared-utils'; import type { OrderEditorComponent } from '../order-editor/order-editor.component'; import { AddedLine, ModifyOrderData, OrderSnapshot } from '../../common/modify-order-types'; @Component({ selector: 'vdr-order-modification-summary', templateUrl: './order-modification-summary.component.html', styleUrls: ['./order-modification-summary.component.css'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderModificationSummaryComponent { @Input() orderSnapshot: OrderSnapshot; @Input() modifyOrderInput: ModifyOrderData; @Input() addedLines: AddedLine[]; @Input() shippingAddressForm: OrderEditorComponent['shippingAddressForm']; @Input() billingAddressForm: OrderEditorComponent['billingAddressForm']; @Input() updatedShippingMethods: OrderEditorComponent['updatedShippingMethods']; @Input() couponCodesControl: FormControl<string[] | null>; get adjustedLines(): string[] { return (this.modifyOrderInput.adjustOrderLines || []) .map(l => { const line = this.orderSnapshot.lines.find(line => line.id === l.orderLineId); if (line) { const delta = l.quantity - line.quantity; const sign = delta === 0 ? '' : delta > 0 ? '+' : '-'; return delta ? `${sign}${Math.abs(delta)} ${line.productVariant.name}` : line.productVariant.name; } }) .filter(notNullOrUndefined); } getModifiedFields(formGroup: FormGroup): string { if (!formGroup.dirty) { return ''; } return Object.entries(formGroup.controls) .map(([key, control]) => { if (control.dirty) { return key; } }) .filter(notNullOrUndefined) .join(', '); } getUpdatedShippingMethodLines() { return Object.entries(this.updatedShippingMethods || {}) .map(([lineId, shippingMethod]) => { const previousMethod = this.orderSnapshot.shippingLines.find(l => l.id === lineId); if (!previousMethod) { return; } const previousName = previousMethod.shippingMethod.name || previousMethod.shippingMethod.code; const newName = shippingMethod.name || shippingMethod.code; return `${previousName} -> ${newName}`; }) .filter(notNullOrUndefined); } get couponCodeChanges(): string[] { const originalCodes = this.orderSnapshot.couponCodes || []; const newCodes = this.couponCodesControl.value || []; const addedCodes = newCodes.filter(c => !originalCodes.includes(c)).map(c => `+ ${c}`); const removedCodes = originalCodes.filter(c => !newCodes.includes(c)).map(c => `- ${c}`); return [...addedCodes, ...removedCodes]; } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { CurrencyCode, OrderDetailFragment } from '@vendure/admin-ui/core'; type Payment = NonNullable<OrderDetailFragment['payments']>[number]; @Component({ selector: 'vdr-order-payment-card', templateUrl: './order-payment-card.component.html', styleUrls: ['./order-payment-card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderPaymentCardComponent { @Input() payment: Payment; @Input() currencyCode: CurrencyCode; @Output() settlePayment = new EventEmitter<Payment>(); @Output() transitionPaymentState = new EventEmitter<{ payment: Payment; state: string }>(); @Output() settleRefund = new EventEmitter<Payment['refunds'][number]>(); refundHasMetadata(refund?: Payment['refunds'][number]): boolean { return !!refund && Object.keys(refund.metadata).length > 0; } nextOtherStates(): string[] { if (!this.payment) { return []; } return this.payment.nextStates.filter(s => s !== 'Settled' && s !== 'Error'); } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { CancelOrderInput, DataService, Dialog, OrderProcessState, ServerConfigService, } from '@vendure/admin-ui/core'; import { Observable } from 'rxjs'; @Component({ selector: 'vdr-order-process-graph-dialog', templateUrl: './order-process-graph-dialog.component.html', styleUrls: ['./order-process-graph-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderProcessGraphDialogComponent implements OnInit, Dialog<void> { activeState: string; states: OrderProcessState[] = []; constructor(private serverConfigService: ServerConfigService) {} ngOnInit(): void { this.states = this.serverConfigService.getOrderProcessStates(); } resolveWith: (result: void | undefined) => void; }
export const NODE_HEIGHT = 72;
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; import { OrderProcessNodeComponent } from './order-process-node.component'; @Component({ selector: 'vdr-order-process-edge', templateUrl: './order-process-edge.component.html', styleUrls: ['./order-process-edge.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderProcessEdgeComponent implements OnInit { @Input() from: OrderProcessNodeComponent; @Input() to: OrderProcessNodeComponent; @Input() index: number; active$: Observable<boolean>; ngOnInit() { this.active$ = this.from.active$ .asObservable() .pipe(tap((active) => this.to.activeTarget$.next(active))); } getStyle() { const direction = this.from.index < this.to.index ? 'down' : 'up'; const startPos = this.from.getPos(direction === 'down' ? 'bottom' : 'top'); const endPos = this.to.getPos(direction === 'down' ? 'top' : 'bottom'); const dX = Math.abs(startPos.x - endPos.x); const dY = Math.abs(startPos.y - endPos.y); const length = Math.sqrt(dX ** 2 + dY ** 2); return { 'top.px': startPos.y, 'left.px': startPos.x + (direction === 'down' ? 10 : 40) + this.index * 12, 'height.px': length, 'width.px': 1, ...(direction === 'up' ? { transform: 'rotateZ(180deg)', 'transform-origin': 'top', } : {}), }; } }
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, HostBinding, Input, OnChanges, OnInit, QueryList, SimpleChanges, ViewChildren, } from '@angular/core'; import { OrderProcessState } from '@vendure/admin-ui/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { NODE_HEIGHT } from './constants'; import { OrderProcessNodeComponent } from './order-process-node.component'; import { StateNode } from './types'; @Component({ selector: 'vdr-order-process-graph', templateUrl: './order-process-graph.component.html', styleUrls: ['./order-process-graph.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderProcessGraphComponent implements OnInit, OnChanges, AfterViewInit { @Input() states: OrderProcessState[]; @Input() initialState?: string; setActiveState$ = new BehaviorSubject<string | undefined>(undefined); activeState$: Observable<string | undefined>; nodes: StateNode[] = []; edges: Array<{ from: OrderProcessNodeComponent; to: OrderProcessNodeComponent; index: number }> = []; @ViewChildren(OrderProcessNodeComponent) nodeComponents: QueryList<OrderProcessNodeComponent>; constructor(private changeDetector: ChangeDetectorRef) {} @HostBinding('style.height.px') get outerHeight(): number { return this.nodes.length * NODE_HEIGHT; } ngOnInit() { this.setActiveState$.next(this.initialState); this.activeState$ = this.setActiveState$.pipe(debounceTime(150)); } ngOnChanges(changes: SimpleChanges) { this.populateNodes(); } ngAfterViewInit() { setTimeout(() => this.populateEdges()); } onMouseOver(stateName: string) { this.setActiveState$.next(stateName); } onMouseOut() { this.setActiveState$.next(this.initialState); } getNodeFor(state: string): OrderProcessNodeComponent | undefined { if (this.nodeComponents) { return this.nodeComponents.find((n) => n.node.name === state); } } private populateNodes() { const stateNodeMap = new Map<string, StateNode>(); for (const state of this.states) { stateNodeMap.set(state.name, { name: state.name, to: [], }); } for (const [name, stateNode] of stateNodeMap.entries()) { const targets = this.states.find((s) => s.name === name)?.to ?? []; for (const target of targets) { const targetNode = stateNodeMap.get(target); if (targetNode) { stateNode.to.push(targetNode); } } } this.nodes = [...stateNodeMap.values()].filter((n) => n.name !== 'Cancelled'); } private populateEdges() { for (const node of this.nodes) { const nodeCmp = this.getNodeFor(node.name); let index = 0; for (const to of node.to) { const toCmp = this.getNodeFor(to.name); if (nodeCmp && toCmp && nodeCmp !== toCmp) { this.edges.push({ to: toCmp, from: nodeCmp, index, }); index++; } } } this.edges = [...this.edges]; this.changeDetector.markForCheck(); } }
import { ChangeDetectionStrategy, Component, ElementRef, Input, OnChanges, SimpleChanges, } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { NODE_HEIGHT } from './constants'; import { StateNode } from './types'; @Component({ selector: 'vdr-order-process-node', templateUrl: './order-process-node.component.html', styleUrls: ['./order-process-node.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderProcessNodeComponent implements OnChanges { @Input() node: StateNode; @Input() index: number; @Input() active: boolean; active$ = new BehaviorSubject<boolean>(false); activeTarget$ = new BehaviorSubject<boolean>(false); isCancellable = false; // We use a class field here to prevent the // i18n extractor from extracting a "Cancelled" key cancelledState = 'Cancelled'; constructor(private elementRef: ElementRef<HTMLDivElement>) {} ngOnChanges(changes: SimpleChanges) { this.isCancellable = !!this.node.to.find((s) => s.name === 'Cancelled'); if (changes.active) { this.active$.next(this.active); } } getPos(origin: 'top' | 'bottom' = 'top'): { x: number; y: number } { const rect = this.elementRef.nativeElement.getBoundingClientRect(); const nodeHeight = this.elementRef.nativeElement.querySelector('.node')?.getBoundingClientRect().height ?? 0; return { x: 10, y: this.index * NODE_HEIGHT + (origin === 'bottom' ? nodeHeight : 0), }; } getStyle() { const pos = this.getPos(); return { 'top.px': pos.y, 'left.px': pos.x, }; } }
export type StateNode = { name: string; to: StateNode[]; };
import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Dialog } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-order-state-select-dialog', templateUrl: './order-state-select-dialog.component.html', styleUrls: ['./order-state-select-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderStateSelectDialogComponent implements Dialog<string> { resolveWith: (result?: string) => void; nextStates: string[] = []; message = ''; cancellable: boolean; selectedState = ''; select() { if (this.selectedState) { this.resolveWith(this.selectedState); } } cancel() { this.resolveWith(); } }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { AdjustmentType, CustomFieldConfig, OrderDetailFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-order-table', templateUrl: './order-table.component.html', styleUrls: ['./order-table.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class OrderTableComponent implements OnInit { @Input() order: OrderDetailFragment; @Input() orderLineCustomFields: CustomFieldConfig[]; @Input() isDraft = false; @Output() adjust = new EventEmitter<{ lineId: string; quantity: number }>(); @Output() remove = new EventEmitter<{ lineId: string }>(); orderLineCustomFieldsVisible = false; customFieldsForLine: { [lineId: string]: Array<{ config: CustomFieldConfig; formGroup: UntypedFormGroup; value: any }>; } = {}; get visibleOrderLineCustomFields(): CustomFieldConfig[] { return this.orderLineCustomFieldsVisible ? this.orderLineCustomFields : []; } get showElided(): boolean { return !this.orderLineCustomFieldsVisible && 0 < this.orderLineCustomFields.length; } ngOnInit(): void { this.orderLineCustomFieldsVisible = this.orderLineCustomFields.length < 2; this.getLineCustomFields(); } draftInputBlur(line: OrderDetailFragment['lines'][number], quantity: number) { if (line.quantity !== quantity) { this.adjust.emit({ lineId: line.id, quantity }); } } toggleOrderLineCustomFields() { this.orderLineCustomFieldsVisible = !this.orderLineCustomFieldsVisible; } getLineDiscounts(line: OrderDetailFragment['lines'][number]) { return line.discounts.filter(a => a.type === AdjustmentType.PROMOTION); } private getLineCustomFields() { for (const line of this.order.lines) { const formGroup = new UntypedFormGroup({}); const result = this.orderLineCustomFields .map(config => { const value = (line as any).customFields[config.name]; formGroup.addControl(config.name, new UntypedFormControl(value)); return { config, formGroup, value, }; }) .filter(field => this.orderLineCustomFieldsVisible ? true : field.value != null); this.customFieldsForLine[line.id] = result; } } getPromotionLink(promotion: OrderDetailFragment['discounts'][number]): any[] { const id = promotion.adjustmentSource.split(':')[1]; return ['/marketing', 'promotions', id]; } getCouponCodeForAdjustment( order: OrderDetailFragment, promotionAdjustment: OrderDetailFragment['discounts'][number], ): string | undefined { const id = promotionAdjustment.adjustmentSource.split(':')[1]; const promotion = order.promotions.find(p => p.id === id); if (promotion) { return promotion.couponCode || undefined; } } getShippingNames(order: OrderDetailFragment) { if (order.shippingLines.length) { return order.shippingLines.map(shippingLine => shippingLine.shippingMethod.name).join(', '); } else { return ''; } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { CurrencyCode, OrderDetailFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-payment-detail', templateUrl: './payment-detail.component.html', styleUrls: ['./payment-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PaymentDetailComponent { @Input() payment: NonNullable<OrderDetailFragment['payments']>[number]; @Input() currencyCode: CurrencyCode; }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { OrderDetailFragment } from '@vendure/admin-ui/core'; import { RefundablePayment } from '../../common/get-refundable-payments'; @Component({ selector: 'vdr-payment-for-refund-selector', templateUrl: './payment-for-refund-selector.component.html', styleUrls: ['./payment-for-refund-selector.component.scss'], changeDetection: ChangeDetectionStrategy.Default, }) export class PaymentForRefundSelectorComponent { @Input() refundablePayments: RefundablePayment[]; @Input() order: OrderDetailFragment; @Output() paymentSelected = new EventEmitter<{ payment: RefundablePayment; selected: boolean }>(); }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-payment-state-label', templateUrl: './payment-state-label.component.html', styleUrls: ['./payment-state-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PaymentStateLabelComponent { @Input() state: string; get chipColorType() { switch (this.state) { case 'Authorized': return 'warning'; case 'Settled': return 'success'; case 'Declined': case 'Cancelled': return 'error'; } } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; import { CurrencyCode, OrderDetailFragment } from '@vendure/admin-ui/core'; @Component({ selector: 'vdr-refund-detail', templateUrl: './refund-detail.component.html', styleUrls: ['./refund-detail.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RefundDetailComponent { @Input() refund: NonNullable<OrderDetailFragment['payments']>[number]['refunds'][number]; @Input() currencyCode: CurrencyCode; }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; import { CancelOrderInput, Dialog, getAppConfig, I18nService, OrderDetailFragment, OrderLineInput, PaymentWithRefundsFragment, RefundOrderInput, } from '@vendure/admin-ui/core'; import { summate } from '@vendure/common/lib/shared-utils'; import { getRefundablePayments, RefundablePayment } from '../../common/get-refundable-payments'; type SelectionLine = { quantity: number; cancel: boolean }; @Component({ selector: 'vdr-refund-order-dialog', templateUrl: './refund-order-dialog.component.html', styleUrls: ['./refund-order-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RefundOrderDialogComponent implements OnInit, Dialog<{ cancel: CancelOrderInput; refunds: RefundOrderInput[] }> { order: OrderDetailFragment; resolveWith: (result?: { cancel: CancelOrderInput; refunds: RefundOrderInput[] }) => void; reason: string; lineQuantities: { [lineId: string]: SelectionLine } = {}; refundablePayments: RefundablePayment[] = []; refundShippingLineIds: string[] = []; reasons = getAppConfig().cancellationReasons ?? [ _('order.refund-reason-customer-request'), _('order.refund-reason-not-available'), ]; manuallySetRefundTotal = false; refundTotal = 0; constructor(private i18nService: I18nService) { this.reasons = this.reasons.map(r => this.i18nService.translate(r)); } get totalRefundableAmount(): number { return summate(this.refundablePayments, 'refundableAmount'); } get amountToRefundTotal(): number { return this.refundablePayments.reduce( (total, payment) => total + payment.amountToRefundControl.value, 0, ); } lineCanBeRefundedOrCancelled(line: OrderDetailFragment['lines'][number]): boolean { const refundedCount = this.order.payments ?.reduce( (all, payment) => [...all, ...payment.refunds], [] as PaymentWithRefundsFragment['refunds'], ) .filter(refund => refund.state !== 'Failed') .reduce( (all, refund) => [...all, ...refund.lines], [] as Array<{ orderLineId: string; quantity: number }>, ) .filter(refundLine => refundLine.orderLineId === line.id) .reduce((sum, refundLine) => sum + refundLine.quantity, 0) ?? 0; return refundedCount < line.orderPlacedQuantity; } ngOnInit() { this.lineQuantities = this.order.lines.reduce( (result, line) => ({ ...result, [line.id]: { quantity: 0, refund: true, cancel: false, }, }), {}, ); this.refundablePayments = getRefundablePayments(this.order.payments); } updateRefundTotal() { if (!this.manuallySetRefundTotal) { const itemTotal = this.order.lines.reduce((total, line) => { const lineRef = this.lineQuantities[line.id]; const refundCount = lineRef.quantity || 0; return total + line.proratedUnitPriceWithTax * refundCount; }, 0); const shippingTotal = this.order.shippingLines.reduce((total, line) => { if (this.refundShippingLineIds.includes(line.id)) { return total + line.discountedPriceWithTax; } else { return total; } }, 0); this.refundTotal = itemTotal + shippingTotal; } // allocate the refund total across the refundable payments const refundablePayments = this.refundablePayments.filter(p => p.selected); let refundsAllocated = 0; for (const payment of refundablePayments) { const amountToRefund = Math.min(payment.refundableAmount, this.refundTotal - refundsAllocated); payment.amountToRefundControl.setValue(amountToRefund); refundsAllocated += amountToRefund; } } toggleShippingRefund(lineId: string) { const index = this.refundShippingLineIds.indexOf(lineId); if (index === -1) { this.refundShippingLineIds.push(lineId); } else { this.refundShippingLineIds.splice(index, 1); } this.updateRefundTotal(); } onRefundQuantityChange(orderLineId: string, quantity: number) { this.manuallySetRefundTotal = false; const selectionLine = this.lineQuantities[orderLineId]; if (selectionLine) { const previousQuantity = selectionLine.quantity; if (quantity === 0) { selectionLine.cancel = false; } else if (previousQuantity === 0 && quantity > 0) { selectionLine.cancel = true; } selectionLine.quantity = quantity; this.updateRefundTotal(); } } onPaymentSelected(payment: RefundablePayment, selected: boolean) { if (selected) { const outstandingRefundAmount = this.refundTotal - this.refundablePayments .filter(p => p.id !== payment.id) .reduce((total, p) => total + p.amountToRefundControl.value, 0); if (0 < outstandingRefundAmount) { payment.amountToRefundControl.setValue( Math.min(outstandingRefundAmount, payment.refundableAmount), ); } } else { payment.amountToRefundControl.setValue(0); } } isRefunding(): boolean { const result = Object.values(this.lineQuantities).reduce( (isRefunding, line) => isRefunding || 0 < line.quantity, false, ); return result; } isCancelling(): boolean { const result = Object.values(this.lineQuantities).reduce( (isCancelling, line) => isCancelling || (0 < line.quantity && line.cancel), false, ); return result; } canSubmit(): boolean { return 0 < this.refundTotal && this.amountToRefundTotal === this.refundTotal && !!this.reason; } select() { const refundLines = this.getOrderLineInput(() => true); const cancelLines = this.getOrderLineInput(line => line.cancel); this.resolveWith({ refunds: this.refundablePayments .filter(rp => rp.selected && 0 < rp.amountToRefundControl.value) .map(payment => { return { lines: refundLines, reason: this.reason, paymentId: payment.id, amount: payment.amountToRefundControl.value, shipping: 0, adjustment: 0, }; }), cancel: { lines: cancelLines, orderId: this.order.id, reason: this.reason, cancelShipping: this.refundShippingLineIds.length > 0, }, }); } cancel() { this.resolveWith(); } private getOrderLineInput(filterFn: (line: SelectionLine) => boolean): OrderLineInput[] { return Object.entries(this.lineQuantities) .filter(([orderLineId, line]) => 0 < line.quantity && filterFn(line)) .map(([orderLineId, line]) => ({ orderLineId, quantity: line.quantity, })); } }
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'vdr-refund-state-label', templateUrl: './refund-state-label.component.html', styleUrls: ['./refund-state-label.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RefundStateLabelComponent { @Input() state: string; get chipColorType() { switch (this.state) { case 'Pending': return 'warning'; case 'Settled': return 'success'; case 'Failed': return 'error'; } } }
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { AddressFragment, CreateAddressInput, DataService, Dialog, GetAvailableCountriesQuery, GetCustomerAddressesDocument, OrderAddressFragment, } from '@vendure/admin-ui/core'; import { pick } from '@vendure/common/lib/pick'; import { Observable, of } from 'rxjs'; import { tap } from 'rxjs/operators'; import { Customer } from '../select-customer-dialog/select-customer-dialog.component'; @Component({ selector: 'vdr-select-address-dialog', templateUrl: './select-address-dialog.component.html', styleUrls: ['./select-address-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectAddressDialogComponent implements OnInit, Dialog<CreateAddressInput> { resolveWith: (result?: CreateAddressInput) => void; availableCountries$: Observable<GetAvailableCountriesQuery['countries']['items']>; addresses$: Observable<AddressFragment[]>; customerId: string | undefined; currentAddress: OrderAddressFragment | undefined; addressForm: UntypedFormGroup; selectedAddress: AddressFragment | undefined; useExisting = true; createNew = false; constructor(private dataService: DataService, private formBuilder: UntypedFormBuilder) {} ngOnInit(): void { this.addressForm = this.formBuilder.group({ fullName: [this.currentAddress?.fullName ?? ''], company: [this.currentAddress?.company ?? ''], streetLine1: [this.currentAddress?.streetLine1 ?? '', Validators.required], streetLine2: [this.currentAddress?.streetLine2 ?? ''], city: [this.currentAddress?.city ?? '', Validators.required], province: [this.currentAddress?.province ?? ''], postalCode: [this.currentAddress?.postalCode ?? '', Validators.required], countryCode: [this.currentAddress?.countryCode ?? '', Validators.required], phoneNumber: [this.currentAddress?.phoneNumber ?? ''], }); this.useExisting = !!this.customerId; this.addresses$ = this.customerId ? this.dataService .query(GetCustomerAddressesDocument, { customerId: this.customerId }) .mapSingle(({ customer }) => customer?.addresses ?? []) .pipe( tap(addresses => { if (this.currentAddress) { this.selectedAddress = addresses.find( a => a.streetLine1 === this.currentAddress?.streetLine1 && a.postalCode === this.currentAddress?.postalCode, ); } if (addresses.length === 0) { this.createNew = true; this.useExisting = false; } }), ) : of([]); this.availableCountries$ = this.dataService.settings .getAvailableCountries() .mapSingle(({ countries }) => countries.items); } trackByFn(item: Customer) { return item.id; } addressIdFn(item: AddressFragment) { return item.streetLine1 + item.postalCode; } cancel() { this.resolveWith(); } select() { if (this.useExisting && this.selectedAddress) { this.resolveWith({ ...pick(this.selectedAddress, [ 'fullName', 'company', 'streetLine1', 'streetLine2', 'city', 'province', 'phoneNumber', 'postalCode', ]), countryCode: this.selectedAddress.country.code, }); } if (this.createNew && this.addressForm.valid) { const formValue = this.addressForm.value; this.resolveWith(formValue); } } }
import { ADDRESS_FRAGMENT } from '@vendure/admin-ui/core'; import { gql } from 'apollo-angular'; export const GET_CUSTOMER_ADDRESSES = gql` query GetCustomerAddresses($customerId: ID!) { customer(id: $customerId) { id addresses { ...Address } } } ${ADDRESS_FRAGMENT} `;
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { CreateCustomerInput, DataService, Dialog, GetCustomerListQuery } from '@vendure/admin-ui/core'; import { concat, Observable, of, Subject } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, switchMap, tap } from 'rxjs/operators'; import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker'; export type Customer = GetCustomerListQuery['customers']['items'][number]; export type SelectCustomerDialogResult = (Customer | CreateCustomerInput) & { note: string }; @Component({ selector: 'vdr-select-customer-dialog', templateUrl: './select-customer-dialog.component.html', styleUrls: ['./select-customer-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectCustomerDialogComponent implements OnInit, Dialog<SelectCustomerDialogResult> { resolveWith: (result?: SelectCustomerDialogResult) => void; // populated by the dialog service canCreateNew = true; includeNoteInput = false; title: string = _('order.set-customer-for-order'); customerForm: UntypedFormGroup; customers$: Observable<Customer[]>; isLoading = false; input$ = new Subject<string>(); selectedCustomer: Customer[] = []; useExisting = true; createNew = false; note = ''; constructor(private dataService: DataService, private formBuilder: UntypedFormBuilder) { this.customerForm = this.formBuilder.group({ title: '', firstName: ['', Validators.required], lastName: ['', Validators.required], phoneNumber: '', emailAddress: ['', [Validators.required, Validators.email]], }); } ngOnInit(): void { this.customers$ = concat( of([]), // default items this.input$.pipe( debounceTime(200), distinctUntilChanged(), tap(() => (this.isLoading = true)), switchMap(term => this.dataService.customer .getCustomerList(10, 0, term) .mapStream(({ customers }) => customers.items) .pipe( catchError(() => of([])), // empty list on error tap(() => (this.isLoading = false)), ), ), ), ); } trackByFn(item: Customer) { return item.id; } cancel() { this.resolveWith(); } select() { if (this.useExisting && this.selectedCustomer.length === 1) { this.resolveWith({ ...this.selectedCustomer[0], note: this.note }); } else if (this.createNew && this.customerForm.valid) { const formValue = this.customerForm.value; this.resolveWith({ ...formValue, note: this.note }); } } }
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { CreateAddressInput, CurrencyCode, Dialog, DraftOrderEligibleShippingMethodsQuery, } from '@vendure/admin-ui/core'; type ShippingMethodQuote = DraftOrderEligibleShippingMethodsQuery['eligibleShippingMethodsForDraftOrder'][number]; @Component({ selector: 'vdr-select-shipping-method-dialog', templateUrl: './select-shipping-method-dialog.component.html', styleUrls: ['./select-shipping-method-dialog.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SelectShippingMethodDialogComponent implements OnInit, Dialog<string> { resolveWith: (result?: string) => void; eligibleShippingMethods: ShippingMethodQuote[]; currentSelectionId: string; currencyCode: CurrencyCode; selectedMethod: ShippingMethodQuote | undefined; ngOnInit(): void { if (this.currentSelectionId) { this.selectedMethod = this.eligibleShippingMethods.find(m => m.id === this.currentSelectionId); } } methodIdFn(item: ShippingMethodQuote) { return item.id; } cancel() { this.resolveWith(); } select() { if (this.selectedMethod) { this.resolveWith(this.selectedMethod.id); } } }
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ChannelService, DataService, GetSellerOrdersQuery, GetSellerOrdersQueryVariables, } from '@vendure/admin-ui/core'; import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants'; import { Observable } from 'rxjs'; import { GET_SELLER_ORDERS } from './seller-orders-card.graphql'; type SellerOrder = NonNullable<NonNullable<GetSellerOrdersQuery['order']>['sellerOrders']>[number]; @Component({ selector: 'vdr-seller-orders-card', templateUrl: './seller-orders-card.component.html', styleUrls: ['./seller-orders-card.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SellerOrdersCardComponent implements OnInit { @Input() orderId: string; sellerOrders$: Observable<SellerOrder[]>; constructor( private router: Router, private dataService: DataService, private channelService: ChannelService, ) {} ngOnInit() { this.sellerOrders$ = this.dataService .query<GetSellerOrdersQuery, GetSellerOrdersQueryVariables>(GET_SELLER_ORDERS, { orderId: this.orderId, }) .mapSingle(({ order }) => order?.sellerOrders ?? []); } getSeller(order: SellerOrder) { const sellerChannel = order.channels.find(channel => channel.code !== DEFAULT_CHANNEL_CODE); return sellerChannel?.seller; } navigateToSellerOrder(order: SellerOrder) { this.router.navigate(['/orders', order.id]); } }
import { gql } from 'apollo-angular'; export const GET_SELLER_ORDERS = gql` query GetSellerOrders($orderId: ID!) { order(id: $orderId) { id sellerOrders { id code state orderPlacedAt currencyCode totalWithTax channels { id code seller { id name } } } } } `;