add payments history tanstak-table

This commit is contained in:
smanylov
2026-02-21 15:07:37 +07:00
parent 4f7b464bed
commit c88646b64c
8 changed files with 616 additions and 29 deletions
+39 -1
View File
@@ -1,7 +1,7 @@
'use server' 'use server'
import { YooCheckout, ICreatePayment } from '@a2seven/yoo-checkout'; import { YooCheckout, ICreatePayment } from '@a2seven/yoo-checkout';
import { getSessionData } from '@/app/actions/session'; import { getSessionData, deleteSession } from '@/app/actions/session';
import { API_BASE_URL } from '@/app/actions/definitions'; import { API_BASE_URL } from '@/app/actions/definitions';
const checkout = new YooCheckout({ shopId: '1276731', secretKey: 'test_0Yns_0NHV5GJf6ypJ5HC4NSfnLO8SJkw-1PwrVWsDl4' }); const checkout = new YooCheckout({ shopId: '1276731', secretKey: 'test_0Yns_0NHV5GJf6ypJ5HC4NSfnLO8SJkw-1PwrVWsDl4' });
@@ -77,3 +77,41 @@ export async function yooKasaCreatePayment(amount: number, tariff: number, opera
return null return null
} }
} }
export async function fetchPaymentsHistory() {
const email = await getSessionData('email');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30005,
message_body: {
action: 'user_payments',
email: email
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
const parsed = await response.json();
if (parsed.message_code === 0) {
return {
payments: parsed.message_body.payments,
error: null
};
} else {
throw parsed.message_code;
}
} else {
return null
}
} catch (error) {
return null
}
}
@@ -14,8 +14,8 @@ import {
import { IconEye, IconDoubleArrowRight, IconArrowRight, IconDoubleArrowLeft, IconArrowLeft, IconArrowUp, IconArrowDown, IconFilter, IconFileDownload, IconShieldExclamation, IconInfo } from '@/app/ui/icons/icons'; import { IconEye, IconDoubleArrowRight, IconArrowRight, IconDoubleArrowLeft, IconArrowLeft, IconArrowUp, IconArrowDown, IconFilter, IconFileDownload, IconShieldExclamation, IconInfo } from '@/app/ui/icons/icons';
import { useTranslations, useLocale } from 'next-intl'; import { useTranslations, useLocale } from 'next-intl';
import DropDownList from '@/app/components/DropDownList'; import DropDownList from '@/app/components/DropDownList';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useQuery, useQueryClient } from '@tanstack/react-query';
import { getUserFilesData, removeUserFile, viewFileInfo } from '@/app/actions/fileEntity'; import { getUserFilesData, viewFileInfo } from '@/app/actions/fileEntity';
import ModalWindow from '@/app/components/ModalWindow'; import ModalWindow from '@/app/components/ModalWindow';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { pluralize } from '@/app/lib/pluralize'; import { pluralize } from '@/app/lib/pluralize';
@@ -25,7 +25,7 @@ import { FileMonitoringModalWindow } from '@/app/ui/modal-windows/file-monitorin
import { FileTypeIcon } from '@/app/components/FileTypeIcon'; import { FileTypeIcon } from '@/app/components/FileTypeIcon';
import { fetchReferralUserStats } from '@/app/actions/referralsActions'; import { fetchReferralUserStats } from '@/app/actions/referralsActions';
import { MonitoringDropDown } from '@/app/components/tanstak-table/MonitoringDropDown'; import { MonitoringDropDown } from '@/app/components/tanstak-table/MonitoringDropDown';
import { useUserProfile } from '@/app/hooks/react-query/useUserDataInfo'; import {formatDate, formatDateTime} from '@/app/lib/formatDate';
type FileType = 'image' | 'video' | 'audio'; type FileType = 'image' | 'video' | 'audio';
@@ -59,24 +59,6 @@ type ApiResponse = {
files?: ApiFile[]; files?: ApiFile[];
}; };
// Форматирование даты из timestamp
const formatDate = (timestamp: number) => {
const date = new Date(timestamp);
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
return `${day}.${month}.${year}`;
};
const formatDateTime = (timestamp: number) => {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
};
const cutFileName = (fileName: string) => { const cutFileName = (fileName: string) => {
const MAX_FILE_NAME_LENGTH = 26; const MAX_FILE_NAME_LENGTH = 26;
const lastDotIndex = fileName.lastIndexOf('.'); const lastDotIndex = fileName.lastIndexOf('.');
@@ -367,6 +349,8 @@ export default function TanstakFilesTable({ fileType }: { fileType: string }) {
{formatDate(row.original.uploadDate)} {formatDate(row.original.uploadDate)}
<br /> <br />
{formatDateTime(row.original.uploadDate)} {formatDateTime(row.original.uploadDate)}
<br />
{row.original.uploadDate}
</> </>
) : ( ) : (
<div>-</div> <div>-</div>
@@ -583,7 +567,7 @@ export default function TanstakFilesTable({ fileType }: { fileType: string }) {
} }
return result; return result;
}, [tableData, typeFilter, dateFilter]); //tut }, [tableData, typeFilter, dateFilter]);
useEffect(() => { useEffect(() => {
const currentPageRows = table.getRowModel().rows; const currentPageRows = table.getRowModel().rows;
@@ -0,0 +1,37 @@
import { useQuery } from '@tanstack/react-query';
import { fetchPaymentsHistory } from '@/app/actions/yooKassa';
export interface PaymentsData {
amount: number,
cancellationReason: string | null,
createdAt: string,
id: number,
operationType: string,
paymentUuid: string,
status: string,
updatedAt: string,
}
export interface UserPaymentsData {
payments: PaymentsData[],
error: string | null
}
export const useUserPaymentsData = () => {
return useQuery({
queryKey: ['userPaymentsData'],
queryFn: fetchPaymentsHistory,
select: (data): UserPaymentsData => {
if (!data) {
return {
payments: [],
error: null
}
}
return data;
},
retry: false
});
};
+17
View File
@@ -0,0 +1,17 @@
// Форматирование даты из timestamp
export const formatDate = (timestamp: number | string) => {
const date = new Date(timestamp);
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
return `${day}.${month}.${year}`;
};
export const formatDateTime = (timestamp: number | string) => {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
};
+5 -2
View File
@@ -835,8 +835,11 @@
.table-item-status { .table-item-status {
padding: 2px 10px; padding: 2px 10px;
border-radius: 15px; border-radius: 15px;
background-color: #dcfce7;
color: #166534; &.succeeded {
background-color: #dcfce7;
color: #166534;
}
} }
.actions { .actions {
@@ -1,7 +1,507 @@
'use client'
import { useUserPaymentsData, PaymentsData } from '@/app/hooks/react-query/useUserPaymentsData';
import { useEffect, useMemo, useState } from 'react';
import { useReactTable, getCoreRowModel, getSortedRowModel, getPaginationRowModel, getFilteredRowModel, ColumnDef, SortingState, ColumnFiltersState } from '@tanstack/react-table';
import { useTranslations } from 'next-intl';
import { IconArrowUp, IconArrowDown, IconFilter, IconDoubleArrowRight, IconArrowRight, IconDoubleArrowLeft, IconArrowLeft } from '@/app/ui/icons/icons';
import { formatDate, formatDateTime } from '@/app/lib/formatDate';
import DropDownList from '@/app/components/DropDownList';
export default function PaymentTabTransactionHistory() { export default function PaymentTabTransactionHistory() {
const { data: userPaymentsData, isLoading, isError, error, } = useUserPaymentsData();
const t = useTranslations('Global');
// Состояния
const [sorting, setSorting] = useState<SortingState>([]);
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const [dateFilter, setDateFilter] = useState<string>('all');
const [pagination, setPagination] = useState({
pageIndex: 0,
pageSize: 10,
});
const columns = useMemo<ColumnDef<PaymentsData>[]>(
() => [
{
accessorKey: 'id',
header: ({ column }) => (
<div className="column">
<span>
ID
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="sort-button"
>
{
column.getIsSorted() === 'asc' ?
<span>
<IconArrowUp />
</span>
: column.getIsSorted() === 'desc' ?
<span>
<IconArrowDown />
</span>
: <span>
<IconFilter />
</span>
}
</button>
</div>
),
cell: ({ row }) => {
return (
<div>
<div className="text-center table-item table-item-id">
{row.original.id ? row.original.id : '-'}
</div>
</div>
)
}
},
{
accessorKey: 'amount',
header: ({ column }) => (
<div className="column">
<span>
{t('amount')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="sort-button"
>
{
column.getIsSorted() === 'asc' ?
<span>
<IconArrowUp />
</span>
: column.getIsSorted() === 'desc' ?
<span>
<IconArrowDown />
</span>
: <span>
<IconFilter />
</span>
}
</button>
</div>
),
cell: ({ row }) => (
<div className="text-center table-item">
{row.original.amount}
</div>
),
},
{
accessorKey: 'operationType',
header: ({ column }) => (
<div className="column">
<span>
{t('operation-type')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="sort-button"
>
{
column.getIsSorted() === 'asc' ?
<span>
<IconArrowUp />
</span>
: column.getIsSorted() === 'desc' ?
<span>
<IconArrowDown />
</span>
: <span>
<IconFilter />
</span>
}
</button>
</div>
),
cell: ({ row }) => (
<div className="text-center table-item">
{row.original.operationType}
</div>
),
},
{
accessorKey: 'status',
header: ({ column }) => (
<div className="column">
<span>
{t('status')}
</span>
<button
onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
className="sort-button"
>
{
column.getIsSorted() === 'asc' ?
<span>
<IconArrowUp />
</span>
: column.getIsSorted() === 'desc' ?
<span>
<IconArrowDown />
</span>
: <span>
<IconFilter />
</span>
}
</button>
</div>
),
cell: ({ row }) => {
return (
<div className="text-center font-semibold table-item">
<p className={`table-item-status ${row.original.status.toLocaleLowerCase()}`}>
{t(row.original.status.toLocaleLowerCase())}
</p>
</div>
)
},
},
{
accessorKey: 'date',
header: ({ column }) => (
<div className="column">
<span>
{t('date')}
</span>
<button
onClick={() => {
column.toggleSorting(column.getIsSorted() === 'asc')
}}
className="sort-button"
>
{
column.getIsSorted() === 'asc' ?
<span>
<IconArrowUp />
</span>
: column.getIsSorted() === 'desc' ?
<span>
<IconArrowDown />
</span>
: <span>
<IconFilter />
</span>
}
</button>
</div>
),
cell: ({ row }) => {
return (
<div className="text-center table-item">
{row.original.createdAt ? (
<>
{formatDate(row.original.createdAt)}
<br />
{formatDateTime(row.original.createdAt)}
</>
) : (
<div>-</div>
)}
</div>
)
},
sortingFn: (rowA, rowB) => {
const dateA = new Date(rowA.original.createdAt).getTime();
const dateB = new Date(rowB.original.createdAt).getTime();
return dateA - dateB;
},
enableColumnFilter: false,
},
],
[]
)
const filteredData = useMemo(() => {
let result = userPaymentsData?.payments;
if (!result) {
return [];
}
// Фильтр по дате
if (dateFilter !== 'all') {
const now = Date.now();
const oneDay = 24 * 60 * 60 * 1000;
const sevenDays = 7 * oneDay;
const thirtyDays = 30 * oneDay;
switch (dateFilter) {
case 'today':
const todayStart = new Date().setHours(0, 0, 0, 0);
result = result.filter(item => {
if (item.createdAt) {
return new Date(item.createdAt).getTime() >= todayStart
} else {
return 0
}
});
break;
case 'week':
const weekAgo = now - sevenDays;
result = result.filter(item => {
if (item.createdAt) {
return new Date(item.createdAt).getTime() >= weekAgo;
}
});
break;
case 'month':
const monthAgo = now - thirtyDays;
result = result.filter(item => {
if (item.createdAt) {
return new Date(item.createdAt).getTime() >= monthAgo;
}
});
break;
case 'older':
const monthAgo2 = now - thirtyDays;
result = result.filter(item => {
if (item.createdAt) {
return new Date(item.createdAt).getTime() < monthAgo2;
}
});
break;
}
}
return result
}, [userPaymentsData?.payments, dateFilter])
const table = useReactTable({
data: filteredData,
columns,
state: {
sorting,
columnFilters,
pagination
},
autoResetPageIndex: false,
onPaginationChange: setPagination,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFilteredRowModel: getFilteredRowModel(),
initialState: {
pagination: {
pageSize: 10,
},
},
});
return ( return (
<div className="tab-content"> <div
payment-tab-transaction-history className="block-wrapper"
>
<div className="tab-content">
<div
className="tanstak-table-wrapper"
>
<h3
className="tanstak-table-title"
>
История покупок
</h3>
{/* Фильтры */}
<div className="tanstak-table-filtres">
<div className="table-filtres-wrapper">
<div className="table-filtres-item">
<div className="table-filtres-label">{t('date-filter')}:</div>
<DropDownList
value={dateFilter}
translatedValue={(() => {
switch (dateFilter) {
case 'all':
return t('all-dates')
case 'week':
return t('for-a-week')
case 'month':
return t('for-a-month')
case 'older':
return t('older-than-a-month')
default:
return t('today')
}
})()}
callBack={setDateFilter}
>
<li value="all">
{t('all-dates')}
</li>
<li value="today">
{t('today')}
</li>
<li value="week">
{t('for-a-week')}
</li>
<li value="month">
{t('for-a-month')}
</li>
<li value="older">
{t('older-than-a-month')}
</li>
</DropDownList>
</div>
</div>
<div
className="table-filtres-wrapper"
>
<div className="table-filtres-item">
<div className="table-filtres-label">{t('items-per-page')}:</div>
<DropDownList
value={table.getState().pagination.pageSize}
//@ts-ignore сделал так потому что для table.setPageSize нужна цифра
callBack={table.setPageSize}
>
{[5, 10, 20, 50, 100].map(pageSize => (
<li key={pageSize} value={pageSize}>
{t('show')} {pageSize}
</li>
))}
</DropDownList>
</div>
</div>
</div>
{/* Таблица */}
<div className="tanstak-table-block">
<table className="tanstak-table">
<thead className="tanstak-table-head">
{table.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => (
<th
key={header.id}
>
{header.isPlaceholder
? null
: typeof header.column.columnDef.header === 'function'
? header.column.columnDef.header(header.getContext())
: header.column.columnDef.header as string}
</th>
))}
</tr>
))}
</thead>
<tbody className="tanstak-table-body">
{table.getRowModel().rows.length > 0 ? (
table.getRowModel().rows.map(row => (
<tr key={row.id}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>
{typeof cell.column.columnDef.cell === 'function'
? cell.column.columnDef.cell(cell.getContext())
: cell.getValue() as string}
</td>
))}
</tr>
))
) : (
<tr>
<td colSpan={columns.length} className="text-center">
{t('no-data-for-selected-filters')}
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* Пагинация */}
<div className="tanstak-table-pagination">
<div className="pagination-info">
<span className="pagination-info-pages">
{t('page')}{' '}
<strong>
{table.getState().pagination.pageIndex + 1} {t('out-of')} {table.getPageCount() ? table.getPageCount() : 1}
</strong>
</span>
<span className="pagination-info-files">
| {t('shown')} {table.getRowModel().rows.length} {t('out-of')} {filteredData.length}
</span>
</div>
<div className="pagination-controls">
{table.getCanPreviousPage() && (
<button
className="arrow"
onClick={() => table.firstPage()}
disabled={!table.getCanPreviousPage()}
>
<IconDoubleArrowLeft />
</button>
)}
{table.getCanPreviousPage() && (
<button
className="arrow"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<IconArrowLeft />
</button>
)}
<div className="pagination-controls-pages">
{Array.from({ length: Math.min(5, table.getPageCount()) }, (_, i) => {
const pageIndex = Math.max(
0,
Math.min(
table.getPageCount() - 5,
table.getState().pagination.pageIndex - 2
)
) + i;
if (pageIndex < table.getPageCount()) {
return (
<button
key={pageIndex}
className={`${table.getState().pagination.pageIndex === pageIndex
? 'current'
: 'other'
}`}
onClick={() => table.setPageIndex(pageIndex)}
>
{pageIndex + 1}
</button>
);
}
return null;
})}
</div>
{table.getCanNextPage() && (
<button
className="arrow"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<IconArrowRight />
</button>
)}
{table.getCanNextPage() && (
<button
className="arrow"
onClick={() => table.lastPage()}
disabled={!table.getCanNextPage()}
>
<IconDoubleArrowRight />
</button>
)}
</div>
</div>
</div>
</div>
</div> </div>
) )
} }
+5 -1
View File
@@ -234,7 +234,11 @@
"without-monitoring" : "Without monitoring", "without-monitoring" : "Without monitoring",
"every-day": "Every day", "every-day": "Every day",
"every-week": "Every week", "every-week": "Every week",
"every-month": "Every day" "every-month": "Every day",
"amount": "Amount",
"date": "Date",
"operation-type": "Operation type",
"succeeded": "Succeeded"
}, },
"Login-register-form": { "Login-register-form": {
"and": "and", "and": "and",
+5 -1
View File
@@ -234,7 +234,11 @@
"without-monitoring": "Без мониторинга", "without-monitoring": "Без мониторинга",
"every-day": "Каждый день", "every-day": "Каждый день",
"every-week": "Каждую неделю", "every-week": "Каждую неделю",
"every-month": "Каждый месяц" "every-month": "Каждый месяц",
"amount": "Сумма",
"date": "Дата",
"operation-type": "Тип операции",
"succeeded": "Успешно"
}, },
"Login-register-form": { "Login-register-form": {
"and": "и", "and": "и",