Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce guard to change routing targets if quote cart #17669

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion feature-libs/cart/base/root/cart-base-root.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
MINI_CART_FEATURE,
} from './feature-name';
import { ActiveCartOrderEntriesContextToken } from './tokens/context';
import { QuoteCartGuard } from './guards/quote-cart.guard';

export function defaultCartComponentsConfig() {
const config = {
Expand Down Expand Up @@ -63,7 +64,7 @@ export function defaultCartComponentsConfig() {
{
// @ts-ignore
path: null,
canActivate: [CmsPageGuard],
canActivate: [CmsPageGuard, QuoteCartGuard],
component: PageLayoutComponent,
data: {
cxRoute: 'cart',
Expand Down
8 changes: 8 additions & 0 deletions feature-libs/cart/base/root/guards/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* SPDX-FileCopyrightText: 2023 SAP Spartacus team <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/

export * from './quote-cart.service';
export * from './quote-cart.guard';
40 changes: 40 additions & 0 deletions feature-libs/cart/base/root/guards/quote-cart.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* SPDX-FileCopyrightText: 2023 SAP Spartacus team <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/

import { Injectable } from '@angular/core';
import { CanActivate, UrlTree } from '@angular/router';

import { Observable, combineLatest } from 'rxjs';
import { QuoteCartService } from './quote-cart.service';
import { map } from 'rxjs/operators';
import { RoutingService } from '@spartacus/core';

@Injectable({
providedIn: 'root',
})
export class QuoteCartGuard implements CanActivate {
constructor(
protected routingService: RoutingService,
protected quoteCartService: QuoteCartService
) {}
canActivate(): Observable<boolean | UrlTree> {
return combineLatest([
this.quoteCartService.getQuoteCartActive(),
this.quoteCartService.getQuoteId(),
]).pipe(
map(([isQuoteCartActive, quoteId]) => {
if (isQuoteCartActive) {
this.routingService.go({
cxRoute: 'quoteDetails',
params: { quoteId: quoteId },
});
return false;
}
return true;
})
);
}
}
37 changes: 37 additions & 0 deletions feature-libs/cart/base/root/guards/quote-cart.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* SPDX-FileCopyrightText: 2023 SAP Spartacus team <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/

import { Injectable } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class QuoteCartService {
private quoteId: Observable<string> = new ReplaySubject<string>(1);
private quoteCartActive: Observable<boolean> = new ReplaySubject<boolean>(1);

constructor() {
(this.quoteCartActive as ReplaySubject<boolean>).next(false);
(this.quoteId as ReplaySubject<string>).next('');
}

public setQuoteId(quoteId: string): void {
(this.quoteId as ReplaySubject<string>).next(quoteId);
}

public getQuoteId(): Observable<string> {
return this.quoteId;
}

public setQuoteCartActive(quoteCartActive: boolean): void {
(this.quoteCartActive as ReplaySubject<boolean>).next(quoteCartActive);
}

public getQuoteCartActive(): Observable<boolean> {
return this.quoteCartActive;
}
}
1 change: 1 addition & 0 deletions feature-libs/cart/base/root/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from './facade/index';
export * from './feature-name';
export * from './models/index';
export * from './tokens/index';
export * from './guards/index';

/** AUGMENTABLE_TYPES_START */
export { Cart, DeliveryMode, OrderEntry } from './models/cart.model';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CartNotEmptyGuard } from '../guards/cart-not-empty.guard';
import { CheckoutAuthGuard } from '../guards/checkout-auth.guard';
import { CheckoutGuard } from '../guards/checkout.guard';
import { CheckoutOrchestratorComponent } from './checkout-orchestrator.component';
import { QuoteCartGuard } from '@spartacus/cart/base/root';

@NgModule({
imports: [CommonModule],
Expand All @@ -19,7 +20,12 @@ import { CheckoutOrchestratorComponent } from './checkout-orchestrator.component
cmsComponents: {
CheckoutOrchestrator: {
component: CheckoutOrchestratorComponent,
guards: [CheckoutAuthGuard, CartNotEmptyGuard, CheckoutGuard],
guards: [
QuoteCartGuard,
CheckoutAuthGuard,
CartNotEmptyGuard,
CheckoutGuard,
],
},
},
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ import { QuoteActionsByRoleComponent } from './quote-actions-by-role.component';
QuoteActionType.SUBMIT,
],
actionsOrderByState: {
BUYER_DRAFT: [QuoteActionType.CANCEL, QuoteActionType.SUBMIT],
BUYER_DRAFT: [
QuoteActionType.CANCEL,
QuoteActionType.EDIT,
QuoteActionType.SUBMIT,
],
BUYER_OFFER: [
QuoteActionType.CANCEL,
QuoteActionType.EDIT,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { TestBed } from '@angular/core/testing';
import {
CartAddEntryFailEvent,
CartUiEventAddToCart,
} from '@spartacus/cart/base/root';
import { CxEvent, EventService } from '@spartacus/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { QuoteAddedToCartEventListener } from './quote-added-to-cart-event.listener';

const mockEventStream$ = new BehaviorSubject<CxEvent>({});

class MockEventService implements Partial<EventService> {
get(): Observable<any> {
return mockEventStream$.asObservable();
}
dispatch() {}
}

const mockEvent = new CartUiEventAddToCart();
mockEvent.productCode = 'test';
mockEvent.quantity = 3;
mockEvent.numberOfEntriesBeforeAdd = 1;
mockEvent.pickupStoreName = 'testStore';

const mockFailEvent = new CartAddEntryFailEvent();
mockFailEvent.error = {};

describe('AddToCartDialogEventListener', () => {
let listener: QuoteAddedToCartEventListener;

beforeEach(() => {
TestBed.configureTestingModule({
providers: [
QuoteAddedToCartEventListener,
{
provide: EventService,
useClass: MockEventService,
},
],
});

listener = TestBed.inject(QuoteAddedToCartEventListener);
});

describe('onAddToCart', () => {
it('Should ', () => {
expect(listener).toBeDefined();
mockEventStream$.next(mockEvent);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* SPDX-FileCopyrightText: 2023 SAP Spartacus team <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/

import { Injectable, OnDestroy } from '@angular/core';
import { CartUiEventAddToCart } from '@spartacus/cart/base/root';
import { EventService } from '@spartacus/core';
import { QuoteDetailsReloadQueryEvent } from '@spartacus/quote/root';

import { Subscription } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class QuoteAddedToCartEventListener implements OnDestroy {
protected subscription = new Subscription();

constructor(protected eventService: EventService) {
this.onAddToCart();
}

protected onAddToCart() {
this.subscription.add(
this.eventService.get(CartUiEventAddToCart).subscribe(() => {
this.eventService.dispatch({}, QuoteDetailsReloadQueryEvent);
})
);
}

ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
}
40 changes: 36 additions & 4 deletions feature-libs/quote/core/facade/quote.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
*/

import { Injectable } from '@angular/core';
import { ActiveCartFacade, MultiCartFacade } from '@spartacus/cart/base/root';
import {
ActiveCartFacade,
MultiCartFacade,
QuoteCartService,
} from '@spartacus/cart/base/root';
import {
Comment,
QuoteFacade,
Expand Down Expand Up @@ -86,6 +90,8 @@ export class QuoteService implements QuoteFacade {
active: true,
},
});
this.quoteCartService.setQuoteCartActive(true);
this.quoteCartService.setQuoteId(quote.code);
this.eventService.dispatch({}, QuoteDetailsReloadQueryEvent);
}),
map(([_, _userId, quote]) => quote)
Expand All @@ -105,6 +111,7 @@ export class QuoteService implements QuoteFacade {
(payload) =>
this.userIdService.takeUserId().pipe(
take(1),

switchMap((userId) =>
this.quoteConnector.editQuote(
userId,
Expand Down Expand Up @@ -159,6 +166,13 @@ export class QuoteService implements QuoteFacade {
tap(() => {
this.isActionPerforming$.next(false);
this.eventService.dispatch({}, QuoteDetailsReloadQueryEvent);
if (payload.quoteAction === QuoteActionType.SUBMIT) {
this.quoteCartService.setQuoteCartActive(false);
}
if (payload.quoteAction === QuoteActionType.EDIT) {
this.quoteCartService.setQuoteCartActive(true);
this.quoteCartService.setQuoteId(payload.quoteCode);
}
})
);
},
Expand Down Expand Up @@ -197,8 +211,25 @@ export class QuoteService implements QuoteFacade {
this.routingService.getRouterState().pipe(
withLatestFrom(this.userIdService.takeUserId()),
switchMap(([{ state }, userId]) =>
this.quoteConnector.getQuote(userId, state.params.quoteId)
)
zip(
this.quoteConnector.getQuote(userId, state.params.quoteId),
this.quoteCartService.getQuoteCartActive(),
this.quoteCartService.getQuoteId(),
of(userId)
)
),
tap(([quote, isActive, quoteId, userId]) => {
if (isActive && quote.code === quoteId) {
this.multiCartService.loadCart({
userId: userId,
cartId: quote.cartId as string,
extraData: {
active: true,
},
});
}
}),
map(([quote, _]) => quote)
),
{
reloadOn: [QuoteDetailsReloadQueryEvent, LoginEvent],
Expand Down Expand Up @@ -244,7 +275,8 @@ export class QuoteService implements QuoteFacade {
protected commandService: CommandService,
protected activeCartService: ActiveCartFacade,
protected routingService: RoutingService,
protected multiCartService: MultiCartFacade
protected multiCartService: MultiCartFacade,
protected quoteCartService: QuoteCartService
) {}

createQuote(quoteMetadata: QuoteMetadata): Observable<Quote> {
Expand Down
7 changes: 6 additions & 1 deletion feature-libs/quote/core/quote-core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { HttpErrorHandler } from '@spartacus/core';
import { QuoteConnector } from './connectors/quote.connector';
import { facadeProviders } from './facade/facade-providers';
import { QuoteBadRequestHandler } from './http-interceptors/quote-bad-request.handler';
import { QuoteAddedToCartEventListener } from './event/quote-added-to-cart-event.listener';

@NgModule({
providers: [
Expand All @@ -21,4 +22,8 @@ import { QuoteBadRequestHandler } from './http-interceptors/quote-bad-request.ha
},
],
})
export class QuoteCoreModule {}
export class QuoteCoreModule {
constructor(_quoteAddedToCartEventListener: QuoteAddedToCartEventListener) {
// Intentional empty constructor
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import {
QuoteActionType,
QuoteState,
} from '@spartacus/quote/root';
import { createEmptyQuote } from '../../core/testing/quote-test-utils';
import {
createEmptyQuote,
QUOTE_CODE,
} from '../../core/testing/quote-test-utils';
import { OccQuoteActionNormalizer } from './occ-quote-action-normalizer';

const SUBMIT_AND_CANCEL_UNORDERED = [
Expand Down Expand Up @@ -95,7 +98,8 @@ describe('OccQuoteActionNormalizer', () => {
it('should return sorted list according to config', () => {
const orderedActions = service['getOrderedActions'](
QuoteState.BUYER_DRAFT,
SUBMIT_AND_CANCEL_UNORDERED
SUBMIT_AND_CANCEL_UNORDERED,
QUOTE_CODE
);
expect(orderedActions).toEqual([
QuoteActionType.CANCEL,
Expand All @@ -106,15 +110,17 @@ describe('OccQuoteActionNormalizer', () => {
quoteCoreConfig.quote = undefined;
const orderedActions = service['getOrderedActions'](
QuoteState.BUYER_DRAFT,
SUBMIT_AND_CANCEL_UNORDERED
SUBMIT_AND_CANCEL_UNORDERED,
QUOTE_CODE
);
expect(orderedActions).toEqual(SUBMIT_AND_CANCEL_UNORDERED);
});
it('should return unsorted list if no actions are defined in the config', () => {
(quoteCoreConfig?.quote ?? {}).actions = undefined;
const orderedActions = service['getOrderedActions'](
QuoteState.BUYER_DRAFT,
SUBMIT_AND_CANCEL_UNORDERED
SUBMIT_AND_CANCEL_UNORDERED,
QUOTE_CODE
);
expect(orderedActions).toEqual(SUBMIT_AND_CANCEL_UNORDERED);
});
Expand All @@ -123,7 +129,8 @@ describe('OccQuoteActionNormalizer', () => {
(quoteCoreConfig.quote?.actions ?? {}).actionsOrderByState = undefined;
const orderedActions = service['getOrderedActions'](
QuoteState.BUYER_DRAFT,
SUBMIT_AND_CANCEL_UNORDERED
SUBMIT_AND_CANCEL_UNORDERED,
QUOTE_CODE
);
expect(orderedActions).toEqual(SUBMIT_AND_CANCEL_UNORDERED);
});
Expand Down
Loading
Loading