Обновлен компонент PvzReturnsTab: добавлена интеграция с API Wildberries для загрузки заявок на возврат, реализована обработка данных и фильтрация по статусам. Улучшен интерфейс с новыми элементами управления и отображением информации о заявках. Добавлены проверки на наличие API ключа и обработка ошибок при загрузке данных.

This commit is contained in:
Bivekich
2025-07-24 16:13:38 +03:00
parent c6bffd1d9b
commit 1e22f6fef9
3 changed files with 910 additions and 865 deletions

View File

@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@ -13,51 +13,130 @@ import {
AlertCircle,
Eye,
MapPin,
RefreshCw,
ExternalLink,
MessageCircle,
} from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { WildberriesService, type WBClaim, type WBClaimsResponse } from "@/services/wildberries-service";
import { toast } from "sonner";
// Мок данные для возвратов с ПВЗ
const mockPvzReturns = [
{
id: "1",
productName: "Смартфон Samsung Galaxy S23",
sku: "SAM-S23-128-BLK",
pvzAddress: "ул. Ленина, 15, ПВЗ №1234",
returnDate: "2024-01-13",
status: "collected",
quantity: 3,
reason: "Брак товара",
estimatedValue: 150000,
seller: "TechWorld",
},
{
id: "2",
productName: "Кроссовки Nike Air Max",
sku: "NIKE-AM-42-WHT",
pvzAddress: "пр. Мира, 88, ПВЗ №5678",
returnDate: "2024-01-12",
status: "pending",
quantity: 2,
reason: "Не подошел размер",
estimatedValue: 24000,
seller: "SportsGear",
},
{
id: "3",
productName: "Планшет iPad Air",
sku: "IPAD-AIR-256-GRY",
pvzAddress: "ул. Советская, 42, ПВЗ №9012",
returnDate: "2024-01-11",
status: "processed",
quantity: 1,
reason: "Передумал покупать",
estimatedValue: 85000,
seller: "AppleStore",
},
];
// Интерфейс для обработанных данных возврата
interface ProcessedClaim {
id: string;
productName: string;
nmId: number;
returnDate: string;
status: string;
reason: string;
price: number;
userComment: string;
wbComment: string;
photos: string[];
videoPaths: string[];
actions: string[];
orderDate: string;
lastUpdate: string;
}
export function PvzReturnsTab() {
const { user } = useAuth();
const [searchTerm, setSearchTerm] = useState("");
const [statusFilter, setStatusFilter] = useState("all");
const [archiveFilter, setArchiveFilter] = useState(false);
const [claims, setClaims] = useState<ProcessedClaim[]>([]);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [total, setTotal] = useState(0);
// Загрузка заявок
const loadClaims = async (showToast = false) => {
const isInitialLoad = !refreshing;
if (isInitialLoad) setLoading(true);
else setRefreshing(true);
try {
const wbApiKey = user?.organization?.apiKeys?.find(
(key) => key.marketplace === "WILDBERRIES" && key.isActive
);
if (!wbApiKey) {
if (showToast) {
toast.error("API ключ Wildberries не настроен");
}
return;
}
const apiToken = wbApiKey.apiKey;
console.log("WB Claims: Loading claims with archive =", archiveFilter);
const response = await WildberriesService.getClaims(apiToken, {
isArchive: archiveFilter,
limit: 100,
offset: 0,
});
const processedClaims = response.claims.map(processClaim);
setClaims(processedClaims);
setTotal(response.total);
console.log(`WB Claims: Loaded ${processedClaims.length} claims`);
if (showToast) {
toast.success(`Загружено заявок: ${processedClaims.length}`);
}
} catch (error) {
console.error("Error loading claims:", error);
if (showToast) {
toast.error("Ошибка загрузки заявок на возврат");
}
} finally {
setLoading(false);
setRefreshing(false);
}
};
// Обработка данных из API в удобный формат
const processClaim = (claim: WBClaim): ProcessedClaim => {
const getStatusLabel = (status: number, statusEx: number) => {
// Мапинг статусов на основе документации API
switch (status) {
case 1:
return "На рассмотрении";
case 2:
return "Одобрена";
case 3:
return "Отклонена";
case 4:
return "В архиве";
default:
return `Статус ${status}`;
}
};
return {
id: claim.id,
productName: claim.imt_name,
nmId: claim.nm_id,
returnDate: claim.dt,
status: getStatusLabel(claim.status, claim.status_ex),
reason: claim.user_comment || "Не указана",
price: claim.price,
userComment: claim.user_comment,
wbComment: claim.wb_comment,
photos: claim.photos || [],
videoPaths: claim.video_paths || [],
actions: claim.actions || [],
orderDate: claim.order_dt,
lastUpdate: claim.dt_update,
};
};
// Загрузка при монтировании компонента
useEffect(() => {
loadClaims();
}, [user, archiveFilter]);
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat("ru-RU", {
@ -77,26 +156,28 @@ export function PvzReturnsTab() {
const getStatusBadge = (status: string) => {
const statusConfig = {
pending: {
"На рассмотрении": {
color: "text-yellow-300 border-yellow-400/30",
label: "Ожидает сбора",
label: "На рассмотрении",
},
collected: {
color: "text-blue-300 border-blue-400/30",
label: "Собрано",
},
processed: {
"Одобрена": {
color: "text-green-300 border-green-400/30",
label: "Обработано",
label: "Одобрена",
},
disposed: {
"Отклонена": {
color: "text-red-300 border-red-400/30",
label: "Утилизировано",
label: "Отклонена",
},
"В архиве": {
color: "text-gray-300 border-gray-400/30",
label: "В архиве",
},
};
const config =
statusConfig[status as keyof typeof statusConfig] || statusConfig.pending;
const config = statusConfig[status as keyof typeof statusConfig] || {
color: "text-gray-300 border-gray-400/30",
label: status,
};
return (
<Badge variant="outline" className={`glass-secondary ${config.color}`}>
@ -105,64 +186,57 @@ export function PvzReturnsTab() {
);
};
const getReasonBadge = (reason: string) => {
const reasonConfig = {
"Брак товара": { color: "text-red-300 border-red-400/30" },
"Не подошел размер": { color: "text-orange-300 border-orange-400/30" },
"Передумал покупать": { color: "text-blue-300 border-blue-400/30" },
Другое: { color: "text-gray-300 border-gray-400/30" },
};
const config =
reasonConfig[reason as keyof typeof reasonConfig] ||
reasonConfig["Другое"];
return (
<Badge
variant="outline"
className={`glass-secondary ${config.color} text-xs`}
>
{reason}
</Badge>
);
};
const filteredReturns = mockPvzReturns.filter((returnItem) => {
const filteredClaims = claims.filter((claim) => {
const matchesSearch =
returnItem.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
returnItem.sku.toLowerCase().includes(searchTerm.toLowerCase()) ||
returnItem.pvzAddress.toLowerCase().includes(searchTerm.toLowerCase()) ||
returnItem.seller.toLowerCase().includes(searchTerm.toLowerCase());
claim.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
claim.nmId.toString().includes(searchTerm) ||
claim.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
claim.id.toLowerCase().includes(searchTerm.toLowerCase());
const matchesStatus =
statusFilter === "all" || returnItem.status === statusFilter;
statusFilter === "all" || claim.status === statusFilter;
return matchesSearch && matchesStatus;
});
const getTotalValue = () => {
return filteredReturns.reduce(
(sum, returnItem) => sum + returnItem.estimatedValue,
0
);
};
const getTotalQuantity = () => {
return filteredReturns.reduce(
(sum, returnItem) => sum + returnItem.quantity,
0
);
return filteredClaims.reduce((sum, claim) => sum + claim.price, 0);
};
const getPendingCount = () => {
return filteredReturns.filter(
(returnItem) => returnItem.status === "pending"
).length;
return filteredClaims.filter((claim) => claim.status === "На рассмотрении")
.length;
};
const getUniqueStatuses = () => {
const statuses = [...new Set(claims.map((claim) => claim.status))];
return statuses;
};
const hasWBApiKey = user?.organization?.apiKeys?.some(
(key) => key.marketplace === "WILDBERRIES" && key.isActive
);
if (!hasWBApiKey) {
return (
<div className="h-full flex flex-col items-center justify-center space-y-4 p-8">
<AlertCircle className="h-12 w-12 text-yellow-400" />
<div className="text-center">
<h3 className="text-lg font-semibold text-white mb-2">
API ключ Wildberries не настроен
</h3>
<p className="text-white/60 mb-4">
Для просмотра заявок на возврат необходимо настроить API ключ
Wildberries в настройках организации.
</p>
</div>
</div>
);
}
return (
<div className="h-full flex flex-col space-y-4 p-4">
{/* Статистика с кнопкой */}
{/* Статистика с кнопками */}
<div className="flex items-center justify-between gap-4">
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 flex-1">
<Card className="glass-card p-3 h-[60px]">
@ -171,9 +245,9 @@ export function PvzReturnsTab() {
<RotateCcw className="h-3 w-3 text-blue-400" />
</div>
<div>
<p className="text-white/60 text-xs">Возвратов</p>
<p className="text-white/60 text-xs">Заявок</p>
<p className="text-lg font-bold text-white">
{filteredReturns.length}
{filteredClaims.length}
</p>
</div>
</div>
@ -185,7 +259,7 @@ export function PvzReturnsTab() {
<AlertCircle className="h-3 w-3 text-yellow-400" />
</div>
<div>
<p className="text-white/60 text-xs">Ожидает сбора</p>
<p className="text-white/60 text-xs">На рассмотрении</p>
<p className="text-lg font-bold text-white">
{getPendingCount()}
</p>
@ -199,7 +273,7 @@ export function PvzReturnsTab() {
<TrendingUp className="h-3 w-3 text-green-400" />
</div>
<div>
<p className="text-white/60 text-xs">Стоимость</p>
<p className="text-white/60 text-xs">Общая стоимость</p>
<p className="text-lg font-bold text-white">
{formatCurrency(getTotalValue())}
</p>
@ -213,22 +287,27 @@ export function PvzReturnsTab() {
<MapPin className="h-3 w-3 text-purple-400" />
</div>
<div>
<p className="text-white/60 text-xs">Товаров</p>
<p className="text-lg font-bold text-white">
{getTotalQuantity()}
</p>
<p className="text-white/60 text-xs">Всего в базе</p>
<p className="text-lg font-bold text-white">{total}</p>
</div>
</div>
</Card>
</div>
<Button
size="sm"
className="bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white text-sm px-6 h-[60px] whitespace-nowrap"
>
<Plus className="h-4 w-4 mr-2" />
Запланировать сбор
</Button>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => loadClaims(true)}
disabled={loading || refreshing}
className="border-white/20 text-white hover:bg-white/10 h-[60px]"
>
<RefreshCw
className={`h-4 w-4 mr-2 ${refreshing ? "animate-spin" : ""}`}
/>
Обновить
</Button>
</div>
</div>
{/* Фильтры */}
@ -236,7 +315,7 @@ export function PvzReturnsTab() {
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/40" />
<Input
placeholder="Поиск по товарам, ПВЗ, селлерам..."
placeholder="Поиск по товару, номеру заявки, причине..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="glass-input pl-10 text-white placeholder:text-white/40"
@ -249,87 +328,175 @@ export function PvzReturnsTab() {
className="glass-input text-white text-sm px-3 py-2 rounded-lg bg-white/5 border border-white/10"
>
<option value="all">Все статусы</option>
<option value="pending">Ожидает сбора</option>
<option value="collected">Собрано</option>
<option value="processed">Обработано</option>
<option value="disposed">Утилизировано</option>
{getUniqueStatuses().map((status) => (
<option key={status} value={status}>
{status}
</option>
))}
</select>
<label className="flex items-center gap-2 text-white text-sm">
<input
type="checkbox"
checked={archiveFilter}
onChange={(e) => setArchiveFilter(e.target.checked)}
className="rounded"
/>
Только архив
</label>
</div>
{/* Список возвратов */}
{/* Список заявок */}
<div className="flex-1 overflow-hidden">
<div className="h-full overflow-y-auto space-y-3">
{filteredReturns.map((returnItem) => (
<Card
key={returnItem.id}
className="glass-card p-4 hover:bg-white/10 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h3 className="text-white font-medium">
{returnItem.productName}
</h3>
{getStatusBadge(returnItem.status)}
{getReasonBadge(returnItem.reason)}
</div>
{loading ? (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
<span className="ml-3 text-white/60">Загрузка заявок...</span>
</div>
) : (
<div className="h-full overflow-y-auto space-y-3">
{filteredClaims.length === 0 ? (
<Card className="glass-card p-8 text-center">
<RotateCcw className="h-12 w-12 text-white/40 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-white mb-2">
{claims.length === 0
? "Нет заявок на возврат"
: "Нет заявок по фильтру"}
</h3>
<p className="text-white/60">
{claims.length === 0
? "Заявки на возврат товаров появятся здесь"
: "Попробуйте изменить параметры фильтрации"}
</p>
</Card>
) : (
filteredClaims.map((claim) => (
<Card
key={claim.id}
className="glass-card p-4 hover:bg-white/10 transition-colors"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3 mb-3">
<h3 className="text-white font-medium">
{claim.productName}
</h3>
{getStatusBadge(claim.status)}
</div>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
<div>
<p className="text-white/60">SKU</p>
<p className="text-white font-mono">{returnItem.sku}</p>
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm mb-3">
<div>
<p className="text-white/60">Артикул WB</p>
<p className="text-white font-mono">{claim.nmId}</p>
</div>
<div>
<p className="text-white/60">ID заявки</p>
<p className="text-white font-mono text-xs">
{claim.id.substring(0, 8)}...
</p>
</div>
<div>
<p className="text-white/60">Стоимость</p>
<p className="text-white font-semibold">
{formatCurrency(claim.price)}
</p>
</div>
<div>
<p className="text-white/60">Дата заявки</p>
<p className="text-white">
{formatDate(claim.returnDate)}
</p>
</div>
</div>
{claim.userComment && (
<div className="mb-3">
<p className="text-white/60 text-sm mb-1">
Комментарий покупателя:
</p>
<p className="text-white text-sm bg-white/5 rounded p-2">
{claim.userComment}
</p>
</div>
)}
{claim.wbComment && (
<div className="mb-3">
<p className="text-white/60 text-sm mb-1">
Ответ WB:
</p>
<p className="text-white text-sm bg-blue-500/10 rounded p-2">
{claim.wbComment}
</p>
</div>
)}
{claim.photos.length > 0 && (
<div className="mb-3">
<p className="text-white/60 text-sm mb-2">
Фотографии ({claim.photos.length}):
</p>
<div className="flex gap-2">
{claim.photos.slice(0, 3).map((photo, index) => (
<a
key={index}
href={`https:${photo}`}
target="_blank"
rel="noopener noreferrer"
className="block w-16 h-16 bg-white/10 rounded overflow-hidden hover:bg-white/20 transition-colors"
>
<img
src={`https:${photo}`}
alt={`Фото ${index + 1}`}
className="w-full h-full object-cover"
/>
</a>
))}
{claim.photos.length > 3 && (
<div className="w-16 h-16 bg-white/10 rounded flex items-center justify-center text-white/60 text-xs">
+{claim.photos.length - 3}
</div>
)}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-white/60">
<span>
Заказ от: {formatDate(claim.orderDate)}
</span>
<span>
Обновлено: {formatDate(claim.lastUpdate)}
</span>
</div>
</div>
<div>
<p className="text-white/60">Селлер</p>
<p className="text-white">{returnItem.seller}</p>
</div>
<div>
<p className="text-white/60">Количество</p>
<p className="text-white font-semibold">
{returnItem.quantity} шт.
</p>
</div>
<div>
<p className="text-white/60">Дата возврата</p>
<p className="text-white">
{formatDate(returnItem.returnDate)}
</p>
<div className="flex items-center gap-2 ml-4">
<Button
size="sm"
variant="ghost"
className="text-white/60 hover:text-white hover:bg-white/10"
title="Подробности"
>
<Eye className="h-4 w-4" />
</Button>
{claim.actions.length > 0 && (
<Button
size="sm"
variant="ghost"
className="text-white/60 hover:text-white hover:bg-white/10"
title="Ответить на заявку"
>
<MessageCircle className="h-4 w-4" />
</Button>
)}
</div>
</div>
<div className="mt-3">
<p className="text-white/60 text-sm flex items-center gap-2">
<MapPin className="h-3 w-3" />
ПВЗ:{" "}
<span className="text-white">
{returnItem.pvzAddress}
</span>
</p>
</div>
<div className="mt-2 flex items-center justify-between">
<span className="text-white/60 text-sm">
Оценочная стоимость:{" "}
<span className="text-green-400 font-semibold">
{formatCurrency(returnItem.estimatedValue)}
</span>
</span>
</div>
</div>
<div className="flex items-center gap-2 ml-4">
<Button
size="sm"
variant="ghost"
className="text-white/60 hover:text-white hover:bg-white/10"
>
<Eye className="h-4 w-4" />
</Button>
</div>
</div>
</Card>
))}
</div>
</Card>
))
)}
</div>
)}
</div>
</div>
);