Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Development #363

Merged
merged 8 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/pages/reputation-score/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useAccount, useReadContract } from 'wagmi';

import { engagementContracts } from '@/lib/contracts/engagement/contracts';

import SimpleBackdrop from '@/components/global/LoadingBackdrop';
import SEO from '@/components/global/SEO';
import TcBoxContainer from '@/components/shared/TcBox/TcBoxContainer';

Expand All @@ -25,13 +26,17 @@ function ReputationScore() {
(contract) => contract.chainId === chainId
);

const { data: hasMinted } = useReadContract({
const { data: hasMinted, isLoading } = useReadContract({
address: engagementContract?.address as `0x${string}`,
abi: engagementContract?.abi as Abi,
functionName: 'balanceOf',
args: [address, dynamicNFTModuleInfo?.metadata[0]?.tokenId],
});

if(isConnected && isLoading) {
return <SimpleBackdrop />
}

return (
<>
<SEO titleTemplate='Reputation Score' />
Expand Down Expand Up @@ -86,7 +91,7 @@ function ReputationScore() {
color='primary'
onClick={() =>
router.push(
`/reputation-score/${dynamicNFTModuleInfo?.metadata[0]?.tokenId}/${address}/score`
`/reputation-score/score?tokenId=${dynamicNFTModuleInfo?.metadata[0]?.tokenId}&address=${address}`
)
}
disabled={!isConnected}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { FiShare2 } from 'react-icons/fi';

import GaugeChart from '@/components/global/GaugeChart';
Expand All @@ -15,50 +16,42 @@ import { withRoles } from '@/utils/withRoles';
const ScorePage = () => {
const { showMessage } = useSnackbar();
const { retrieveReputationScore } = useAppStore();
const router = useRouter();

const [communityName, setCommunityName] = useState<string | null>(null);
const [reputationScore, setReputationScore] = useState<number | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [tokenId, setTokenId] = useState<string | null>(null);
const [address, setAddress] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
const parseUrl = () => {
const pathSegments = router.asPath.split('/');
const tokenIndex = pathSegments.indexOf('reputation-score') + 1;

if (tokenIndex > 0 && tokenIndex + 1 < pathSegments.length) {
setTokenId(pathSegments[tokenIndex]);
setAddress(pathSegments[tokenIndex + 1]);
const fetchReputationScore = async (tokenId: string, address: string) => {
setLoading(true);
setError(null);

try {
const score = await retrieveReputationScore({ tokenId, address });

setReputationScore(score.reputationScore ?? 0);
setCommunityName(score.communityName);
} catch (err) {
console.error('Error fetching reputation score:', err);
setError('Failed to fetch reputation score.');
} finally {
setLoading(false);
}
};

parseUrl();
}, [router.asPath]);
const params = new URLSearchParams(window.location.search);
const tokenId = params.get('tokenId');
const address = params.get('address');

useEffect(() => {
if (tokenId && address) {
const fetchReputationScore = async () => {
setLoading(true);
try {
const score = await retrieveReputationScore({
tokenId,
address,
});

setReputationScore(score.reputationScore ?? 0);
setCommunityName(score.communityName);
} catch (error) {
console.error('Error fetching reputation score:', error);
} finally {
setLoading(false);
}
};

fetchReputationScore();
if (!tokenId || !address) {
setError('Invalid URL format. Missing tokenId or address.');
setLoading(false);
return;
}
}, [tokenId, address]);

fetchReputationScore(tokenId, address);
}, [retrieveReputationScore]);
mehdi-torabiv marked this conversation as resolved.
Show resolved Hide resolved

const gaugeOptions = {
chart: {
Expand Down Expand Up @@ -102,7 +95,7 @@ const ScorePage = () => {
series: [
{
name: 'Score',
data: [reputationScore ?? 0],
data: [reputationScore ? parseFloat(reputationScore.toFixed(1)) : 0],
tooltip: {
valueSuffix: ' /100',
},
Expand All @@ -126,6 +119,17 @@ const ScorePage = () => {
return <SimpleBackdrop />;
}

if (error) {
return (
<div className='flex min-h-screen items-center justify-center bg-gray-100'>
<div className='max-w-xl rounded-lg bg-white p-6 shadow-lg'>
<h1 className='text-2xl font-bold text-red-600'>Error</h1>
<p className='mt-4 text-gray-600'>{error}</p>
</div>
</div>
);
}

return (
<>
<SEO titleTemplate='Daily Report Reputation Score' />
Expand Down Expand Up @@ -173,4 +177,4 @@ const ScorePage = () => {
);
};

export default withRoles(ScorePage, []);
export default ScorePage;
11 changes: 10 additions & 1 deletion src/utils/withRoles.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use client';

import React, {
ComponentType,
FunctionComponent,
Expand All @@ -6,6 +8,8 @@ import React, {
} from 'react';
import { useRouter } from 'next/router';

import SimpleBackdrop from '@/components/global/LoadingBackdrop';

import useAppStore from '../store/useStore';

interface WithRolesProps {
Expand All @@ -21,7 +25,7 @@ interface ComponentWithLayout<P = {}> extends FunctionComponent<P> {

export function withRoles<P extends WithRolesProps>(
Component: ComponentWithLayout<P>,
requiredPermissions: string[]
requiredPermissions: string[] = []
): ComponentWithLayout<P> {
const WithRolesWrapper: ComponentWithLayout<P> = (props) => {
const userPermissions = useAppStore(
Expand All @@ -31,6 +35,11 @@ export function withRoles<P extends WithRolesProps>(
const router = useRouter();

useEffect(() => {
if (requiredPermissions.length === 0) {
setIsPermissionLoaded(true);
return;
}

const hasPermission = requiredPermissions.some((permission) =>
userPermissions.includes(permission)
);
Expand Down
Loading