Skip to content

Commit

Permalink
Revert "Bc victor/bun 1383/callbacks manager (#875)"
Browse files Browse the repository at this point in the history
This reverts commit 4bab6d3.
  • Loading branch information
BrianJiang2021 authored and libruce committed Dec 26, 2023
1 parent 3fbe938 commit 52ce297
Show file tree
Hide file tree
Showing 9 changed files with 181 additions and 327 deletions.
2 changes: 0 additions & 2 deletions apps/storefront/src/components/HeadlessController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
LineItems,
startMasquerade,
} from '@/utils'
import CallbackManager from '@/utils/b3Callbacks'
import createShoppingList from '@/utils/b3ShoppingList/b3ShoppingList'

interface QuoteDraftItem {
Expand Down Expand Up @@ -177,7 +176,6 @@ export default function HeadlessController({

useEffect(() => {
window.b2b = {
callbacks: new CallbackManager(),
utils: {
openPage: (page) => {
setOpenPage({ isOpen: false })
Expand Down
1 change: 0 additions & 1 deletion apps/storefront/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ declare interface Window {
globalTipDispatch: any
B3Local: any
b2b: {
callbacks: import('@/utils/b3Callbacks').default
utils: {
openPage: (page: import('./constants').HeadlessRoute) => void
quote: {
Expand Down
322 changes: 155 additions & 167 deletions apps/storefront/src/pages/quote/QuoteDraft.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
useState,
} from 'react'
import { useNavigate } from 'react-router-dom'
import useCallbacks from '@b3/hooks/useCustomCallbacks'
import { useB3Lang } from '@b3/lang'
import { ArrowBackIosNew } from '@mui/icons-material'
import {
Expand Down Expand Up @@ -402,203 +401,192 @@ function QuoteDraft({ setOpenPage }: QuoteDraftProps) {
}))
}

const handleSubmit = useCallbacks(
'on-quote-create',
async (_e, handleEvent) => {
setLoading(true)
try {
const info = B3LStorage.get('MyQuoteInfo')
const contactInfo = info?.contactInfo || {}

const isComplete = Object.keys(contactInfo).every((key: string) => {
if (key === 'phoneNumber' || key === 'companyName') {
return true
}
return !!contactInfo[key]
})
const handleSubmit = async () => {
setLoading(true)
try {
const info = B3LStorage.get('MyQuoteInfo')
const contactInfo = info?.contactInfo || {}

if (JSON.stringify(contactInfo) === '{}' || !isComplete) {
snackbar.error(b3Lang('quoteDraft.addQuoteInfo'))
return
const isComplete = Object.keys(contactInfo).every((key: string) => {
if (key === 'phoneNumber' || key === 'companyName') {
return true
}
return !!contactInfo[key]
})

const b2bQuoteDraftList = B3LStorage.get('b2bQuoteDraftList')

if (!b2bQuoteDraftList || b2bQuoteDraftList.length === 0) {
snackbar.error(b3Lang('quoteDraft.submit'))
return
}
if (JSON.stringify(contactInfo) === '{}' || !isComplete) {
snackbar.error(b3Lang('quoteDraft.addQuoteInfo'))
return
}

const emailAddress = B3SStorage.get('B3EmailAddress')
const b2bQuoteDraftList = B3LStorage.get('b2bQuoteDraftList')

const note = info?.note || ''
const newNote = note.trim().replace(/[\r\n]/g, '\\n')
if (!b2bQuoteDraftList || b2bQuoteDraftList.length === 0) {
snackbar.error(b3Lang('quoteDraft.submit'))
return
}

const perfectAddress = (address: CustomFieldStringItems) => {
const newAddress = {
...address,
}
const emailAddress = B3SStorage.get('B3EmailAddress')

const countryItem = countriesList?.find(
(item: Country) => item.countryCode === newAddress.country
)
const note = info?.note || ''
const newNote = note.trim().replace(/[\r\n]/g, '\\n')

if (countryItem) {
newAddress.country = countryItem.countryName
}
const perfectAddress = (address: CustomFieldStringItems) => {
const newAddress = {
...address,
}

newAddress.addressLine1 = address?.address || ''
newAddress.addressLine2 = address?.apartment || ''
const countryItem = countriesList?.find(
(item: Country) => item.countryCode === newAddress.country
)

return newAddress
if (countryItem) {
newAddress.country = countryItem.countryName
}

const {
shippingAddress: editShippingAddress,
billingAddress: editBillingAddress,
} = billingRef?.current ? getAddress() : info
newAddress.addressLine1 = address?.address || ''
newAddress.addressLine2 = address?.apartment || ''

const shippingAddress = editShippingAddress
? perfectAddress(editShippingAddress)
: {}
return newAddress
}

const billingAddress = editBillingAddress
? perfectAddress(editBillingAddress)
: {}
const {
shippingAddress: editShippingAddress,
billingAddress: editBillingAddress,
} = billingRef?.current ? getAddress() : info

let allPrice = 0
let allTaxPrice = 0
const shippingAddress = editShippingAddress
? perfectAddress(editShippingAddress)
: {}

const calculationTime = (value: string | number) => {
if (typeof value === 'string' && value.includes('-')) {
return `${new Date(value).getTime() / 1000}`
}
return value
}
const billingAddress = editBillingAddress
? perfectAddress(editBillingAddress)
: {}

const productList = b2bQuoteDraftList.map(
(item: QuoteListitemProps) => {
const { node } = item
const product: any = {
...node.productsSearch,
selectOptions: node?.optionList || '',
}
let allPrice = 0
let allTaxPrice = 0

const productFields = getProductOptionsFields(product, {})
const optionsList: CustomFieldItems[] =
productFields
.map((item) => ({
optionId: item.optionId,
optionValue:
item.fieldType === 'date'
? calculationTime(item.optionValue)
: item.optionValue,
optionLabel: `${item.valueText}`,
optionName: item.valueLabel,
}))
.filter((list: CustomFieldItems) => !!list.optionName) || []

const varants = node.productsSearch.variants
const varantsItem = varants.find(
(item: CustomFieldItems) => item.sku === node.variantSku
)

// const salePrice = getBCPrice(+(node?.basePrice || 0), +(node?.taxPrice || 0))

allPrice += +(node?.basePrice || 0) * +(node?.quantity || 0)

allTaxPrice += +(node?.taxPrice || 0) * +(node?.quantity || 0)

const items = {
productId: node.productsSearch.id,
sku: node.variantSku,
basePrice: (+(node?.basePrice || 0)).toFixed(decimalPlaces),
discount: '0.00',
offeredPrice: (+(node?.basePrice || 0)).toFixed(decimalPlaces),
quantity: node.quantity,
variantId: varantsItem.variant_id,
imageUrl: node.primaryImage,
productName: node.productName,
options: optionsList,
}
const calculationTime = (value: string | number) => {
if (typeof value === 'string' && value.includes('-')) {
return `${new Date(value).getTime() / 1000}`
}
return value
}

return items
}
const productList = b2bQuoteDraftList.map((item: QuoteListitemProps) => {
const { node } = item
const product: any = {
...node.productsSearch,
selectOptions: node?.optionList || '',
}

const productFields = getProductOptionsFields(product, {})
const optionsList: CustomFieldItems[] =
productFields
.map((item) => ({
optionId: item.optionId,
optionValue:
item.fieldType === 'date'
? calculationTime(item.optionValue)
: item.optionValue,
optionLabel: `${item.valueText}`,
optionName: item.valueLabel,
}))
.filter((list: CustomFieldItems) => !!list.optionName) || []

const varants = node.productsSearch.variants
const varantsItem = varants.find(
(item: CustomFieldItems) => item.sku === node.variantSku
)

const currency = getDefaultCurrencyInfo()

const fileList = getFileList(info.fileInfo || [])

const data = {
// notes: note,
message: newNote,
legalTerms: '',
totalAmount: enteredInclusiveTax
? allPrice.toFixed(decimalPlaces)
: (allPrice + allTaxPrice).toFixed(decimalPlaces),
grandTotal: allPrice.toFixed(decimalPlaces),
subtotal: allPrice.toFixed(decimalPlaces),
companyId: isB2BUser ? companyB2BId || salesRepCompanyId : '',
storeHash,
discount: '0.00',
channelId,
userEmail: emailAddress,
shippingAddress,
billingAddress,
contactInfo,
productList,
fileList,
taxTotal: allTaxPrice.toFixed(decimalPlaces),
currency: {
currencyExchangeRate: currency.currency_exchange_rate,
token: currency.token,
location: currency.token_location,
decimalToken: currency.decimal_token,
decimalPlaces: currency.decimal_places,
thousandsToken: currency.thousands_token,
currencyCode: currency.currency_code,
},
}
// const salePrice = getBCPrice(+(node?.basePrice || 0), +(node?.taxPrice || 0))

const fn = +role === 99 ? createBCQuote : createQuote
allPrice += +(node?.basePrice || 0) * +(node?.quantity || 0)

if (!handleEvent(data)) {
throw new Error()
allTaxPrice += +(node?.taxPrice || 0) * +(node?.quantity || 0)

const items = {
productId: node.productsSearch.id,
sku: node.variantSku,
basePrice: (+(node?.basePrice || 0)).toFixed(decimalPlaces),
discount: '0.00',
offeredPrice: (+(node?.basePrice || 0)).toFixed(decimalPlaces),
quantity: node.quantity,
variantId: varantsItem.variant_id,
imageUrl: node.primaryImage,
productName: node.productName,
options: optionsList,
}

const {
quoteCreate: {
quote: { id, createdAt },
},
} = await fn(data)
return items
})

const currency = getDefaultCurrencyInfo()

const fileList = getFileList(info.fileInfo || [])

const data = {
// notes: note,
message: newNote,
legalTerms: '',
totalAmount: enteredInclusiveTax
? allPrice.toFixed(decimalPlaces)
: (allPrice + allTaxPrice).toFixed(decimalPlaces),
grandTotal: allPrice.toFixed(decimalPlaces),
subtotal: allPrice.toFixed(decimalPlaces),
companyId: isB2BUser ? companyB2BId || salesRepCompanyId : '',
storeHash,
discount: '0.00',
channelId,
userEmail: emailAddress,
shippingAddress,
billingAddress,
contactInfo,
productList,
fileList,
taxTotal: allTaxPrice.toFixed(decimalPlaces),
currency: {
currencyExchangeRate: currency.currency_exchange_rate,
token: currency.token,
location: currency.token_location,
decimalToken: currency.decimal_token,
decimalPlaces: currency.decimal_places,
thousandsToken: currency.thousands_token,
currencyCode: currency.currency_code,
},
}

if (id) {
const cartId = B3LStorage.get('cartToQuoteId')
const fn = +role === 99 ? createBCQuote : createQuote

await deleteCart(cartId)
}
const {
quoteCreate: {
quote: { id, createdAt },
},
} = await fn(data)

navigate(`/quoteDetail/${id}?date=${createdAt}`, {
state: {
to: 'draft',
},
})
if (id) {
const cartId = B3LStorage.get('cartToQuoteId')

B3LStorage.delete('b2bQuoteDraftList')
B3LStorage.delete('MyQuoteInfo')
B3LStorage.delete('cartToQuoteId')
} catch (error: any) {
if (error.message.length > 0) {
snackbar.error(error.message, {
isClose: true,
})
}
} finally {
setLoading(false)
await deleteCart(cartId)
}

navigate(`/quoteDetail/${id}?date=${createdAt}`, {
state: {
to: 'draft',
},
})

B3LStorage.delete('b2bQuoteDraftList')
B3LStorage.delete('MyQuoteInfo')
B3LStorage.delete('cartToQuoteId')
} catch (error: any) {
snackbar.error(error, {
isClose: true,
})
} finally {
setLoading(false)
}
)
}

const backText = () => {
let text =
Expand Down
Loading

0 comments on commit 52ce297

Please sign in to comment.