import * as React from "react"; import { useQuery } from '@apollo/client'; import { GET_ORDERS } from '@/lib/graphql'; interface Order { id: string; orderNumber: string; status: 'PENDING' | 'PAID' | 'PROCESSING' | 'SHIPPED' | 'DELIVERED' | 'CANCELED' | 'REFUNDED'; totalAmount: number; discountAmount: number; finalAmount: number; currency: string; items: Array<{ id: string; name: string; article?: string; brand?: string; price: number; quantity: number; totalPrice: number; }>; deliveryAddress?: string; comment?: string; createdAt: string; updatedAt: string; } interface ProfileOrdersMainProps { // Добавьте необходимые пропсы, если они нужны } const tabs = [ { label: "Все", status: null }, { label: "Текущие", status: ['PENDING', 'PAID', 'PROCESSING', 'SHIPPED'] }, { label: "Выполненные", status: ['DELIVERED'] }, { label: "Отмененные", status: ['CANCELED', 'REFUNDED'] }, ]; const statusLabels = { PENDING: 'Ожидает оплаты', PAID: 'Оплачен', PROCESSING: 'В обработке', SHIPPED: 'Отправлен', DELIVERED: 'Доставлен', CANCELED: 'Отменен', REFUNDED: 'Возвращен' }; const statusColors = { PENDING: '#F59E0B', PAID: '#10B981', PROCESSING: '#3B82F6', SHIPPED: '#8B5CF6', DELIVERED: '#10B981', CANCELED: '#EF4444', REFUNDED: '#6B7280' }; const ProfileOrdersMain: React.FC = (props) => { const [activeTab, setActiveTab] = React.useState(0); const [search, setSearch] = React.useState(""); const [period, setPeriod] = React.useState("Все"); const periodOptions = ["Все", "Сегодня", "Неделя", "Месяц", "Год"]; const [deliveryMethod, setDeliveryMethod] = React.useState("Все"); const deliveryOptions = ["Все", "Самовывоз", "Доставка"]; const [isPeriodOpen, setIsPeriodOpen] = React.useState(false); const [isDeliveryOpen, setIsDeliveryOpen] = React.useState(false); const [clientId, setClientId] = React.useState(null); // Получаем ID клиента из localStorage React.useEffect(() => { const userData = localStorage.getItem('userData'); if (userData) { try { const user = JSON.parse(userData); setClientId(user.id); } catch (error) { console.error('Ошибка парсинга userData:', error); } } }, []); // Загружаем заказы const { data, loading, error, refetch } = useQuery(GET_ORDERS, { variables: { clientId: clientId?.startsWith('client_') ? clientId.substring(7) : clientId, limit: 100, offset: 0 }, skip: !clientId, // Не выполняем запрос пока нет clientId fetchPolicy: 'cache-and-network' }); const orders: Order[] = data?.orders?.orders || []; // Фильтруем заказы по активной вкладке const filteredOrdersByTab = React.useMemo(() => { const currentTab = tabs[activeTab]; if (!currentTab.status) { return orders; // Все заказы } return orders.filter(order => currentTab.status!.includes(order.status)); }, [orders, activeTab]); // Фильтруем по поиску const filteredOrders = React.useMemo(() => { if (!search) return filteredOrdersByTab; const searchLower = search.toLowerCase(); return filteredOrdersByTab.filter(order => order.orderNumber.toLowerCase().includes(searchLower) || order.items.some(item => item.name.toLowerCase().includes(searchLower) || item.article?.toLowerCase().includes(searchLower) || item.brand?.toLowerCase().includes(searchLower) ) ); }, [filteredOrdersByTab, search]); const formatPrice = (price: number, currency = 'RUB') => { return `${price.toLocaleString('ru-RU')} ${currency === 'RUB' ? '₽' : currency}`; }; const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' }); }; if (!clientId) { return (

Необходимо авторизоваться для просмотра заказов

); } if (loading) { return (

Загрузка заказов...

); } if (error) { return (

Ошибка загрузки заказов: {error.message}

); } return (
{tabs.map((tab, idx) => (
setActiveTab(idx)} >
{tab.label}
))}
setSearch(e.target.value)} placeholder="Поиск по заказам" className="flex-1 shrink self-stretch my-auto basis-0 text-ellipsis outline-none bg-transparent text-gray-950 placeholder:text-gray-400" />
{tabs[activeTab].label}
{filteredOrders.length === 0 ? (
{search ? 'Заказы не найдены' : 'У вас пока нет заказов'}
{!search && (
Оформите первый заказ в нашем каталоге
)}
) : (
{filteredOrders.map((order) => (
{statusLabels[order.status]}
Заказ {order.orderNumber} от {formatDate(order.createdAt)}
Производитель
Артикул
Наименование
Кол-во
Стоимость
{order.items.map((item, index) => (
{index + 1}
{item.brand || '-'}
{item.article || '-'}
{item.name}
{item.quantity} шт.
{formatPrice(item.totalPrice, order.currency)}
))}
{/* Итоговая сумма */}
Сумма товаров: {formatPrice(order.totalAmount, order.currency)}
{order.discountAmount > 0 && (
Скидка: -{formatPrice(order.discountAmount, order.currency)}
)}
Итого: {formatPrice(order.finalAmount, order.currency)}
{/* Адрес доставки */} {order.deliveryAddress && (
Адрес доставки:
{order.deliveryAddress}
)} {/* Комментарий */} {order.comment && (
Комментарий:
{order.comment}
)}
))}
)}
); }; export default ProfileOrdersMain;