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

feat(RSS_ECOMM-5_99): blog carts #339

Merged
merged 8 commits into from
Jun 5, 2024
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
4 changes: 2 additions & 2 deletions src/app/App/model/AppModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ class AppModel {
return new AboutUsPageModel(this.appView.getHTML());
},
[PAGE_ID.BLOG]: async (): Promise<Page> => {
const { default: PostListModel } = await import('@/pages/Blog/PostList/model/PostListModel.ts');
return new PostListModel(this.appView.getHTML());
const { default: BlogPageModel } = await import('@/pages/BlogPage/model/BlogPageModel.ts');
return new BlogPageModel(this.appView.getHTML());
},
[PAGE_ID.CART_PAGE]: async (): Promise<Page> => {
const { default: CartPageModel } = await import('@/pages/CartPage/model/CartPageModel.ts');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default class PostView {
private createCardInfoHTML(): string {
const ln = getStore().getState().currentLanguage;
const read =
ln === 'en' ? `Read in ${this.post.time.toString()} minutes` : `Π§ΠΈΡ‚Π°Ρ‚ΡŒ Π·Π° ${this.post.time.toString()} ΠΌΠΈΠ½ΡƒΡ‚Ρ‹`;
ln === 'en' ? `Read in ${this.post.time.toString()} min.` : `Π§ΠΈΡ‚Π°Ρ‚ΡŒ Π·Π° ${this.post.time.toString()} ΠΌΠΈΠ½.`;
const readMore = ln === 'en' ? 'Read more...' : 'Π§ΠΈΡ‚Π°Ρ‚ΡŒ Π΄Π°Π»Π΅Π΅...';
const content = `
<article class=${styles.article}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
display: block;
margin: 0 auto;
width: 100%;
height: auto;
object-fit: cover;
}

.dataTime {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import type { Post } from '@/shared/constants/blog.ts';
import type { Page } from '@/shared/types/page.ts';

import PostView from '@/pages/Blog/Post/view/PostView.ts';
import PostView from '@/entities/Post/view/PostView.ts';
import getStore from '@/shared/Store/Store.ts';
import { setCurrentPage } from '@/shared/Store/actions.ts';
import observeStore, { selectCurrentLanguage } from '@/shared/Store/observer.ts';
import { PAGE_ID } from '@/shared/constants/pages.ts';

import postsData from '../../data/posts.ts';
import BlogPageView from '../view/PostListView.ts';
import postsData from '../../../shared/Posts/posts.ts';
import BlogPageView from '../view/BlogPageView.ts';

export default class PostListModel implements Page {
export default class BlogPageModel implements Page {
private parent: HTMLDivElement;

private postClickHandler = (post: PostView): void => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type BlogPostView from '@/pages/Blog/Post/view/PostView';
import type BlogPostView from '@/entities/Post/view/PostView';

import getStore from '@/shared/Store/Store.ts';
import { BLOG_DESCRIPTION } from '@/shared/constants/pages.ts';
import createBaseElement from '@/shared/utils/createBaseElement.ts';

import styles from './postListView.module.scss';
import styles from './blogPageView.module.scss';

export default class PostListView {
export default class BlogPageView {
private description: HTMLParagraphElement;

private page: HTMLDivElement;
Expand Down
70 changes: 35 additions & 35 deletions src/pages/CartPage/model/CartPageModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,38 @@ import CartPageView from '../view/CartPageView.ts';
class CartPageModel implements Page {
private cart: Cart | null = null;

private changeProductHandler = (cart: Cart): void => {
private productsItem: ProductOrderModel[] = [];

private view: CartPageView;

constructor(parent: HTMLDivElement) {
this.view = new CartPageView(parent, this.clearCart.bind(this), this.addDiscountHandler.bind(this));

this.init().catch(showErrorMessage);
}

private async addDiscountHandler(discountCode: string): Promise<void> {
if (discountCode.trim()) {
const loader = new LoaderModel(LOADER_SIZE.SMALL).getHTML();
this.view.getCouponButton().append(loader);
await getCartModel()
.addCoupon(discountCode)
.then((cart) => {
if (cart) {
serverMessageModel.showServerMessage(
SERVER_MESSAGE_KEYS.SUCCESSFUL_ADD_COUPON_TO_CART,
MESSAGE_STATUS.SUCCESS,
);
this.cart = cart;
this.view.updateTotal(this.cart);
}
})
.catch(showErrorMessage)
.finally(() => loader.remove());
}
}

private changeProductHandler(cart: Cart): void {
this.cart = cart;
this.productsItem = this.productsItem.filter((productItem) => {
const searchEl = this.cart?.products.find((item) => item.lineItemId === productItem.getProduct().lineItemId);
Expand All @@ -33,9 +64,9 @@ class CartPageModel implements Page {
this.view.renderEmpty();
}
this.view.updateTotal(this.cart);
};
}

private clearCart = async (): Promise<void> => {
private async clearCart(): Promise<void> {
await getCartModel()
.clearCart()
.then((cart) => {
Expand All @@ -55,37 +86,6 @@ class CartPageModel implements Page {
showErrorMessage(error);
return this.cart;
});
};

private productsItem: ProductOrderModel[] = [];

private view: CartPageView;

constructor(parent: HTMLDivElement) {
this.view = new CartPageView(parent, this.clearCart, this.addDiscountHandler.bind(this));

this.init().catch(showErrorMessage);
}

private async addDiscountHandler(discountCode: string): Promise<void> {
if (discountCode.trim()) {
const loader = new LoaderModel(LOADER_SIZE.SMALL).getHTML();
this.view.getCouponButton().append(loader);
await getCartModel()
.addCoupon(discountCode)
.then((cart) => {
if (cart) {
serverMessageModel.showServerMessage(
SERVER_MESSAGE_KEYS.SUCCESSFUL_ADD_COUPON_TO_CART,
MESSAGE_STATUS.SUCCESS,
);
this.cart = cart;
this.view.updateTotal(this.cart);
}
})
.catch(showErrorMessage)
.finally(() => loader.remove());
}
}

private async init(): Promise<void> {
Expand All @@ -98,7 +98,7 @@ class CartPageModel implements Page {
private renderCart(): void {
if (this.cart) {
this.cart.products.forEach((product) => {
this.productsItem.push(new ProductOrderModel(product, this.changeProductHandler));
this.productsItem.push(new ProductOrderModel(product, this.changeProductHandler.bind(this)));
});

if (this.productsItem.length) {
Expand Down
4 changes: 4 additions & 0 deletions src/pages/CartPage/view/cartPageView.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@
.applyBtn {
border-radius: 0 var(--small-br) var(--small-br) 0;

div {
position: absolute;
}

&:active {
transform: scale(1);
}
Expand Down
6 changes: 3 additions & 3 deletions src/pages/MainPage/model/MainPageModel.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { Page } from '@/shared/types/page.ts';

import PromoCodeSliderModel from '@/entities/PromocodeSlider/model/PromoCodeSliderModel.ts';
import PostWidgetModel from '@/pages/Blog/PostWidget/model/PostWidgetModel.ts';
import getStore from '@/shared/Store/Store.ts';
import { setCurrentPage } from '@/shared/Store/actions.ts';
import { PAGE_ID } from '@/shared/constants/pages.ts';
import BlogWidgetModel from '@/widgets/Blog/model/BogWidgetModel.ts';

import MainPageView from '../view/MainPageView.ts';

class MainPageModel implements Page {
private blogWidget: PostWidgetModel;
private blogWidget: BlogWidgetModel;

private parent: HTMLDivElement;

Expand All @@ -20,7 +20,7 @@ class MainPageModel implements Page {
constructor(parent: HTMLDivElement) {
this.parent = parent;
this.view = new MainPageView(this.parent);
this.blogWidget = new PostWidgetModel(this.view.getHTML());
this.blogWidget = new BlogWidgetModel(this.view.getHTML());
this.init();
}

Expand Down
47 changes: 28 additions & 19 deletions src/shared/API/cart/model/CartModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,31 @@ export class CartModel {

private cart: Cart | null = null;

private isSetAnonymousId = false;

private root: CartApi;

constructor() {
this.root = getCartApi();
this.getCart().catch(showErrorMessage);
this.getCart()
.then(() => {
const { anonymousId } = getStore().getState();
if (anonymousId && this.cart?.anonymousId !== anonymousId) {
this.updateCartCustomer(anonymousId).catch(showErrorMessage);
}
})
.catch(showErrorMessage);
}

private adaptCart(data: CartResponse): Cart {
if (data.anonymousId && !getStore().getState().authToken) {
const { anonymousId, authToken } = getStore().getState();
if (data.anonymousId && !authToken) {
getStore().dispatch(setAnonymousCartId(data.id));
}
if (data.anonymousId && !authToken && !anonymousId) {
getStore().dispatch(setAnonymousId(data.anonymousId));
}
const discount = data.discountOnTotalPrice?.discountedAmount?.centAmount;
return {
anonymousId: data.anonymousId || null,
discounts: discount ? discount / PRICE_FRACTIONS : 0,
id: data.id,
products: data.lineItems.map((lineItem) => this.adaptLineItem(lineItem)),
Expand Down Expand Up @@ -97,27 +106,18 @@ export class CartModel {
this.callback.forEach((callback) => (this.cart !== null ? callback(this.cart) : null));
}

private async getAnonymousCart(anonymousCartId: string, anonymousId: string): Promise<Cart | null> {
private async getAnonymousCart(anonymousCartId: string): Promise<Cart | null> {
const data = await this.root.getAnonymCart(anonymousCartId);
if (!data.body.customerId) {
this.cart = this.getCartFromData(data);
const cartAnonymId = data.body.anonymousId;
if (cartAnonymId !== anonymousId && !this.isSetAnonymousId) {
this.isSetAnonymousId = true;
const actions: CartSetAnonymousIdAction = {
action: ACTIONS.setAnonymousId,
anonymousId,
};
const dataSetId = await this.root.setAnonymousId(this.cart, actions);
this.cart = this.getCartFromData(dataSetId);
}
}

return this.cart;
}

private getCartFromData(data: CartResponse | ClientResponse<CartPagedQueryResponse | CartResponse>): Cart {
let cart: Cart = {
anonymousId: null,
discounts: 0,
id: '',
products: [],
Expand Down Expand Up @@ -149,6 +149,18 @@ export class CartModel {
return this.cart;
}

private async updateCartCustomer(anonymousId: string): Promise<Cart | null> {
if (this.cart) {
const actions: CartSetAnonymousIdAction = {
action: ACTIONS.setAnonymousId,
anonymousId,
};
const dataSetId = await this.root.setAnonymousId(this.cart, actions);
this.cart = this.getCartFromData(dataSetId);
}
return this.cart;
}

public async addCoupon(discountCode: string): Promise<Cart> {
if (!this.cart) {
this.cart = await this.getCart();
Expand Down Expand Up @@ -261,10 +273,7 @@ export class CartModel {
if (!this.cart) {
const { anonymousCartId, anonymousId } = getStore().getState();
if (anonymousCartId && anonymousId) {
// const data = await this.root.getAnonymCart(anonymousCartId);
// this.cart = this.getCartFromData(data);

this.cart = await this.getAnonymousCart(anonymousCartId, anonymousId);
this.cart = await this.getAnonymousCart(anonymousCartId);
}
if (!this.cart) {
this.cart = await this.getUserCart();
Expand Down
12 changes: 0 additions & 12 deletions src/shared/API/sdk/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { UserCredentials } from '@/shared/types/user';

import getStore from '@/shared/Store/Store.ts';
import { setAnonymousId } from '@/shared/Store/actions.ts';
import showErrorMessage from '@/shared/utils/userMessage.ts';
import { type ByProjectKeyRequestBuilder, createApiBuilderFromCtpClient } from '@commercetools/platform-sdk';
import {
type AnonymousAuthMiddlewareOptions,
Expand Down Expand Up @@ -63,8 +62,6 @@ export class ApiClient {
this.anonymConnection = this.createAnonymConnection();
}
this.adminConnection = this.createAdminConnection();

this.init().catch(showErrorMessage);
}

private addAuthMiddleware(
Expand Down Expand Up @@ -169,15 +166,6 @@ export class ApiClient {
};
}

private async init(): Promise<void> {
await this.apiRoot()
.get()
.execute()
.catch((error: Error) => {
showErrorMessage(error);
});
}

public adminRoot(): ByProjectKeyRequestBuilder {
return this.adminConnection;
}
Expand Down
7 changes: 5 additions & 2 deletions src/shared/API/shopping-list/model/ShoppingListModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,13 @@ export class ShoppingListModel {
}

private adaptShopList(data: ShoppingListResponse): ShoppingList {
if (data.anonymousId && !getStore().getState().authToken) {
getStore().dispatch(setAnonymousId(data.anonymousId));
const { anonymousId, authToken } = getStore().getState();
if (data.anonymousId && !authToken) {
getStore().dispatch(setAnonymousShopListId(data.id));
}
if (data.anonymousId && !authToken && !anonymousId) {
getStore().dispatch(setAnonymousId(data.anonymousId));
}
return {
id: data.id,
products: data.lineItems.map((lineItem) => this.adaptLineItem(lineItem)),
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions src/shared/types/cart.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { SizeType, localization } from './product.ts';

export interface Cart {
anonymousId: null | string;
discounts: number;
id: string;
products: CartProduct[];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
import PostView from '@/pages/Blog/Post/view/PostView.ts';
import PostView from '@/entities/Post/view/PostView.ts';
import observeStore, { selectCurrentLanguage } from '@/shared/Store/observer.ts';

import postsData from '../../data/posts.ts';
import PostWidgetView from '../view/PostWidgetView.ts';
import postsData from '../../../shared/Posts/posts.ts';
import BlogWidgetView from '../view/BlogWidgetView.ts';

const CART_COUNT = 3;
const HALF_RANDOM = 0.5;

export default class PostWidgetModel {
export default class BlogWidgetModel {
private postClickHandler = (post: PostView): void => {
this.view.openPost(post);
};

private posts: PostView[];

private view: PostWidgetView;
private view: BlogWidgetView;

constructor(parent: HTMLDivElement) {
const shuffledPosts = [...postsData].sort(() => HALF_RANDOM - Math.random());
const newPost = shuffledPosts.slice(0, CART_COUNT);
this.posts = newPost.map((post) => new PostView(post, this.postClickHandler));
this.view = new PostWidgetView(parent, this.posts);
this.view = new BlogWidgetView(parent, this.posts);
this.init();
}

Expand Down
Loading