Skip to content
This repository was archived by the owner on Jul 3, 2025. It is now read-only.
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
116 changes: 79 additions & 37 deletions app/api/client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ClientBuilder, type HttpMiddlewareOptions } from '@commercetools/ts-client'
import {
type ByProjectKeyMeRequestBuilder,
type ApiRequest,
type ByProjectKeyRequestBuilder,
type ClientResponse,
createApiBuilderFromCtpClient,
Expand Down Expand Up @@ -99,19 +100,37 @@ export class CtpApiClient {
}
}

private static isAnonymousIdError(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'statusCode' in error &&
error.statusCode === 400 &&
'message' in error &&
typeof error.message === 'string' &&
error.message.includes('anonymousId')
)
}

public async login(email: string, password: string): Promise<ClientResponse<Customer>> {
await this.public
.me()
.login()
.post({
body: {
email,
password,
activeCartSignInMode: 'UseAsNewActiveCustomerCart',
updateProductData: true
}
})
.execute()
const request: () => ApiRequest<CustomerSignInResult> = () =>
this.public
.me()
.login()
.post({
body: {
email,
password,
activeCartSignInMode: 'UseAsNewActiveCustomerCart',
updateProductData: true
}
})

try {
await request().execute()
} catch (error) {
await this.handleError<CustomerSignInResult>({ error, request })
}

this.protected = this.createProtectedWithCredentials(email, password)
this.current = this.protected
Expand Down Expand Up @@ -139,31 +158,37 @@ export class CtpApiClient {
const billingAddressIndex = payload.addresses.findIndex(({ type }) => type === CUSTOMER_ADDRESS_TYPE.BILLING)
const shippingAddressIndex = payload.addresses.findIndex(({ type }) => type === CUSTOMER_ADDRESS_TYPE.SHIPPING)

return this.public
.me()
.signup()
.post({
body: {
addresses: payload.addresses.map(
(address): Omit<CustomerAddress, 'type'> => ({
city: address.city,
country: address.country,
firstName: payload.firstName,
lastName: payload.lastName,
postalCode: address.postalCode,
streetName: address.streetName
})
),
dateOfBirth: payload.dateOfBirth,
defaultBillingAddress: billingAddressIndex === -1 ? undefined : billingAddressIndex,
defaultShippingAddress: shippingAddressIndex === -1 ? undefined : shippingAddressIndex,
email: payload.email,
firstName: payload.firstName,
lastName: payload.lastName,
password: payload.password
}
})
.execute()
const request: () => ApiRequest<CustomerSignInResult> = () =>
this.public
.me()
.signup()
.post({
body: {
addresses: payload.addresses.map(
(address): Omit<CustomerAddress, 'type'> => ({
city: address.city,
country: address.country,
firstName: payload.firstName,
lastName: payload.lastName,
postalCode: address.postalCode,
streetName: address.streetName
})
),
dateOfBirth: payload.dateOfBirth,
defaultBillingAddress: billingAddressIndex === -1 ? undefined : billingAddressIndex,
defaultShippingAddress: shippingAddressIndex === -1 ? undefined : shippingAddressIndex,
email: payload.email,
firstName: payload.firstName,
lastName: payload.lastName,
password: payload.password
}
})

try {
return await request().execute()
} catch (error) {
return await this.handleError<CustomerSignInResult>({ error, request })
}
}

private getHttpOptions(): HttpMiddlewareOptions {
Expand Down Expand Up @@ -247,6 +272,23 @@ export class CtpApiClient {
})
}

private async handleError<T>({
error,
request
}: {
error: unknown
request: () => ApiRequest<T>
}): Promise<ClientResponse<T>> {
if (!CtpApiClient.isAnonymousIdError(error)) {
throw error
}

console.log('Anonymous ID is already in use. Creating new anonymous ID...')

this.logout()
return await request().execute()
}

private getOrCreateAnonymousId(): string {
let id = this.getAnonymousIdFromStorage()

Expand Down
10 changes: 6 additions & 4 deletions app/pages/cart/CartTotalPrice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ type CartTotalPriceProps = {

export function CartTotalPrice({ totalPrice, discount }: CartTotalPriceProps): ReactElement {
const hasDiscount = discount !== undefined
const fullPrice = (totalPrice ?? 0) + (discount?.discountedAmount?.centAmount ?? 0)
const discountedPrice = totalPrice ?? 0

return (
<div className="text-center m-0 text-sm sm:text-base font-semibold">
{hasDiscount
? `Total price with discount code applied: ${formatProductItemPrice(discount.discountedAmount?.centAmount ?? 0)}`
: `Total price: ${formatProductItemPrice(totalPrice ?? 0)}`}
<div className="text-center m-0 text-sm sm:text-base font-semibold justify-items-start">
<div>Total price: {formatProductItemPrice(fullPrice)}</div>
{hasDiscount && <div>Total price with discount code applied: {formatProductItemPrice(discountedPrice)}</div>}
</div>
)
}