Skip to content

Commit

Permalink
feat: reimplement add-to-shopping-list-from-page function (#852)
Browse files Browse the repository at this point in the history
* feat: implement add-to-shopping-list button

* fix: address improvement

* fix: use stored platform on redux
  • Loading branch information
bc-marco authored and libruce committed Dec 27, 2023
1 parent 11ceb9a commit c465ee2
Show file tree
Hide file tree
Showing 6 changed files with 842 additions and 841 deletions.
32 changes: 12 additions & 20 deletions apps/storefront/src/components/HeadlessController.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { Dispatch, SetStateAction, useContext, useEffect, useRef } from 'react'
import { useDispatch } from 'react-redux'
import globalB3 from '@b3/global-b3'
import type { OpenPageState } from '@b3/hooks'
import { useB3Lang } from '@b3/lang'

import { HeadlessRoutes } from '@/constants'
import { addProductFromPage as addProductFromPageToShoppingList } from '@/hooks/dom/useOpenPDP'
import {
addProductFromProductPageToQuote,
addProductsFromCartToQuote,
addProductsToDraftQuote,
} from '@/hooks/dom/utils'
Expand Down Expand Up @@ -81,6 +79,10 @@ const transformOptionSelectionsToAttributes = (items: LineItems[]) =>
}
})

export type ProductMappedAttributes = ReturnType<
typeof transformOptionSelectionsToAttributes
>

