Добавлены новые зависимости: react-datepicker и обновлены импорты в компоненте WBProductCards. Реализован новый функционал для выбора даты поставки с использованием календаря. Обновлены компоненты для улучшения взаимодействия с пользователем и оптимизации кода.

This commit is contained in:
Bivekich
2025-07-23 15:16:10 +03:00
parent 5bb38574fe
commit 158411cc98
15 changed files with 1896 additions and 1079 deletions

View File

@ -8,8 +8,10 @@ import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Calendar as CalendarComponent } from '@/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import DatePicker from "react-datepicker"
import "react-datepicker/dist/react-datepicker.css"
import { Sidebar } from '@/components/dashboard/sidebar'
import { useSidebar } from '@/hooks/useSidebar'
import {
@ -17,7 +19,7 @@ import {
Plus,
Minus,
ShoppingCart,
Calendar,
Calendar as CalendarIcon,
Phone,
User,
MapPin,
@ -42,6 +44,8 @@ import { SelectedCard, FulfillmentService, ConsumableService, WildberriesCard }
interface Organization {
id: string
name?: string
@ -52,17 +56,29 @@ interface Organization {
interface WBProductCardsProps {
onBack: () => void
onComplete: (selectedCards: SelectedCard[]) => void
showSummary?: boolean
setShowSummary?: (show: boolean) => void
selectedCards?: SelectedCard[]
setSelectedCards?: (cards: SelectedCard[]) => void
}
export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
export function WBProductCards({ onBack, onComplete, showSummary: externalShowSummary, setShowSummary: externalSetShowSummary, selectedCards: externalSelectedCards, setSelectedCards: externalSetSelectedCards }: WBProductCardsProps) {
const { user } = useAuth()
const { getSidebarMargin } = useSidebar()
const [searchTerm, setSearchTerm] = useState('')
const [loading, setLoading] = useState(false)
const [wbCards, setWbCards] = useState<WildberriesCard[]>([])
const [selectedCards, setSelectedCards] = useState<SelectedCard[]>([]) // Товары в корзине
// Используем внешнее состояние если передано
const actualSelectedCards = externalSelectedCards !== undefined ? externalSelectedCards : selectedCards
const actualSetSelectedCards = externalSetSelectedCards || setSelectedCards
const [preparingCards, setPreparingCards] = useState<SelectedCard[]>([]) // Товары, готовящиеся к добавлению
const [showSummary, setShowSummary] = useState(false)
// Используем внешнее состояние если передано
const actualShowSummary = externalShowSummary !== undefined ? externalShowSummary : showSummary
const actualSetShowSummary = externalSetShowSummary || setShowSummary
const [globalDeliveryDate, setGlobalDeliveryDate] = useState<Date | undefined>(undefined)
const [fulfillmentServices, setFulfillmentServices] = useState<FulfillmentService[]>([])
const [organizationServices, setOrganizationServices] = useState<{[orgId: string]: Array<{id: string, name: string, description?: string, price: number}>}>({})
@ -243,7 +259,7 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
// Автоматически загружаем услуги и расходники для уже выбранных организаций
useEffect(() => {
selectedCards.forEach(sc => {
actualSelectedCards.forEach(sc => {
if (sc.selectedFulfillmentOrg && !organizationServices[sc.selectedFulfillmentOrg]) {
loadOrganizationServices(sc.selectedFulfillmentOrg)
}
@ -541,24 +557,22 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
return
}
setSelectedCards(prev => {
const newCards = [...prev]
validCards.forEach(prepCard => {
const cardWithDate = {
...prepCard,
deliveryDate: globalDeliveryDate.toISOString().split('T')[0]
}
const existingIndex = newCards.findIndex(sc => sc.card.nmID === prepCard.card.nmID)
if (existingIndex >= 0) {
// Обновляем существующий товар
newCards[existingIndex] = cardWithDate
} else {
// Добавляем новый товар
newCards.push(cardWithDate)
}
})
return newCards
const newCards = [...actualSelectedCards]
validCards.forEach(prepCard => {
const cardWithDate = {
...prepCard,
deliveryDate: globalDeliveryDate.toISOString().split('T')[0]
}
const existingIndex = newCards.findIndex(sc => sc.card.nmID === prepCard.card.nmID)
if (existingIndex >= 0) {
// Обновляем существующий товар
newCards[existingIndex] = cardWithDate
} else {
// Добавляем новый товар
newCards.push(cardWithDate)
}
})
actualSetSelectedCards(newCards)
// Очищаем подготовленные товары
setPreparingCards([])
@ -621,7 +635,7 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
}
const getTotalAmount = () => {
return selectedCards.reduce((sum, sc) => {
return actualSelectedCards.reduce((sum, sc) => {
const additionalCostPerUnit = calculateAdditionalCostPerUnit(sc)
const totalCostPerUnit = (sc.customPrice / sc.selectedQuantity) + additionalCostPerUnit
const totalCostForAllItems = totalCostPerUnit * sc.selectedQuantity
@ -630,7 +644,7 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
}
const getTotalItems = () => {
return selectedCards.reduce((sum, sc) => sum + sc.selectedQuantity, 0)
return actualSelectedCards.reduce((sum, sc) => sum + sc.selectedQuantity, 0)
}
// Функция больше не нужна, так как услуги выбираются индивидуально
@ -667,7 +681,7 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
try {
const supplyInput = {
deliveryDate: selectedCards[0]?.deliveryDate || null,
cards: selectedCards.map(sc => ({
cards: actualSelectedCards.map(sc => ({
nmId: sc.card.nmID.toString(),
vendorCode: sc.card.vendorCode,
title: sc.card.title,
@ -689,7 +703,7 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
}
}
if (showSummary) {
if (actualShowSummary) {
return (
<div className="h-screen flex overflow-hidden">
<Sidebar />
@ -700,30 +714,115 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
<Button
variant="ghost"
size="sm"
onClick={() => setShowSummary(false)}
onClick={() => actualSetShowSummary(false)}
className="text-white/60 hover:text-white hover:bg-white/10"
>
<ArrowLeft className="h-4 w-4 mr-2" />
Назад к товарам
Назад
</Button>
<div>
<h2 className="text-2xl font-bold text-white mb-1">Сводка заказа</h2>
<p className="text-white/60">Проверьте данные перед созданием поставки</p>
<h2 className="text-2xl font-bold text-white mb-1">Корзина</h2>
<p className="text-white/60">{actualSelectedCards.length} карточек товаров</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onBack}
className="text-white/60 hover:text-white hover:bg-white/10"
>
Отмена
</Button>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-4">
{selectedCards.map((sc) => {
{/* Массовое назначение поставщиков */}
<Card className="bg-blue-500/10 backdrop-blur border-blue-500/20 p-4 mb-6">
<h3 className="text-white font-semibold mb-4">Быстрое назначение</h3>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="text-white/60 text-sm mb-2 block">Поставщик услуг для всех товаров:</label>
<Select onValueChange={(value) => {
if (value && value !== 'none') {
// Загружаем услуги для выбранной организации
loadOrganizationServices(value)
actualSelectedCards.forEach(sc => {
updateCardSelection(sc.card, 'selectedFulfillmentOrg', value)
// Сбрасываем выбранные услуги при смене организации
updateCardSelection(sc.card, 'selectedFulfillmentServices', [])
})
}
}}>
<SelectTrigger className="bg-white/5 border-white/20 text-white">
<SelectValue placeholder="Выберите поставщика" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Не выбран</SelectItem>
{((counterpartiesData?.myCounterparties || []).filter((org: Organization) => org.type === 'FULFILLMENT')).map((org: Organization) => (
<SelectItem key={org.id} value={org.id}>
{org.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<label className="text-white/60 text-sm mb-2 block">Поставщик расходников для всех:</label>
<Select onValueChange={(value) => {
if (value && value !== 'none') {
// Загружаем расходники для выбранной организации
loadOrganizationSupplies(value)
actualSelectedCards.forEach(sc => {
updateCardSelection(sc.card, 'selectedConsumableOrg', value)
// Сбрасываем выбранные расходники при смене организации
updateCardSelection(sc.card, 'selectedConsumableServices', [])
})
}
}}>
<SelectTrigger className="bg-white/5 border-white/20 text-white">
<SelectValue placeholder="Выберите поставщика" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Не выбран</SelectItem>
{((counterpartiesData?.myCounterparties || []).filter((org: Organization) => org.type === 'FULFILLMENT')).map((org: Organization) => (
<SelectItem key={org.id} value={org.id}>
{org.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<label className="text-white/60 text-sm mb-2 block">Дата поставки для всех:</label>
<Popover>
<PopoverTrigger asChild>
<button
className="w-full bg-white/5 border border-white/20 text-white hover:bg-white/10 justify-start text-left font-normal h-10 px-3 py-2 rounded-md flex items-center transition-colors"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{globalDeliveryDate ? format(globalDeliveryDate, "dd.MM.yyyy") : "Выберите дату"}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<DatePicker
selected={globalDeliveryDate}
onChange={(date: Date | null) => {
setGlobalDeliveryDate(date || undefined)
if (date) {
const dateString = date.toISOString().split('T')[0]
actualSelectedCards.forEach(sc => {
updateCardSelection(sc.card, 'deliveryDate', dateString)
})
}
}}
minDate={new Date()}
inline
locale="ru"
/>
</PopoverContent>
</Popover>
</div>
</div>
</Card>
<div className="grid grid-cols-1 xl:grid-cols-4 gap-6">
<div className="xl:col-span-3 space-y-4">
{actualSelectedCards.map((sc) => {
const fulfillmentOrgs = (counterpartiesData?.myCounterparties || []).filter((org: Organization) => org.type === 'FULFILLMENT')
const consumableOrgs = (counterpartiesData?.myCounterparties || []).filter((org: Organization) => org.type === 'FULFILLMENT')
@ -962,21 +1061,21 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
})}
</div>
<div className="lg:col-span-1">
<Card className="bg-white/10 backdrop-blur border-white/20 p-6 sticky top-4">
<div className="xl:col-span-1">
<Card className="bg-white/10 backdrop-blur border-white/20 p-4 sticky top-4">
<h3 className="text-white font-semibold text-lg mb-4">Итого</h3>
<div className="space-y-3">
<div className="flex justify-between">
<div className="flex justify-between text-sm">
<span className="text-white/60">Товаров:</span>
<span className="text-white">{getTotalItems()}</span>
</div>
<div className="flex justify-between">
<div className="flex justify-between text-sm">
<span className="text-white/60">Карточек:</span>
<span className="text-white">{selectedCards.length}</span>
<span className="text-white">{actualSelectedCards.length}</span>
</div>
<div className="border-t border-white/20 pt-3 flex justify-between">
<span className="text-white font-semibold">Общая сумма:</span>
<span className="text-white font-bold text-xl">{formatCurrency(getTotalAmount())}</span>
<span className="text-white font-bold text-lg">{formatCurrency(getTotalAmount())}</span>
</div>
<Button
className="w-full bg-gradient-to-r from-green-500 to-emerald-500 hover:from-green-600 hover:to-emerald-600 text-white"
@ -998,18 +1097,6 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
return (
<div className="space-y-4">
<div className="flex items-center justify-end">
{selectedCards.length > 0 && (
<Button
onClick={() => setShowSummary(true)}
className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white"
>
<ShoppingCart className="h-4 w-4 mr-2" />
Корзина ({getTotalItems()})
</Button>
)}
</div>
{/* Поиск */}
{/* Поиск товаров и выбор даты поставки */}
@ -1030,62 +1117,26 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
<div className="w-44">
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="sm"
className="w-full justify-start text-left font-normal bg-white/5 border-white/20 text-white hover:bg-white/10 hover:text-white h-9 text-xs"
<button
className="w-full justify-start text-left font-normal bg-white/5 border border-white/20 text-white hover:bg-white/10 h-9 text-xs px-3 py-2 rounded-md flex items-center transition-colors"
>
<Calendar className="mr-1 h-3 w-3" />
<CalendarIcon className="mr-1 h-3 w-3" />
{globalDeliveryDate ? (
format(globalDeliveryDate, "dd.MM.yy", { locale: ru })
) : (
<span className="text-white/50">Дата поставки</span>
)}
</Button>
</button>
</PopoverTrigger>
<PopoverContent className="w-72 p-0 glass-card" align="end">
<div className="p-4 border-b border-white/10">
<p className="text-white font-medium text-sm">Дата поставки</p>
<p className="text-white/60 text-xs">Выберите дату для всех товаров</p>
</div>
<CalendarComponent
mode="single"
selected={globalDeliveryDate}
onSelect={setGlobalDeliveryDate}
disabled={(date) => date < new Date()}
initialFocus
locale={ru}
className="glass-card border-0 p-3"
classNames={{
months: "flex flex-col space-y-3",
month: "space-y-3",
caption: "flex justify-center pt-2 relative items-center",
caption_label: "text-sm font-medium text-white",
nav: "space-x-1 flex items-center",
nav_button: "h-7 w-7 glass-secondary text-white hover:bg-white/20 hover:text-white rounded-md border-white/20",
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell: "text-white/70 rounded-md w-9 font-normal text-xs",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-xs p-0 relative focus-within:relative focus-within:z-20",
day: "h-9 w-9 p-0 font-normal text-white hover:bg-white/15 hover:text-white rounded-md transition-colors",
day_selected: "glass-button text-white hover:bg-gradient-to-r hover:from-purple-500 hover:to-pink-500",
day_today: "bg-white/15 text-white font-semibold border border-white/30",
day_outside: "text-white/30 opacity-50",
day_disabled: "text-white/20 opacity-30",
}}
/>
{globalDeliveryDate && (
<div className="p-4 border-t border-white/10">
<Badge className="glass-secondary text-white border-white/20 text-xs">
<Calendar className="h-3 w-3 mr-1" />
{format(globalDeliveryDate, "dd MMMM yyyy", { locale: ru })}
</Badge>
</div>
)}
</PopoverContent>
<PopoverContent className="w-auto p-0" align="end">
<DatePicker
selected={globalDeliveryDate}
onChange={(date: Date | null) => setGlobalDeliveryDate(date || undefined)}
minDate={new Date()}
inline
locale="ru"
/>
</PopoverContent>
</Popover>
</div>
@ -1127,7 +1178,7 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
{wbCards.map((card) => {
const selectedQuantity = getSelectedQuantity(card)
const isSelected = selectedQuantity > 0
const selectedCard = selectedCards.find(sc => sc.card.nmID === card.nmID)
const selectedCard = actualSelectedCards.find(sc => sc.card.nmID === card.nmID)
return (
<Card key={card.nmID} className={`bg-white/10 backdrop-blur border-white/20 transition-all hover:scale-105 hover:shadow-2xl group ${isSelected ? 'ring-2 ring-purple-500/50 bg-purple-500/10' : ''} relative overflow-hidden`}>
@ -1210,9 +1261,9 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
updateCardSelection(card, 'selectedQuantity', newQuantity)
}}
disabled={selectedQuantity <= 0}
className="h-7 w-7 p-0 text-white/60 hover:text-white hover:bg-white/10 border border-white/20 disabled:opacity-50"
className="h-6 w-6 p-0 text-white/60 hover:text-white hover:bg-white/10 border border-white/20 disabled:opacity-50 flex-shrink-0"
>
<Minus className="h-3 w-3" />
<Minus className="h-2.5 w-2.5" />
</Button>
<input
type="text"
@ -1225,8 +1276,8 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
updateCardSelection(card, 'selectedQuantity', numValue)
}}
onFocus={(e) => e.target.select()}
className="flex-1 h-7 text-center bg-white/10 border border-white/20 text-white text-xs rounded focus:outline-none focus:ring-1 focus:ring-purple-500 focus:border-transparent [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
placeholder="Кол-во"
className="flex-1 h-6 text-center bg-white/10 border border-white/20 text-white text-xs rounded focus:outline-none focus:ring-1 focus:ring-purple-500 focus:border-transparent [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none min-w-0"
placeholder="0"
/>
<Button
variant="ghost"
@ -1235,9 +1286,9 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
const newQuantity = selectedQuantity + 1
updateCardSelection(card, 'selectedQuantity', newQuantity)
}}
className="h-7 w-7 p-0 text-white/60 hover:text-white hover:bg-white/10 border border-white/20"
className="h-6 w-6 p-0 text-white/60 hover:text-white hover:bg-white/10 border border-white/20 flex-shrink-0"
>
<Plus className="h-3 w-3" />
<Plus className="h-2.5 w-2.5" />
</Button>
</div>
@ -1253,8 +1304,8 @@ export function WBProductCards({ onBack, onComplete }: WBProductCardsProps) {
updateCardSelection(card, 'customPrice', totalPrice)
}}
onFocus={(e) => e.target.select()}
className="w-full h-7 text-center bg-white/10 border border-white/20 text-white text-xs rounded focus:outline-none focus:ring-1 focus:ring-green-500 focus:border-transparent"
placeholder={`Общая цена за ${selectedQuantity} шт`}
className="w-full h-6 text-center bg-white/10 border border-white/20 text-white text-xs rounded focus:outline-none focus:ring-1 focus:ring-green-500 focus:border-transparent"
placeholder={`Цена за ${selectedQuantity} шт`}
/>
)}