420 lines
15 KiB
TypeScript
420 lines
15 KiB
TypeScript
import React, { useState, useEffect, useMemo } from 'react'
|
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
|
import { Save, Pencil, EllipsisVertical, Shuffle } from 'lucide-react'
|
|
import {
|
|
AppContainer,
|
|
p as MyText,
|
|
pInput as MyTextInput,
|
|
BottomDialog,
|
|
Checkbox,
|
|
MyFlatList,
|
|
} from 'web-components'
|
|
import MultiSelect from '@/components/MultiSelect'
|
|
import { trpc } from '@/lib/trpc-client'
|
|
|
|
export const Route = createFileRoute('/dashboard/prices')({
|
|
component: PricesOverview,
|
|
})
|
|
|
|
interface SkuItemProps {
|
|
sku: any
|
|
productName: string
|
|
hasChanges: (skuId: number) => boolean
|
|
pendingChanges: Record<string, any>
|
|
setPendingChanges: React.Dispatch<React.SetStateAction<Record<string, any>>>
|
|
openEditDialog: (sku: any, productName: string) => void
|
|
}
|
|
|
|
const SkuItemComponent: React.FC<SkuItemProps> = ({
|
|
sku,
|
|
productName,
|
|
hasChanges,
|
|
pendingChanges,
|
|
setPendingChanges,
|
|
openEditDialog,
|
|
}) => {
|
|
const changed = hasChanges(sku.id)
|
|
const change = pendingChanges[sku.id] || {}
|
|
const displayPrice = change.price !== undefined ? change.price : sku.price
|
|
const displayMarketPrice = change.marketPrice !== undefined ? change.marketPrice : sku.marketPrice
|
|
const displayFlashPrice = change.flashPrice !== undefined ? change.flashPrice : sku.flashPrice
|
|
const displayUnit = (sku.features || []).map((f: any) => f.featureValue).join(' ') || '—'
|
|
|
|
return (
|
|
<div className="relative mb-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
|
|
<div className="absolute right-2 top-2">
|
|
<div
|
|
className={`flex h-4 w-4 items-center justify-center rounded-full ${changed ? 'bg-green-500' : 'bg-gray-300'}`}
|
|
>
|
|
{changed && (
|
|
<svg width={10} height={10} viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth={3} strokeLinecap="round" strokeLinejoin="round">
|
|
<polyline points="20 6 9 17 4 12" />
|
|
</svg>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mb-2 flex flex-row items-center">
|
|
<img
|
|
src={sku.images?.[0] || 'https://via.placeholder.com/32x32?text=No+Image'}
|
|
className="mr-3 h-10 w-10 rounded-lg object-cover"
|
|
alt=""
|
|
/>
|
|
|
|
<div className="flex flex-1 flex-row items-center">
|
|
<div className="flex-1">
|
|
<MyText className="text-base font-medium text-gray-800" numberOfLines={1}>
|
|
{productName.length > 20 ? productName.substring(0, 20) + '...' : productName}
|
|
</MyText>
|
|
<MyText className="text-xs text-gray-500" numberOfLines={1}>
|
|
{sku.displayName || sku.name || ''}
|
|
</MyText>
|
|
</div>
|
|
<div className="ml-2 flex flex-row items-center">
|
|
<span className="mr-1">
|
|
<Checkbox
|
|
checked={change.isFlashAvailable ?? sku.isFlashAvailable ?? false}
|
|
onPress={() => {
|
|
const currentValue = change.isFlashAvailable ?? sku.isFlashAvailable ?? false
|
|
setPendingChanges((prev) => ({
|
|
...prev,
|
|
[sku.id]: {
|
|
...prev[sku.id],
|
|
isFlashAvailable: !currentValue,
|
|
},
|
|
}))
|
|
}}
|
|
/>
|
|
</span>
|
|
<MyText className="text-sm text-gray-600">Flash</MyText>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-row items-center justify-between">
|
|
<div className="flex flex-col items-center">
|
|
<MyText className="mb-1 text-xs text-gray-500">Our Price</MyText>
|
|
<div className="flex flex-row items-center">
|
|
<MyText className="text-sm font-bold text-green-600">₹{displayPrice}</MyText>
|
|
<button onClick={() => openEditDialog(sku, productName)} className="ml-1">
|
|
<Pencil size={14} color="#6b7280" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-col items-center">
|
|
<MyText className="mb-1 text-xs text-gray-500">Market Price</MyText>
|
|
<div className="flex flex-row items-center">
|
|
<MyText className="text-sm text-gray-600">{displayMarketPrice ? `₹${displayMarketPrice}` : 'N/A'}</MyText>
|
|
<button onClick={() => openEditDialog(sku, productName)} className="ml-1">
|
|
<Pencil size={14} color="#6b7280" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-col items-center">
|
|
<MyText className="mb-1 text-xs text-gray-500">Flash Price</MyText>
|
|
<div className="flex flex-row items-center">
|
|
<MyText className="text-sm text-orange-600">{displayFlashPrice ? `₹${displayFlashPrice}` : 'N/A'}</MyText>
|
|
<button onClick={() => openEditDialog(sku, productName)} className="ml-1">
|
|
<Pencil size={14} color="#6b7280" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-col items-center">
|
|
<MyText className="mb-1 text-xs text-gray-500">Size</MyText>
|
|
<div className="flex flex-row items-center">
|
|
<MyText className="text-sm text-blue-600">{displayUnit}</MyText>
|
|
<button onClick={() => openEditDialog(sku, productName)} className="ml-1">
|
|
<Pencil size={14} color="#6b7280" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
interface PendingChange {
|
|
price?: number
|
|
marketPrice?: number | null
|
|
flashPrice?: number | null
|
|
isFlashAvailable?: boolean
|
|
}
|
|
|
|
interface EditDialogState {
|
|
open: boolean
|
|
sku: any
|
|
productName: string
|
|
tempPrice: string
|
|
tempMarketPrice: string
|
|
tempFlashPrice: string
|
|
}
|
|
|
|
function PricesOverview() {
|
|
const navigate = useNavigate()
|
|
const [selectedStores, setSelectedStores] = useState<string[]>([])
|
|
const [pendingChanges, setPendingChanges] = useState<Record<number, PendingChange>>({})
|
|
const [editDialog, setEditDialog] = useState<EditDialogState>({
|
|
open: false,
|
|
sku: null,
|
|
productName: '',
|
|
tempPrice: '',
|
|
tempMarketPrice: '',
|
|
tempFlashPrice: '',
|
|
})
|
|
const [showMenu, setShowMenu] = useState(false)
|
|
|
|
const { data: productsData, isLoading: productsLoading, refetch: refetchProducts } =
|
|
trpc.admin.product.getProducts.useQuery()
|
|
const { data: storesData, isLoading: storesLoading } =
|
|
trpc.admin.store.getStores.useQuery()
|
|
|
|
const updatePricesMutation = trpc.admin.product.updateProductPrices.useMutation()
|
|
|
|
const stores = storesData?.stores || []
|
|
const allProducts = productsData?.products || []
|
|
|
|
const sortedStores = useMemo(() =>
|
|
[...stores].sort((a, b) => a.name.localeCompare(b.name)),
|
|
[stores]
|
|
)
|
|
|
|
const storeOptions = useMemo(() =>
|
|
sortedStores.map((store) => ({
|
|
label: store.name,
|
|
value: store.id.toString(),
|
|
})),
|
|
[sortedStores]
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (stores.length > 0 && selectedStores.length === 0) {
|
|
setSelectedStores(stores.map((s) => s.id.toString()))
|
|
}
|
|
}, [stores, selectedStores])
|
|
|
|
const allSkus = useMemo(() => {
|
|
const skus: any[] = []
|
|
for (const product of allProducts) {
|
|
if (product.skus && product.skus.length > 0) {
|
|
for (const sku of product.skus) {
|
|
skus.push({ ...sku, _productName: product.name, _storeId: product.storeId })
|
|
}
|
|
}
|
|
}
|
|
return skus
|
|
}, [allProducts])
|
|
|
|
const filteredSkus = useMemo(() => {
|
|
if (selectedStores.length === 0) return allSkus
|
|
return allSkus.filter((sku) =>
|
|
sku._storeId && selectedStores.includes(sku._storeId.toString())
|
|
)
|
|
}, [allSkus, selectedStores])
|
|
|
|
const hasChanges = (skuId: number) => !!pendingChanges[skuId]
|
|
|
|
const openEditDialog = (sku: any, productName: string) => {
|
|
const change = pendingChanges[sku.id] || {}
|
|
setEditDialog({
|
|
open: true,
|
|
sku,
|
|
productName,
|
|
tempPrice: (change.price ?? sku.price)?.toString() || '',
|
|
tempMarketPrice: (change.marketPrice ?? sku.marketPrice)?.toString() || '',
|
|
tempFlashPrice: (change.flashPrice ?? sku.flashPrice)?.toString() || '',
|
|
})
|
|
}
|
|
|
|
const saveEditDialog = () => {
|
|
const price = parseFloat(editDialog.tempPrice)
|
|
const marketPrice = editDialog.tempMarketPrice ? parseFloat(editDialog.tempMarketPrice) : null
|
|
const flashPrice = editDialog.tempFlashPrice ? parseFloat(editDialog.tempFlashPrice) : null
|
|
|
|
if (isNaN(price) || price <= 0) {
|
|
window.alert('Please enter a valid price')
|
|
return
|
|
}
|
|
|
|
if (editDialog.tempMarketPrice && (isNaN(marketPrice!) || marketPrice! <= 0)) {
|
|
window.alert('Please enter a valid market price')
|
|
return
|
|
}
|
|
|
|
if (editDialog.tempFlashPrice && (isNaN(flashPrice!) || flashPrice! <= 0)) {
|
|
window.alert('Please enter a valid flash price')
|
|
return
|
|
}
|
|
|
|
setPendingChanges((prev) => ({
|
|
...prev,
|
|
[editDialog.sku.id]: {
|
|
price: price !== parseFloat(editDialog.sku.price) ? price : undefined,
|
|
marketPrice: marketPrice !== parseFloat(editDialog.sku.marketPrice || '0') ? marketPrice : undefined,
|
|
flashPrice: flashPrice !== parseFloat(editDialog.sku.flashPrice || '0') ? flashPrice : undefined,
|
|
},
|
|
}))
|
|
|
|
}
|
|
|
|
const handleSave = () => {
|
|
const updates = Object.entries(pendingChanges).map(([skuId, change]) => {
|
|
const sku = allSkus.find((s) => s.id === parseInt(skuId))
|
|
const update: any = { skuId: sku?.id }
|
|
if (change.price !== undefined) update.price = change.price
|
|
if (change.marketPrice !== undefined) update.marketPrice = change.marketPrice
|
|
if (change.flashPrice !== undefined) update.flashPrice = change.flashPrice
|
|
if (change.isFlashAvailable !== undefined) update.isFlashAvailable = change.isFlashAvailable
|
|
return update
|
|
})
|
|
|
|
updatePricesMutation.mutate(
|
|
{ updates },
|
|
{
|
|
onSuccess: () => {
|
|
setPendingChanges({})
|
|
refetchProducts()
|
|
window.alert('Prices updated successfully')
|
|
},
|
|
onError: (error: any) => {
|
|
window.alert(`Failed to update prices: ${error.message || 'Unknown error'}`)
|
|
},
|
|
}
|
|
)
|
|
}
|
|
|
|
const changeCount = Object.keys(pendingChanges).length
|
|
|
|
return (
|
|
<div className="flex-1 bg-gray-50">
|
|
<div className="flex flex-row items-center border-b border-gray-200 bg-white px-4 py-4">
|
|
<div className="mr-4 flex-1">
|
|
<MultiSelect
|
|
label="Filter by Stores"
|
|
options={storeOptions}
|
|
value={selectedStores}
|
|
onValueChange={(value) => setSelectedStores(value as string[])}
|
|
placeholder="Select stores"
|
|
/>
|
|
</div>
|
|
<button
|
|
className={`mr-3 flex flex-row items-center rounded-lg px-4 py-2 ${
|
|
changeCount > 0 && !updatePricesMutation.isPending ? 'bg-blue-600' : 'bg-gray-300'
|
|
}`}
|
|
onClick={handleSave}
|
|
disabled={changeCount === 0 || updatePricesMutation.isPending}
|
|
>
|
|
{updatePricesMutation.isPending ? (
|
|
<span className={`mr-2 h-4 w-4 animate-spin rounded-full border-2 ${changeCount > 0 ? 'border-white/40 border-t-white' : 'border-gray-400/40 border-t-gray-500'}`} />
|
|
) : (
|
|
<Save
|
|
size={20}
|
|
color={changeCount > 0 ? 'white' : '#6b7280'}
|
|
className="mr-2"
|
|
/>
|
|
)}
|
|
<MyText
|
|
className={`font-medium ${changeCount > 0 ? 'text-white' : 'text-gray-500'}`}
|
|
>
|
|
Save ({changeCount})
|
|
</MyText>
|
|
</button>
|
|
<button
|
|
onClick={() => setShowMenu(true)}
|
|
className="-mr-2 p-2"
|
|
>
|
|
<EllipsisVertical size={16} color="#9CA3AF" />
|
|
</button>
|
|
</div>
|
|
|
|
{productsLoading || storesLoading ? (
|
|
<div className="flex flex-1 flex-col items-center justify-center">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-blue-500" />
|
|
<MyText className="mt-4 text-gray-500">Loading...</MyText>
|
|
</div>
|
|
) : (
|
|
<MyFlatList
|
|
data={filteredSkus}
|
|
renderItem={(item) => (
|
|
<SkuItemComponent
|
|
sku={item}
|
|
productName={item._productName}
|
|
hasChanges={hasChanges}
|
|
pendingChanges={pendingChanges}
|
|
setPendingChanges={setPendingChanges}
|
|
openEditDialog={openEditDialog}
|
|
/>
|
|
)}
|
|
keyExtractor={(item) => item.id.toString()}
|
|
className="p-4"
|
|
/>
|
|
)}
|
|
|
|
<BottomDialog open={editDialog.open} onClose={() => setEditDialog({ ...editDialog, open: false, tempFlashPrice: '', tempMarketPrice: '', tempPrice: '' })}>
|
|
<div className="p-4">
|
|
<MyText className="mb-1 text-lg font-bold">{editDialog.productName}</MyText>
|
|
<MyText className="mb-4 text-sm text-gray-500">{editDialog.sku?.displayName || editDialog.sku?.name || ''}</MyText>
|
|
|
|
<div className="mb-4">
|
|
<MyText className="mb-1 text-sm font-medium">Our Price</MyText>
|
|
<MyTextInput
|
|
value={editDialog.tempPrice}
|
|
onChange={(e) => setEditDialog({ ...editDialog, tempPrice: e.target.value })}
|
|
type="number"
|
|
placeholder="Enter price"
|
|
/>
|
|
</div>
|
|
|
|
<div className="mb-4">
|
|
<MyText className="mb-1 text-sm font-medium">Market Price (Optional)</MyText>
|
|
<MyTextInput
|
|
value={editDialog.tempMarketPrice}
|
|
onChange={(e) => setEditDialog({ ...editDialog, tempMarketPrice: e.target.value })}
|
|
type="number"
|
|
placeholder="Enter market price"
|
|
/>
|
|
</div>
|
|
|
|
<div className="mb-4">
|
|
<MyText className="mb-1 text-sm font-medium">Flash Price (Optional)</MyText>
|
|
<MyTextInput
|
|
value={editDialog.tempFlashPrice}
|
|
onChange={(e) => setEditDialog({ ...editDialog, tempFlashPrice: e.target.value })}
|
|
type="number"
|
|
placeholder="Enter flash price"
|
|
/>
|
|
</div>
|
|
|
|
<button
|
|
className="w-full items-center rounded-md bg-blue-600 py-3"
|
|
onClick={saveEditDialog}
|
|
>
|
|
<MyText className="font-medium text-white">Update Price</MyText>
|
|
</button>
|
|
</div>
|
|
</BottomDialog>
|
|
|
|
<BottomDialog open={showMenu} onClose={() => setShowMenu(false)}>
|
|
<div className="p-6">
|
|
<MyText className="mb-6 text-lg font-bold text-gray-800">
|
|
Options
|
|
</MyText>
|
|
<button
|
|
className="flex w-full flex-row items-center rounded-lg bg-gray-50 p-4"
|
|
onClick={() => {
|
|
navigate({ to: '/dashboard/rebalance' })
|
|
setShowMenu(false)
|
|
}}
|
|
>
|
|
<Shuffle size={20} color="#6B7280" />
|
|
<MyText className="ml-3 font-medium text-gray-800">
|
|
Re-Balance Orders
|
|
</MyText>
|
|
</button>
|
|
</div>
|
|
</BottomDialog>
|
|
</div>
|
|
)
|
|
}
|