413 lines
14 KiB
TypeScript
413 lines
14 KiB
TypeScript
import React, { useState, useEffect } from 'react'
|
|
import { createFileRoute } from '@tanstack/react-router'
|
|
import { useQueryClient } from '@tanstack/react-query'
|
|
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core'
|
|
import { SortableContext, useSortable, arrayMove, verticalListSortingStrategy } from '@dnd-kit/sortable'
|
|
import { CSS } from '@dnd-kit/utilities'
|
|
import { GripVertical, Image as ImageIcon, Trash2, ChevronLeft, CircleAlert, Package, Plus } from 'lucide-react'
|
|
import { AppContainer, p as MyText, BottomDialog } from 'web-components'
|
|
import ProductsSelector from '../components/ProductsSelector'
|
|
import { trpc } from '@/lib/trpc-client'
|
|
import type { StoreProductCard } from '@packages/shared'
|
|
import type { DragOrderItemProps } from '@/types/drag-order-item'
|
|
|
|
export const Route = createFileRoute('/dashboard/customize-app/popular')({
|
|
component: CustomizePopularItems,
|
|
})
|
|
|
|
type PopularProduct = Omit<
|
|
StoreProductCard,
|
|
'price' | 'marketPrice' | 'unitNotation' | 'images'
|
|
> & {
|
|
price: number
|
|
marketPrice: number | null
|
|
images: string[] | null
|
|
storeId: number | null
|
|
nextDeliveryDate: string | null
|
|
}
|
|
|
|
interface ProductItemProps extends DragOrderItemProps<PopularProduct> {
|
|
onDelete: (id: number) => void
|
|
}
|
|
|
|
const ProductItem: React.FC<ProductItemProps> = ({
|
|
item,
|
|
isActive,
|
|
onDelete,
|
|
}) => {
|
|
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: item.id })
|
|
const active = isActive || isDragging
|
|
|
|
return (
|
|
<div
|
|
ref={setNodeRef}
|
|
style={{
|
|
transform: CSS.Translate.toString(transform),
|
|
transition,
|
|
opacity: isDragging ? 0.9 : 1,
|
|
zIndex: isDragging ? 50 : undefined,
|
|
marginLeft: 16,
|
|
marginRight: 16,
|
|
marginTop: 8,
|
|
marginBottom: 8,
|
|
}}
|
|
>
|
|
<div
|
|
className={`bg-white p-4 rounded-xl border ${
|
|
active
|
|
? 'shadow-xl border-blue-500 z-50'
|
|
: 'shadow-sm border-gray-100'
|
|
}`}
|
|
>
|
|
<div className="flex flex-row items-center">
|
|
<div {...attributes} {...listeners} className="mr-4" style={{ cursor: 'grab', touchAction: 'none' }}>
|
|
<GripVertical
|
|
size={24}
|
|
color={active ? '#3b82f6' : '#9ca3af'}
|
|
/>
|
|
</div>
|
|
|
|
{item.images?.[0] ? (
|
|
<img
|
|
src={item.images[0]}
|
|
className="mr-4 h-12 w-12 rounded-lg object-cover"
|
|
alt={item.name}
|
|
/>
|
|
) : (
|
|
<div className="mr-4 flex h-12 w-12 items-center justify-center rounded-lg bg-gray-100">
|
|
<ImageIcon size={20} color="#9ca3af" />
|
|
</div>
|
|
)}
|
|
|
|
<div className="flex-1">
|
|
<MyText className="text-base font-semibold text-gray-900" numberOfLines={2}>
|
|
{item.name}
|
|
</MyText>
|
|
<MyText className="mt-1 text-sm font-bold text-green-600">
|
|
₹{item.price}
|
|
</MyText>
|
|
</div>
|
|
|
|
<button
|
|
onClick={() => onDelete(item.id)}
|
|
className="ml-2 p-2"
|
|
>
|
|
<Trash2 size={20} color="#ef4444" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function CustomizePopularItems() {
|
|
const queryClient = useQueryClient()
|
|
const [popularProducts, setPopularProducts] = useState<PopularProduct[]>([])
|
|
const [hasChanges, setHasChanges] = useState(false)
|
|
const [showAddDialog, setShowAddDialog] = useState(false)
|
|
const [selectedProductIds, setSelectedProductIds] = useState<number[]>([])
|
|
|
|
const { data: constants, isLoading: isLoadingConstants, error: constantsError } = trpc.admin.region.getRegionConstants.useQuery()
|
|
const { data: allProducts, isLoading: isLoadingProducts, error: productsError } = trpc.common.product.getAllProductsSummary.useQuery()
|
|
const updateConstants = trpc.admin.region.updateRegionConstants.useMutation()
|
|
|
|
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }))
|
|
|
|
useEffect(() => {
|
|
if (constants && allProducts?.products) {
|
|
const popularItemsConstant = constants.find((c) => c.key === 'popularItems')
|
|
|
|
let popularIds: number[] = []
|
|
|
|
if (popularItemsConstant) {
|
|
const value = popularItemsConstant.value
|
|
|
|
if (Array.isArray(value)) {
|
|
popularIds = value.map((id: any) => parseInt(id))
|
|
} else if (typeof value === 'string') {
|
|
popularIds = value.split(',').map((id: string) => parseInt(id.trim())).filter((id) => !isNaN(id))
|
|
}
|
|
|
|
const popularProds: PopularProduct[] = []
|
|
|
|
for (const id of popularIds) {
|
|
const product = allProducts.products.find((p) => p.id === id)
|
|
if (product) {
|
|
popularProds.push(product as PopularProduct)
|
|
}
|
|
}
|
|
|
|
setPopularProducts(popularProds)
|
|
}
|
|
}
|
|
}, [constants, allProducts])
|
|
|
|
const handleDragEnd = (event: DragEndEvent) => {
|
|
const { active, over } = event
|
|
if (over && active.id !== over.id) {
|
|
setPopularProducts((prev) => {
|
|
const oldIndex = prev.findIndex((p) => p.id === active.id)
|
|
const newIndex = prev.findIndex((p) => p.id === over.id)
|
|
return arrayMove(prev, oldIndex, newIndex)
|
|
})
|
|
setHasChanges(true)
|
|
}
|
|
}
|
|
|
|
const handleDelete = (productId: number) => {
|
|
if (window.confirm('Are you sure you want to remove this product from popular items?')) {
|
|
setPopularProducts((prev) => prev.filter((p) => p.id !== productId))
|
|
setHasChanges(true)
|
|
}
|
|
}
|
|
|
|
const handleAddProduct = () => {
|
|
if (selectedProductIds.length > 0) {
|
|
const newProducts = selectedProductIds
|
|
.map((id) => allProducts?.products.find((p) => p.id === id))
|
|
.filter((product): product is NonNullable<typeof product> =>
|
|
product !== undefined && !popularProducts.find((p) => p.id === product.id)
|
|
)
|
|
|
|
if (newProducts.length > 0) {
|
|
setPopularProducts((prev) => [...prev, ...newProducts as PopularProduct[]])
|
|
setHasChanges(true)
|
|
}
|
|
|
|
setSelectedProductIds([])
|
|
setShowAddDialog(false)
|
|
}
|
|
}
|
|
|
|
const handleSave = () => {
|
|
const popularIds = popularProducts.map((p) => p.id)
|
|
|
|
updateConstants.mutate(
|
|
{
|
|
constants: [{
|
|
key: 'popularItems',
|
|
value: popularIds.join(','),
|
|
}],
|
|
},
|
|
{
|
|
onSuccess: () => {
|
|
setHasChanges(false)
|
|
window.alert('Popular items updated successfully!')
|
|
queryClient.invalidateQueries({ queryKey: ['region.getRegionConstants'] })
|
|
},
|
|
onError: (error) => {
|
|
window.alert('Failed to update popular items. Please try again.')
|
|
console.error('Update popular items error:', error)
|
|
},
|
|
}
|
|
)
|
|
}
|
|
|
|
const availableProducts = (allProducts?.products || []).filter(
|
|
(product) => !popularProducts.find((p) => p.id === product.id)
|
|
)
|
|
|
|
if (isLoadingConstants || isLoadingProducts) {
|
|
return (
|
|
<AppContainer>
|
|
<div className="flex-1 bg-gray-50">
|
|
<div className="flex flex-row items-center justify-between border-b border-gray-200 bg-white px-4 py-4">
|
|
<button
|
|
onClick={() => window.history.back()}
|
|
className="-ml-4 p-2"
|
|
>
|
|
<ChevronLeft size={24} color="#374151" />
|
|
</button>
|
|
|
|
<MyText className="text-xl font-bold text-gray-900">Popular Items</MyText>
|
|
|
|
<div className="w-16" />
|
|
</div>
|
|
|
|
<div className="flex flex-1 flex-col items-center justify-center p-8">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-blue-500" />
|
|
<MyText className="mt-4 text-center text-gray-500">
|
|
{isLoadingConstants ? 'Loading constants...' : 'Loading products...'}
|
|
</MyText>
|
|
</div>
|
|
</div>
|
|
</AppContainer>
|
|
)
|
|
}
|
|
|
|
if (constantsError || productsError) {
|
|
return (
|
|
<AppContainer>
|
|
<div className="flex-1 bg-gray-50">
|
|
<div className="flex flex-row items-center justify-between border-b border-gray-200 bg-white px-4 py-4">
|
|
<button
|
|
onClick={() => window.history.back()}
|
|
className="-ml-4 p-2"
|
|
>
|
|
<ChevronLeft size={24} color="#374151" />
|
|
</button>
|
|
|
|
<MyText className="text-xl font-bold text-gray-900">Popular Items</MyText>
|
|
|
|
<div className="w-16" />
|
|
</div>
|
|
|
|
<div className="flex flex-1 flex-col items-center justify-center p-8">
|
|
<CircleAlert size={64} color="#ef4444" />
|
|
<MyText className="mt-4 text-lg font-bold text-gray-900">Error</MyText>
|
|
<MyText className="mt-2 text-center text-gray-500">
|
|
{constantsError ? 'Failed to load constants' : 'Failed to load products'}
|
|
</MyText>
|
|
<button
|
|
onClick={() => window.history.back()}
|
|
className="mt-6 rounded-full bg-blue-600 px-6 py-3"
|
|
>
|
|
<MyText className="font-semibold text-white">Go Back</MyText>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</AppContainer>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="relative flex-1 bg-gray-50">
|
|
<div className="flex flex-row items-center justify-between border-b border-gray-200 bg-white px-4 py-4">
|
|
<button
|
|
onClick={() => window.history.back()}
|
|
className="-ml-4 p-2"
|
|
>
|
|
<ChevronLeft size={24} color="#374151" />
|
|
</button>
|
|
|
|
<MyText className="text-xl font-bold text-gray-900">Popular Items</MyText>
|
|
|
|
<button
|
|
onClick={handleSave}
|
|
disabled={!hasChanges || updateConstants.isPending}
|
|
className={`rounded-lg px-4 py-2 ${
|
|
hasChanges && !updateConstants.isPending
|
|
? 'bg-blue-600'
|
|
: 'bg-gray-300'
|
|
}`}
|
|
>
|
|
<MyText className={`font-semibold ${
|
|
hasChanges && !updateConstants.isPending
|
|
? 'text-white'
|
|
: 'text-gray-500'
|
|
}`}>
|
|
{updateConstants.isPending ? 'Saving...' : 'Save'}
|
|
</MyText>
|
|
</button>
|
|
</div>
|
|
|
|
{popularProducts.length === 0 ? (
|
|
<div className="flex flex-1 flex-col items-center justify-center p-8">
|
|
<Package size={64} color="#e5e7eb" />
|
|
<MyText className="mt-4 text-center text-lg text-gray-500">
|
|
No popular items configured
|
|
</MyText>
|
|
<MyText className="mt-2 text-center text-gray-400">
|
|
Add products to display as popular items
|
|
</MyText>
|
|
</div>
|
|
) : (
|
|
<div className="flex flex-1 flex-col pb-20">
|
|
<div className="bg-blue-50 px-4 py-2 mb-2">
|
|
<MyText className="text-center text-xs text-blue-700">
|
|
Long press an item to drag and reorder
|
|
</MyText>
|
|
</div>
|
|
|
|
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
|
<SortableContext items={popularProducts.map((p) => p.id)} strategy={verticalListSortingStrategy}>
|
|
{popularProducts.map((product) => (
|
|
<ProductItem
|
|
key={product.id}
|
|
item={product}
|
|
drag={() => {}}
|
|
isActive={false}
|
|
onDelete={handleDelete}
|
|
/>
|
|
))}
|
|
</SortableContext>
|
|
</DndContext>
|
|
</div>
|
|
)}
|
|
|
|
<div className="fixed bottom-12 right-6 z-50">
|
|
<button
|
|
onClick={() => setShowAddDialog(true)}
|
|
className="rounded-full bg-blue-600 p-4 shadow-lg"
|
|
>
|
|
<Plus size={24} color="white" />
|
|
</button>
|
|
</div>
|
|
|
|
<BottomDialog
|
|
open={showAddDialog}
|
|
onClose={() => {
|
|
setShowAddDialog(false)
|
|
setSelectedProductIds([])
|
|
}}
|
|
>
|
|
<div className="px-4 pb-8 pt-2">
|
|
<div className="mb-6 flex flex-col items-center">
|
|
<div className="mb-4 h-1.5 w-12 rounded-full bg-gray-200" />
|
|
<MyText className="text-lg font-bold text-gray-900">
|
|
Add Popular Items
|
|
</MyText>
|
|
<MyText className="text-sm text-gray-500">
|
|
Select products to add to popular items
|
|
</MyText>
|
|
</div>
|
|
|
|
{availableProducts.length === 0 ? (
|
|
<div className="flex flex-col items-center py-8">
|
|
<Package size={48} color="#e5e7eb" />
|
|
<MyText className="mt-4 text-center text-gray-500">
|
|
All products are already in popular items
|
|
</MyText>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<ProductsSelector
|
|
value={selectedProductIds}
|
|
onChange={(val) => setSelectedProductIds(val as number[])}
|
|
multiple={true}
|
|
label="Select Products"
|
|
placeholder="Choose products..."
|
|
labelFormat={(product) => `${product.productName} - ₹${product.price}`}
|
|
/>
|
|
|
|
<div className="mt-6 flex flex-row gap-3">
|
|
<button
|
|
onClick={() => setShowAddDialog(false)}
|
|
className="flex-1 rounded-lg bg-gray-100 p-3"
|
|
>
|
|
<MyText className="text-center font-semibold text-gray-700">
|
|
Cancel
|
|
</MyText>
|
|
</button>
|
|
|
|
<button
|
|
onClick={handleAddProduct}
|
|
disabled={selectedProductIds.length === 0}
|
|
className={`flex-1 rounded-lg p-3 ${
|
|
selectedProductIds.length > 0 ? 'bg-blue-600' : 'bg-gray-300'
|
|
}`}
|
|
>
|
|
<MyText className="text-center font-semibold text-white">
|
|
{selectedProductIds.length > 0
|
|
? `Add ${selectedProductIds.length} Product${selectedProductIds.length > 1 ? 's' : ''}`
|
|
: 'Add Products'}
|
|
</MyText>
|
|
</button>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</BottomDialog>
|
|
</div>
|
|
)
|
|
}
|