Skip to content

Commit

Permalink
feat: add user actions (#493)
Browse files Browse the repository at this point in the history
* feat: add funtion to get profile data

* feat: add functions to get masquerade state and b2b token

* feat: add functions for masquerade and login with storefront token

* refactor: change way to use jwt token

* refactor: use functions for shared logic

* fix: remove line

* fix: improve way to interact functions

* fix: change type
  • Loading branch information
bc-marco authored and kris-liu-smile committed Jun 27, 2023
1 parent 8bddec3 commit f8f9d83
Show file tree
Hide file tree
Showing 14 changed files with 190 additions and 78 deletions.
7 changes: 4 additions & 3 deletions apps/storefront/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { GlobaledContext } from '@/shared/global'
import { gotoAllowedAppPage } from '@/shared/routes'
import { setChannelStoreType } from '@/shared/service/b2b'
import {
B3SStorage,
getCompanyUserInfo,
getCurrentCustomerInfo,
getQuoteEnabled,
Expand All @@ -43,7 +44,6 @@ export default function App() {
state: {
isB2BUser,
customerId,
BcToken,
role,
realRole,
B3UserId,
Expand Down Expand Up @@ -141,8 +141,9 @@ export default function App() {
storeDispatch(setOpenPageReducer(setOpenPage))
loginAndRegister()
const init = async () => {
// bc token
if (!BcToken || isRelogin) {
// bc graphql token
const bcGraphqlToken = B3SStorage.get('bcGraphqlToken')
if (!bcGraphqlToken || isRelogin) {
await loginInfo()
}
setChannelStoreType(currentChannelId)
Expand Down
1 change: 0 additions & 1 deletion apps/storefront/src/components/B3StoreContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ export function B3StoreContainer(props: B3StoreContainerProps) {
) {
showPageMask(dispatch, true)
}
// if (!B3SStorage.get('bcJwtToken')) showPageMask(dispatch, true)

try {
const { storeBasicInfo }: CustomFieldItems = await getBCStoreChannelId()
Expand Down
56 changes: 54 additions & 2 deletions apps/storefront/src/components/HeadlessController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import {
addProductsToDraftQuote,
} from '@/hooks/dom/utils'
import { GlobaledContext } from '@/shared/global'
import { superAdminCompanies } from '@/shared/service/b2b'
import {
B3SStorage,
endMasquerade,
getCurrentCustomerInfo,
startMasquerade,
} from '@/utils'

interface HeadlessControllerProps {
setOpenPage: Dispatch<SetStateAction<OpenPageState>>
Expand All @@ -17,16 +24,26 @@ export default function HeadlessController({
setOpenPage,
}: HeadlessControllerProps) {
const {
state: { role },
state: { customerId, role, customer, B3UserId, salesRepCompanyId = 0 },
dispatch,
} = useContext(GlobaledContext)
const { addToQuote: addProductFromPage } =
addProductFromProductPageToQuote(setOpenPage)
const { addToQuote: addProductsFromCart } =
addProductsFromCartToQuote(setOpenPage)

// Keep updated role value
// Keep updated values
const addProductFromPageRef = useRef(() => addProductFromPage(role))
const B3UserIdRef = useRef(+B3UserId)
const salesRepCompanyIdRef = useRef(+salesRepCompanyId)
const customerIdRef = useRef(customerId)
const customerRef = useRef(customer)

addProductFromPageRef.current = () => addProductFromPage(role)
B3UserIdRef.current = +B3UserId
salesRepCompanyIdRef.current = +salesRepCompanyId
customerIdRef.current = customerId
customerRef.current = customer

useEffect(() => {
window.b2b = {
Expand All @@ -43,6 +60,41 @@ export default function HeadlessController({
addProductsFromCart: () => addProductsFromCart(),
addProducts: (items) => addProductsToDraftQuote(items),
},
user: {
getProfile: () => ({ ...customerRef.current, role }),
getMasqueradeState: async () => {
// get companies list
const {
superAdminCompanies: { edges: companies = [] },
} = await superAdminCompanies(B3UserIdRef.current, {
first: 50,
offset: 0,
})

return {
current_company_id: salesRepCompanyIdRef.current,
companies: companies.map(
({ node }: { node: CustomFieldStringItems }) => node
),
}
},
getB2BToken: () => B3SStorage.get('B3B2BToken') || '',
setMasqueradeCompany: (companyId) =>
startMasquerade({
dispatch,
companyId,
B3UserId: B3UserIdRef.current,
customerId: customerIdRef.current,
}),
endMasquerade: () =>
endMasquerade({
dispatch,
salesRepCompanyId: salesRepCompanyIdRef.current,
B3UserId: B3UserIdRef.current,
}),
logInWithStorefrontToken: (customerJWTToken: string) =>
getCurrentCustomerInfo(dispatch, customerJWTToken),
},
},
}
}, [])
Expand Down
13 changes: 13 additions & 0 deletions apps/storefront/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ declare interface Window {
addProductsFromCart: () => Promise<void>
addProducts: (items: CustomFieldItems[]) => Promise<boolean>
}
user: {
getProfile: () => Record<string, string | number>
getMasqueradeState: () => Promise<{
current_company_id: number
companies: CustomFieldStringItems[]
}>
getB2BToken: () => string
setMasqueradeCompany: (companyId: number) => Promise<void>
endMasquerade: () => Promise<void>
logInWithStorefrontToken: (
customerJWTToken: string
) => Promise<{ role: number; userType: string } | undefined>
}
}
}
}
61 changes: 13 additions & 48 deletions apps/storefront/src/pages/dashboard/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,8 @@ import { B3Sping, showPageMask } from '@/components'
import { B3PaginationTable } from '@/components/table/B3PaginationTable'
import { TableColumnItem } from '@/components/table/B3Table'
import { GlobaledContext } from '@/shared/global'
import {
getAgentInfo,
superAdminBeginMasquerade,
superAdminCompanies,
superAdminEndMasquerade,
} from '@/shared/service/b2b'
import { B3SStorage } from '@/utils'
import { superAdminCompanies } from '@/shared/service/b2b'
import { endMasquerade, startMasquerade } from '@/utils'

import B3FilterSearch from '../../components/filter/B3FilterSearch'

Expand Down Expand Up @@ -133,32 +128,6 @@ function Dashboard(props: DashboardProps) {

const location = useLocation()

const setMasqueradeInfo = async () => {
try {
setIsRequestLoading(true)
const data: any = await getAgentInfo(customerId)
if (data?.superAdminMasquerading) {
const { id, companyName } = data.superAdminMasquerading
B3SStorage.set('isAgenting', true)
B3SStorage.set('salesRepCompanyId', id)
B3SStorage.set('salesRepCompanyName', companyName)
// B3SStorage.set('isB2BUser', true)

dispatch({
type: 'common',
payload: {
salesRepCompanyId: id,
salesRepCompanyName: companyName,
isAgenting: true,
isB2BUser: true,
},
})
}
} finally {
setIsRequestLoading(false)
}
}

const getSuperAdminCompaniesList = async (params: ListItem) => {
const {
superAdminCompanies: { edges = [], totalCount },
Expand All @@ -173,8 +142,12 @@ function Dashboard(props: DashboardProps) {
const startActing = async (id?: number) => {
try {
setIsRequestLoading(true)
await superAdminBeginMasquerade(id || currentSalesRepCompanyId, +B3UserId)
await setMasqueradeInfo()
await startMasquerade({
dispatch,
customerId,
companyId: id || currentSalesRepCompanyId,
B3UserId: +B3UserId,
})

setOpenPage({
isOpen: true,
Expand All @@ -184,26 +157,18 @@ function Dashboard(props: DashboardProps) {
setFilterData({
...filterData,
})
} catch (error) {
} finally {
setIsRequestLoading(false)
}
}

const endActing = async () => {
try {
showPageMask(dispatch, true)
await superAdminEndMasquerade(+salesRepCompanyId, +B3UserId)
location.state = null
B3SStorage.delete('isAgenting')
B3SStorage.delete('salesRepCompanyId')
B3SStorage.delete('salesRepCompanyName')
dispatch({
type: 'common',
payload: {
salesRepCompanyId: '',
salesRepCompanyName: '',
isAgenting: false,
},
await endMasquerade({
dispatch,
salesRepCompanyId: +salesRepCompanyId,
B3UserId: +B3UserId,
})
setFilterData({
...filterData,
Expand Down
2 changes: 0 additions & 2 deletions apps/storefront/src/shared/global/context/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export interface TimeFormatProps {
export interface GlobalState {
isCheckout: boolean
isCloseGotoBCHome: boolean
BcToken: string
isB2BUser: boolean
customerId: number | string
customer: CustomerInfo
Expand Down Expand Up @@ -122,7 +121,6 @@ export interface GlobalState {
export const initState = {
isCheckout: false,
isCloseGotoBCHome: false,
BcToken: B3SStorage.get('BcToken') || '',
isB2BUser: B3SStorage.get('isB2BUser') || false,
customerId: B3SStorage.get('B3CustomerId') || '',
B3UserId: B3SStorage.get('B3UserId') || '',
Expand Down
4 changes: 2 additions & 2 deletions apps/storefront/src/shared/service/b2b/api/login.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import getProxyInfo from './proxy'

const getBCToken = getProxyInfo
const getBCGraphqlToken = getProxyInfo

export default getBCToken
export default getBCGraphqlToken
11 changes: 7 additions & 4 deletions apps/storefront/src/shared/service/b2b/graphql/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { convertArrayToGraphql, storeHash } from '@/utils'

import B3Request from '../../request/b3Fetch'

const getB2BTokenQl = (bcJwtToken: string, channelId: number) => `mutation {
const getB2BTokenQl = (
currentCustomerJWTToken: string,
channelId: number
) => `mutation {
authorization(authData: {
bcToken: "${bcJwtToken}"
bcToken: "${currentCustomerJWTToken}"
channelId: ${channelId}
}) {
result {
Expand Down Expand Up @@ -178,11 +181,11 @@ const taxZoneRates = () => `{
}`

export const getB2BToken = (
bcJwtToken: string,
currentCustomerJWTToken: string,
channelId = 1
): CustomFieldItems =>
B3Request.graphqlB2B({
query: getB2BTokenQl(bcJwtToken, channelId),
query: getB2BTokenQl(currentCustomerJWTToken, channelId),
})

export const getAgentInfo = (customerId: string | number): CustomFieldItems =>
Expand Down
4 changes: 2 additions & 2 deletions apps/storefront/src/shared/service/b2b/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import validateAddressExtraFields from './api/address'
import { setChannelStoreType, uploadB2BFile } from './api/global'
import getBCToken from './api/login'
import getBCGraphqlToken from './api/login'
import getBCOrders from './api/order'
import {
createBCCompanyUser,
Expand Down Expand Up @@ -172,6 +172,7 @@ export {
getBCCustomerAddress,
getBCCustomerAddresses,
getBCForcePasswordReset,
getBCGraphqlToken,
getBCOrderDetails,
getBCOrders,
getBcOrderStatusType,
Expand All @@ -180,7 +181,6 @@ export {
getBcShoppingList,
getBcShoppingListDetails,
getBCStoreChannelId,
getBCToken,
getBcVariantInfoBySkus,
getCurrencies,
getOrdersCreatedByUser,
Expand Down
6 changes: 4 additions & 2 deletions apps/storefront/src/shared/service/request/b3Fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,15 @@ const B3Request = {
customMessage = false
): Promise<any> {
const config = {
Authorization: `Bearer ${B3SStorage.get('bcJwtToken') || ''}`,
Authorization: `Bearer ${
B3SStorage.get('currentCustomerJWTToken') || ''
}`,
}
return graphqlRequest(RequestType.B2BGraphql, data, config, customMessage)
},
graphqlBC: function post<T>(data: T): Promise<any> {
const config = {
Authorization: `Bearer ${B3SStorage.get('BcToken') || ''}`,
Authorization: `Bearer ${B3SStorage.get('bcGraphqlToken') || ''}`,
}
return graphqlRequest(RequestType.BCGraphql, data, config)
},
Expand Down
4 changes: 3 additions & 1 deletion apps/storefront/src/shared/service/request/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ function b3Fetch(
try {
await getCurrentJwt()
const config = {
Authorization: `Bearer ${B3SStorage.get('bcJwtToken') || ''}`,
Authorization: `Bearer ${
B3SStorage.get('currentCustomerJWTToken') || ''
}`,
}
const headers = {
'content-type': 'application/json',
Expand Down
1 change: 1 addition & 0 deletions apps/storefront/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export {
setModifierQtyPrice,
validProductQty,
} from './b3Product/b3Product'
export * from './masquerade'
export {
getQuoteConfig,
getStoreTaxZoneRates,
Expand Down
Loading

0 comments on commit f8f9d83

Please sign in to comment.