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

Sort donation wishes #1545

Merged
merged 3 commits into from
Aug 10, 2023
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: 8 additions & 1 deletion public/locales/bg/campaigns.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,14 @@
"others": "други",
"profile": "Профил:",
"status": "Статус:",
"messages": "Послания:",
"messages": "Кампанията подкрепиха:",
"sort": {
"title" : "Сортирай по:",
"date" : "Дата",
"amount": "Дарение",
"search": "Търси...",
"noResults": "Не са открити резултати"
},
"gallery": "Галерия",
"report-irregularity": "Сигнализирай за злоупотреба",
"financial-report": "Финансови отчети",
Expand Down
7 changes: 7 additions & 0 deletions public/locales/en/campaigns.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@
"guarantor": "guarantor",
"others": "others",
"messages": "Messages:",
"sort": {
"title" : "Sort by:",
"date" : "Date",
"amount": "Amount",
"search": "Search...",
"noResults": "No messages found"
},
"profile": "Profile:",
"status": "Status:",
"gallery": "Gallery",
Expand Down
12 changes: 10 additions & 2 deletions src/common/hooks/donationWish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,18 @@ import { useQuery } from '@tanstack/react-query'
import { endpoints } from 'service/apiEndpoints'

import { DonationWishPaginatedResponse } from 'gql/donationWish'
import { PaginationData, SortData } from 'gql/types'

