From 0a43d943fa05a634711b6ee6b6d1d2f443b4ce1e Mon Sep 17 00:00:00 2001 From: aniketceminds Date: Thu, 12 Dec 2024 13:08:17 +0530 Subject: [PATCH] feat(open-spark): modified code to impl admin bap flow --- apps/open-spark/components/signIn/SignIn.tsx | 20 +- apps/open-spark/lib/config.ts | 2 + apps/open-spark/locales/en.ts | 3 +- apps/open-spark/pages/adminDashboard.tsx | 294 +++++++++++++++ apps/open-spark/pages/dashboard.tsx | 355 ++++++++++++++++++ apps/open-spark/pages/index.tsx | 352 +---------------- apps/open-spark/pages/profile.tsx | 117 +++--- apps/open-spark/pages/tradeDetails.tsx | 110 +++--- packages/common/lib/types/auth.ts | 5 + .../src/components/subHeader/subHeader.tsx | 13 +- 10 files changed, 817 insertions(+), 454 deletions(-) create mode 100644 apps/open-spark/pages/adminDashboard.tsx create mode 100644 apps/open-spark/pages/dashboard.tsx diff --git a/apps/open-spark/components/signIn/SignIn.tsx b/apps/open-spark/components/signIn/SignIn.tsx index a541bae4..8a44d472 100644 --- a/apps/open-spark/components/signIn/SignIn.tsx +++ b/apps/open-spark/components/signIn/SignIn.tsx @@ -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) } diff --git a/apps/open-spark/lib/config.ts b/apps/open-spark/lib/config.ts index 92f62758..03c96ddb 100644 --- a/apps/open-spark/lib/config.ts +++ b/apps/open-spark/lib/config.ts @@ -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' } diff --git a/apps/open-spark/locales/en.ts b/apps/open-spark/locales/en.ts index bca40d7c..7fcbbc95 100644 --- a/apps/open-spark/locales/en.ts +++ b/apps/open-spark/locales/en.ts @@ -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 diff --git a/apps/open-spark/pages/adminDashboard.tsx b/apps/open-spark/pages/adminDashboard.tsx new file mode 100644 index 00000000..78b928dc --- /dev/null +++ b/apps/open-spark/pages/adminDashboard.tsx @@ -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([]) + const [isLoading, setIsLoading] = useState(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 ( + <> + t[key]} + profileSection={{ + src: profileIcon, + handleClick: () => router.push('/profile') + }} + /> + + + + + + + + + + + + + + + + + {items.length > 0 ? ( + items.map((item, index) => ( + { + router.push({ pathname: '/tradeDetails', query: { id: item.id, pagename: item.name } }) + }} + > + + + + + + )) + ) : ( + + + + )} + +
+ + Unit + + + + Consumer + + + + Date + + + +
+ + + + + + + nav_icon +
+ +
+
+
+ +
+
+ + ) +} + +export default LockDemand diff --git a/apps/open-spark/pages/dashboard.tsx b/apps/open-spark/pages/dashboard.tsx new file mode 100644 index 00000000..6236ba47 --- /dev/null +++ b/apps/open-spark/pages/dashboard.tsx @@ -0,0 +1,355 @@ +'use client' + +import React, { useEffect, useState } from 'react' +import { formatDate, TopSheet, useGeolocation } from '@beckn-ui/common' +import { useLanguage } from '@hooks/useLanguage' +import { useRouter } from 'next/router' +import profileIcon from '@public/images/user_profile.svg' +import { Input, Typography } from '@beckn-ui/molecules' +import { Box, Flex, HStack, Tag, TagLabel, Divider, Text, TagCloseButton } from '@chakra-ui/react' +import CustomeDateInput from '@components/dateRangePicker/CustomeDateInput' +import SelectDate from '@components/dateRangePicker/SelectDate' +import TotalEnergyUnits from '@components/totalEnerguUnit/TotalEnergyUnits' +import { QuestionOutlineIcon } from '@chakra-ui/icons' +import { LiaPenSolid } from 'react-icons/lia' +import EmptyCurrentTrade from '@components/currentTrade/EmptyCurrentTrade' +import CurrentTrade from '@components/currentTrade/CurrentTrade' +import { DetailCard, OrderStatusProgress } from '@beckn-ui/becknified-components' +import BecknButton from '@beckn-ui/molecules/src/components/button/Button' +import { format } from 'date-fns' +import { RootState } from '@store/index' +import { useSelector } from 'react-redux' +import { ROLE, ROUTE_TYPE } from '@lib/config' +import { useBapTradeDashboardQuery, useBppTradeDashboardQuery } from '@services/DashboardService' +import Cookies from 'js-cookie' +import axios from 'axios' +import { DashboardData, StatusItem, TradeData } from '@lib/types/dashboard' +import { parseAndFormatDate } from '@utils/parsedFormatDate-utils' + +const Dashboard = () => { + const { t } = useLanguage() + const router = useRouter() + const apiKeyForGoogle = process.env.NEXT_PUBLIC_GOOGLE_API_KEY + const today = format(new Date(), 'dd/MM/yy') + const { role } = useSelector((state: RootState) => state.auth) + const { + currentAddress, + error: currentLocationFetchError, + loading: loadingForCurrentAddress + } = useGeolocation(apiKeyForGoogle as string) + const [isModalOpen, setIsModalOpen] = useState(false) + const [startDate, setStartDate] = useState(today) + const [endDate, setEndDate] = useState(today) + const [totalEnergyUnits, setTotalEnergyUnits] = useState(0) + const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_URL + const bearerToken = Cookies.get('authToken') || '' + const [currentTradeData, setCurrentTradeData] = useState([]) + const [currentStatusData, setCurrentStatusData] = useState([]) + const [dashboardTotalEnergyUnitsData, setDashboardTotalEnergyUnitsData] = useState({ + previous_month: 0, + current_month: 0, + average: 0 + }) + const [preferencesTags, setPreferencesTags] = useState([]) + const totalEnergyText = role === ROLE.PRODUCER ? 'Produced' : 'Consumption' + + const payloadStartDate = parseAndFormatDate(startDate) + const payloadEndDate = parseAndFormatDate(endDate) + + const { data: bapDashboardData } = useBapTradeDashboardQuery( + { + startDate: payloadStartDate, + endDate: payloadEndDate, + credentials: bearerToken + }, + { + skip: role !== ROLE.CONSUMER + } + ) + + const { data: bppDashboardData } = useBppTradeDashboardQuery( + { + startDate: payloadStartDate, + endDate: payloadEndDate, + credentials: bearerToken + }, + { + skip: role !== ROLE.PRODUCER + } + ) + + // const handleRemoveTag = (tagToRemove: string) => { + // setPreferencesTags(prevTags => prevTags.filter(tag => tag !== tagToRemove)) + // } + + const handleModalOpen = () => setIsModalOpen(true) + const handleModalClose = () => setIsModalOpen(false) + + const handleDateChange = (start: string, end: string) => { + setStartDate(start) + setEndDate(end) + handleModalClose() + } + useEffect(() => { + if (role === ROLE.CONSUMER && bapDashboardData?.data?.consumption) { + const { previous_month, current_month, average, totalInRange } = bapDashboardData.data.consumption + setDashboardTotalEnergyUnitsData({ previous_month, current_month, average }) + setTotalEnergyUnits(totalInRange) + } else if (role === ROLE.PRODUCER && bppDashboardData?.data?.production) { + const { previous_month, current_month, average, totalInRange } = bppDashboardData.data.production + setDashboardTotalEnergyUnitsData({ previous_month, current_month, average }) + setTotalEnergyUnits(totalInRange) + } + }, [role, bapDashboardData, bppDashboardData, startDate, endDate]) + + const fetchLastTradeData = async () => { + try { + const response = await axios.get(`${strapiUrl}${ROUTE_TYPE[role!]}/trade`, { + headers: { Authorization: `Bearer ${bearerToken}` }, + withCredentials: true + }) + + const result = response.data + + const lastTrade = result[result.length - 1] + + const mappedTrade: TradeData = { + id: lastTrade.id, + quantity: lastTrade.quantity, + price: lastTrade.price || 0 + } + + setCurrentTradeData([mappedTrade]) + const statusData = createStatusData(lastTrade) + setCurrentStatusData(statusData) + + const tags = [lastTrade.trusted_source && 'Trusted Source', lastTrade.cred_required && 'Solar Energy'].filter( + Boolean + ) + setPreferencesTags(tags) + } catch (error) { + console.error('Error fetching last trade data:', error) + } + } + useEffect(() => { + fetchLastTradeData() + }, []) + + const StatusLabel = () => { + return ( + + For more details go to{' '} + router.push('/myTrades')} + > + My Trades + + + ) + } + + const createStatusData = (tradeData: { status: string; createdAt: string }) => { + const { status, createdAt } = tradeData + const statusTime = formatDate(createdAt, 'hh:mm a') + const label = status === 'RECEIVED' ? 'Requirement Received' : 'Requirement Completed' + + return [ + { + label, + status, + statusTime, + noLine: false, + lastElement: false + }, + { + label: , + statusTime: '', + noLine: true, + lastElement: true + } + ] + } + + const latestStatus = currentStatusData.find(item => typeof item.status === 'string' && item.status !== '') + return ( + <> + t[key]} + profileSection={{ + src: profileIcon, + handleClick: () => router.push('/profile') + }} + /> + + + + { + console.log('Energy units changed') + }} + label={'Energy Units'} + disabled={true} + /> + + + + + + + + + + + + {currentTradeData.length < 0 ? ( + <> + ) : ( + router.push(role === ROLE.PRODUCER ? '/sellingPreference' : '/buyingPreference')} + /> + )} + + {currentTradeData.length < 0 ? ( + + ) : ( + + )} + + + + + {preferencesTags.map((tag, index) => ( + + {tag} + {/* handleRemoveTag(tag)} /> */} + + ))} + + + {role !== ROLE.PRODUCER && ( + + + + + + + + + {currentStatusData.length > 0 ? ( + currentStatusData.map((data, index) => ( + + )) + ) : ( + No status updates available + )} + + + + )} + + router.push(role === ROLE.PRODUCER ? '/sellingPreference' : '/buyingPreference')} + sx={{ marginTop: '30px' }} + /> + + + + ) +} + +export default Dashboard diff --git a/apps/open-spark/pages/index.tsx b/apps/open-spark/pages/index.tsx index 29afd277..174c4aba 100644 --- a/apps/open-spark/pages/index.tsx +++ b/apps/open-spark/pages/index.tsx @@ -1,358 +1,16 @@ 'use client' -import React, { useEffect, useState } from 'react' -import { formatDate, TopSheet, useGeolocation } from '@beckn-ui/common' -import { useLanguage } from '@hooks/useLanguage' -import { useRouter } from 'next/router' -import profileIcon from '@public/images/user_profile.svg' -import { Input, Typography } from '@beckn-ui/molecules' -import { Box, Flex, HStack, Tag, TagLabel, Divider, Text, TagCloseButton } from '@chakra-ui/react' -import CustomeDateInput from '@components/dateRangePicker/CustomeDateInput' -import SelectDate from '@components/dateRangePicker/SelectDate' -import TotalEnergyUnits from '@components/totalEnerguUnit/TotalEnergyUnits' -import { QuestionOutlineIcon } from '@chakra-ui/icons' -import { LiaPenSolid } from 'react-icons/lia' -import EmptyCurrentTrade from '@components/currentTrade/EmptyCurrentTrade' -import CurrentTrade from '@components/currentTrade/CurrentTrade' -import { DetailCard, OrderStatusProgress } from '@beckn-ui/becknified-components' -import BecknButton from '@beckn-ui/molecules/src/components/button/Button' -import { format } from 'date-fns' +import { ROLE } from '@lib/config' import { RootState } from '@store/index' +import React from 'react' import { useSelector } from 'react-redux' -import { ROLE, ROUTE_TYPE } from '@lib/config' -import { useBapTradeDashboardQuery, useBppTradeDashboardQuery } from '@services/DashboardService' -import Cookies from 'js-cookie' -import axios from 'axios' -import { DashboardData, StatusItem, TradeData } from '@lib/types/dashboard' -import { parseAndFormatDate } from '@utils/parsedFormatDate-utils' +import Dashboard from './dashboard' +import AdminDashbaord from './adminDashboard' const Homepage = () => { - const { t } = useLanguage() - const router = useRouter() - const apiKeyForGoogle = process.env.NEXT_PUBLIC_GOOGLE_API_KEY - const today = format(new Date(), 'dd/MM/yy') const { role } = useSelector((state: RootState) => state.auth) - const { - currentAddress, - error: currentLocationFetchError, - loading: loadingForCurrentAddress - } = useGeolocation(apiKeyForGoogle as string) - const [isModalOpen, setIsModalOpen] = useState(false) - const [startDate, setStartDate] = useState(today) - const [endDate, setEndDate] = useState(today) - const [totalEnergyUnits, setTotalEnergyUnits] = useState(0) - const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_URL - const bearerToken = Cookies.get('authToken') || '' - const [currentTradeData, setCurrentTradeData] = useState([]) - const [currentStatusData, setCurrentStatusData] = useState([]) - const [dashboardTotalEnergyUnitsData, setDashboardTotalEnergyUnitsData] = useState({ - previous_month: 0, - current_month: 0, - average: 0 - }) - const [preferencesTags, setPreferencesTags] = useState([]) - const totalEnergyText = role === ROLE.PRODUCER ? 'Produced' : 'Consumption' - const currentAndPreffernceTest = role === ROLE.PRODUCER ? 'My Preferences' : 'Current Trade' - const payloadStartDate = parseAndFormatDate(startDate) - const payloadEndDate = parseAndFormatDate(endDate) - - const { data: bapDashboardData } = useBapTradeDashboardQuery( - { - startDate: payloadStartDate, - endDate: payloadEndDate, - credentials: bearerToken - }, - { - skip: role !== ROLE.CONSUMER - } - ) - - const { data: bppDashboardData } = useBppTradeDashboardQuery( - { - startDate: payloadStartDate, - endDate: payloadEndDate, - credentials: bearerToken - }, - { - skip: role !== ROLE.PRODUCER - } - ) - - // const handleRemoveTag = (tagToRemove: string) => { - // setPreferencesTags(prevTags => prevTags.filter(tag => tag !== tagToRemove)) - // } - - const handleModalOpen = () => setIsModalOpen(true) - const handleModalClose = () => setIsModalOpen(false) - - const handleDateChange = (start: string, end: string) => { - setStartDate(start) - setEndDate(end) - handleModalClose() - } - useEffect(() => { - if (role === ROLE.CONSUMER && bapDashboardData?.data?.consumption) { - const { previous_month, current_month, average, totalInRange } = bapDashboardData.data.consumption - setDashboardTotalEnergyUnitsData({ previous_month, current_month, average }) - setTotalEnergyUnits(totalInRange) - } else if (role === ROLE.PRODUCER && bppDashboardData?.data?.production) { - const { previous_month, current_month, average, totalInRange } = bppDashboardData.data.production - setDashboardTotalEnergyUnitsData({ previous_month, current_month, average }) - setTotalEnergyUnits(totalInRange) - } - }, [role, bapDashboardData, bppDashboardData, startDate, endDate]) - - const fetchLastTradeData = async () => { - try { - const response = await axios.get(`${strapiUrl}${ROUTE_TYPE[role!]}/trade`, { - headers: { Authorization: `Bearer ${bearerToken}` }, - withCredentials: true - }) - - const result = response.data - - const lastTrade = result[result.length - 1] - - const mappedTrade: TradeData = { - id: lastTrade.id, - quantity: lastTrade.quantity, - price: lastTrade.price || 0 - } - - setCurrentTradeData([mappedTrade]) - const statusData = createStatusData(lastTrade) - setCurrentStatusData(statusData) - - const tags = [lastTrade.trusted_source && 'Trusted Source', lastTrade.cred_required && 'Solar Energy'].filter( - Boolean - ) - setPreferencesTags(tags) - } catch (error) { - console.error('Error fetching last trade data:', error) - } - } - useEffect(() => { - fetchLastTradeData() - }, []) - - const StatusLabel = () => { - return ( - - For more details go to{' '} - router.push('/myTrades')} - > - My Trades - - - ) - } - - const createStatusData = (tradeData: { status: string; createdAt: string }) => { - const { status, createdAt } = tradeData - const statusTime = formatDate(createdAt, 'hh:mm a') - const label = status === 'RECEIVED' ? 'Requirement Received' : 'Requirement Completed' - - return [ - { - label, - status, - statusTime, - noLine: false, - lastElement: false - }, - { - label: , - statusTime: '', - noLine: true, - lastElement: true - } - ] - } - - const latestStatus = currentStatusData.find(item => typeof item.status === 'string' && item.status !== '') - return ( - <> - t[key]} - profileSection={{ - src: profileIcon, - handleClick: () => router.push('/profile') - }} - /> - - - - { - console.log('Energy units changed') - }} - label={'Energy Units'} - disabled={true} - /> - - - - - - - - - - - - {currentTradeData.length < 0 ? ( - <> - ) : ( - router.push(role === ROLE.PRODUCER ? '/sellingPreference' : '/buyingPreference')} - /> - )} - - {currentTradeData.length < 0 ? ( - - ) : ( - - )} - - - - - {preferencesTags.map((tag, index) => ( - - {tag} - {/* handleRemoveTag(tag)} /> */} - - ))} - - - {role !== ROLE.PRODUCER && ( - - - - - {currentStatusData.length < 0 ? ( - - ) : null} - - - - {currentStatusData.length > 0 ? ( - currentStatusData.map((data, index) => ( - - )) - ) : ( - No status updates available - )} - - - - )} - - router.push(role === ROLE.PRODUCER ? '/sellingPreference' : '/buyingPreference')} - sx={{ marginTop: '100px' }} - /> - - - - ) + return <>{role === ROLE.ADMIN ? : } } export default Homepage diff --git a/apps/open-spark/pages/profile.tsx b/apps/open-spark/pages/profile.tsx index 4c494708..51232e99 100644 --- a/apps/open-spark/pages/profile.tsx +++ b/apps/open-spark/pages/profile.tsx @@ -4,7 +4,6 @@ import { useLanguage } from '@hooks/useLanguage' import { profileValidateForm } from '@beckn-ui/common/src/utils' import Cookies from 'js-cookie' import React, { useEffect, useMemo, useRef, useState } from 'react' -import { isEmpty } from '@beckn-ui/common/src/utils' import { useDispatch, useSelector } from 'react-redux' import { FormErrors, ProfileProps } from '@beckn-ui/common/lib/types' import axios from '@services/axios' @@ -16,9 +15,10 @@ import logoutIcon from '@public/images/logOutIcon.svg' import NavigationItem from '@components/navigationItem' import { setProfileEditable, UserRootState } from '@store/user-slice' import { feedbackActions, logout } from '@beckn-ui/common' -import { ROUTE_TYPE } from '@lib/config' +import { ROLE, ROUTE_TYPE } from '@lib/config' import { AuthRootState } from '@store/auth-slice' import { useRouter } from 'next/router' +import { InputProps } from '@beckn-ui/molecules' const ProfilePage = () => { const dispatch = useDispatch() @@ -41,6 +41,8 @@ const ProfilePage = () => { const { profileEditable } = useSelector((state: UserRootState) => state.user) const { role } = useSelector((state: AuthRootState) => state.auth) + const isAdmin = useRef(role === ROLE.ADMIN) + useEffect(() => { return () => { dispatch(setProfileEditable({ profileEditable: false })) @@ -142,6 +144,48 @@ const ProfilePage = () => { ) }, [formData, formErrors]) + const getInputs = () => { + const inputs: InputProps[] = [ + { + type: 'text', + name: 'name', + value: formData.name, + handleChange: handleInputChange, + label: t.fullName, + error: formErrors.name, + dataTest: testIds.profile_inputName, + disabled: !profileEditable, + customInputBlurHandler: updateProfile + }, + { + type: 'text', + name: 'customerId', + value: formData.customerId!, + handleChange: handleInputChange, + label: t.formCustomerId, + error: formErrors.customerId, + dataTest: testIds.profile_customerId, + disabled: true + }, + { + type: 'text', + name: 'address', + value: formData.address!, + handleChange: handleInputChange, + label: t.formAddress, + error: formErrors.address, + dataTest: testIds.profile_address, + disabled: !profileEditable, + customInputBlurHandler: updateProfile + } + ] + if (isAdmin.current) { + inputs.splice(1, 1) + } + + return inputs + } + return ( { dataTestForm={testIds.profile_form} schema={{ buttons: [], - inputs: [ - { - type: 'text', - name: 'name', - value: formData.name, - handleChange: handleInputChange, - label: t.fullName, - error: formErrors.name, - dataTest: testIds.profile_inputName, - disabled: !profileEditable, - customInputBlurHandler: updateProfile - }, - { - type: 'text', - name: 'customerId', - value: formData.customerId!, - handleChange: handleInputChange, - label: t.formCustomerId, - error: formErrors.customerId, - dataTest: testIds.profile_customerId, - disabled: true - }, - { - type: 'text', - name: 'address', - value: formData.address!, - handleChange: handleInputChange, - label: t.formAddress, - error: formErrors.address, - dataTest: testIds.profile_address, - disabled: !profileEditable, - customInputBlurHandler: updateProfile - } - ] + inputs: getInputs() }} isLoading={isLoading} customComponent={ - router.push('/myCredentials')} - /> - router.push('/myTrades')} - /> - router.push('/myDers')} - /> + {!isAdmin.current && ( + <> + router.push('/myCredentials')} + /> + router.push('/myTrades')} + /> + router.push('/myDers')} + /> + + )} { .get(`${strapiUrl}${ROUTE_TYPE[role!]}/trade?id=${id}`, requestOptions) .then(response => { const result = response.data - console.log(result) + const tags: string[] = [] + if (result.trusted_source) { + tags.push('Trusted Source') + } + if (result.cred_required) { + tags.push('Solar Energy') + } setTradeDetails({ - orderId: result.id, + orderId: result.orderId, name: result.item_name, price: result.price || 0, quantity: result.quantity, @@ -55,7 +61,7 @@ const TradeDetails = () => { status: result.status, tradeId: result.id, tradeEvents: result.trade_events, - preferencesTags: ['Solar', 'Biomass', 'Wind Power'] + preferencesTags: tags }) }) .catch(error => { @@ -104,56 +110,62 @@ const TradeDetails = () => { } ]} /> - - - - {tradeDetails?.preferencesTags?.map((tag, index) => ( - - {tag} - - ))} - - - - - + {tradeDetails?.preferencesTags && tradeDetails?.preferencesTags?.length > 0 && ( + - - - - - + + {tradeDetails?.preferencesTags?.map((tag, index) => ( + + {tag} + + ))} + + + )} + + {tradeDetails?.orderId && ( + + + + + )} + {tradeDetails?.tradeId && ( + + + + + )} diff --git a/packages/common/lib/types/auth.ts b/packages/common/lib/types/auth.ts index 74ffc90d..51152901 100644 --- a/packages/common/lib/types/auth.ts +++ b/packages/common/lib/types/auth.ts @@ -13,6 +13,11 @@ export interface User { first_name: string last_name: string } + role?: { + id: number + name: string + type: string + } } // Sign-In related models diff --git a/packages/common/src/components/subHeader/subHeader.tsx b/packages/common/src/components/subHeader/subHeader.tsx index ef3b4f45..ebf89ec1 100644 --- a/packages/common/src/components/subHeader/subHeader.tsx +++ b/packages/common/src/components/subHeader/subHeader.tsx @@ -17,7 +17,8 @@ const getHeaderTitleForPage = ( name: string, pathName: string, locale: string | undefined, - headerConstants: SubHeaderConstants + headerConstants: SubHeaderConstants, + customPagename?: string ) => { const { headerNames: { defaultNames, frenchNames }, @@ -31,7 +32,7 @@ const getHeaderTitleForPage = ( className={Styles.header_title_text} data-test={testIds.pageName} > - {values[pathName]} + {customPagename || values[pathName]} ) default: @@ -92,7 +93,13 @@ const SubHeader = (props: SubHeaderProps) => { )} - {getHeaderTitleForPage(storedHeaderText, router.pathname, locale, headerConstants)} + {getHeaderTitleForPage( + storedHeaderText, + router.pathname, + locale, + headerConstants, + (router.query?.pagename || '') as string + )} {showCartIcon && (
{!cartIconList?.includes(router.pathname) && (