-
Notifications
You must be signed in to change notification settings - Fork 0
Feat/add remove product cart #205
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
Merged
Golosova76
merged 8 commits into
release/basket-about_us
from
feat/add-remove-product-cart
Jun 12, 2024
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
347bca0
refactor: add refactor API request
Golosova76 21d6d2d
refactor: add refactor API request
Golosova76 20c2bc1
feat: add button add cart
Golosova76 597f6a7
feat: add create cart user
bd43244
feat: add anonym cart products
Golosova76 ee29b1e
feat: add register cart products
Golosova76 5684975
feat: add register cart products
Golosova76 43dab2f
Merge pull request #204 from Friday-13/feat/RSS-ECOMM-4_07
Golosova76 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { ClientResponse, Cart } from '@commercetools/platform-sdk'; | ||
| import apiRoot from './api-root'; | ||
|
|
||
| // Отправляет запрос на добавление товара в корзину | ||
| // При успешном добавлении товара вызывает successCallback с обновленными данными корзины | ||
| // eslint-disable-next-line import/prefer-default-export | ||
| export const addProductToCart = ( | ||
| cartId: string, | ||
| cartVersion: number, | ||
| productId: string, | ||
| quantity: number, | ||
| successCallback: (cartData: Cart) => void, | ||
| errorCallback: (message: string) => void | ||
| ): void => { | ||
| console.log('addProductToCart called with:', { | ||
| cartId, | ||
| cartVersion, | ||
| productId, | ||
| quantity, | ||
| }); | ||
| apiRoot | ||
| .carts() | ||
| .withId({ ID: cartId }) | ||
| .post({ | ||
| body: { | ||
| version: cartVersion, | ||
| actions: [ | ||
| { | ||
| action: 'addLineItem', | ||
| productId, | ||
| quantity, | ||
| }, | ||
| ], | ||
| }, | ||
| }) | ||
| .execute() | ||
| .then((response: ClientResponse<Cart>) => { | ||
| const cartData: Cart = response.body; | ||
| console.log('Product added to cart successfully:', cartData); | ||
| successCallback(cartData); | ||
| }) | ||
| .catch((error: ClientResponse<{ message: string }>) => { | ||
| console.error('Error adding product to cart:', error.body); | ||
| errorCallback(error.body.message); | ||
| }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import fetch from 'isomorphic-fetch'; | ||
| // eslint-disable-next-line import/no-extraneous-dependencies | ||
| import SdkAuth from '@commercetools/sdk-auth'; | ||
| import { getCustomerToken } from '@models/customer'; | ||
| import { clientConfig } from './client'; | ||
|
|
||
| const AUTH_TOKEN_KEY = 'authToken'; | ||
|
|
||
| interface IUserCredentials { | ||
| username: string; | ||
| password: string; | ||
| } | ||
|
|
||
| const sdkAuth = new SdkAuth({ | ||
| host: clientConfig.VITE_CTP_AUTH_URL, | ||
| projectKey: clientConfig.VITE_CTP_PROJECT_KEY, | ||
| credentials: { | ||
| clientId: clientConfig.VITE_CTP_CLIENT_ID, | ||
| clientSecret: clientConfig.VITE_CTP_CLIENT_SECRET, | ||
| }, | ||
| fetch, | ||
| }); | ||
|
|
||
| export async function getUserToken( | ||
| credentials: IUserCredentials | ||
| ): Promise<string> { | ||
| const tokenResponse = await sdkAuth.customerPasswordFlow({ | ||
| username: credentials.username, | ||
| password: credentials.password, | ||
| }); | ||
|
|
||
| if (!tokenResponse.access_token) { | ||
| throw new Error('Failed to fetch token'); | ||
| } | ||
|
|
||
| return tokenResponse.access_token; | ||
| } | ||
|
|
||
| // Функция для получения токена и сохранения его в локальное хранилище | ||
| export async function fetchAndStoreUserToken(): Promise<void> { | ||
| const customerData = getCustomerToken(); | ||
| console.log('Customer data from localStorage:', customerData); | ||
| if (!customerData) { | ||
| throw new Error('No customer data found in localStorage.'); | ||
| } | ||
|
|
||
| if (!customerData.email || !customerData.password) { | ||
| throw new Error('Customer data is missing required fields.'); | ||
| } | ||
|
|
||
| const credentials: IUserCredentials = { | ||
| username: customerData.email, | ||
| password: customerData.password, | ||
| }; | ||
|
|
||
| console.log('Credentials for token request:', credentials); | ||
|
|
||
| try { | ||
| const token = await getUserToken(credentials); | ||
| localStorage.setItem(AUTH_TOKEN_KEY, token); | ||
| console.log('Token saved to localStorage:', token); | ||
| } catch (error) { | ||
| console.error('Error fetching user token:', error); | ||
| throw new Error('Failed to fetch user token.'); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import { addProductToCart } from './add-product-cart'; | ||
| import { createAnonymousCart, createCustomerCart } from './carts'; | ||
|
|
||
| class CartHandler { | ||
| private currentCartId: string | null = null; | ||
|
|
||
| private currentCartVersion: number | null = null; | ||
|
|
||
| private userId: string | null = null; | ||
|
|
||
| constructor(userId: string | null) { | ||
| this.userId = userId; | ||
| if (!userId) { | ||
| this.loadCartFromLocalStorage(); | ||
| } else { | ||
| this.loadCartFromServer(userId); | ||
| } | ||
| } | ||
|
|
||
| public handleAddToCart(productId: string, quantity: number): void { | ||
| if (!this.currentCartId || !this.currentCartVersion) { | ||
| this.createCartAndAddProduct(productId, quantity); | ||
| } else { | ||
| this.addProductToExistingCart( | ||
| this.currentCartId, | ||
| this.currentCartVersion, | ||
| productId, | ||
| quantity | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| private createCartAndAddProduct(productId: string, quantity: number): void { | ||
| if (this.userId) { | ||
| createCustomerCart( | ||
| this.userId, | ||
| (cartData) => { | ||
| this.currentCartId = cartData.id; | ||
| this.currentCartVersion = cartData.version; | ||
| this.addProductToExistingCart( | ||
| this.currentCartId, | ||
| this.currentCartVersion, | ||
| productId, | ||
| quantity | ||
| ); | ||
| }, | ||
| (errorMessage) => { | ||
| console.error('Error creating user cart:', errorMessage); | ||
| } | ||
| ); | ||
| } else { | ||
| createAnonymousCart( | ||
| (cartData) => { | ||
| this.currentCartId = cartData.id; | ||
| this.currentCartVersion = cartData.version; | ||
| this.saveCartToLocalStorage(); | ||
| this.addProductToExistingCart( | ||
| this.currentCartId, | ||
| this.currentCartVersion, | ||
| productId, | ||
| quantity | ||
| ); | ||
| }, | ||
| (errorMessage) => { | ||
| console.error('Error creating anonymous cart:', errorMessage); | ||
| } | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| private addProductToExistingCart( | ||
| cartId: string, | ||
| cartVersion: number, | ||
| productId: string, | ||
| quantity: number | ||
| ): void { | ||
| addProductToCart( | ||
| cartId, | ||
| cartVersion, | ||
| productId, | ||
| quantity, | ||
| (cartData) => { | ||
| this.currentCartId = cartData.id; | ||
| this.currentCartVersion = cartData.version; | ||
| if (!this.userId) { | ||
| this.saveCartToLocalStorage(); | ||
| } | ||
| console.log('Product added to cart:', cartData); | ||
| }, | ||
| (errorMessage) => { | ||
| console.error('Error adding product to cart:', errorMessage); | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| private saveCartToLocalStorage(): void { | ||
| const cartData = { | ||
| currentCartId: this.currentCartId, | ||
| currentCartVersion: this.currentCartVersion, | ||
| }; | ||
| localStorage.setItem('anonymousCart', JSON.stringify(cartData)); | ||
| } | ||
|
|
||
| private loadCartFromLocalStorage(): void { | ||
| const savedCart = localStorage.getItem('anonymousCart'); | ||
| if (savedCart) { | ||
| const cartData = JSON.parse(savedCart); | ||
| this.currentCartId = cartData.currentCartId; | ||
| this.currentCartVersion = cartData.currentCartVersion; | ||
| } | ||
| } | ||
|
|
||
| // метод для загрузки корзины зарегистрированного пользователя с сервера | ||
| // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars | ||
| private loadCartFromServer(userId: string): void {} | ||
| } | ||
|
|
||
| export default CartHandler; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { Cart, ClientResponse } from '@commercetools/platform-sdk'; | ||
| import apiRoot from './api-root'; | ||
|
|
||
| // запрос на создание анон cart | ||
| // При успешном создании корзины вызывает successCallback с данными корзины. | ||
| export const createAnonymousCart = ( | ||
| successCallback: (cartData: Cart) => void, | ||
| errorCallback: (message: string) => void | ||
| ): void => { | ||
| apiRoot | ||
| .carts() | ||
| .post({ | ||
| body: { | ||
| currency: 'USD', | ||
| }, | ||
| }) | ||
| .execute() | ||
| .then((response: ClientResponse<Cart>) => { | ||
| const cartData: Cart = response.body; | ||
| console.log(cartData); | ||
| successCallback(cartData); | ||
| }) | ||
| .catch((error: ClientResponse<{ message: string }>) => { | ||
| errorCallback(error.body.message); | ||
| }); | ||
| }; | ||
|
|
||
| export const createCustomerCart = ( | ||
| customerId: string, | ||
| successCallback: (cartData: Cart) => void, | ||
| errorCallback: (message: string) => void | ||
| ): void => { | ||
| apiRoot | ||
| .carts() | ||
| .post({ | ||
| body: { | ||
| currency: 'USD', | ||
| customerId, | ||
| }, | ||
| }) | ||
| .execute() | ||
| .then((response: ClientResponse<Cart>) => { | ||
| const cartData: Cart = response.body; | ||
| successCallback(cartData); | ||
| }) | ||
| .catch((error: ClientResponse<{ message: string }>) => { | ||
| errorCallback(error.body.message); | ||
| }); | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clean code, nice work!