Skip to content
Merged
5 changes: 5 additions & 0 deletions src/app/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import currentCart from '@services/current-cart';
import isPageAccessable from '@utils/access-control';
import CookieManager from '@utils/cookie';

import {
Error404,
Expand Down Expand Up @@ -39,6 +41,9 @@ class App {

window.addEventListener('hashchange', this.route);
window.addEventListener('load', this.route);

const userId = CookieManager.getUserId();
currentCart.initCurrentCart(userId);
}

private addHeader(): void {
Expand Down
5 changes: 2 additions & 3 deletions src/app/services/cart-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export const createCartData = (cart: Cart): ICartData => {

export const getCartById = (
cartId: string,
successCallback: (cartData: ICartData) => void,
successCallback: (cartData: Cart) => void,
errorCallback: (message: string) => void
): void => {
ApiRoot.root
Expand All @@ -107,8 +107,7 @@ export const getCartById = (
.get()
.execute()
.then(({ body }) => {
const cartData = createCartData(body);
successCallback(cartData);
successCallback(body);
})
.catch((error) => {
errorCallback(`Failed to load cart: ${error.message}`);
Expand Down
10 changes: 5 additions & 5 deletions src/app/services/cart-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ class CartHandler {
this.currentCustomerCartId = null;
this.currentCustomerCartVersion = null;

if (!userId) {
this.loadCartFromLocalStorage();
} else {
this.loadCartAuthFromLocalStorage();
}
// if (!userId) {
// this.loadCartFromLocalStorage();
// } else {
// this.loadCartAuthFromLocalStorage();
// }
}

public handleAddToCart(productId: string, quantity: number): void {
Expand Down
27 changes: 26 additions & 1 deletion src/app/services/carts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,36 @@ export const createCustomerCart = (
});
};

export const isCustomerCartExist = (
customerId: string,
successCallback: (cartData: Cart) => void,
errorCallback: (customerId: string) => void
): void => {
ApiRoot.root
.carts()
.withCustomerId({ customerId })
.get()
.execute()
.then((response) => {
const { body } = response;
successCallback(body);
})
.catch((err) => {
if (err.statusCode === 404) {
errorCallback(customerId);
} else {
throw err;
}
});
};

export const removeProductFromCart = (
cartId: string,
cartVersion: number,
lineItemId: string,
successCallback: (cartData: Cart) => void,
errorCallback: (message: string) => void
errorCallback: (message: string) => void,
quantity?: number
): void => {
ApiRoot.root
.carts()
Expand All @@ -76,6 +100,7 @@ export const removeProductFromCart = (
{
action: 'removeLineItem',
lineItemId,
quantity,
},
],
},
Expand Down
211 changes: 211 additions & 0 deletions src/app/services/current-cart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
import { ICartData } from '@models/cart';
import { Cart, DiscountCodeReference } from '@commercetools/platform-sdk';
import CookieManager from '@utils/cookie';
import LocalStorageManager from '@utils/local-cart-id';
import {
createAnonymousCart,
createCustomerCart,
isCustomerCartExist,
removeProductFromCart,
} from './carts';
import { createCartData, getCartById } from './cart-data';
import { addProductToCart } from './add-product-cart';
import applyPromocodeToCart from './apply-promocode-to-cart';
import removePromocodeFromCart from './remove-promocode-from-cart';
import recalculateCart from './recalculate-cart';

class CurrentCart {
cartData: ICartData;

public currentCartId?: string;

public currentCartVersion?: number;

constructor(userId?: string) {
this.initCurrentCart(userId);
}

public initCurrentCart(userId?: string, sucessCallback?: () => void) {
console.log(`Initializing ID ${userId}`);
if (userId) {
this.loadCustomerCart(userId, sucessCallback);
LocalStorageManager.removeAnonymusCart();
} else {
this.loadAnonymusCart(sucessCallback);
}
}

private loadCustomerCart(userId: string, successCallback?: () => void) {
isCustomerCartExist(
userId,
(cart: Cart) => {
this.updateCartData(cart);
if (successCallback) {
successCallback();
}
},
(id: string) => {
this.createCustomerCart(id);
if (successCallback) {
successCallback();
}
}
);
}

private loadAnonymusCart(successCallback?: () => void) {
const savedCart = localStorage.getItem('anonymousCart');
if (savedCart) {
const cartData = JSON.parse(savedCart);
this.currentCartId = cartData.currentCartId as string;
this.currentCartVersion = cartData.currentCartVersion;
getCartById(
this.currentCartId,
(cart: Cart) => {
this.updateCartData(cart);
if (successCallback) {
successCallback();
}
},
(msg) => {
console.log(`Error on loading local cart: ${msg} `);
}
);
} else {
createAnonymousCart(this.updateCartData.bind(this), () => {
console.log('Problem on creating');
});
}
}

updateCartData(cart: Cart) {
this.currentCartId = cart.id;
this.currentCartVersion = cart.version;
this.cartData = createCartData(cart);
this.saveCartToLocalStorage();
}

public saveCartToLocalStorage(): void {
const cartData = {
currentCartId: this.currentCartId,
currentCartVersion: this.currentCartVersion,
};
localStorage.setItem('anonymousCart', JSON.stringify(cartData));
}

addProduct(
productId: string,
quantity: number,
successCallback?: () => void
) {
addProductToCart(
this.cartData.id,
this.cartData.version,
productId,
quantity,
(cart: Cart) => {
this.updateCartData(cart);
if (successCallback) {
successCallback();
}
},
(msg) => {
console.log(`Error on adding ${msg}`);
}
);
}

removeProduct(
productId: string,
successCallback?: () => void,
quantity?: number
) {
removeProductFromCart(
this.cartData.id,
this.cartData.version,
productId,
(cart: Cart) => {
this.updateCartData(cart);
if (successCallback) {
successCallback();
}
},
(msg) => {
console.log(`Error on adding ${msg}`);
},
quantity
);
}

createCustomerCart(userId: string) {
createCustomerCart(userId, this.updateCartData.bind(this), (msg) =>
console.log(`Creating customer cart error ${msg}`)
);
}

applyPromocode(
promocode: string,
sucessCallback: () => void,
errorCallabck: () => void
) {
applyPromocodeToCart(
this.cartData.id,
this.cartData.version,
promocode,
(cartData) => {
this.updateCartData(cartData);
sucessCallback();
},
errorCallabck
);
}

removePromocode(
promocode: DiscountCodeReference,
sucessCallback: (cartData: Cart) => void,
errorCallabck: () => void
) {
removePromocodeFromCart(
this.cartData.id,
this.cartData.version,
(cartData: Cart) => {
this.updateCartData(cartData);
sucessCallback(cartData);
},
errorCallabck,
promocode
);
}

removeAllPromocodes() {
console.log('removing all promocodes');

this.cartData.discountCodes.forEach((codeId) => {
this.removePromocode(
{ id: codeId.id, typeId: 'discount-code' },
() => {},
() => {}
);
});
}

recalculate(
sucessCallback: (cartData: Cart) => void,
errorCallabck: () => void
) {
recalculateCart(
this.cartData.id,
this.cartData.version,
(cartData: Cart) => {
this.updateCartData(cartData);
sucessCallback(cartData);
},
errorCallabck
);
}
}
const userId = CookieManager.getUserId();

const currentCart = new CurrentCart(userId);

export default currentCart;
2 changes: 2 additions & 0 deletions src/app/services/customer-registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { customerTokenResponse } from '@models/customer';
import CookieManager from '@utils/cookie';
import ApiRoot from './api-root';
import login from './login-authorization';
import currentCart from './current-cart';

const EMAIL_EXIST_ADD_MSG = 'Use another email or try to login';
const EMAIL_EXIST_DEF_MSG =
Expand All @@ -23,6 +24,7 @@ const registration = (
const customerDataForId = customerTokenResponse(response.body.customer);
if (customerDataForId && customerDataForId.id) {
CookieManager.setUserId(customerDataForId.id);
currentCart.createCustomerCart(customerDataForId.id);
}
login(
{ email: customer.email, password: customer.password as string },
Expand Down
1 change: 0 additions & 1 deletion src/app/services/get-active-promocodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export default function getActivePromocodes(
})
.execute()
.then((response) => {
console.log(response);
sucessCallback(response.body.results);
})
.catch((error) => {
Expand Down
14 changes: 13 additions & 1 deletion src/app/services/login-authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { customerTokenResponse } from '@models/customer';
import { UserAuthOptions } from '@commercetools/sdk-client-v2';
import CookieManager from '@utils/cookie';
import ApiRoot from './api-root';
import currentCart from './current-cart';

function login(
customer: { email: string; password: string },
Expand All @@ -15,12 +16,23 @@ function login(
const root = ApiRoot.getPasswordRoot(user);
root
.login()
.post({ body: customer })
.post({
body: {
email: customer.email,
password: customer.password,
anonymousCart: {
id: currentCart.cartData.id,
typeId: 'cart',
},
},
})
.execute()
.then((response) => {
const customerDataForId = customerTokenResponse(response.body.customer);
if (customerDataForId && customerDataForId.id) {
CookieManager.setUserId(customerDataForId.id);
const userId = CookieManager.getUserId();
currentCart.initCurrentCart(userId);
}
sucessCallback('You have successfully logged in!');
})
Expand Down
4 changes: 4 additions & 0 deletions src/app/services/logout-customer.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { clearCustomer } from '@models/customer';
import CookieManager from '@utils/cookie';
import LocalStorageManager from '@utils/local-cart-id';
import currentCart from './current-cart';

function logoutCustomer() {
clearCustomer();
CookieManager.clearUserId();
LocalStorageManager.removeAnonymusCart();
currentCart.initCurrentCart();
}

export default logoutCustomer;
Loading