Skip to content

Commit

Permalink
Merge pull request #13 from pieceowater-dev/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
baynt1 authored May 21, 2024
2 parents bbfc0ac + 2349c62 commit 7a75414
Show file tree
Hide file tree
Showing 13 changed files with 183 additions and 76 deletions.
29 changes: 24 additions & 5 deletions src/entities/dashboard/bar-chart/bar-chart.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useNotify } from 'app/providers/app'
import { useEffect } from 'react'
import dayjs from 'dayjs'
import { IBarChartResponse } from 'entities/dashboard/bar-chart/model/iterface'
import { useEffect, useState } from 'react'
import { getAxiosInstance } from 'shared/api/api-query/api-query'
import { useAppSelector } from 'shared/redux/store'

Expand All @@ -8,14 +10,31 @@ export const useBarChart = () => {
const dateType = useAppSelector((state) => state.dashboard.typeDate)
const { start, end } = useAppSelector((state) => state.dashboard.selectedDates)
const posts = useAppSelector((state) => state.dashboard.posts)
const [barData, setBarData] = useState([])
const [barLabels, setBarLabels] = useState([''])

const fetchData = async () => {
try {
const axiosInstance = await getAxiosInstance()
const res = await axiosInstance.get('/payments/pie-posts', {
const res = await axiosInstance.get('/payments/day-debit', {
params: { dateType: dateType, start: start, end: end, posts: posts },
})
console.log(res.data)
if (res.data.length > 0) {
const dataSet = res.data.map((item: IBarChartResponse) => item.sum)
const labels = res.data.map((item: IBarChartResponse) => {
if (item.date) {
return dayjs(item.date).format('DD-MM-YYYY')
} else {
return 'Некоректная дата'
}
})

setBarData(dataSet)
setBarLabels(labels)
} else {
setBarData([])
setBarLabels([])
}
} catch (error) {
openNotification('Произошла ошибка при загрузке данных о платежах')
}
Expand All @@ -26,11 +45,11 @@ export const useBarChart = () => {
}, [dateType, start, end, posts])

const bar = {
labels: ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'],
labels: barLabels,
datasets: [
{
label: 'Общая сумма',
data: [12, 19, 3, 5, 2, 3, 7],
data: barData,
backgroundColor: 'rgb(110, 189, 116)',
},
],
Expand Down
5 changes: 5 additions & 0 deletions src/entities/dashboard/bar-chart/model/iterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface IBarChartResponse {
date: string
sum: number
count: string
}
3 changes: 1 addition & 2 deletions src/entities/dashboard/payment-data/payment-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { IColumnPayments } from 'entities/dashboard/payment-data/model/interface
import { IPostsResponse } from 'entities/settings/posts-table/model/interface'
import { useEffect, useState } from 'react'
import { getAxiosInstance } from 'shared/api/api-query/api-query'
import { setPaymentsPostsData, setPaymentsState } from 'shared/redux/dashboard/dashboard-slice'
import { setPaymentsState } from 'shared/redux/dashboard/dashboard-slice'
import { useAppDispatch } from 'shared/redux/store'

export const usePaymentData = () => {
Expand All @@ -21,7 +21,6 @@ export const usePaymentData = () => {
label: item.name,
}))
setPostSelect(select)
dispatch(setPaymentsPostsData(select))
} catch (error) {
openNotification('Произошла ошибка при загрузке данных о пользователях')
}
Expand Down
11 changes: 8 additions & 3 deletions src/entities/dashboard/pie-chart/pie-chart.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useNotify } from 'app/providers/app'
import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import { getAxiosInstance } from 'shared/api/api-query/api-query'
import { useAppSelector } from 'shared/redux/store'

Expand All @@ -8,14 +8,19 @@ export const usePieChart = () => {
const dateType = useAppSelector((state) => state.dashboard.typeDate)
const { start, end } = useAppSelector((state) => state.dashboard.selectedDates)
const posts = useAppSelector((state) => state.dashboard.posts)
const [pieData, setPieData] = useState([0, 0])

const fetchData = async () => {
try {
const axiosInstance = await getAxiosInstance()
const res = await axiosInstance.get('/payments/pie-type', {
params: { dateType: dateType, start: start, end: end, posts: posts },
})
console.log(res.data)
if (res.data.length > 0) {
setPieData([res.data[0].sum, res.data[1].sum])
} else {
setPieData([0, 0])
}
} catch (error) {
openNotification('Произошла ошибка при загрузке данных о платежах')
}
Expand All @@ -29,7 +34,7 @@ export const usePieChart = () => {
labels: ['Наличные', 'Каспи'],
datasets: [
{
data: [60, 40],
data: pieData,
backgroundColor: ['rgb(110, 189, 116)', 'rgba(218,18,18,0.8)'],
},
],
Expand Down
3 changes: 3 additions & 0 deletions src/entities/dashboard/posts-chart/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { usePostsChart } from 'entities/dashboard/posts-chart/posts-chart'

export { usePostsChart }
6 changes: 6 additions & 0 deletions src/entities/dashboard/posts-chart/model/interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface IPostsChartsResponse {
id: number
name: string
sum: number
count: string
}
42 changes: 42 additions & 0 deletions src/entities/dashboard/posts-chart/posts-chart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useNotify } from 'app/providers/app'
import { IPostsChartsResponse } from 'entities/dashboard/posts-chart/model/interface'
import { useEffect, useState } from 'react'
import { getAxiosInstance } from 'shared/api/api-query/api-query'
import { useAppSelector } from 'shared/redux/store'

export const usePostsChart = () => {
const [postsData, setPostsData] = useState<{ label: string; value: number }[]>([])
const { openNotification } = useNotify()
const dateType = useAppSelector((state) => state.dashboard.typeDate)
const { start, end } = useAppSelector((state) => state.dashboard.selectedDates)
const posts = useAppSelector((state) => state.dashboard.posts)

const fetchData = async () => {
try {
const axiosInstance = await getAxiosInstance()
const res = await axiosInstance.get('/payments/pie-posts', {
params: { dateType: dateType, start: start, end: end, posts: posts },
})
if (res.data.length > 0) {
const response = res.data.map((item: IPostsChartsResponse) => {
return {
label: item.name,
value: item.sum,
}
})

setPostsData(response)
} else {
setPostsData([])
}
} catch (error) {
openNotification('Произошла ошибка при загрузке данных о платежах')
}
}

useEffect(() => {
fetchData()
}, [dateType, start, end, posts])

return { postsData }
}
2 changes: 1 addition & 1 deletion src/entities/dashboard/table-data/model/interface.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export interface IRowsPaymentResponse {
id: number
date: number
datetime: number | string
sum: string
device: {
id: number
Expand Down
2 changes: 1 addition & 1 deletion src/entities/dashboard/table-data/table-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const useTableData = () => {
setPaymentTableSum((prevState) => prevState + transformPrice(row.sum))
return {
key: row.id,
date: row.date ? unixDate(row.date * 1000, 'DMYHM') : '',
date: row.datetime ? unixDate(+row.datetime * 1000, 'DMYHM') : '',
post: row.device.name,
sum: transformPrice(row.sum),
}
Expand Down
133 changes: 86 additions & 47 deletions src/features/settings/new-post/new-post.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,26 @@ export const NewPost: FC<INewPostProps> = ({ open, handeOpen, item, refetch }) =
const { openNotification } = useNotify()
const [form] = Form.useForm()
const [loading, setLoading] = useState(false)
const [tokenLoading, setTokenLoading] = useState(false)
const [token, setToken] = useState('')

const options = useAppSelector((state) => state.settings.users)

const fetchToken = async () => {
setTokenLoading(true)

try {
const axiosInstance = await getAxiosInstance()
if (item && item.id)
await axiosInstance.post('/post-token', { postId: item.id }).then((res) => {
setTokenLoading(false)
setToken(res.data.token)
})
} catch (error) {
openNotification('Что-то пошло не так')
}
}

const fetchData = async () => {
try {
const axiosInstance = await getAxiosInstance()
Expand Down Expand Up @@ -76,57 +93,79 @@ export const NewPost: FC<INewPostProps> = ({ open, handeOpen, item, refetch }) =
}

return (
<Drawer title='Создание нового поста' onClose={handeOpen} open={open}>
<Form
form={form}
onFinish={onFinish}
layout={'vertical'}
initialValues={{
name: item?.name || '',
address: item?.address || '',
identifier: item?.identifier || '',
}}
style={{ height: '100%' }}
>
<Form.Item<INewPostFormArgs>
label={'Имя поста'}
name={'name'}
rules={[{ required: true, message: 'Введите имя поста' }]}
<>
<Drawer title='Создание нового поста' onClose={handeOpen} open={open}>
<Form
form={form}
onFinish={onFinish}
layout={'vertical'}
initialValues={{
name: item?.name || '',
address: item?.address || '',
identifier: item?.identifier || '',
}}
style={{ height: '100%' }}
>
<Input />
</Form.Item>
<Form.Item<INewPostFormArgs>
label={'Имя поста'}
name={'name'}
rules={[{ required: true, message: 'Введите имя поста' }]}
>
<Input />
</Form.Item>

<Form.Item<INewPostFormArgs>
label={'Адрес'}
name={'address'}
rules={[{ required: true, message: 'Введите адрес' }]}
>
<Input />
</Form.Item>
<Form.Item<INewPostFormArgs>
label={'Адрес'}
name={'address'}
rules={[{ required: true, message: 'Введите адрес' }]}
>
<Input />
</Form.Item>

<Form.Item<INewPostFormArgs>
label={'Индификатор'}
name={'identifier'}
rules={[{ required: true, message: 'Введите Индификатор' }]}
>
<Input />
</Form.Item>
<Form.Item<INewPostFormArgs>
label={'Индификатор'}
name={'identifier'}
rules={[{ required: true, message: 'Введите Индификатор' }]}
>
<Input />
</Form.Item>

<Form.Item<INewPostFormArgs> label={'Посты'} name={'users'}>
<Select
mode={'multiple'}
allowClear={true}
style={{ width: '100%', marginTop: 5 }}
options={options}
/>
</Form.Item>

<Form.Item>
<div style={{ display: 'flex', gap: '10px' }}>
<Button type='primary' htmlType='submit' loading={loading}>
Сохранить
</Button>

<Form.Item<INewPostFormArgs> label={'Посты'} name={'users'}>
<Select
mode={'multiple'}
allowClear={true}
style={{ width: '100%', marginTop: 5 }}
options={options}
/>
</Form.Item>
<Button type='primary' onClick={fetchToken} loading={tokenLoading}>
Получить токен
</Button>
</div>
</Form.Item>

<Form.Item>
<Button type='primary' htmlType='submit' loading={loading}>
Сохранить
</Button>
</Form.Item>
</Form>
</Drawer>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<div>Токен показывается только 1 раз, затем генерируется новый</div>
<Input value={token} disabled={true} />
<Button
type='primary'
onClick={() => {
navigator.clipboard.writeText(token)
openNotification('Токен скопирован', 'success')
}}
>
Скопировать
</Button>
</div>
</Form>
</Drawer>
</>
)
}
8 changes: 3 additions & 5 deletions src/pages/dashboard/ui/dashboard-charts/dashboard-charts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import {
} from 'chart.js'
import { useBarChart } from 'entities/dashboard/bar-chart'
import { usePieChart } from 'entities/dashboard/pie-chart'
import { usePostsChart } from 'entities/dashboard/posts-chart'
import { FC } from 'react'
import { Bar, Pie } from 'react-chartjs-2'
import { useMediaQuery } from 'react-responsive'
import { useAppSelector } from 'shared/redux/store'
import { PostCard } from 'shared/ui/post-card'

ChartJS.register(ArcElement, Tooltip, Legend, CategoryScale, LinearScale, BarElement)
Expand All @@ -21,9 +21,7 @@ export const DashboardCharts: FC = () => {
const isMobile = useMediaQuery({ query: '(max-width: 768px )' })
const { pie } = usePieChart()
const { bar } = useBarChart()
const posts: { label: string; value: number }[] = useAppSelector(
(state) => state.dashboard.postsData,
)
const { postsData } = usePostsChart()

return (
<>
Expand Down Expand Up @@ -59,7 +57,7 @@ export const DashboardCharts: FC = () => {
alignItems: 'center',
}}
>
{posts.map((item) => (
{postsData.map((item) => (
<PostCard key={item.value} value={item.value} name={item.label} />
))}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const DashboardFilters: FC<IDashboardProps> = ({ refetch, options }) => {
<DatePicker.RangePicker
onChange={(date) => {
dispatch(
setPaymentsSelectedDates({ start: date?.[0]?.toDate(), end: date?.[1]?.toDate() }),
setPaymentsSelectedDates({ start: date?.[0]?.unix(), end: date?.[1]?.unix() }),
)
}}
/>
Expand Down
Loading

0 comments on commit 7a75414

Please sign in to comment.