const getDraftQuote = () => {
const itemsList: QuoteDraftItem[] = B3LStorage.get('b2bQuoteDraftList')
let productList: FormatedQuoteItem[] = []
Expand Down Expand Up @@ -134,10 +136,8 @@ export default function HeadlessController({
},
} = useContext(GlobaledContext)
const {
state: { addQuoteBtn },
state: { addQuoteBtn, shoppingListBtn },
} = useContext(CustomStyleContext)
const { addToQuote: addProductFromPageToQuote } =
addProductFromProductPageToQuote(setOpenPage)
const { addToQuote: addProductsFromCart } =
addProductsFromCartToQuote(setOpenPage)

Expand All @@ -158,9 +158,6 @@ export default function HeadlessController({
}

// Keep updated values
const addProductFromPageToQuoteRef = useRef(() =>
addProductFromPageToQuote(role)
)
const B3UserIdRef = useRef(+B3UserId)
const salesRepCompanyIdRef = useRef(+salesRepCompanyId)
const customerIdRef = useRef(customerId)
Expand All @@ -169,7 +166,6 @@ export default function HeadlessController({
const isB2BUserRef = useRef(isB2BUser)
const currentChannelIdRef = useRef(currentChannelId)

addProductFromPageToQuoteRef.current = () => addProductFromPageToQuote(role)
B3UserIdRef.current = +B3UserId
salesRepCompanyIdRef.current = +salesRepCompanyId
customerIdRef.current = customerId
Expand All @@ -189,7 +185,8 @@ export default function HeadlessController({
)
},
quote: {
addProductFromPage: addProductFromPageToQuoteRef.current,
addProductFromPage: (item) =>
addProductsToDraftQuote([item], setOpenPage),
addProductsFromCart: () => addProductsFromCart(),
addProducts: (items) => addProductsToDraftQuote(items, setOpenPage),
getCurrent: getDraftQuote,
Expand Down Expand Up @@ -236,16 +233,10 @@ export default function HeadlessController({
},
},
shoppingList: {
addProductFromPage: () => {
dispatch({
type: 'common',
payload: {
shoppingListClickNode: document.querySelector(
globalB3['dom.productView']
),
},
})

itemFromCurrentPage: [],
addProductFromPage: (item) => {
window.b2b.utils.shoppingList.itemFromCurrentPage =
transformOptionSelectionsToAttributes([item])
addProductFromPageToShoppingList({
role: roleRef.current,
storeDispatch,
Expand Down Expand Up @@ -273,6 +264,7 @@ export default function HeadlessController({

return shoppingListsCreate.shoppingList
},
getButtonInfo: () => shoppingListBtn,
},
},
}
Expand Down
10 changes: 6 additions & 4 deletions apps/storefront/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ declare interface Window {
utils: {
openPage: (page: import('./constants').HeadlessRoute) => void
quote: {
addProductFromPage: () => Promise<void>
addProductFromPage: (item: import('@/utils').LineItems) => void
addProductsFromCart: () => Promise<void>
addProducts: (items: import('@/utils').LineItems[]) => Promise<void>
getCurrent: () => {
productList: import('@/components').FormatedQuoteItem[]
}
getButtonInfo: () => import('@/shared/customStyleButtton/context/config').AddQuoteBtnProperties
getButtonInfo: () => import('@/shared/customStyleButtton/context/config').BtnProperties
}
user: {
getProfile: () => Record<string, string | number>
Expand All @@ -39,15 +39,17 @@ declare interface Window {
) => Promise<void>
}
shoppingList: {
addProductFromPage: () => void
itemFromCurrentPage: import('@/components').ProductMappedAttributes
addProductFromPage: (item: import('@/utils').LineItems) => void
addProducts: (
shoppingListId: number,
items: import('@/utils').LineItems[]
) => Promise<void>
) => void
createNewShoppingList: (
name: string,
description: string
) => Promise<{ id: number; name: string; description: string }>
getButtonInfo: () => import('@/shared/customStyleButtton/context/config').BtnProperties
}
}
}
Expand Down
56 changes: 35 additions & 21 deletions apps/storefront/src/pages/pdp/PDP.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export const serialize = (form: any) => {
return arr
}

export const getProductOptionList = (optionMap: CustomFieldItems) => {
export const getProductOptionList = (optionMap: CustomFieldItems = {}) => {
const optionList: CustomFieldItems[] = []
Object.keys(optionMap).forEach((item) => {
if (item.includes('attribute') && item.match(/\[([0-9]+)\]/g)) {
Expand Down Expand Up @@ -216,6 +216,7 @@ function PDP({ setOpenPage }: PDPProps) {
customer: { customerGroupId },
},
} = useContext(GlobaledContext)
const platform = useSelector(({ global }) => global.storeInfo.platform)
const b3Lang = useB3Lang()

const [openShoppingList, setOpenShoppingList] = useState<boolean>(false)
Expand Down Expand Up @@ -251,40 +252,53 @@ function PDP({ setOpenPage }: PDPProps) {
})
}

const handleShoppingConfirm = async (shoppingListId: string) => {
if (!shoppingListClickNode) return
const getShoppingListItem = () => {
if (platform !== 'bigcommerce') {
const {
itemFromCurrentPage: [product],
} = window.b2b.utils.shoppingList
return product
}

if (!shoppingListClickNode) return undefined

const productView: HTMLElement | null = shoppingListClickNode.closest(
globalB3['dom.productView']
)
if (!productView) return
if (!productView) return undefined

const productId = (
productView.querySelector('input[name=product_id]') as any
)?.value
const quantity =
(productView.querySelector('[name="qty[]"]') as any)?.value ?? 1
const sku = (
productView.querySelector('[data-product-sku]')?.innerHTML ?? ''
).trim()
const form = productView.querySelector('form[data-cart-item-add]')
return {
productId: +productId,
sku,
quantity: +quantity,
optionSelections: serialize(form),
}
}

const handleShoppingConfirm = async (shoppingListId: string) => {
const product = getShoppingListItem()

if (!product) return
try {
setIsRequestLoading(true)
const productId = (
productView.querySelector('input[name=product_id]') as any
)?.value
const quantity =
(productView.querySelector('[name="qty[]"]') as any)?.value ?? 1
const sku = (
productView.querySelector('[data-product-sku]')?.innerHTML ?? ''
).trim()
const form = productView.querySelector('form[data-cart-item-add]')
await addProductsToShoppingList({
isB2BUser,
customerGroupId,
shoppingListId,
items: [
{
productId: +productId,
sku,
quantity: +quantity,
optionSelections: serialize(form),
},
],
items: [product],
gotoShoppingDetail,
b3Lang,
})

handleShoppingClose()
} finally {
setIsRequestLoading(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ interface BtnStyle {
css?: string
}

export interface AddQuoteBtnProperties {
export interface BtnProperties {
classSelector: string
color: string
customCss: string
Expand All @@ -52,7 +52,8 @@ export interface AddQuoteBtnProperties {

export interface CustomStyleButtonState
extends Record<BtnKeys, Partial<BtnStyle>> {
addQuoteBtn: AddQuoteBtnProperties
addQuoteBtn: BtnProperties
shoppingListBtn: BtnProperties
globalButtonBackgroundColor: string
}

Expand Down
13 changes: 5 additions & 8 deletions apps/storefront/src/utils/b3ClearCart.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getBCStoreChannelId } from '@/shared/service/b2b'
import { deleteCart, getCart } from '@/shared/service/bc/graphql/cart'
import { setCartNumber, store } from '@/store'

Expand All @@ -9,14 +8,12 @@ const clearInvoiceCart = async () => {
try {
const url = window.location.pathname
const isInvoicePay = localStorage.getItem('invoicePay')
const getStoreInfo = async () => {
const { storeBasicInfo }: CustomFieldItems = await getBCStoreChannelId()
const [storeInfo] = storeBasicInfo.storeSites

return storeInfo?.platform
}

const platform = await getStoreInfo()
const {
global: {
storeInfo: { platform },
},
} = store.getState()

if (url !== '/checkout' && isInvoicePay === '1') {
const cartEntityId: string = getCookie('cartId')
Expand Down
Loading

0 comments on commit c465ee2

Please sign in to comment.