export function useDonationWishesList(camapignId: string, pageIndex?: number, pageSize?: number) {
export function useDonationWishesList(
campaignId: string,
paginationData?: PaginationData,
sort?: SortData,
searchData?: string,
) {
return useQuery<DonationWishPaginatedResponse>({
queryKey: [endpoints.donationWish.listDonationWishes(camapignId, pageIndex, pageSize).url],
queryKey: [
endpoints.donationWish.listDonationWishes(campaignId, paginationData, sort, searchData).url,
],
keepPreviousData: true,
})
}
170 changes: 135 additions & 35 deletions src/components/client/campaigns/DonationWishes.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,73 @@
import React, { useRef, useState } from 'react'
import React, { useMemo, useRef, useState } from 'react'

import { useTranslation } from 'next-i18next'

import { Unstable_Grid2 as Grid2, Stack, Typography, Grid } from '@mui/material'
import RateReviewIcon from '@mui/icons-material/RateReview'
import {
Unstable_Grid2 as Grid2,
Stack,
Typography,
Grid,
Button,
TextField,
InputAdornment,
} from '@mui/material'
import SearchIcon from '@mui/icons-material/Search'
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp'
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'
import AccountCircleIcon from '@mui/icons-material/AccountCircle'
import Pagination from '@mui/material/Pagination'

import { bg, enUS } from 'date-fns/locale'
import { moneyPublic } from 'common/util/money'
import { useDonationWishesList } from 'common/hooks/donationWish'
import { getExactDate } from 'common/util/date'
import theme from 'common/theme'
import { SortData } from 'gql/types'
import { debounce } from 'lodash'

type SortButton = {
label: string
value: string
}

type Props = {
campaignId: string
pageSize?: number
}

export default function DonationWishes({ campaignId, pageSize = 12 }: Props) {
export default function DonationWishes({ campaignId, pageSize = 5 }: Props) {
const { t, i18n } = useTranslation('campaigns')
const locale = i18n.language == 'bg' ? bg : enUS
const titleRef = useRef<HTMLElement>(null)
const [pageIndex, setPageIndex] = useState<number>(0)
const { data, isSuccess } = useDonationWishesList(campaignId, pageIndex, pageSize)
const [searchValue, setSearchValue] = useState('')

const [sort, setSort] = useState<SortData>({
sortBy: 'createdAt',
sortOrder: 'desc',
})

const { data, isSuccess } = useDonationWishesList(
campaignId,
{ pageIndex, pageSize },
sort,
searchValue,
)
const numOfPages = isSuccess && data ? Math.ceil(data.totalCount / pageSize) : 0

const handleSort = (value: string) => {
setSort((sort) => ({
sortBy: value,
sortOrder: sort.sortBy === value ? (sort.sortOrder === 'desc' ? 'asc' : 'desc') : 'desc',
}))
}

const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchValue(event.target.value)
}

const debounceSearch = useMemo(() => debounce(handleSearch, 300), [])

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

const handlePageChange = (_e: React.ChangeEvent<unknown>, page: number) => {
// <Pagination /> 's impl is 1 index based
// Our pagination apis are 0 index based
Expand All @@ -37,37 +80,78 @@ export default function DonationWishes({ campaignId, pageSize = 12 }: Props) {
}
}

const sortButtons: SortButton[] = [
{
label: t('campaign.sort.date'),
value: 'createdAt',
},
{
label: t('campaign.sort.amount'),
value: 'amount',
},
]

return (
<Grid2 container direction="column" rowGap={4}>
<Grid2>
<Stack direction="row" alignItems="center">
<RateReviewIcon
color="action"
sx={{
width: theme.spacing(1.75),
height: theme.spacing(1.75),
marginRight: theme.spacing(1),
}}
/>
<Typography
sx={{
color: '#000',
fontSize: theme.typography.pxToRem(25),
paddingBottom: '1rem',
}}>
{t('campaign.messages')}
</Typography>
<Stack
direction="row"
alignItems="center"
justifyContent={{ xs: 'center', sm: 'start' }}
gap={2}
useFlexGap
flexWrap="wrap">
<Typography
ref={titleRef}
sx={{
color: theme.palette.grey[800],
fontSize: theme.typography.pxToRem(16),
fontWeight: 500,
color: theme.palette.grey[900],
fontSize: theme.typography.pxToRem(12),
fontWeight: 600,
}}>
{t('campaign.messages')}
{t('campaign.sort.title')}
</Typography>
{sortButtons.map(({ label, value }) => (
<Button
key={value}
variant="text"
onClick={() => handleSort(value)}
sx={{
fontSize: theme.typography.pxToRem(14),
color: 'rgba(0, 0, 0, 0.54)',
}}>
{label}
{sort.sortBy === value &&
(sort.sortOrder === 'asc' ? <KeyboardArrowDownIcon /> : <KeyboardArrowUpIcon />)}
</Button>
))}
<TextField
placeholder={t('campaign.sort.search')}
size="small"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
variant="outlined"
onChange={debounceSearch}
/>
</Stack>
</Grid2>
<Grid2 container direction="column" rowGap={3}>
{isSuccess &&
data &&
data.items &&
data.items.map((wish) => (
data?.items?.map(({ id, person, donation, message, createdAt }) => (
<Grid2
container
key={wish.id}
key={id}
direction="row"
sx={{ p: 2, bgcolor: 'grey.100', borderRadius: theme.spacing(2) }}>
<Grid2 xs={12}>
Expand All @@ -86,18 +170,29 @@ export default function DonationWishes({ campaignId, pageSize = 12 }: Props) {
fontSize: theme.typography.pxToRem(16),
color: theme.palette.grey[800],
}}>
{wish.person
? wish.person.firstName + ' ' + wish.person.lastName
: t('donations.anonymous')}
</Typography>
<Typography
variant="caption"
sx={{
fontSize: theme.typography.pxToRem(14),
color: 'rgba(0, 0, 0, 0.54)',
}}>
{getExactDate(wish.createdAt, locale)}
{person ? person.firstName + ' ' + person.lastName : t('donations.anonymous')}
</Typography>
<Stack direction="row">
{donation && (
<Typography
variant="caption"
sx={{
fontSize: theme.typography.pxToRem(14),
color: 'rgba(0, 0, 0, 0.54)',
'&:after': { content: '"|"', paddingX: '5px' },
}}>
{moneyPublic(donation.amount, donation.currency)}
</Typography>
)}
<Typography
variant="caption"
sx={{
fontSize: theme.typography.pxToRem(14),
color: 'rgba(0, 0, 0, 0.54)',
}}>
{getExactDate(createdAt, locale)}
</Typography>
</Stack>
<Typography
component="blockquote"
sx={{
Expand All @@ -107,13 +202,18 @@ export default function DonationWishes({ campaignId, pageSize = 12 }: Props) {
'&:before': { content: 'open-quote', verticalAlign: theme.spacing(1.25) },
'&:after': { content: 'close-quote' },
}}>
{wish.message}
{message}
</Typography>
</Stack>
</Stack>
</Grid2>
</Grid2>
))}
<Grid2 xs={12}>
{data?.items?.length === 0 && searchValue !== '' && (
<Typography align="center"> {t('campaign.sort.noResults')}</Typography>
)}
</Grid2>
<Grid2 xs={12}>
{numOfPages > 1 && (
<Pagination
Expand Down
1 change: 1 addition & 0 deletions src/gql/donationWish.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type DonationWishResponse = {
donationId?: UUID
personId?: UUID
person?: { firstName: string; lastName: string }
donation?: { amount: number; currency: string }
createdAt: DateTime
}

Expand Down
5 changes: 5 additions & 0 deletions src/gql/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ export type PaginationData = {
pageSize: number
}

export type SortData = {
sortBy: string
sortOrder: string
}

export type FilterData = {
status: DonationStatus
paymentProvider: PaymentProvider
Expand Down
19 changes: 14 additions & 5 deletions src/service/apiEndpoints.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Method } from 'axios'
import { DonationStatus } from 'gql/donations.enums'
import { FilterData, PaginationData } from 'gql/types'
import { FilterData, PaginationData, SortData } from 'gql/types'

type Endpoint = {
url: string
Expand Down Expand Up @@ -308,10 +308,19 @@ export const endpoints = {
},
donationWish: {
createDonationWish: <Endpoint>{ url: '/donation-wish', method: 'POST' },
listDonationWishes: (campaignId?: string, pageIndex?: number, pageSize?: number) =>
<Endpoint>{
url: `/donation-wish/list/${campaignId}?pageindex=${pageIndex}&pagesize=${pageSize}`,
listDonationWishes: (
campaignId?: string,
paginationData?: PaginationData,
sort?: SortData,
searchData?: string,
) => {
const { pageIndex, pageSize } = (paginationData as PaginationData) || {}
const { sortBy, sortOrder } = (sort as SortData) || {}

return <Endpoint>{
url: `/donation-wish/list/${campaignId}?pageindex=${pageIndex}&pagesize=${pageSize}&search=${searchData}&sortBy=${sortBy}&sortOrder=${sortOrder}`,
method: 'GET',
},
}
},
},
}
Loading