freshyo/apps/web-ui/src/routes/me.orders.tsx
shafi54 5e96f7a747 Revert "enh"
This reverts commit a724cd7bff.
2026-10-28 20:02:04 +05:30

421 lines
17 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { trpc } from '../lib/trpc-client'
import { useCallback, useEffect, useState } from 'react'
import { MeOrderMenu } from '../components/me/MeOrderMenu'
import { MeScreenHeader } from '../components/me/MeScreenHeader'
import { orderStatusManipulator } from '../lib/string-manipulators'
import dayjs from 'dayjs'
import { AlertCircle, Package, MapPin } from 'lucide-react'
export const Route = createFileRoute('/me/orders')({ component: OrdersPage })
const PAGE_SIZE = 10
type StatusStyle = {
bg: string
text: string
iconColor: string
icon: React.ReactNode
label: string
}
function getStatusStyle(status: string): StatusStyle {
const s = status.toLowerCase()
switch (s) {
case 'delivered':
case 'success':
case 'completed':
return { bg: 'bg-emerald-50', text: 'text-emerald-700', iconColor: '#059669', icon: <span>✓</span>, label: 'Delivered' }
case 'cancelled':
case 'failed':
return { bg: 'bg-rose-50', text: 'text-rose-700', iconColor: '#E11D48', icon: <span>✕</span>, label: 'Cancelled' }
case 'pending':
return { bg: 'bg-amber-50', text: 'text-amber-700', iconColor: '#D97706', icon: <span>🕐</span>, label: 'Pending' }
case 'packaged':
return { bg: 'bg-brand-50', text: 'text-brand-700', iconColor: '#1570EF', icon: <span>📦</span>, label: 'Packaged' }
case 'processing':
case 'confirmed':
case 'shipped':
return { bg: 'bg-brand-50', text: 'text-brand-700', iconColor: '#1570EF', icon: <span>🚚</span>, label: s.charAt(0).toUpperCase() + s.slice(1) }
default:
return { bg: 'bg-slate-50', text: 'text-slate-700', iconColor: '#64748B', icon: <span>i</span>, label: status }
}
}
function OrderCard({
item,
getStatusStyle,
onPress,
onViewMoreItems,
refetch,
}: {
item: any
getStatusStyle: (s: string) => StatusStyle
onPress: (orderId: number) => void
onViewMoreItems: (orderId: number) => void
refetch: () => void
}) {
const mainStatus = getStatusStyle(item.orderStatus)
const deliveryStatus = getStatusStyle(item.deliveryStatus)
const totalAmount = item.totalAmount
return (
<button
onClick={() => onPress(item.id)}
className="mb-6 w-full overflow-hidden rounded-[28px] border border-slate-100 bg-white text-left shadow-sm transition-colors hover:bg-slate-50/50"
>
{/* Top Header: Order ID and Status */}
<div className="flex flex-row items-center justify-between border-b border-slate-100 bg-slate-50/50 px-5 py-4">
<div>
<div className="flex flex-row items-center">
<span className="mr-2 h-2 w-2 rounded-full bg-brand-500" />
<p className="text-[10px] font-bold uppercase tracking-tighter text-slate-400">
Order Reference
</p>
</div>
<p className="mt-0.5 text-base font-extrabold text-slate-900">#{item.orderId}</p>
</div>
<div className="flex flex-row items-center gap-2">
{item.orderStatus.toLowerCase() === 'cancelled' && (
<span className={`flex flex-row items-center rounded-full border px-3 py-1.5 ${mainStatus.bg} border-rose-100`}>
<span style={{ color: mainStatus.iconColor }} className="mr-1.5 text-[11px]">
{mainStatus.icon}
</span>
<span className={`text-[11px] font-bold uppercase tracking-wide ${mainStatus.text}`}>
{orderStatusManipulator(mainStatus.label)}
</span>
</span>
)}
{item.isFlashDelivery && (
<span className="flex flex-row items-center rounded-full border border-amber-200 bg-amber-100 px-2 py-1">
<span className="mr-1 text-[10px]">⚡</span>
<span className="text-[10px] font-black uppercase text-amber-700">Flash</span>
</span>
)}
{!!item.regionName && (
<span className="flex flex-row items-center rounded-full border border-slate-200 bg-slate-100 px-2 py-1">
<MapPin className="h-3 w-3 text-slate-500" />
<span className="ml-1 text-[10px] font-bold text-slate-600">{item.regionName}</span>
</span>
)}
</div>
</div>
<div className="p-5">
{/* Order Date & Quick Stats */}
<div className="mb-5 flex flex-row items-start justify-between">
<div className="flex flex-1 flex-col gap-3">
{(item.deliveryDate || item.isFlashDelivery) && (
<div className="flex flex-row items-center">
<div
className={`mr-3 flex h-9 w-9 items-center justify-center rounded-xl ${
item.isFlashDelivery ? 'bg-amber-50' : 'bg-brand-50'
}`}
>
<span className="text-[16px]">{item.isFlashDelivery ? '⚡' : '🕐'}</span>
</div>
<div>
<p
className={`text-[10px] font-bold uppercase ${
item.isFlashDelivery ? 'text-amber-700' : 'text-brand-700'
}`}
>
{item.isFlashDelivery ? '1 Hr Delivery' : 'Delivery Time'}
</p>
<p
className={`text-sm font-extrabold ${
item.isFlashDelivery ? 'text-amber-900' : 'text-brand-900'
}`}
>
{item.isFlashDelivery
? dayjs(item.createdAt || item.orderDate).add(30, 'minutes').format('DD MMM, hh:mm A')
: (() => {
const startTime = dayjs(item.deliveryDate)
const endTime = startTime.add(1, 'hour')
return `${startTime.format('DD MMM, hh:mm A')} - ${endTime.format('hh:mm A')}`
})()}
</p>
{item.isFlashDelivery && (
<p className="mt-1 text-[9px] font-bold uppercase text-amber-600">⚡ 1-Hour Delivery</p>
)}
</div>
</div>
)}
<div className="flex flex-row items-center">
<div className="mr-3 flex h-9 w-9 items-center justify-center rounded-xl bg-slate-100">
<span className="text-[16px]">📅</span>
</div>
<div>
<p className="text-[10px] font-bold uppercase text-slate-400">Placed On</p>
<p className="text-sm font-semibold text-slate-800">
{dayjs(item.orderDate).format('DD MMM YYYY, hh:mm A')}
</p>
</div>
</div>
</div>
<MeOrderMenu orderId={item.id} postActionHandler={refetch} />
</div>
{/* Items Section */}
<div className="mb-5 rounded-2xl border border-slate-100 bg-slate-50/50 p-3">
<div className="mb-3 flex flex-row items-center justify-between px-1">
<p className="text-[11px] font-bold uppercase tracking-wider text-slate-500">Items Summary</p>
<p className="text-[11px] font-bold text-brand-600">
{item.items.length} {item.items.length === 1 ? 'Item' : 'Items'}
</p>
</div>
{item.items.slice(0, 2).map((product: any, pIndex: number) => (
<div key={pIndex} className="mb-3 flex flex-row items-center last:mb-0">
<div className="relative">
<img
src={product.image || undefined}
alt=""
className="h-12 w-12 rounded-xl border border-slate-200 bg-white object-cover"
/>
<div className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border-2 border-white bg-brand-500">
<p className="text-[10px] font-bold text-white">{product.quantity}</p>
</div>
</div>
<div className="ml-4 min-w-0 flex-1">
<p className="truncate text-sm font-bold text-slate-800">{product.productName}</p>
<p className="mt-0.5 text-xs font-medium text-slate-500">
Unit Price: ₹{product.price}
</p>
</div>
<p className="ml-2 text-sm font-extrabold text-slate-900">₹{product.amount}</p>
</div>
))}
{item.items.length > 2 && (
<button
onClick={(e) => {
e.stopPropagation()
onViewMoreItems(item.id)
}}
className="mt-2 w-full border-t border-slate-100 pt-2 text-center"
>
<p className="text-xs font-bold text-brand-600">
+ {item.items.length - 2} more {item.items.length - 2 === 1 ? 'item' : 'items'} in this order
</p>
</button>
)}
</div>
{/* Delivery Status - Single Line */}
<div className="mb-5 flex flex-row items-center justify-between">
<div className="flex min-w-0 flex-1 flex-row items-center">
<span
className="mr-2 rounded-lg p-1.5"
style={{ backgroundColor: deliveryStatus.iconColor + '15' }}
>
<span className="text-[14px]">{item.isFlashDelivery ? '⚡' : '🚚'}</span>
</span>
<p className="mr-2 shrink-0 text-[10px] font-bold uppercase text-slate-400">
{item.isFlashDelivery ? '1 Hr Delivery:' : 'Shipping Status:'}
</p>
<p className={`truncate text-xs font-bold ${deliveryStatus.text}`}>
{orderStatusManipulator(item.deliveryStatus)}
</p>
</div>
{item.isFlashDelivery && (
<span className="ml-2 shrink-0 rounded-full border border-amber-200 bg-amber-100 px-2 py-0.5">
<p className="text-[8px] font-black uppercase text-amber-700">⚡ Fast</p>
</span>
)}
</div>
{/* User Notes */}
{item.userNotes && (
<div className="mb-5">
<div className="flex flex-row items-start rounded-2xl border border-amber-100 bg-amber-50/50 p-3">
<span className="mt-0.5 text-[16px]">📝</span>
<div className="ml-3 flex-1">
<p className="text-[10px] font-bold uppercase text-amber-700">Your Instructions</p>
<p className="mt-0.5 line-clamp-2 text-xs font-medium text-amber-900">
{item.userNotes}
</p>
</div>
</div>
</div>
)}
{/* Cancellation Info */}
{item.cancelReason && (
<div className="mb-5 rounded-2xl border border-rose-100 bg-rose-50 p-4">
<div className="mb-2 flex flex-row items-center">
<span className="text-[16px]">⚠️</span>
<p className="ml-2 text-xs font-bold text-rose-800">Cancellation Details</p>
</div>
<p className="text-xs font-medium leading-relaxed text-rose-600">{item.cancelReason}</p>
</div>
)}
{/* Footer: Price and CTA */}
<div className="flex flex-row items-center justify-between border-t border-slate-100 pt-5">
<div>
<p className="text-[10px] font-bold uppercase tracking-wider text-slate-400">Amount to Pay</p>
<p className="text-2xl font-black text-slate-900">₹{totalAmount}</p>
{item.discountAmount ? (
<div className="mt-1 flex flex-row items-center self-start rounded-full bg-emerald-50 px-2 py-0.5">
<span className="mr-1 text-[10px]">🏷️</span>
<p className="text-[10px] font-bold text-emerald-700">Saved ₹{item.discountAmount}</p>
</div>
) : null}
{item.deliveryCharge > 0 && (
<div className="mt-1 flex flex-row items-center">
<span className="mr-1 text-[12px]">🚚</span>
<p className="text-[10px] font-medium text-slate-600">Delivery: ₹{item.deliveryCharge}</p>
</div>
)}
</div>
<div className="flex flex-row items-center rounded-2xl bg-brand-600 px-5 py-3 shadow-lg">
<p className="mr-1 text-sm font-bold text-white">View Details</p>
<span className="text-[16px] text-white">→</span>
</div>
</div>
</div>
</button>
)
}
function OrdersPage() {
const navigate = useNavigate()
// Infinite scroll state
const [allOrders, setAllOrders] = useState<any[]>([])
const [currentPage, setCurrentPage] = useState<number>(1)
const [isLoadingMore, setIsLoadingMore] = useState<boolean>(false)
const [hasNextPage, setHasNextPage] = useState<boolean>(true)
const [loadMoreError, setLoadMoreError] = useState<string | null>(null)
const { data: ordersData, isLoading, error, refetch } = trpc.user.order.getOrders.useQuery({
page: currentPage,
pageSize: PAGE_SIZE,
})
// Handle data accumulation for infinite scroll
useEffect(() => {
if (ordersData?.data) {
if (currentPage === 1) {
setAllOrders(ordersData.data)
} else {
setAllOrders((prev) => [...prev, ...ordersData.data])
}
const totalPages = ordersData.pagination?.totalPages || 1
setHasNextPage(currentPage < totalPages)
setIsLoadingMore(false)
setLoadMoreError(null)
}
}, [ordersData, currentPage])
// Handle errors during infinite scroll loading
useEffect(() => {
if (error && currentPage > 1) {
setIsLoadingMore(false)
setLoadMoreError('Failed to load more orders. Please try again.')
}
}, [error, currentPage])
const loadMoreOrders = useCallback(() => {
if (!isLoadingMore && hasNextPage && !isLoading) {
setIsLoadingMore(true)
setCurrentPage((prev) => prev + 1)
}
}, [isLoadingMore, hasNextPage, isLoading])
return (
<div className="min-h-screen bg-gray-50">
<MeScreenHeader title="My Orders" />
{isLoading && currentPage === 1 && (
<div className="flex min-h-[60vh] flex-1 items-center justify-center bg-gray-50">
<p className="font-medium text-gray-500">Loading your orders...</p>
</div>
)}
{error && currentPage === 1 && !isLoading && (
<div className="flex min-h-[60vh] flex-1 flex-col items-center justify-center bg-gray-50 p-6">
<div className="mb-4 rounded-full bg-white p-6 shadow-sm">
<AlertCircle className="h-12 w-12 text-red-500" />
</div>
<p className="mt-2 text-xl font-bold text-gray-900">Unable to load orders</p>
<p className="mt-2 mb-6 text-center text-gray-500">Please check your connection and try again</p>
<button
onClick={() => refetch()}
className="rounded-full bg-blue-600 px-8 py-3 font-bold text-white shadow-md transition-colors hover:bg-blue-700"
>
Retry
</button>
</div>
)}
{!isLoading && !error && (
<div className="mx-auto w-full max-w-2xl px-4 py-6">
{allOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20">
<div className="mb-4 rounded-full bg-white p-6 shadow-sm">
<Package className="h-16 w-16 text-gray-200" />
</div>
<p className="mt-2 text-lg font-bold text-gray-900">No orders yet</p>
<p className="mt-2 text-center text-gray-500">Your order history will appear here</p>
<button
onClick={() => navigate({ to: '/home' })}
className="mt-6 rounded-full bg-blue-600 px-6 py-3 font-bold text-white shadow-md transition-colors hover:bg-blue-700"
>
Start Shopping
</button>
</div>
) : (
<>
{allOrders.map((order) => (
<OrderCard
key={order.id}
item={order}
getStatusStyle={getStatusStyle}
onPress={(orderId) => navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })}
onViewMoreItems={(orderId) =>
navigate({ to: '/me/orders/$id', params: { id: String(orderId) } })
}
refetch={refetch}
/>
))}
{/* Footer / infinite scroll sentinel */}
<div className="flex flex-col items-center py-4">
{isLoadingMore && <p className="text-sm text-gray-500">Loading more orders...</p>}
{loadMoreError && (
<div className="flex flex-col items-center gap-2">
<p className="mb-2 text-sm text-red-500">{loadMoreError}</p>
<button
onClick={() => {
setLoadMoreError(null)
loadMoreOrders()
}}
className="rounded-lg bg-blue-500 px-4 py-2 text-sm font-medium text-white"
>
Retry
</button>
</div>
)}
{!hasNextPage && allOrders.length > 0 && (
<p className="text-xs text-gray-400">End of list</p>
)}
{hasNextPage && !isLoadingMore && !loadMoreError && (
<button onClick={loadMoreOrders} className="rounded-lg bg-gray-200 px-5 py-2 text-sm font-medium text-gray-700">
Load more
</button>
)}
</div>
</>
)}
</div>
)}
</div>
)
}