Обновлен компонент 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>
);

View File

@ -1,301 +1,142 @@
"use client";
import React, { 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";
import { Badge } from "@/components/ui/badge";
import { StatsCard } from "../ui/stats-card";
import { StatsGrid } from "../ui/stats-grid";
import {
ChevronDown,
ChevronRight,
Calendar,
Package,
MapPin,
Building2,
TrendingDown,
AlertTriangle,
DollarSign,
RotateCcw,
RefreshCcw,
Plus,
Search,
TrendingUp,
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";
// Типы данных для возвратов с ПВЗ
interface ReturnProduct {
// Интерфейс для обработанных данных возврата
interface ProcessedClaim {
id: string;
name: string;
sku: string;
category: string;
returnQty: number;
defectQty: number;
returnPrice: number;
returnReason:
| "customer_return"
| "defect"
| "damage"
| "wrong_item"
| "other";
}
interface PvzPoint {
id: string;
name: string;
address: string;
contact: string;
products: ReturnProduct[];
totalAmount: number;
}
interface ReturnRoute {
id: string;
from: string;
fromAddress: string;
to: string;
toAddress: string;
pvzPoints: PvzPoint[];
totalReturnPrice: number;
logisticsPrice: number;
totalAmount: number;
}
interface PvzReturnSupply {
id: string;
number: number;
productName: string;
nmId: number;
returnDate: string;
createdDate: string;
routes: ReturnRoute[];
totalReturnQty: number;
totalDefectQty: number;
totalReturnPrice: number;
totalLogisticsPrice: number;
grandTotal: number;
status: "planned" | "in-transit" | "delivered" | "completed";
status: string;
reason: string;
price: number;
userComment: string;
wbComment: string;
photos: string[];
videoPaths: string[];
actions: string[];
orderDate: string;
lastUpdate: string;
}
// Моковые данные для возвратов с ПВЗ
const mockPvzReturns: PvzReturnSupply[] = [
{
id: "pvz1",
number: 3001,
returnDate: "2024-01-20",
createdDate: "2024-01-15",
status: "delivered",
totalReturnQty: 45,
totalDefectQty: 12,
totalReturnPrice: 890000,
totalLogisticsPrice: 15000,
grandTotal: 905000,
routes: [
{
id: "pvzr1",
from: "ПВЗ Сеть",
fromAddress: "Москва, различные точки",
to: "SFERAV Logistics ФФ",
toAddress: "Москва, ул. Складская, 15",
totalReturnPrice: 890000,
logisticsPrice: 15000,
totalAmount: 905000,
pvzPoints: [
{
id: "pvzp1",
name: 'ПВЗ "На Тверской"',
address: "Москва, ул. Тверская, 15",
contact: "+7 (495) 123-45-67",
totalAmount: 450000,
products: [
{
id: "pvzprod1",
name: "Смартфон iPhone 15 (возврат)",
sku: "APL-IP15-128-RET",
category: "Электроника",
returnQty: 15,
defectQty: 3,
returnPrice: 70000,
returnReason: "customer_return",
},
{
id: "pvzprod2",
name: "Наушники AirPods (брак)",
sku: "APL-AP-PRO2-DEF",
category: "Аудио",
returnQty: 8,
defectQty: 8,
returnPrice: 22000,
returnReason: "defect",
},
],
},
{
id: "pvzp2",
name: 'ПВЗ "Арбатский"',
address: "Москва, ул. Арбат, 25",
contact: "+7 (495) 987-65-43",
totalAmount: 440000,
products: [
{
id: "pvzprod3",
name: "Планшет iPad Air (повреждение)",
sku: "APL-IPAD-AIR-DMG",
category: "Планшеты",
returnQty: 12,
defectQty: 1,
returnPrice: 35000,
returnReason: "damage",
},
],
},
],
},
],
},
{
id: "pvz2",
number: 3002,
returnDate: "2024-01-25",
createdDate: "2024-01-18",
status: "in-transit",
totalReturnQty: 28,
totalDefectQty: 5,
totalReturnPrice: 560000,
totalLogisticsPrice: 12000,
grandTotal: 572000,
routes: [
{
id: "pvzr2",
from: "ПВЗ Сеть Подольск",
fromAddress: "Подольск, различные точки",
to: "MegaFulfillment",
toAddress: "Подольск, ул. Складская, 25",
totalReturnPrice: 560000,
logisticsPrice: 12000,
totalAmount: 572000,
pvzPoints: [
{
id: "pvzp3",
name: 'ПВЗ "Центральный"',
address: "Подольск, ул. Центральная, 10",
contact: "+7 (4967) 55-66-77",
totalAmount: 560000,
products: [
{
id: "pvzprod4",
name: "Ноутбук MacBook (возврат)",
sku: "APL-MBP-14-RET",
category: "Компьютеры",
returnQty: 8,
defectQty: 2,
returnPrice: 180000,
returnReason: "customer_return",
},
],
},
],
},
],
},
];
export function PvzReturnsTab() {
const [expandedSupplies, setExpandedSupplies] = useState<Set<string>>(
new Set()
);
const [expandedRoutes, setExpandedRoutes] = useState<Set<string>>(new Set());
const [expandedPvzPoints, setExpandedPvzPoints] = useState<Set<string>>(
new Set()
);
const [expandedProducts, setExpandedProducts] = useState<Set<string>>(
new Set()
);
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 toggleSupplyExpansion = (supplyId: string) => {
const newExpanded = new Set(expandedSupplies);
if (newExpanded.has(supplyId)) {
newExpanded.delete(supplyId);
} else {
newExpanded.add(supplyId);
// Загрузка заявок
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);
}
setExpandedSupplies(newExpanded);
};
const toggleRouteExpansion = (routeId: string) => {
const newExpanded = new Set(expandedRoutes);
if (newExpanded.has(routeId)) {
newExpanded.delete(routeId);
} else {
newExpanded.add(routeId);
}
setExpandedRoutes(newExpanded);
};
const togglePvzPointExpansion = (pvzPointId: string) => {
const newExpanded = new Set(expandedPvzPoints);
if (newExpanded.has(pvzPointId)) {
newExpanded.delete(pvzPointId);
} else {
newExpanded.add(pvzPointId);
}
setExpandedPvzPoints(newExpanded);
};
const toggleProductExpansion = (productId: string) => {
const newExpanded = new Set(expandedProducts);
if (newExpanded.has(productId)) {
newExpanded.delete(productId);
} else {
newExpanded.add(productId);
}
setExpandedProducts(newExpanded);
};
const getStatusBadge = (status: PvzReturnSupply["status"]) => {
const statusMap = {
planned: {
label: "Запланирован",
color: "bg-blue-500/20 text-blue-300 border-blue-500/30",
},
"in-transit": {
label: "В пути",
color: "bg-yellow-500/20 text-yellow-300 border-yellow-500/30",
},
delivered: {
label: "Доставлен",
color: "bg-green-500/20 text-green-300 border-green-500/30",
},
completed: {
label: "Завершен",
color: "bg-purple-500/20 text-purple-300 border-purple-500/30",
},
// Обработка данных из 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,
};
const { label, color } = statusMap[status];
return <Badge className={`${color} border`}>{label}</Badge>;
};
const getReturnReasonBadge = (reason: ReturnProduct["returnReason"]) => {
const reasonMap = {
customer_return: {
label: "Возврат клиента",
color: "bg-blue-500/20 text-blue-300 border-blue-500/30",
},
defect: {
label: "Брак",
color: "bg-red-500/20 text-red-300 border-red-500/30",
},
damage: {
label: "Повреждение",
color: "bg-orange-500/20 text-orange-300 border-orange-500/30",
},
wrong_item: {
label: "Неправильный товар",
color: "bg-yellow-500/20 text-yellow-300 border-yellow-500/30",
},
other: {
label: "Прочее",
color: "bg-gray-500/20 text-gray-300 border-gray-500/30",
},
};
const { label, color } = reasonMap[reason];
return <Badge className={`${color} border text-xs`}>{label}</Badge>;
};
// Загрузка при монтировании компонента
useEffect(() => {
loadClaims();
}, [user, archiveFilter]);
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat("ru-RU", {
@ -313,420 +154,350 @@ export function PvzReturnsTab() {
});
};
const calculateProductTotal = (product: ReturnProduct) => {
return product.returnQty * product.returnPrice;
const getStatusBadge = (status: string) => {
const statusConfig = {
"На рассмотрении": {
color: "text-yellow-300 border-yellow-400/30",
label: "На рассмотрении",
},
"Одобрена": {
color: "text-green-300 border-green-400/30",
label: "Одобрена",
},
"Отклонена": {
color: "text-red-300 border-red-400/30",
label: "Отклонена",
},
"В архиве": {
color: "text-gray-300 border-gray-400/30",
label: "В архиве",
},
};
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}`}>
{config.label}
</Badge>
);
};
return (
<div className="h-full flex flex-col space-y-6">
{/* Статистика возвратов с ПВЗ */}
<StatsGrid>
<StatsCard
title="Возвратов с ПВЗ"
value={mockPvzReturns.length}
icon={RefreshCcw}
iconColor="text-red-400"
iconBg="bg-red-500/20"
trend={{ value: 7, isPositive: false }}
subtitle="Обработка возвратов"
/>
const filteredClaims = claims.filter((claim) => {
const matchesSearch =
claim.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
claim.nmId.toString().includes(searchTerm) ||
claim.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
claim.id.toLowerCase().includes(searchTerm.toLowerCase());
<StatsCard
title="Сумма возвратов"
value={formatCurrency(
mockPvzReturns.reduce((sum, supply) => sum + supply.grandTotal, 0)
)}
icon={TrendingDown}
iconColor="text-orange-400"
iconBg="bg-orange-500/20"
trend={{ value: 4, isPositive: false }}
subtitle="Общая стоимость"
/>
const matchesStatus =
statusFilter === "all" || claim.status === statusFilter;
<StatsCard
title="В пути"
value={
mockPvzReturns.filter((supply) => supply.status === "in-transit")
.length
}
icon={Calendar}
iconColor="text-yellow-400"
iconBg="bg-yellow-500/20"
subtitle="Активные возвраты"
/>
return matchesSearch && matchesStatus;
});
<StatsCard
title="С дефектами"
value={
mockPvzReturns.filter((supply) => supply.totalDefectQty > 0).length
}
icon={AlertTriangle}
iconColor="text-red-400"
iconBg="bg-red-500/20"
trend={{ value: 15, isPositive: false }}
subtitle="Бракованные товары"
/>
</StatsGrid>
const getTotalValue = () => {
return filteredClaims.reduce((sum, claim) => sum + claim.price, 0);
};
{/* Таблица возвратов с ПВЗ */}
<Card className="bg-white/10 backdrop-blur border-white/20 overflow-hidden flex-1 flex flex-col">
<div className="overflow-auto flex-1">
<table className="w-full">
<thead>
<tr className="border-b border-white/20">
<th className="text-left p-4 text-white font-semibold"></th>
<th className="text-left p-4 text-white font-semibold">
Дата возврата
</th>
<th className="text-left p-4 text-white font-semibold">
Дата создания
</th>
<th className="text-left p-4 text-white font-semibold">
Возвратов
</th>
<th className="text-left p-4 text-white font-semibold">
Дефектов
</th>
<th className="text-left p-4 text-white font-semibold">
Сумма возвратов
</th>
<th className="text-left p-4 text-white font-semibold">
Логистика
</th>
<th className="text-left p-4 text-white font-semibold">
Итого сумма
</th>
<th className="text-left p-4 text-white font-semibold">
Статус
</th>
</tr>
</thead>
<tbody>
{mockPvzReturns.map((supply) => {
const isSupplyExpanded = expandedSupplies.has(supply.id);
const getPendingCount = () => {
return filteredClaims.filter((claim) => claim.status === "На рассмотрении")
.length;
};
return (
<React.Fragment key={supply.id}>
{/* Основная строка возврата */}
<tr
className="border-b border-white/10 hover:bg-white/5 transition-colors bg-red-500/10 cursor-pointer"
onClick={() => toggleSupplyExpansion(supply.id)}
>
<td className="p-4">
<div className="flex items-center space-x-2">
<span className="text-white font-normal text-lg">
{supply.number}
</span>
</div>
</td>
<td className="p-4">
<div className="flex items-center space-x-2">
<Calendar className="h-4 w-4 text-white/40" />
<span className="text-white font-semibold">
{formatDate(supply.returnDate)}
</span>
</div>
</td>
<td className="p-4">
<span className="text-white/80">
{formatDate(supply.createdDate)}
</span>
</td>
<td className="p-4">
<span className="text-white font-semibold">
{supply.totalReturnQty}
</span>
</td>
<td className="p-4">
<span
className={`font-semibold ${
supply.totalDefectQty > 0
? "text-red-400"
: "text-white"
}`}
>
{supply.totalDefectQty}
</span>
</td>
<td className="p-4">
<span className="text-orange-400 font-semibold">
{formatCurrency(supply.totalReturnPrice)}
</span>
</td>
<td className="p-4">
<span className="text-purple-400 font-semibold">
{formatCurrency(supply.totalLogisticsPrice)}
</span>
</td>
<td className="p-4">
<div className="flex items-center space-x-2">
<DollarSign className="h-4 w-4 text-white/40" />
<span className="text-white font-bold text-lg">
{formatCurrency(supply.grandTotal)}
</span>
</div>
</td>
<td className="p-4">{getStatusBadge(supply.status)}</td>
</tr>
const getUniqueStatuses = () => {
const statuses = [...new Set(claims.map((claim) => claim.status))];
return statuses;
};
{/* Развернутые уровни - аналогично другим компонентам */}
{isSupplyExpanded &&
supply.routes.map((route) => {
const isRouteExpanded = expandedRoutes.has(route.id);
return (
<React.Fragment key={route.id}>
<tr className="border-b border-white/10 hover:bg-white/5 transition-colors bg-blue-500/10">
<td className="p-4 pl-12">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() =>
toggleRouteExpansion(route.id)
}
className="h-6 w-6 p-0 text-white/60 hover:text-white hover:bg-white/10"
>
{isRouteExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</Button>
<MapPin className="h-4 w-4 text-blue-400" />
<span className="text-white font-medium">
Маршрут возврата
</span>
</div>
</td>
<td className="p-4" colSpan={2}>
<div className="text-white">
<div className="flex items-center space-x-2 mb-1">
<span className="font-medium">
{route.from}
</span>
<span className="text-white/60"></span>
<span className="font-medium">
{route.to}
</span>
</div>
<div className="text-xs text-white/60">
{route.fromAddress} {route.toAddress}
</div>
</div>
</td>
<td className="p-4">
<span className="text-white/80">
{route.pvzPoints.reduce(
(sum, p) =>
sum +
p.products.reduce(
(pSum, prod) => pSum + prod.returnQty,
0
),
0
)}
</span>
</td>
<td className="p-4">
<span className="text-white/80">
{route.pvzPoints.reduce(
(sum, p) =>
sum +
p.products.reduce(
(pSum, prod) => pSum + prod.defectQty,
0
),
0
)}
</span>
</td>
<td className="p-4">
<span className="text-orange-400 font-medium">
{formatCurrency(route.totalReturnPrice)}
</span>
</td>
<td className="p-4">
<span className="text-purple-400 font-medium">
{formatCurrency(route.logisticsPrice)}
</span>
</td>
<td className="p-4">
<span className="text-white font-semibold">
{formatCurrency(route.totalAmount)}
</span>
</td>
<td className="p-4"></td>
</tr>
const hasWBApiKey = user?.organization?.apiKeys?.some(
(key) => key.marketplace === "WILDBERRIES" && key.isActive
);
{/* ПВЗ точки */}
{isRouteExpanded &&
route.pvzPoints.map((pvzPoint) => {
const isPvzPointExpanded =
expandedPvzPoints.has(pvzPoint.id);
return (
<React.Fragment key={pvzPoint.id}>
<tr className="border-b border-white/10 hover:bg-white/5 transition-colors bg-green-500/10">
<td className="p-4 pl-20">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() =>
togglePvzPointExpansion(
pvzPoint.id
)
}
className="h-6 w-6 p-0 text-white/60 hover:text-white hover:bg-white/10"
>
{isPvzPointExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</Button>
<Building2 className="h-4 w-4 text-green-400" />
<span className="text-white font-medium">
ПВЗ
</span>
</div>
</td>
<td className="p-4" colSpan={2}>
<div className="text-white">
<div className="font-medium mb-1">
{pvzPoint.name}
</div>
<div className="text-xs text-white/60 mb-1">
{pvzPoint.address}
</div>
<div className="text-xs text-white/60">
{pvzPoint.contact}
</div>
</div>
</td>
<td className="p-4">
<span className="text-white/80">
{pvzPoint.products.reduce(
(sum, p) => sum + p.returnQty,
0
)}
</span>
</td>
<td className="p-4">
<span className="text-white/80">
{pvzPoint.products.reduce(
(sum, p) => sum + p.defectQty,
0
)}
</span>
</td>
<td className="p-4">
<span className="text-orange-400 font-medium">
{formatCurrency(
pvzPoint.products.reduce(
(sum, p) =>
sum + calculateProductTotal(p),
0
)
)}
</span>
</td>
<td className="p-4"></td>
<td className="p-4">
<span className="text-white font-semibold">
{formatCurrency(pvzPoint.totalAmount)}
</span>
</td>
<td className="p-4"></td>
</tr>
{/* Возвращенные товары */}
{isPvzPointExpanded &&
pvzPoint.products.map((product) => (
<tr
key={product.id}
className="border-b border-white/10 hover:bg-white/5 transition-colors bg-yellow-500/10"
>
<td className="p-4 pl-28">
<div className="flex items-center space-x-2">
<Package className="h-4 w-4 text-yellow-400" />
<span className="text-white font-medium">
Возврат
</span>
</div>
</td>
<td className="p-4" colSpan={2}>
<div className="text-white">
<div className="font-medium mb-1">
{product.name}
</div>
<div className="text-xs text-white/60 mb-1">
Артикул: {product.sku}
</div>
<div className="flex gap-2">
<Badge className="bg-gray-500/20 text-gray-300 border-gray-500/30 border text-xs">
{product.category}
</Badge>
{getReturnReasonBadge(
product.returnReason
)}
</div>
</div>
</td>
<td className="p-4">
<span className="text-white font-semibold">
{product.returnQty}
</span>
</td>
<td className="p-4">
<span
className={`font-semibold ${
product.defectQty > 0
? "text-red-400"
: "text-white"
}`}
>
{product.defectQty}
</span>
</td>
<td className="p-4">
<div className="text-white">
<div className="font-medium">
{formatCurrency(
calculateProductTotal(product)
)}
</div>
<div className="text-xs text-white/60">
{formatCurrency(
product.returnPrice
)}{" "}
за шт.
</div>
</div>
</td>
<td className="p-4"></td>
<td className="p-4">
<span className="text-white font-semibold">
{formatCurrency(
calculateProductTotal(product)
)}
</span>
</td>
<td className="p-4"></td>
</tr>
))}
</React.Fragment>
);
})}
</React.Fragment>
);
})}
</React.Fragment>
);
})}
</tbody>
</table>
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>
</Card>
</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]">
<div className="flex items-center space-x-2 h-full">
<div className="p-1.5 bg-blue-500/20 rounded">
<RotateCcw className="h-3 w-3 text-blue-400" />
</div>
<div>
<p className="text-white/60 text-xs">Заявок</p>
<p className="text-lg font-bold text-white">
{filteredClaims.length}
</p>
</div>
</div>
</Card>
<Card className="glass-card p-3 h-[60px]">
<div className="flex items-center space-x-2 h-full">
<div className="p-1.5 bg-yellow-500/20 rounded">
<AlertCircle className="h-3 w-3 text-yellow-400" />
</div>
<div>
<p className="text-white/60 text-xs">На рассмотрении</p>
<p className="text-lg font-bold text-white">
{getPendingCount()}
</p>
</div>
</div>
</Card>
<Card className="glass-card p-3 h-[60px]">
<div className="flex items-center space-x-2 h-full">
<div className="p-1.5 bg-green-500/20 rounded">
<TrendingUp className="h-3 w-3 text-green-400" />
</div>
<div>
<p className="text-white/60 text-xs">Общая стоимость</p>
<p className="text-lg font-bold text-white">
{formatCurrency(getTotalValue())}
</p>
</div>
</div>
</Card>
<Card className="glass-card p-3 h-[60px]">
<div className="flex items-center space-x-2 h-full">
<div className="p-1.5 bg-purple-500/20 rounded">
<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">{total}</p>
</div>
</div>
</Card>
</div>
<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>
{/* Фильтры */}
<div className="flex items-center gap-3">
<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="Поиск по товару, номеру заявки, причине..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="glass-input pl-10 text-white placeholder:text-white/40"
/>
</div>
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="glass-input text-white text-sm px-3 py-2 rounded-lg bg-white/5 border border-white/10"
>
<option value="all">Все статусы</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">
{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 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 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>
</Card>
))
)}
</div>
)}
</div>
</div>
);
}

View File

@ -335,6 +335,49 @@ export interface WBStatisticsData {
buyoutPercentage: number
}
export interface WBClaimStatus {
1: 'На рассмотрении'
2: 'Одобрена'
3: 'Отклонена'
4: 'В архиве'
}
export interface WBClaimType {
1: 'Претензия'
2: 'Возврат'
}
export interface WBClaim {
id: string
claim_type: number
status: number
status_ex: number
nm_id: number
user_comment: string
wb_comment: string
dt: string
imt_name: string
order_dt: string
dt_update: string
photos: string[]
video_paths: string[]
actions: string[]
price: number
currency_code: string
srid: string
}
export interface WBClaimsResponse {
claims: WBClaim[]
total: number
}
export interface WBClaimResponseRequest {
id: string
action: string
comment?: string
}
class WildberriesService {
private apiKey: string
private baseURL = 'https://statistics-api.wildberries.ru'
@ -1260,6 +1303,70 @@ class WildberriesService {
}
}
// Получение заявок покупателей на возврат товаров
async getClaims(options: {
isArchive: boolean
id?: string
limit?: number
offset?: number
nmId?: number
}): Promise<WBClaimsResponse> {
const { isArchive, id, limit = 50, offset = 0, nmId } = options
// Используем правильный API endpoint для возвратов
let url = `https://returns-api.wildberries.ru/api/v1/claims?is_archive=${isArchive}`
if (id) url += `&id=${id}`
if (limit) url += `&limit=${limit}`
if (offset) url += `&offset=${offset}`
if (nmId) url += `&nm_id=${nmId}`
console.log(`WB Claims API: Getting customer claims from ${url}`)
try {
const response = await this.makeRequest<WBClaimsResponse>(url, {
method: 'GET'
})
console.log(`WB Claims API: Got ${response.claims?.length || 0} claims, total: ${response.total || 0}`)
return response
} catch (error) {
console.error(`WB Claims API: Error getting claims:`, error)
return { claims: [], total: 0 }
}
}
// Ответ на заявку покупателя на возврат
async respondToClaim(request: WBClaimResponseRequest): Promise<boolean> {
const url = `https://returns-api.wildberries.ru/api/v1/claim`
console.log(`WB Claims API: Responding to claim ${request.id} with action ${request.action}`)
try {
await this.makeRequest(url, {
method: 'PATCH',
body: JSON.stringify(request)
})
console.log(`WB Claims API: Successfully responded to claim ${request.id}`)
return true
} catch (error) {
console.error(`WB Claims API: Error responding to claim:`, error)
return false
}
}
// Статический метод для получения заявок с токеном
static async getClaims(apiKey: string, options: {
isArchive: boolean
id?: string
limit?: number
offset?: number
nmId?: number
}): Promise<WBClaimsResponse> {
const service = new WildberriesService(apiKey)
return service.getClaims(options)
}
}