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

429 lines
No EOL
17 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
import { trpc } from '../lib/trpc-client'
import { useState, useEffect } from 'react'
import { ChevronLeft, CreditCard, CheckCircle, Zap, Edit2, Tag, XCircle, X, AlertCircle, Loader2, MapPin } from 'lucide-react'
import { BottomDialog } from 'web-components'
import ComplaintForm from '../components/ComplaintForm'
import { orderStatusManipulator } from '../lib/string-manipulators'
import dayjs from 'dayjs'
export const Route = createFileRoute('/me/orders/$id')({
component: OrderDetailPage,
})
function OrderDetailPage() {
const { id } = useParams({ from: '/me/orders/$id' })
const navigate = useNavigate()
const {
data: orderData,
isLoading,
error,
refetch,
} = trpc.user.order.getOrderById.useQuery(
{ orderId: id },
{ enabled: !!id }
)
const [isEditingNotes, setIsEditingNotes] = useState(false)
const [notesText, setNotesText] = useState('')
const [notesInput, setNotesInput] = useState('')
const [cancelDialogOpen, setCancelDialogOpen] = useState(false)
const [cancelReason, setCancelReason] = useState('')
const [complaintDialogOpen, setComplaintDialogOpen] = useState(false)
const updateNotesMutation = trpc.user.order.updateUserNotes.useMutation({
onSuccess: () => {
setNotesText(notesInput)
setIsEditingNotes(false)
refetch()
alert('Notes updated successfully')
},
onError: (error: any) => {
alert(error.message || 'Failed to update notes')
},
})
const cancelOrderMutation = trpc.user.order.cancelOrder.useMutation({
onSuccess: () => {
setCancelDialogOpen(false)
setCancelReason('')
refetch()
alert('Order cancelled successfully')
},
onError: (error: any) => {
alert(error.message || 'Failed to cancel order')
},
})
const handleCancelOrder = () => {
if (!order) return
if (!cancelReason.trim()) {
alert('Please enter a reason for cancellation')
return
}
cancelOrderMutation.mutate({ id: order.id, reason: cancelReason })
}
useEffect(() => {
if (orderData?.userNotes) {
setNotesText(orderData.userNotes)
setNotesInput(orderData.userNotes)
}
}, [orderData])
if (isLoading) {
return (
<div className="flex min-h-screen flex-1 items-center justify-center bg-white">
<p className="font-medium text-slate-400">Loading details...</p>
</div>
)
}
if (error || !orderData) {
return (
<div className="flex min-h-screen flex-1 flex-col items-center justify-center bg-white p-8">
<AlertCircle className="mb-4 h-12 w-12 text-red-500" />
<p className="mt-4 text-lg font-bold text-slate-900">Failed to load</p>
<button
onClick={() => navigate({ to: '/me/orders' })}
className="mt-6 rounded-xl bg-slate-900 px-6 py-2 font-bold text-white"
>
Go Back
</button>
</div>
)
}
const order = orderData
const orderAny = order as any
const getStatusConfig = (status: string) => {
const s = status.toLowerCase()
switch (s) {
case 'delivered':
case 'success':
return { label: 'Delivered', color: '#10B981' }
case 'cancelled':
case 'failed':
return { label: 'Cancelled', color: '#EF4444' }
case 'pending':
case 'processing':
return { label: 'Pending', color: '#F59E0B' }
default:
return { label: status, color: '#1570EF' }
}
}
const subtotal = order.items.reduce((sum: number, item: any) => sum + item.amount, 0)
const discountAmount = order.discountAmount || 0
const deliveryCharge = orderAny.deliveryCharge || 0
const totalAmount = order.orderAmount
const statusConfig = getStatusConfig(order.deliveryStatus || 'pending')
return (
<div className="flex min-h-screen flex-1 flex-col bg-slate-50">
{/* Header */}
<div className="flex flex-row items-center justify-between border-b border-slate-100 bg-white px-6 pb-4 pt-4">
<div className="flex flex-row items-center">
<button
onClick={() => navigate({ to: '/me/orders' })}
className="-ml-2 mr-3 p-2"
>
<ChevronLeft className="h-6 w-6 text-slate-800" />
</button>
<div>
<p className="text-lg font-bold text-slate-900">Order #{order.orderId || order.id}</p>
<p className="text-xs text-slate-400">
{dayjs(order.orderDate || order.createdAt).format('DD MMM, h:mm A')}
</p>
{!!(order as any).regionName && (
<p className="mt-0.5 flex items-center text-[10px] text-slate-400">
<MapPin className="mr-1 h-3 w-3" />
{(order as any).regionName}
</p>
)}
{order.isFlashDelivery && (
<p className="mt-1 text-xs font-bold text-amber-600">⚡ 1 Hr Delivery</p>
)}
</div>
</div>
<div className="flex flex-row items-center gap-2">
<div
className="rounded-full px-3 py-1"
style={{ backgroundColor: statusConfig.color + '10' }}
>
<p
className="text-[10px] font-bold uppercase"
style={{ color: statusConfig.color }}
>
{orderStatusManipulator(statusConfig.label)}
</p>
</div>
{order.isFlashDelivery && (
<div className="rounded-full border border-amber-200 bg-amber-100 px-2 py-1">
<p className="text-[10px] font-black uppercase text-amber-700">⚡</p>
</div>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto p-4 pb-12">
{/* 1 Hr Delivery Banner */}
{order.isFlashDelivery && (
<div className="mb-4 rounded-2xl border border-amber-200 bg-gradient-to-r from-amber-50 to-yellow-50 p-4">
<div className="flex flex-row items-center">
<Zap className="h-6 w-6 text-amber-600" />
<div className="ml-3 flex-1">
<p className="text-sm font-bold text-amber-900">1 Hr Delivery Order</p>
<p className="mt-1 text-xs text-amber-700">
Your order will be delivered within 1 hr of placement
</p>
</div>
</div>
</div>
)}
{/* Main Info Card */}
<div className="mb-4 rounded-2xl border border-slate-100 bg-white p-5">
{(order.deliveryDate || order.isFlashDelivery) &&
['delivered', 'success'].includes((order.deliveryStatus || '').toLowerCase()) && (
<div className="flex flex-row items-center border-t border-slate-50 pt-4">
{order.isFlashDelivery ? (
<Zap className="h-4 w-4 text-amber-600" />
) : (
<CheckCircle className="h-4 w-4 text-green-600" />
)}
<p className={`ml-2 text-xs font-medium ${order.isFlashDelivery ? 'text-amber-700' : 'text-slate-600'}`}>
{order.isFlashDelivery
? `Flash Delivered on ${dayjs(order.createdAt || order.orderDate).add(30, 'minutes').format('DD MMM YYYY, h:mm A')}`
: `Delivered on ${dayjs(order.deliveryDate).format('DD MMM YYYY, h:mm A')}`}
</p>
</div>
)}
{order.isFlashDelivery &&
!['delivered', 'success'].includes((order.deliveryStatus || '').toLowerCase()) && (
<div className="flex flex-row items-center border-t border-slate-50 pt-4">
<Zap className="h-4 w-4 text-amber-600" />
<p className="ml-2 text-xs font-medium text-amber-700">
1 Hr Delivery: {dayjs(order.createdAt || order.orderDate).add(30, 'minutes').format('DD MMM YYYY, h:mm A')}
</p>
</div>
)}
</div>
{/* Special Instructions */}
<div className="mb-4 rounded-2xl border border-slate-100 bg-white p-5">
<div className="mb-3 flex flex-row items-center justify-between">
<p className="text-[10px] font-bold uppercase text-slate-400">Special Instructions</p>
{isEditingNotes ? (
<div className="flex flex-row gap-2">
<button
onClick={() => {
setIsEditingNotes(false)
setNotesInput(notesText)
}}
className="rounded-lg bg-slate-100 px-3 py-1"
>
<p className="text-xs font-bold text-slate-600">Cancel</p>
</button>
<button
onClick={() => {
updateNotesMutation.mutate({ id: order.id, userNotes: notesInput })
}}
disabled={updateNotesMutation.isPending}
className="rounded-lg bg-brand-500 px-3 py-1"
>
<p className="text-xs font-bold text-white">
{updateNotesMutation.isPending ? 'Saving...' : 'Save'}
</p>
</button>
</div>
) : (
<button
onClick={() => {
setNotesInput(notesText || '')
setIsEditingNotes(true)
}}
className="flex flex-row items-center rounded-lg bg-slate-50 px-2 py-1"
>
<Edit2 className="mr-1 h-3 w-3 text-slate-500" />
<p className="text-xs font-medium text-slate-500">{notesText ? 'Edit' : 'Add'}</p>
</button>
)}
</div>
{isEditingNotes ? (
<textarea
className="min-h-20 rounded-xl border border-slate-200 bg-slate-50 p-3 text-sm text-slate-700"
value={notesInput}
onChange={(e) => setNotesInput(e.target.value)}
placeholder="Add special delivery instructions..."
rows={4}
/>
) : (
<p className="text-sm leading-5 text-slate-700">
{notesText || 'No instructions added'}
</p>
)}
</div>
{/* Cancellation Detail */}
{order.cancelReason && (
<div className="mb-4 rounded-2xl border border-rose-100 bg-rose-50 p-5">
<p className="mb-2 text-[10px] font-bold uppercase text-rose-700">Cancellation Reason</p>
<p className="text-sm font-medium text-rose-900">{order.cancelReason}</p>
</div>
)}
{/* Items Section */}
<div className="mb-2 px-1">
<p className="mb-3 text-base font-bold text-slate-900">Order Items</p>
</div>
{order.items.map((item: any, index: number) => (
<div
key={index}
className="mb-3 flex flex-row items-center rounded-2xl border border-slate-100 bg-white p-3 shadow-sm"
>
<div className="mr-4 flex h-14 w-14 items-center justify-center overflow-hidden rounded-xl border border-slate-100 bg-slate-50 p-1">
{item.image ? (
<img
src={item.image}
alt={item.productName}
className="h-full w-full rounded-lg object-cover"
/>
) : (
<div className="text-[10px] font-bold text-slate-400">No img</div>
)}
</div>
<div className="flex-1">
<p className="line-clamp-1 text-sm font-bold text-slate-900">{item.productName}</p>
<p className="mt-1 text-xs text-slate-400">{item.quantity}{item.unitNotation ? ` × ${item.unitNotation}` : ''} · ₹{item.price}</p>
</div>
<p className="ml-2 text-base font-bold text-slate-900">₹{item.amount}</p>
</div>
))}
{/* Coupon */}
{order.couponCode && (
<div className="mb-4 mt-2 flex flex-row items-center justify-between rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
<div className="flex flex-row items-center">
<Tag className="h-5 w-5 text-emerald-600" />
<div className="ml-3">
<p className="text-sm font-bold text-emerald-900">{order.couponCode}</p>
<p className="text-[10px] text-emerald-600">Coupon Applied</p>
</div>
</div>
<p className="font-bold text-emerald-700">-₹{order.discountAmount}</p>
</div>
)}
{/* Summary Section */}
<div className="mb-6 rounded-2xl border border-slate-100 bg-white p-5">
<div className="mb-3 flex flex-row justify-between">
<p className="text-sm text-slate-500">Subtotal</p>
<p className="font-medium text-slate-900">₹{subtotal}</p>
</div>
{discountAmount > 0 && (
<div className="mb-3 flex flex-row justify-between">
<p className="text-sm text-emerald-600">Discount</p>
<p className="font-medium text-emerald-600">-₹{discountAmount}</p>
</div>
)}
<div className="mb-3 flex flex-row justify-between">
<p className="text-sm text-slate-500">Delivery</p>
<p className="font-medium text-slate-900">
{deliveryCharge > 0 ? `₹${deliveryCharge}` : 'Free'}
</p>
</div>
<div className="flex flex-row items-center justify-between border-t border-slate-50 pt-4">
<p className="text-base font-bold text-slate-900">Total Amount</p>
<p className="text-xl font-bold text-slate-900">₹{totalAmount}</p>
</div>
</div>
{/* Footer Actions */}
<div className="flex flex-row gap-3">
<button
onClick={() => navigate({ to: '/me' })}
className="flex-1 rounded-xl bg-slate-100 py-3.5 text-center font-bold text-slate-600"
>
Back
</button>
<button
onClick={() => setComplaintDialogOpen(true)}
className="flex-1 rounded-xl bg-blue-600 py-3.5 text-center font-bold text-white"
>
Raise Complaint
</button>
</div>
{/* Cancel Order Button */}
{order.deliveryStatus !== 'success' && order.deliveryStatus !== 'cancelled' && (
<div className="mt-4">
<button
onClick={() => setCancelDialogOpen(true)}
className="flex w-full flex-row items-center justify-center rounded-xl border border-red-100 bg-red-50 py-3.5"
>
<XCircle className="mr-2 h-5 w-5 text-red-600" />
<p className="font-bold text-red-600">Cancel Order</p>
</button>
</div>
)}
</div>
{/* Cancel Order Dialog */}
<BottomDialog open={cancelDialogOpen} onClose={() => setCancelDialogOpen(false)}>
<div className="p-6">
<div className="mb-4 flex flex-row items-center justify-between">
<p className="text-xl font-bold text-gray-900">Cancel Order</p>
<button onClick={() => setCancelDialogOpen(false)}>
<X className="h-6 w-6 text-gray-400" />
</button>
</div>
<div className="mb-4 rounded-xl border border-red-100 bg-red-50 p-4">
<p className="text-sm text-red-800">
Are you sure you want to cancel this order? This action cannot be undone.
</p>
</div>
<p className="mb-2 font-medium text-gray-700">Reason for cancellation</p>
<textarea
className="mb-6 min-h-24 w-full rounded-xl border border-gray-200 bg-gray-50 p-4 text-base text-gray-800"
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
placeholder="Please tell us why you are cancelling..."
rows={3}
/>
<button
className={`flex w-full items-center justify-center rounded-xl py-4 text-center font-bold text-white shadow-sm ${
cancelOrderMutation.isPending ? 'bg-red-400 opacity-70' : 'bg-red-600'
}`}
onClick={handleCancelOrder}
disabled={cancelOrderMutation.isPending}
>
{cancelOrderMutation.isPending ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
'Confirm Cancellation'
)}
</button>
</div>
</BottomDialog>
{/* Raise Complaint Dialog */}
<BottomDialog open={complaintDialogOpen} onClose={() => setComplaintDialogOpen(false)}>
<ComplaintForm
open={complaintDialogOpen}
onClose={() => {
setComplaintDialogOpen(false)
refetch()
}}
orderId={order.id}
/>
</BottomDialog>
</div>
)
}