Browse Source

refactor(admin-ui): Tidy up order & collection list components

Michael Bromley 2 years ago
parent
commit
84d620b4aa

+ 17 - 76
packages/admin-ui/src/lib/catalog/src/components/collection-list/collection-list.component.ts

@@ -1,22 +1,16 @@
-import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
-import { ActivatedRoute, Router } from '@angular/router';
+import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
 import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
 import {
-    BaseListComponent,
-    CollectionFilterParameter,
-    CollectionSortParameter,
     DataService,
-    DataTableService,
+    GetCollectionListDocument,
     GetCollectionListQuery,
     ItemOf,
     LanguageCode,
-    ModalService,
-    NavBuilderService,
     NotificationService,
-    ServerConfigService,
+    TypedBaseListComponent,
 } from '@vendure/admin-ui/core';
-import { combineLatest, EMPTY, Observable, of } from 'rxjs';
-import { distinctUntilChanged, map, switchMap, take, takeUntil, tap } from 'rxjs/operators';
+import { combineLatest, Observable, of } from 'rxjs';
+import { distinctUntilChanged, map, switchMap, takeUntil } from 'rxjs/operators';
 import { CollectionOrderEvent } from '../collection-data-table/collection-data-table.component';
 
 @Component({
@@ -26,19 +20,16 @@ import { CollectionOrderEvent } from '../collection-data-table/collection-data-t
     changeDetection: ChangeDetectionStrategy.OnPush,
 })
 export class CollectionListComponent
-    extends BaseListComponent<GetCollectionListQuery, ItemOf<GetCollectionListQuery, 'collections'>>
+    extends TypedBaseListComponent<typeof GetCollectionListDocument, 'collections'>
     implements OnInit
 {
     activeCollectionId$: Observable<string | null>;
     activeCollectionIndex$: Observable<number>;
     activeCollectionTitle$: Observable<string>;
     subCollections$: Observable<Array<ItemOf<GetCollectionListQuery, 'collections'>>>;
-    availableLanguages$: Observable<LanguageCode[]>;
-    contentLanguage$: Observable<LanguageCode>;
     expandedIds: string[] = [];
-    readonly customFields = this.serverConfigService.getCustomFieldsFor('Collection');
-    readonly filters = this.dataTableService
-        .createFilterCollection<CollectionFilterParameter>()
+    readonly customFields = this.getCustomFieldConfig('Collection');
+    readonly filters = this.createFilterCollection()
         .addDateFilters()
         .addFilter({
             name: 'slug',
@@ -56,8 +47,7 @@ export class CollectionListComponent
         })
         .addCustomFieldFilters(this.customFields)
         .connectToRoute(this.route);
-    readonly sorts = this.dataTableService
-        .createSortCollection<CollectionSortParameter>()
+    readonly sorts = this.createSortCollection()
         .defaultSort('position', 'ASC')
         .addSort({ name: 'createdAt' })
         .addSort({ name: 'updatedAt' })
@@ -67,21 +57,12 @@ export class CollectionListComponent
         .addCustomFieldSorts(this.customFields)
         .connectToRoute(this.route);
 
-    constructor(
-        private dataService: DataService,
-        private notificationService: NotificationService,
-        private modalService: ModalService,
-        router: Router,
-        route: ActivatedRoute,
-        private serverConfigService: ServerConfigService,
-        private changeDetectorRef: ChangeDetectorRef,
-        private dataTableService: DataTableService,
-    ) {
-        super(router, route);
-        super.setQueryFn(
-            (...args: any[]) => this.dataService.collection.getCollections().refetchOnChannelChange(),
-            data => data.collections,
-            (skip, _take) => {
+    constructor(protected dataService: DataService, private notificationService: NotificationService) {
+        super();
+        super.configure({
+            document: GetCollectionListDocument,
+            getItems: data => data.collections,
+            setVariables: (skip, _take) => {
                 const topLevelOnly =
                     this.searchTermControl.value === '' && this.filters.activeFilters.length === 0
                         ? true
@@ -99,7 +80,8 @@ export class CollectionListComponent
                     },
                 };
             },
-        );
+            refreshListOnChanges: [this.filters.valueChanges, this.sorts.valueChanges],
+        });
     }
 
     ngOnInit() {
@@ -166,13 +148,6 @@ export class CollectionListComponent
                 return -1;
             }),
         );
