Skip to content

Commit

Permalink
Merge pull request #2703 from beckn/feat/api_integration_myDers
Browse files Browse the repository at this point in the history
feat(open-spark): api integration for my ders page
  • Loading branch information
aniketceminds authored Dec 9, 2024
2 parents d8e2609 + 74f4d5a commit 07e3212
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 76 deletions.
10 changes: 7 additions & 3 deletions apps/open-spark/components/currentTrade/EmptyCurrentTrade.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { Typography } from '@beckn-ui/molecules'
import BecknButton from '@beckn-ui/molecules/src/components/button'
import { Box, Flex, Image } from '@chakra-ui/react'
import { ROLE } from '@lib/config'
import { RootState } from '@store/index'
import React from 'react'
import { Type } from 'react-toastify/dist/utils'
import { useSelector } from 'react-redux'

const EmptyCurrentTrade = () => {
const { role } = useSelector((state: RootState) => state.auth)
const emptyCurrentText = role === ROLE.CONSUMER ? '"Buy"' : '"Sell"'
const sellText = role === ROLE.PRODUCER ? 'sell' : 'purchase'
return (
<Flex
flexDir={'column'}
Expand All @@ -21,10 +25,10 @@ const EmptyCurrentTrade = () => {
sx={{ textAlign: 'center' }}
/>
<Typography
text="Click on “Buy” to purchase energy"
fontSize="15px"
fontWeight="400"
sx={{ textAlign: 'center' }}
text={`Click on ${emptyCurrentText} to ${sellText} energy`}
/>
</Flex>
)
Expand Down
46 changes: 32 additions & 14 deletions apps/open-spark/components/deviceList/AddNewDerModal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from 'react'
import BottomModalScan from '@beckn-ui/common/src/components/BottomModal/BottomModalScan'
import { Input, Typography } from '@beckn-ui/molecules'
import { Input, LoaderWithMessage, Typography } from '@beckn-ui/molecules'
import BecknButton from '@beckn-ui/molecules/src/components/button'
import { Box, Flex, Image } from '@chakra-ui/react'
import uploadIcon from '@public/images/upload_icon.svg'
Expand Down Expand Up @@ -55,20 +55,40 @@ const AddNewDerModal = (props: AddNewDerModalProps) => {
}
const files = uploadedFiles.map(doc => doc.file)
onSubmit(category, files)
.then(() => {
setCategory('')
setUploadedFiles([])
})
.catch(err => {
console.error('Error adding device:', err.message)
})
}

const handleOnDelete = (index: number, document: DocumentProps, type: 'cred' | 'upload') => {
if (type === 'cred') {
setUploadedFiles(prevState => prevState!.filter((_, i) => i !== index))
}
}

return (
<Box>
<BottomModalScan
isOpen={isOpen}
onClose={onClose}
modalHeader="Add New DER"
>
<BottomModalScan
isOpen={isOpen}
onClose={onClose}
modalHeader="Add New DER"
isLoading={isLoading}
>
{isLoading ? (
<Box
display="grid"
height="100%"
alignContent="center"
>
<LoaderWithMessage
loadingText="Please Wait"
loadingSubText="While We are adding DERS"
/>
</Box>
) : (
<Flex
padding="0 20px"
flexDir="column"
Expand All @@ -91,14 +111,13 @@ const AddNewDerModal = (props: AddNewDerModalProps) => {
setAllFilesProcessed(status)
}}
/>

<DragAndDropUpload
multiple={true}
setFiles={handleFileChange}
fileSelectionElement={(fileInputRef: any) => {
return (
<Flex
alignItems={'center'}
alignItems="center"
cursor="pointer"
onClick={() => {
if (fileInputRef.current) {
Expand All @@ -110,9 +129,8 @@ const AddNewDerModal = (props: AddNewDerModalProps) => {
src={uploadIcon}
alt="upload"
/>

<Typography
text={'Upload Documents'}
text="Upload Documents"
sx={{
marginLeft: '0.5rem'
}}
Expand All @@ -122,15 +140,15 @@ const AddNewDerModal = (props: AddNewDerModalProps) => {
}}
/>
<BecknButton
children={'Add DER'}
children="Add DER"
handleClick={handleAddDevice}
disabled={!category.trim() || uploadedFiles.length === 0}
sx={{ marginTop: '20px' }}
isLoading={isLoading}
/>
</Flex>
</BottomModalScan>
</Box>
)}
</BottomModalScan>
)
}

Expand Down
55 changes: 21 additions & 34 deletions apps/open-spark/components/deviceList/DeviceList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import { RootState } from '@store/index'
import Cookies from 'js-cookie'

interface Device {
id: number
name: string
paired: boolean
paired?: boolean
}

interface DeviceListProps {
Expand All @@ -30,36 +31,32 @@ export default function DeviceList({ initialDevices, onDeviceChange, fetchPaired
const [selectedDeviceIndex, setSelectedDeviceIndex] = useState<number | null>(null)
const [isLoading, setIsLoading] = useState<boolean>(false)
const [isDeleteLoading, setIsDeleteLoading] = useState<boolean>(false)

const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_URL
const { role } = useSelector((state: RootState) => state.auth)
const bearerToken = Cookies.get('authToken')

const handleAddDevice = async (category: string, uploadedFiles: File[]) => {
setIsLoading(true)
try {
const type = role === ROLE.PRODUCER ? 'PRODUCER' : 'CONSUMER'
const type = role === ROLE.PRODUCER ? 'prosumer' : 'consumer'
const formData = new FormData()

formData.append('type', type)
formData.append('category', category)
uploadedFiles.forEach(file => formData.append('proofs', file))
uploadedFiles.forEach(file => {
formData.append('proof', file)
})

const response = await axios.post(`${strapiUrl}${ROUTE_TYPE[role!]}/der`, formData, {
headers: { Authorization: `Bearer ${bearerToken}` },
headers: {
Authorization: `Bearer ${bearerToken}`
},
withCredentials: true
})

if (role === ROLE.PRODUCER) {
setDevices(response.data.production)
setIsLoading(false)
} else if (role === ROLE.CONSUMER) {
setDevices(response.data.consumption)
setIsLoading(false)
if (response.status === 200 || response.status === 204) {
fetchPairedData()
setIsModalOpen(false)
}

fetchPairedData()
setIsModalOpen(false)
} catch (error) {
console.error('Error adding device:', error.message)
} finally {
Expand All @@ -82,31 +79,20 @@ export default function DeviceList({ initialDevices, onDeviceChange, fetchPaired
}

const handleRemoveDevice = async (index: number) => {
setIsDeleteLoading(true)
const deviceToRemove = devices[index]

try {
const response = await axios.delete(`${strapiUrl}${ROUTE_TYPE[role!]}/der`, {
params: { id: deviceToRemove.id },
const response = await axios.delete(`${strapiUrl}${ROUTE_TYPE[role!]}/der/${index}`, {
headers: { Authorization: `Bearer ${bearerToken}` },
withCredentials: true
})

if (response.status === 200 || response.status === 204) {
if (role === ROLE.PRODUCER) {
setDevices(response.data.production)
setIsDeleteLoading(false)
} else if (role === ROLE.CONSUMER) {
setDevices(response.data.consumption)
setIsDeleteLoading(false)
}
fetchPairedData()
} else {
console.error('Failed to delete the device:', response.data)
}
} catch (error) {
console.error('Error deleting device:', error.message)
} catch (error: any) {
console.error('Error deleting device:', error?.message)
} finally {
// setIsDeleteLoading(false)
handleDeleteModalClose()
}
}
Expand All @@ -119,8 +105,9 @@ export default function DeviceList({ initialDevices, onDeviceChange, fetchPaired
}

useEffect(() => {
onDeviceChange(devices)
}, [devices, onDeviceChange])
setDevices(initialDevices)
onDeviceChange(initialDevices)
}, [initialDevices, onDeviceChange])

return (
<Container>
Expand Down Expand Up @@ -168,9 +155,9 @@ export default function DeviceList({ initialDevices, onDeviceChange, fetchPaired
_hover={{ bg: 'gray.50' }}
boxShadow="rgba(0, 0, 0, 0.35) 0px 5px 15px"
>
<Typography text={device.name} />
<Typography text={device?.name} />
<CiCircleMinus
onClick={() => handleDeleteModalOpen(index)}
onClick={() => handleDeleteModalOpen(device?.id)}
style={{ cursor: 'pointer' }}
size={24}
opacity="0.5"
Expand Down
2 changes: 1 addition & 1 deletion apps/open-spark/components/header/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ type PathnameObjectType = Record<string, string>

// -------------------------------- Top Header constants --------------------------------
const appLogoBlackList = ['/signIn', '/signUp', '/welcome']
const homeIconBlackList = ['/', '/signIn', '/', '/myRides', '/profile', '/signUp', '/welcome', '/myDers']
const homeIconBlackList = ['/', '/signIn', '/', '/myRides', '/profile', '/signUp', '/welcome']
const menuIconWhiteList = ['/', '/profile', '/myRides', '/buyingPreference', '/sellingPreference', '/myDers']
const topHeaderBlackList: string[] = ['/welcome']
const languageIconWhiteList: string[] = []
Expand Down
6 changes: 3 additions & 3 deletions apps/open-spark/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ const Homepage = () => {
<Box>
<Typography
text="Preferences"
fontSize="15"
fontSize="14px"
fontWeight="600"
sx={{ marginBottom: '10px' }}
/>
Expand All @@ -179,7 +179,7 @@ const Homepage = () => {
borderRadius="md"
variant="outline"
colorScheme="gray"
padding={'8px'}
padding={'4px 8px'}
>
<TagLabel>{tag}</TagLabel>
<TagCloseButton onClick={() => handleRemoveTag(tag)} />
Expand All @@ -197,7 +197,7 @@ const Homepage = () => {
>
<Typography
text="Current Status"
fontSize="15px"
fontSize="14px"
fontWeight="600"
/>
<Typography
Expand Down
29 changes: 11 additions & 18 deletions apps/open-spark/pages/myDers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,11 @@ const MyDers = () => {
const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_URL
const { role } = useSelector((state: RootState) => state.auth)
const bearerToken = Cookies.get('authToken')
const [devices, setDevices] = useState([
{ name: 'Wifi', paired: true },
{ name: 'Orient electric Fan', paired: true },
{ name: 'Sony TV', paired: true },
{ name: 'OLA S1 Air Electric Scooter', paired: true },
{ name: 'Philips LED Light', paired: true },
{ name: 'Solar Panel', paired: true }
])
const [devices, setDevices] = useState<{ id: number; name: string; paired?: boolean }[]>([])

const handleDeviceChange = (updatedDevices: React.SetStateAction<{ name: string; paired: boolean }[]>) => {
const handleDeviceChange = (
updatedDevices: React.SetStateAction<{ id: number; name: string; paired?: boolean }[]>
) => {
setDevices(updatedDevices)
}

Expand All @@ -31,14 +26,13 @@ const MyDers = () => {
withCredentials: true
})

const result = response.data.data
console.log(result)

if (role === ROLE.PRODUCER) {
setDevices(result.production)
} else if (role === ROLE.CONSUMER) {
setDevices(result.consumption)
}
const result = response.data
const mappedDevices = result.map((item: { category: string; id: number }) => ({
name: item.category,
paired: true,
id: item.id
}))
setDevices(mappedDevices)
} catch (error) {
console.error('Error fetching dashboard data:', error)
}
Expand All @@ -49,7 +43,6 @@ const MyDers = () => {
fetchPairedData()
}
}, [role, bearerToken, strapiUrl])

return (
<Box
maxWidth={{ base: '100vw', md: '30rem', lg: '40rem' }}
Expand Down
3 changes: 3 additions & 0 deletions apps/open-spark/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,6 @@ select:-webkit-autofill:focus {
.trade-status-accordion-icon {
display: none !important;
}
.css-1juf683 {
font-size: 12px !important;
}
15 changes: 12 additions & 3 deletions packages/common/src/components/BottomModal/BottomModalScan.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,20 @@ interface ModalProps {
children: React.ReactNode
partialClose?: boolean
modalHeader?: string
isLoading?: boolean
}

const BottomModal: React.FC<ModalProps> = ({ isOpen, onClose, children, modalHeader }) => {
const BottomModal: React.FC<ModalProps> = ({ isOpen, onClose, children, modalHeader, isLoading }) => {
return (
<>
<Modal
isCentered
onClose={onClose}
isOpen={isOpen}
onClose={() => {
if (!isLoading) {
onClose()
}
}}
scrollBehavior="outside"
motionPreset="slideInBottom"
>
Expand All @@ -41,7 +46,11 @@ const BottomModal: React.FC<ModalProps> = ({ isOpen, onClose, children, modalHea
>
{modalHeader}
</ModalHeader>
<Box onClick={onClose}>
<Box
onClick={!isLoading ? onClose : undefined}
cursor={isLoading ? 'not-allowed' : 'pointer'}
opacity={isLoading ? 0.5 : 1}
>
<Image src="/images/crossIcon.svg" />
</Box>
</Flex>
Expand Down

0 comments on commit 07e3212

Please sign in to comment.