Skip to content

Commit

Permalink
Feature/optimize api calls hydra datum button (#524)
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgenavben authored Nov 23, 2023
1 parent 9ea3d1d commit 2602abb
Show file tree
Hide file tree
Showing 8 changed files with 625 additions and 325 deletions.
55 changes: 28 additions & 27 deletions ui/summit-2023/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import SUMMIT2023CONTENT from 'common/resources/data/summit2023Content.json';
import { resolveCardanoNetwork } from './utils/utils';
import { parseError } from 'common/constants/errors';
import { getUserVotes } from 'common/api/voteService';
import { getCategoryLevelStats } from 'common/api/leaderboardService';
import { getVotingResults } from 'common/api/leaderboardService';
import { ProposalContent } from 'pages/Nominees/Nominees.type';
import { setWinners } from 'store/userSlice';
import './App.scss';
Expand All @@ -44,47 +44,48 @@ function App() {

const { isConnected, stakeAddress } = useCardano({ limitNetwork: resolveCardanoNetwork(env.TARGET_NETWORK) });

async function loadWinners(filteredCategory) {
async function loadWinners(votingResults, filteredCategory) {
const filteredCategoryProposals: ProposalContent[] = filteredCategory?.proposals;
try {
await getCategoryLevelStats(filteredCategory?.id).then((response) => {
const updatedAwards = filteredCategoryProposals.map((proposal) => {
const id = proposal.id;
const votes = response?.proposals[id] ? response?.proposals[id].votes : 0;
const rank = 0;
return { ...proposal, votes, rank };
});

updatedAwards.sort((a, b) => b.votes - a.votes);
const categoryResults = votingResults?.find((category) => category.category === filteredCategory.id);

updatedAwards.forEach((item, index, array) => {
if (index > 0 && item.votes === array[index - 1].votes) {
item.rank = array[index - 1].rank;
} else {
item.rank = index + 1;
}
});
const updatedAwards = filteredCategoryProposals.map((proposal) => {
const id = proposal.id;
const votes = categoryResults?.proposals[id] ? categoryResults?.proposals[id].votes : 0;
const rank = 0;
return { ...proposal, votes, rank };
});

const categoryWinners = updatedAwards
.filter((winner) => (winner.rank === 1 && winner.votes > 0))
.map((winner) => {
return { categoryId: filteredCategory.id, proposalId: winner.id };
});
updatedAwards.sort((a, b) => b.votes - a.votes);

dispatch(setWinners({ winners: categoryWinners }));
updatedAwards.forEach((item, index, array) => {
if (index > 0 && item.votes === array[index - 1].votes) {
item.rank = array[index - 1].rank;
} else {
item.rank = index + 1;
}
});

const categoryWinners = updatedAwards
.filter((winner) => (winner.rank === 1 && winner.votes > 0))
.map((winner) => {
return { categoryId: filteredCategory.id, proposalId: winner.id };
});

dispatch(setWinners({ winners: categoryWinners }));
} catch (error) {
const message = `Failed to fecth Nominee stats: ${error?.message || error?.toString()}`;
const message = `Failed to fetch Nominee stats: ${error?.message || error?.toString()}`;
if (process.env.NODE_ENV === 'development') {
console.log(message);
}
eventBus.publish('showToast', i18n.t('toast.failedToFecthNomineeStats'), 'error');
eventBus.publish('showToast', i18n.t('toast.failedToFetchNomineeStats'), 'error');
}
}

const fetchEvent = useCallback(async () => {
try {
const event = await getEvent(env.EVENT_ID);
const votingResults = await getVotingResults();

const staticCategories: CategoryContent[] = SUMMIT2023CONTENT.categories;

Expand All @@ -93,7 +94,7 @@ function App() {
const joinedCategory = staticCategories.find((staticCategory) => staticCategory.id === category.id);
if (joinedCategory) {
if ('proposalsReveal' in event && event.proposalsReveal) {
loadWinners(joinedCategory);
loadWinners(votingResults, joinedCategory);
}
return { ...category, ...joinedCategory };
}
Expand Down
12 changes: 7 additions & 5 deletions ui/summit-2023/src/common/api/leaderboardService.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import { ByEventStats, ByProposalsInCategoryStats } from 'types/voting-app-types';
import { DEFAULT_CONTENT_TYPE_HEADERS, doRequest, HttpMethods } from '../handlers/httpHandler';
import { env } from '../constants/env';
import { TallyResults } from 'types/voting-ledger-follower-types';

const LEADERBOARD_URL = `${env.VOTING_APP_SERVER_URL}/api/leaderboard`;
const HYDRATALLY_URL = `${env.VOTING_LEDGER_FOLLOWER_APP_SERVER_URL}/api/tally/voting-results`;

const getStats = async () =>
await doRequest<ByEventStats>(HttpMethods.GET, `${LEADERBOARD_URL}/${env.EVENT_ID}`, {
...DEFAULT_CONTENT_TYPE_HEADERS,
});

const getCategoryLevelStats = async (categoryId) =>
await doRequest<ByProposalsInCategoryStats>(HttpMethods.GET, `${LEADERBOARD_URL}/${env.EVENT_ID}/${categoryId}`, {
const getVotingResults = async () =>
await doRequest<ByProposalsInCategoryStats>(HttpMethods.GET, `${LEADERBOARD_URL}/${env.EVENT_ID}/results?source=db`, {
...DEFAULT_CONTENT_TYPE_HEADERS,
});

const getHydraTallyStats = async (categoryId) =>
await doRequest<ByProposalsInCategoryStats>(HttpMethods.GET, `${LEADERBOARD_URL}/${env.EVENT_ID}/${categoryId}?source=l1`, {
const getHydraTallyStats = async () =>
await doRequest<TallyResults>(HttpMethods.GET, `${HYDRATALLY_URL}/${env.EVENT_ID}/Hydra_Tally_Experiment`, {
...DEFAULT_CONTENT_TYPE_HEADERS,
});

export { getStats, getCategoryLevelStats, getHydraTallyStats };
export { getStats, getVotingResults, getHydraTallyStats };
8 changes: 5 additions & 3 deletions ui/summit-2023/src/i18n/locales/en/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@
"copyError": "Copied to clipboard failed",
"voteVerified": "Vote proof verified",
"voteNotVerified": "Vote proof not verified",
"failedToFecthStats": "Failed to fecth stats",
"failedToFecthNomineeStats": "Failed to fecth Nominee stats"
"failedToFetchStats": "Failed to fetch stats",
"failedToFetchNomineeStats": "Failed to fetch Nominee stats"
},
"leaderboard": {
"title": "Leaderboard",
Expand Down Expand Up @@ -183,7 +183,9 @@
"tableHeadings": {
"column1": "Winner",
"column2": "Votes"
}
},
"datumInspectorButton": "View Hydra Tally",
"copyAddressButtonTooltip": "Copy Smart Contract Address"
}
}
}
Expand Down
36 changes: 32 additions & 4 deletions ui/summit-2023/src/pages/Leaderboard/Leaderboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import cn from 'classnames';
import { i18n } from 'i18n';
import { makeStyles } from 'tss-react/mui';
import { PieChart } from 'react-minimal-pie-chart';
import { ByCategoryStats } from 'types/voting-app-types';
import { EventPresentation } from 'types/voting-ledger-follower-types';
import { ByCategoryStats, ByProposalsInCategoryStats } from 'types/voting-app-types';
import { EventPresentation, TallyResults } from 'types/voting-ledger-follower-types';
import * as leaderboardService from '../../common/api/leaderboardService';
import { categoryColorsMap, getPercentage } from './utils';
import { StatItem } from './types';
Expand Down Expand Up @@ -83,6 +83,8 @@ const Leaderboard = () => {
const classes = useStyles();
const summitEvent = useSelector((state: RootState) => state.user.event);
const [stats, setStats] = useState<ByCategoryStats[]>();
const [votingResults, setVotingResults] = useState<ByProposalsInCategoryStats>();
const [hydraTallyStats, setHydraTallyStats] = useState<TallyResults>();
const [value, setValue] = useState('2');
const [winnersAvailable, setWinnersAvailable] = useState(Boolean);
const [hydraTallyAvailable, setHydraTallyAvailable] = useState(Boolean);
Expand All @@ -95,11 +97,35 @@ const Leaderboard = () => {
setStats(response.categories);
});
} catch (error) {
const message = `Failed to fecth stats: ${error?.message || error?.toString()}`;
const message = `Failed to fetch stats: ${error?.message || error?.toString()}`;
if (process.env.NODE_ENV === 'development') {
console.log(message);
}
eventBus.publish('showToast', i18n.t('toast.failedToFecthStats'), 'error');
eventBus.publish('showToast', i18n.t('toast.failedToFetchStats'), 'error');
}

try {
await leaderboardService.getVotingResults().then((response) => {
setVotingResults(response);
});
} catch (error) {
const message = `Failed to fetch results stats: ${error?.message || error?.toString()}`;
if (process.env.NODE_ENV === 'development') {
console.log(message);
}
eventBus.publish('showToast', i18n.t('toast.failedToFetchStats'), 'error');
}

try {
await leaderboardService.getHydraTallyStats().then((response) => {
setHydraTallyStats(response);
});
} catch (error) {
const message = `Failed to fetch Hydra Tally stats: ${error?.message || error?.toString()}`;
if (process.env.NODE_ENV === 'development') {
console.log(message);
}
eventBus.publish('showToast', i18n.t('toast.failedToFetchStats'), 'error');
}
}, []);

Expand Down Expand Up @@ -263,6 +289,7 @@ const Leaderboard = () => {
title={item.label}
counter={index}
categoryId={item.id}
votingResults={votingResults}
/>
))}
</Masonry>
Expand Down Expand Up @@ -475,6 +502,7 @@ const Leaderboard = () => {
title={item.label}
counter={index}
categoryId={item.id}
hydraTallyStats={hydraTallyStats}
/>
))}
</Masonry>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,14 @@ import { Link } from 'react-router-dom';
import Card from '@mui/material/Card';
import { i18n } from 'i18n';
import CardContent from '@mui/material/CardContent';
import * as leaderboardService from '../../../../common/api/leaderboardService';
import { eventBus } from 'utils/EventBus';
import SUMMIT2023CONTENT from '../../../../common/resources/data/summit2023Content.json';
import { ProposalContent } from 'pages/Nominees/Nominees.type';
import { CategoryContent } from 'pages/Categories/Category.types';
import styles from './AwardsTile.module.scss';
import cn from 'classnames';
import CATEGORY_IMAGES from '../../../../common/resources/data/categoryImages.json';

const AwardsTile = ({ counter, title, categoryId }) => {
const AwardsTile = ({ counter, title, categoryId, votingResults }) => {
const summit2023Category: CategoryContent = SUMMIT2023CONTENT.categories.find(
(category) => category.id === categoryId
);
Expand All @@ -23,32 +21,32 @@ const AwardsTile = ({ counter, title, categoryId }) => {

const init = useCallback(async () => {
try {
await leaderboardService.getCategoryLevelStats(categoryId).then((response) => {
const updatedAwards = summit2023Proposals.map((proposal) => {
const id = proposal.id;
const votes = response?.proposals[id] ? response?.proposals[id].votes : 0;
const rank = 0;
return { ...proposal, votes, rank };
});
const categoryResults = votingResults?.find((category) => category.category === categoryId);

const updatedAwards = summit2023Proposals.map((proposal) => {
const id = proposal.id;
const votes = categoryResults?.proposals[id] ? categoryResults?.proposals[id].votes : 0;
const rank = 0;
return { ...proposal, votes, rank };
});

updatedAwards.sort((a, b) => b.votes - a.votes);
updatedAwards.sort((a, b) => b.votes - a.votes);

updatedAwards.forEach((item, index, array) => {
if (index > 0 && item.votes === array[index - 1].votes) {
item.rank = array[index - 1].rank;
} else {
item.rank = index + 1;
}
});
setAwards(updatedAwards);
updatedAwards.forEach((item, index, array) => {
if (index > 0 && item.votes === array[index - 1].votes) {
item.rank = array[index - 1].rank;
} else {
item.rank = index + 1;
}
});
setAwards(updatedAwards);
setLoaded(true);
} catch (error) {
const message = `Failed to fecth Nominee stats: ${error?.message || error?.toString()}`;
const message = `Failed to fetch Nominee stats: ${error?.message || error?.toString()}`;
if (process.env.NODE_ENV === 'development') {
console.log(message);
}
eventBus.publish('showToast', i18n.t('toast.failedToFecthNomineeStats'), 'error');
eventBus.publish('showToast', i18n.t('toast.failedToFetchNomineeStats'), 'error');
}
}, []);

Expand Down
Loading

0 comments on commit 2602abb

Please sign in to comment.