Skip to content

Commit

Permalink
Merge pull request #2751 from beckn/feat/admin-bap-flow
Browse files Browse the repository at this point in the history
feat(open-spark): modified code to impl admin bap flow
  • Loading branch information
aniketceminds authored Dec 12, 2024
2 parents e31a7a9 + 0a43d94 commit 1e1a7f9
Show file tree
Hide file tree
Showing 10 changed files with 817 additions and 454 deletions.
20 changes: 17 additions & 3 deletions apps/open-spark/components/signIn/SignIn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,23 @@ const SignIn = ({ initialFormData = { email: '', password: '' } }) => {
}

try {
if (role === ROLE.CONSUMER) await bapTradeLogin(signInData).unwrap()
if (role === ROLE.PRODUCER) await bppTradeLogin(signInData).unwrap()
Router.push('/')
let roleType: ROLE | null = null
if (role === ROLE.CONSUMER) {
const res = await bapTradeLogin(signInData).unwrap()
if (res.user.role?.type.toUpperCase() === ROLE.CONSUMER) {
roleType = ROLE.CONSUMER
} else if (res.user.role?.type.toUpperCase() === ROLE.ADMIN) {
roleType = ROLE.ADMIN
}
}
if (role === ROLE.PRODUCER) {
await bppTradeLogin(signInData).unwrap()
roleType = ROLE.PRODUCER
}
if (roleType) {
dispatch(setRole({ role: roleType! }))
Router.push('/')
}
} catch (error) {
console.error('An error occurred:', error)
}
Expand Down
2 changes: 2 additions & 0 deletions apps/open-spark/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ export const currencyMap = {
}

export enum ROLE {
'ADMIN' = 'ADMIN',
'CONSUMER' = 'CONSUMER',
'PRODUCER' = 'PRODUCER'
}

export const ROUTE_TYPE = {
ADMIN: '/beckn-trade-bap',
CONSUMER: '/beckn-trade-bap',
PRODUCER: '/beckn-trade-bpp'
}
Expand Down
3 changes: 2 additions & 1 deletion apps/open-spark/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const en: { [key: string]: string } = {
logout: 'Logout',
upload: 'Upload',
errorText: 'Something went wrong',
success: 'Success!'
success: 'Success!',
lockDemandSuccess: 'Demand Locked Successfully!'
}
export default en
294 changes: 294 additions & 0 deletions apps/open-spark/pages/adminDashboard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
import { feedbackActions, formatDate, TopSheet, useGeolocation } from '@beckn-ui/common'
import { Typography } from '@beckn-ui/molecules'
import { Box, Flex, Image, Table, Tbody, Td, Th, Thead, Tr } from '@chakra-ui/react'
import { useRouter } from 'next/router'
import React, { useEffect, useState } from 'react'
import NavIcon from '@public/images/nav_icon.svg'
import profileIcon from '@public/images/user_profile.svg'
import { useLanguage } from '@hooks/useLanguage'
import axios from '@services/axios'
import { ROUTE_TYPE } from '@lib/config'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@store/index'
import Cookies from 'js-cookie'
import BecknButton from '@beckn-ui/molecules/src/components/button/Button'

interface PendingTrades {
id: number
name: string
quantity: number
createdAt: string
}