-        this.availableLanguages$ = this.serverConfigService.getAvailableLanguages();
-        this.contentLanguage$ = this.dataService.client
-            .uiState()
-            .mapStream(({ uiState }) => uiState.contentLanguage)
-            .pipe(tap(() => this.refresh()));
-
-        super.refreshListOnChanges(this.contentLanguage$, this.filters.valueChanges, this.sorts.valueChanges);
     }
 
     onRearrange(event: CollectionOrderEvent) {
@@ -187,40 +162,6 @@ export class CollectionListComponent
         });
     }
 
-    deleteCollection(id: string) {
-        this.items$
-            .pipe(
-                take(1),
-                map(items => -1 < items.findIndex(i => i.parentId === id)),
-                switchMap(hasChildren =>
-                    this.modalService.dialog({
-                        title: _('catalog.confirm-delete-collection'),
-                        body: hasChildren
-                            ? _('catalog.confirm-delete-collection-and-children-body')
-                            : undefined,
-                        buttons: [
-                            { type: 'secondary', label: _('common.cancel') },
-                            { type: 'danger', label: _('common.delete'), returnValue: true },
-                        ],
-                    }),
-                ),
-                switchMap(response => (response ? this.dataService.collection.deleteCollection(id) : EMPTY)),
-            )
-            .subscribe(
-                () => {
-                    this.notificationService.success(_('common.notify-delete-success'), {
-                        entity: 'Collection',
-                    });
-                    this.refresh();
-                },
-                err => {
-                    this.notificationService.error(_('common.notify-delete-error'), {
-                        entity: 'Collection',
-                    });
-                },
-            );
-    }
-
     closeContents() {
         const params = { ...this.route.snapshot.params };
         delete params.contents;

File diff suppressed because it is too large
+ 8 - 0
packages/admin-ui/src/lib/core/src/common/generated-types.ts


+ 0 - 20
packages/admin-ui/src/lib/core/src/providers/data-table/data-table.service.ts

@@ -1,20 +0,0 @@
-import { Injectable } from '@angular/core';
-import { Router } from '@angular/router';
-
-import { DataTableFilterCollection } from './data-table-filter-collection';
-import { DataTableSortCollection } from './data-table-sort-collection';
-
-@Injectable({
-    providedIn: 'root',
-})
-export class DataTableService {
-    constructor(private router: Router) {}
-
-    createFilterCollection<FilterInput extends Record<string, any>>() {
-        return new DataTableFilterCollection<FilterInput>(this.router);
-    }
-
-    createSortCollection<SortInput extends Record<string, any>>() {
-        return new DataTableSortCollection<SortInput>(this.router);
-    }
-}

+ 0 - 1
packages/admin-ui/src/lib/core/src/public_api.ts

@@ -92,7 +92,6 @@ export * from './providers/data-table/data-table-filter-collection';
 export * from './providers/data-table/data-table-filter';
 export * from './providers/data-table/data-table-sort-collection';
 export * from './providers/data-table/data-table-sort';
-export * from './providers/data-table/data-table.service';
 export * from './providers/guard/auth.guard';
 export * from './providers/health-check/health-check.service';
 export * from './providers/i18n/custom-http-loader';

+ 39 - 10
packages/admin-ui/src/lib/dashboard/src/widgets/latest-orders-widget/latest-orders-widget.component.ts

@@ -2,13 +2,40 @@ import { ChangeDetectionStrategy, Component, NgModule, OnInit } from '@angular/c
 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',
@@ -16,19 +43,21 @@ import { Observable } from 'rxjs';
     changeDetection: ChangeDetectionStrategy.OnPush,
 })
 export class LatestOrdersWidgetComponent implements OnInit {
-    latestOrders$: Observable<Array<ItemOf<GetOrderListQuery, 'orders'>>>;
+    latestOrders$: Observable<Array<ItemOf<GetLatestOrdersQuery, 'orders'>>>;
     constructor(private dataService: DataService) {}
 
     ngOnInit(): void {
-        this.latestOrders$ = this.dataService.order
-            .getOrders({
-                take: 10,
-                filter: {
-                    active: { eq: false },
-                    state: { notIn: ['Cancelled', 'Draft'] },
-                },
-                sort: {
-                    orderPlacedAt: SortOrder.DESC,
+        this.latestOrders$ = this.dataService
+            .query(GetLatestOrdersDocument, {
+                options: {
+                    take: 10,
+                    filter: {
+                        active: { eq: false },
+                        state: { notIn: ['Cancelled', 'Draft'] },
+                    },
+                    sort: {
+                        orderPlacedAt: SortOrder.DESC,
+                    },
                 },
             })
             .refetchOnChannelChange()

+ 18 - 1
packages/admin-ui/src/lib/order/src/components/order-list/order-list.component.html

@@ -1,3 +1,16 @@
+<vdr-page-block>
+    <vdr-action-bar>
+        <vdr-ab-right>
+            <vdr-action-bar-items locationId="order-list"></vdr-action-bar-items>
+            <ng-container *ngIf="canCreateDraftOrder">
+                <a class="btn" *vdrIfPermissions="['CreateOrder']" [routerLink]="['./draft/create']">
+                    <clr-icon shape="plus"></clr-icon>
+                    {{ 'catalog.create-draft-order' | translate }}
+                </a>
+            </ng-container>
+        </vdr-ab-right>
+    </vdr-action-bar>
+</vdr-page-block>
 <vdr-data-table-2
     class="mt-2"
     id="order-list"
@@ -74,5 +87,9 @@
             {{ getShippingNames(order) }}
         </ng-template>
     </vdr-dt2-column>
-    <vdr-dt2-custom-field-column *ngFor="let customField of customFields" [customField]="customField" [sorts]="sorts" />
+    <vdr-dt2-custom-field-column
+        *ngFor="let customField of customFields"
+        [customField]="customField"
+        [sorts]="sorts"
+    />
 </vdr-data-table-2>

+ 14 - 41
packages/admin-ui/src/lib/order/src/components/order-list/order-list.component.ts

@@ -1,21 +1,13 @@
 import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
-import { ActivatedRoute, Router } from '@angular/router';
 import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
 import {
-    BaseListComponent,
     ChannelService,
-    DataService,
-    DataTableService,
-    GetOrderListQuery,
+    GetOrderListDocument,
     getOrderStateTranslationToken,
-    ItemOf,
-    LocalStorageService,
-    NavBuilderService,
-    OrderFilterParameter,
     OrderListOptions,
-    OrderSortParameter,
     OrderType,
     ServerConfigService,
+    TypedBaseListComponent,
 } from '@vendure/admin-ui/core';
 import { Order } from '@vendure/common/lib/generated-types';
 import { tap } from 'rxjs/operators';
@@ -27,13 +19,12 @@ import { tap } from 'rxjs/operators';
     changeDetection: ChangeDetectionStrategy.OnPush,
 })
 export class OrderListComponent
-    extends BaseListComponent<GetOrderListQuery, ItemOf<GetOrderListQuery, 'orders'>>
+    extends TypedBaseListComponent<typeof GetOrderListDocument, 'orders'>
     implements OnInit
 {
     orderStates = this.serverConfigService.getOrderProcessStates().map(item => item.name);
-    readonly customFields = this.serverConfigService.getCustomFieldsFor('Order');
-    readonly filters = this.dataTableService
-        .createFilterCollection<OrderFilterParameter>()
+    readonly customFields = this.getCustomFieldConfig('Order');
+    readonly filters = this.createFilterCollection()
         .addDateFilters()
         .addFilter({
             name: 'active',
@@ -77,8 +68,7 @@ export class OrderListComponent
         .addCustomFieldFilters(this.customFields)
         .connectToRoute(this.route);
 
-    readonly sorts = this.dataTableService
-        .createSortCollection<OrderSortParameter>()
+    readonly sorts = this.createSortCollection()
         .defaultSort('updatedAt', 'DESC')
         .addSort({ name: 'id' })
         .addSort({ name: 'createdAt' })
@@ -93,32 +83,15 @@ export class OrderListComponent
     canCreateDraftOrder = false;
     private activeChannelIsDefaultChannel = false;
 
-    constructor(
-        private serverConfigService: ServerConfigService,
-        private dataService: DataService,
-        private localStorageService: LocalStorageService,
-        private channelService: ChannelService,
-        private dataTableService: DataTableService,
-        navBuilderService: NavBuilderService,
-        router: Router,
-        route: ActivatedRoute,
-    ) {
-        super(router, route);
-        navBuilderService.addActionBarItem({
-            id: 'create-draft-order',
-            label: _('catalog.create-draft-order'),
-            locationId: 'order-list',
-            icon: 'plus',
-            routerLink: ['./draft/create'],
-            requiresPermission: ['CreateOrder'],
+    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],
         });
-        super.setQueryFn(
-            // eslint-disable-next-line @typescript-eslint/no-shadow
-            (take, skip) => this.dataService.order.getOrders({ take, skip }).refetchOnChannelChange(),
-            data => data.orders,
-            // eslint-disable-next-line @typescript-eslint/no-shadow
-            (skip, take) => this.createQueryOptions(skip, take, this.searchTermControl.value),
-        );
+
         this.canCreateDraftOrder = !!this.serverConfigService
             .getOrderProcessStates()
             .find(state => state.name === 'Created')

Some files were not shown because too many files changed in this diff