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

Add Cart Loading feature #20109

Merged
merged 5 commits into from
Mar 25, 2025
Merged
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
42 changes: 40 additions & 2 deletions integration-libs/punchout/core/facade/punchout.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,14 @@ describe('Punchoutservice', () => {
});
});

it('should getPunchoutSession opens home page when no product item', (done) => {
it('should getPunchoutSession opens home page when no product item and CREATE Level ', (done) => {
spyOn(routingService, 'go').and.returnValue(Promise.resolve(true));
spyOn(connector, 'getPunchoutSession').and.returnValue(
of({ ...mockPunchoutSessionResponse, selectedItem: '' })
of({
...mockPunchoutSessionResponse,
punchOutOperation: PunchOutOperation.CREATE,
selectedItem: '',
})
);

service.getPunchoutSession(mockSessionInput).subscribe({
Expand All @@ -176,4 +180,38 @@ describe('Punchoutservice', () => {
},
});
});

it('should getPunchoutSession opens cart page when no product item and EDIT Level ', (done) => {
spyOn(routingService, 'go').and.returnValue(Promise.resolve(true));
spyOn(connector, 'getPunchoutSession').and.returnValue(
of({
...mockPunchoutSessionResponse,
selectedItem: '',
})
);

service.getPunchoutSession(mockSessionInput).subscribe({
next: () => {
expect(routingService.go).toHaveBeenCalledWith({ cxRoute: 'cart' });
done();
},
});
});

it('should getPunchoutSession opens pdp when selectedItem is present ', (done) => {
spyOn(routingService, 'go').and.returnValue(Promise.resolve(true));
spyOn(connector, 'getPunchoutSession').and.returnValue(
of(mockPunchoutSessionResponse)
);

service.getPunchoutSession(mockSessionInput).subscribe({
next: () => {
expect(routingService.go).toHaveBeenCalledWith({
cxRoute: 'product',
params: { code: mockPunchoutSessionResponse.selectedItem },
});
done();
},
});
});
});
42 changes: 37 additions & 5 deletions integration-libs/punchout/core/facade/punchout.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,32 @@

import { inject, Injectable } from '@angular/core';

import { Command, CommandService, RoutingService } from '@spartacus/core';
import {
Command,
CommandService,
RoutingService,
UserIdService,
} from '@spartacus/core';
import {
PUNCHOUT_ERROR_PAGE_URL,
PunchoutFacade,
PunchOutOperation,
PunchoutRequisition,
PunchoutSession,
PunchoutSessionInput,
PunchoutStoreService,
} from '@spartacus/punchout/root';

import { MultiCartFacade } from '@spartacus/cart/base/root';
import {
catchError,
forkJoin,
map,
Observable,
of,
switchMap,
take,
tap,
throwError,
} from 'rxjs';
import { PunchoutConnector } from '../connectors';
Expand All @@ -35,12 +44,15 @@ export class PunchoutService implements PunchoutFacade {
protected commandService = inject(CommandService);
protected routingService = inject(RoutingService);
protected punchoutStoreService = inject(PunchoutStoreService);
protected multiCartFacade = inject(MultiCartFacade);
protected userIdService = inject(UserIdService);

/**
* getPunchoutSession workflow:
* Get PunchoutSession from occ api
* Logout silently
* Login silently
* Load Cart
* Route to target page based on punchout session info
* Redirect to Punchout Error page if error occurs
*/
Expand All @@ -58,7 +70,8 @@ export class PunchoutService implements PunchoutFacade {
map((punchoutSession) => {
if (
!punchoutSession?.token?.accessToken ||
!punchoutSession?.customerId
!punchoutSession?.customerId ||
!punchoutSession?.cartId
) {
throw new Error('Punchout login info missing');
}
Expand All @@ -76,7 +89,7 @@ export class PunchoutService implements PunchoutFacade {
punchoutSession.token.accessToken,
punchoutSession.customerId
);

this.loadCart(punchoutSession.cartId).subscribe();
this.punchoutStoreService.setPunchoutState({
punchoutSessionId: payload.punchoutSessionId,
punchoutSession: { ...punchoutSession },
Expand Down Expand Up @@ -115,12 +128,31 @@ export class PunchoutService implements PunchoutFacade {
cxRoute: 'product',
params: { code: punchoutSession.selectedItem },
});
} else {
this.routingService.go('/');
return;
}
if (punchoutSession?.punchOutOperation === PunchOutOperation.EDIT) {
this.routingService.go({ cxRoute: 'cart' });
return;
}
this.routingService.go('/');
}

protected displayErrorPage() {
this.routingService.go(PUNCHOUT_ERROR_PAGE_URL);
}

protected loadCart(cartId: string): Observable<string> {
return this.userIdService.takeUserId().pipe(
take(1),
tap((userId) => {
this.multiCartFacade.loadCart({
userId,
cartId,
extraData: {
active: true,
},
});
})
);
}
}
1 change: 1 addition & 0 deletions integration-libs/punchout/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@angular/core": "^19.1.8",
"@angular/router": "^19.1.8",
"@ngrx/store": "^19.0.1",
"@spartacus/cart": "2211.37.0",
"@spartacus/core": "2211.37.0",
"@spartacus/schematics": "2211.37.0",
"rxjs": "^7.8.0"
Expand Down
17 changes: 17 additions & 0 deletions integration-libs/punchout/root/interceptors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* SPDX-FileCopyrightText: 2025 SAP Spartacus team <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { Provider } from '@angular/core';
import { PunchoutCartInterceptor } from './punchout-cart.interceptor';

export const interceptors: Provider[] = [
{
provide: HTTP_INTERCEPTORS,
useExisting: PunchoutCartInterceptor,
multi: true,
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import {
HTTP_INTERCEPTORS,
HttpClient,
provideHttpClient,
withInterceptorsFromDi,
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
TestRequest,
} from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { of, Subscription } from 'rxjs';
import {
PUNCHOUT_SESSION_ID_HEADER_KEY,
PunchOutLevel,
PunchOutOperation,
PunchoutSession,
PunchoutState,
} from '../model';
import { PunchoutStoreService } from '../services';
import { PunchoutCartInterceptor } from './punchout-cart.interceptor';

const mockSessionId = '123abc';
const mockPunchoutSession: PunchoutSession = {
customerId: '[email protected]',
cartId: 'mockCart',
punchOutLevel: PunchOutLevel.PRODUCT,
punchOutOperation: PunchOutOperation.EDIT,
selectedItem: 'mockItemId',
token: {
accessToken: 'mockToken',
tokenType: 'Bearer',
},
};
const mockPunchoutState: PunchoutState = {
punchoutSessionId: mockSessionId,
punchoutSession: mockPunchoutSession,
};
class MockPunchoutStoreService implements Partial<PunchoutStoreService> {
setPunchoutState = () => {};
getPunchoutState = () => of(mockPunchoutState);
clearState = () => {};
getPunchoutSessionId = () => mockPunchoutState.punchoutSessionId;
}

describe('PunchoutCartInterceptor', () => {
let interceptor: PunchoutCartInterceptor;
let punchoutStoreService: PunchoutStoreService;
let httpMock: HttpTestingController;
let http: HttpClient;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [
{ provide: PunchoutStoreService, useClass: MockPunchoutStoreService },
{
provide: HTTP_INTERCEPTORS,
useClass: PunchoutCartInterceptor,
multi: true,
},

provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
],
});

interceptor = TestBed.inject(PunchoutCartInterceptor);
httpMock = TestBed.inject(HttpTestingController);
http = TestBed.inject(HttpClient);
punchoutStoreService = TestBed.inject(PunchoutStoreService);
});

it('should be created', () => {
spyOn(punchoutStoreService, 'getPunchoutSessionId').and.returnValue('');
expect(interceptor).toBeTruthy();
});

it('should add sessionId in header for url related to punchout cart', (done) => {
spyOn(punchoutStoreService, 'getPunchoutState').and.returnValue(
of(mockPunchoutState)
);
const sub: Subscription = http
.get(`/carts/${mockPunchoutState.punchoutSession?.cartId}`)
.subscribe((result) => {
expect(result).toBeTruthy();
done();
});

const mockReq: TestRequest = httpMock.expectOne((req) => {
return req.method === 'GET';
});

const pchtHeader = mockReq.request.headers.get(
PUNCHOUT_SESSION_ID_HEADER_KEY
);
expect(pchtHeader).toEqual(mockSessionId);
mockReq.flush('someData');
sub.unsubscribe();
});

it('should not modify header when no punchout sessionId', (done) => {
spyOn(punchoutStoreService, 'getPunchoutState').and.returnValue(
of({ ...mockPunchoutState, punchoutSessionId: '' })
);
const sub: Subscription = http
.get(`/carts/${mockPunchoutState.punchoutSession?.cartId}`)
.subscribe((result) => {
expect(result).toBeTruthy();
done();
});

const mockReq: TestRequest = httpMock.expectOne((req) => {
return req.method === 'GET';
});

const pchtHeader = mockReq.request.headers.get(
PUNCHOUT_SESSION_ID_HEADER_KEY
);
expect(pchtHeader).toBeFalsy();
mockReq.flush('someData');
sub.unsubscribe();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* SPDX-FileCopyrightText: 2025 SAP Spartacus team <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/

import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable, switchMap, take } from 'rxjs';
import { PUNCHOUT_SESSION_ID_HEADER_KEY } from '../model';
import { PunchoutStoreService } from '../services';

/**
* Add required punchoutsid key/value to request header
* It is applied to all occ requests containing punchout cart Id with shape: 'carts/{punchoutCartId}'
*/

@Injectable({ providedIn: 'root' })
export class PunchoutCartInterceptor implements HttpInterceptor {
protected punchoutStoreService = inject(PunchoutStoreService);
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return this.punchoutStoreService.getPunchoutState().pipe(
take(1),
switchMap((punchoutState) => {
if (
punchoutState?.punchoutSessionId &&
punchoutState?.punchoutSession?.cartId &&
request.url.includes(`/carts/${punchoutState.punchoutSession.cartId}`)
) {
request = request.clone({
headers: request.headers.append(
PUNCHOUT_SESSION_ID_HEADER_KEY,
punchoutState.punchoutSessionId
),
});
}
return next.handle(request);
})
);
}
}
9 changes: 5 additions & 4 deletions integration-libs/punchout/root/model/punchout.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const PUNCHOUT_SESSION_ID = 'punchoutSessionId';
export const PUNCHOUT_SESSION_PAGE_URL = '/punchout/cxml/session';
export const PUNCHOUT_STORAGE_KEY = 'punchout';
export const PUNCHOUT_OCC_API_URL_SEGMENT = 'punchout/sessions';
export const PUNCHOUT_SESSION_ID_HEADER_KEY = 'punchoutsid';

export enum PunchOutLevel {
STORE = 'store',
Expand All @@ -19,10 +20,10 @@ export enum PunchOutLevel {
}

export enum PunchOutOperation {
CREATE = 'create',
EDIT = 'edit',
INSPECT = 'inspect',
SOURCE = 'source',
CREATE = 'CREATE',
EDIT = 'EDIT',
INSPECT = 'INSPECT',
SOURCE = 'SOURCE',
}

export interface PunchoutSessionInput {
Expand Down
2 changes: 2 additions & 0 deletions integration-libs/punchout/root/punchout.root.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
provideDefaultConfigFactory,
} from '@spartacus/core';
import { PUNCHOUT_FEATURE } from './feature-name';
import { interceptors } from './interceptors';
import { PunchoutStatePersistanceService } from './services';
import { PunchoutAuthHttpHeaderService } from './services/punchout-auth-http-header.service';

Expand Down Expand Up @@ -38,6 +39,7 @@ export function punchoutStatePersistenceFactory(): () => void {
);
punchoutPersistenceService.initSync();
}),
...interceptors,
provideDefaultConfigFactory(defaultPunchoutCmsComponentsConfig),
{
provide: AuthHttpHeaderService,
Expand Down
Loading