const LockDemand = () => {
const apiKeyForGoogle = process.env.NEXT_PUBLIC_GOOGLE_API_KEY
const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_URL
const bearerToken = Cookies.get('authToken') || ''

const [items, setItems] = useState<PendingTrades[]>([])
const [isLoading, setIsLoading] = useState<boolean>(false)

const { t } = useLanguage()
const router = useRouter()
const dispatch = useDispatch()
const { role } = useSelector((state: RootState) => state.auth)

const {
currentAddress,
error: currentLocationFetchError,
loading: loadingForCurrentAddress
} = useGeolocation(apiKeyForGoogle as string)

const fetchPendingTrades = async () => {
try {
const response = await axios.get(`${strapiUrl}${ROUTE_TYPE[role!]}/get-pending-trades`, {
headers: { Authorization: `Bearer ${bearerToken}` },
withCredentials: true
})

const result = response.data

const trades = result.map((tr: any) => {
const {
id,
quantity,
createdAt,
profile: { name }
} = tr
return {
id,
name,
quantity,
createdAt
}
})

setItems(trades)
} catch (error) {
console.error('Error fetching pending trade data:', error)
}
}
useEffect(() => {
fetchPendingTrades()
}, [])

const handleOnLockDemand = () => {
setIsLoading(true)

axios
.post(
`${strapiUrl}${ROUTE_TYPE[role!]}/start-trade`,
{},
{
headers: {
Authorization: `Bearer ${bearerToken}`
}
}
)
.then(response => {
console.log('Trade started successfully:', response.data)
dispatch(
feedbackActions.setToastData({
toastData: {
message: t.success,
display: true,
type: 'success',
description: response.data.message || t.lockDemandSuccess
}
})
)
})
.catch(error => {
console.error('Error while lock demand:', error)
})
.finally(() => {
setIsLoading(false)
})
}

return (
<>
<TopSheet
currentLocationFetchError={currentLocationFetchError}
loadingForCurrentAddress={loadingForCurrentAddress}
currentAddress={currentAddress}
t={key => t[key]}
profileSection={{
src: profileIcon,
handleClick: () => router.push('/profile')
}}
/>

<Box
maxWidth={{ base: '100vw', md: '30rem', lg: '40rem' }}
margin="calc(0rem + 68px) auto auto auto"
backgroundColor="white"
height={'calc(100vh - 92px'}
>
<Flex
flexDirection={'column'}
justifyContent={'space-between'}
height="100%"
>
<Box>
<Typography
text="Total Aggregated demand"
fontWeight="600"
fontSize="16px"
/>
<Box
maxH={'calc(100vh - 212px)'}
overflowY="scroll"
overflowX="scroll"
className="hideScroll"
marginTop={'1rem'}
>
<Table variant="simple">
<Thead
position="sticky"
top={0}
bg="white"
zIndex={1}
>
<Tr>
<Th padding="0">
<Box
display="flex"
alignItems="center"
placeContent={'center'}
width={'64px'}
>
Unit
</Box>
</Th>
<Th padding="0">
<Box
display="flex"
alignItems="center"
placeContent={'center'}
width={'130px'}
>
Consumer
</Box>
</Th>
<Th padding="0">
<Box
display="flex"
alignItems="center"
placeContent={'center'}
width={'70px'}
>
Date
</Box>
</Th>
<Th>
<Box
display="flex"
alignItems="center"
width={'5px'}
></Box>
</Th>
</Tr>
</Thead>
<Tbody>
{items.length > 0 ? (
items.map((item, index) => (
<Tr
key={index}
cursor="pointer"
_hover={{ backgroundColor: 'rgba(0, 0, 0, 0.04)' }}
onClick={() => {
router.push({ pathname: '/tradeDetails', query: { id: item.id, pagename: item.name } })
}}
>
<Td
borderBottom={'1px dotted #004e92!important'}
padding="0"
>
<Typography
text={item.quantity}
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: '2',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'normal',
textAlign: 'center',
width: '64px'
}}
/>
</Td>
<Td
borderBottom={'1px dotted #004e92!important'}
padding="0"
>
<Typography
text={item.name}
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: '1',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'normal',
textAlign: 'center',
width: '130px'
}}
/>
</Td>
<Td
borderBottom={'1px dotted #004e92!important'}
padding="0"
>
<Typography
text={formatDate(item.createdAt, 'yyyy-MM-dd')}
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: '2',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'normal',
textAlign: 'center',
width: '70px'
}}
/>
</Td>
<Td borderBottom={'1px dotted #004e92!important'}>
<Image
src={NavIcon}
alt="nav_icon"
width={'6px'}
/>
</Td>
</Tr>
))
) : (
<Tr>
<Td colSpan={5}>
<Typography
text="No rows"
fontWeight="600"
style={{ textAlign: 'center' }}
/>
</Td>
</Tr>
)}
</Tbody>
</Table>
</Box>
</Box>
<BecknButton
children={'Lock Demand'}
isLoading={isLoading}
handleClick={handleOnLockDemand}
sx={{ margin: '1rem 0' }}
/>
</Flex>
</Box>
</>
)
}

export default LockDemand
Loading

0 comments on commit 1e1a7f9

Please sign in to comment.