ifixkart-admin/app/(admin)/logistics/page.tsx

341 lines
15 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import {
Truck,
Wallet,
Package,
Clock,
RefreshCw,
MapPin,
Loader2,
} from 'lucide-react';
import { apiFetch } from '@/services/api/client';
import { API_ENDPOINTS } from '@/services/api/config';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { LogisticsHeaderNav } from '@/components/logistics/LogisticsHeaderNav';
interface LogisticsDashboard {
status: string;
is_enabled: boolean;
mode: string;
wallet_balance_inr: number;
active_shipments_count: number;
couriers: Array<{
id: number;
name: string;
mode: string;
min_weight_kg: number;
estimated_days: number;
rate_inr: number;
rating: number;
}>;
recent_dispatches: Array<{
tracking_id: string;
order_id: string;
courier: string;
destination_city: string;
status: string;
dispatch_date: string;
}>;
}
function inr(amount: number) {
return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
function dateLabel(value?: string) {
if (!value) return '—';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '—';
return format(date, 'dd-MMM-yyyy');
}
export default function LogisticsDashboardPage() {
const [data, setData] = useState<LogisticsDashboard | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [pickupPincode, setPickupPincode] = useState<string>('');
const [deliveryPincode, setDeliveryPincode] = useState<string>('');
const [weightKg, setWeightKg] = useState<number>(0.5);
const [calculatedRates, setCalculatedRates] = useState<LogisticsDashboard['couriers'] | null>(null);
const fetchData = async () => {
try {
setLoading(true);
const res = await apiFetch<LogisticsDashboard>(API_ENDPOINTS.SHIPPING_DASHBOARD);
if (res) {
setData(res);
setCalculatedRates(res.couriers || []);
}
} catch (err: unknown) {
console.error('Failed to load logistics dashboard:', err);
toast.error('Failed to load logistics information');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
const handleCalculateRate = (e: React.FormEvent) => {
e.preventDefault();
if (!pickupPincode || !deliveryPincode) {
toast.error('Please specify valid 6-digit pincodes');
return;
}
if (data?.couriers) {
const adjusted = data.couriers.map(c => ({
...c,
rate_inr: Math.round(c.rate_inr * (weightKg <= 0.5 ? 1 : 1 + (weightKg - 0.5) * 0.8))
}));
setCalculatedRates(adjusted);
toast.success('Courier rates calculated successfully');
}
};
const dataCardShell =
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
const fieldClass =
'w-full h-9 px-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary';
const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5';
const primaryButton =
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
const secondaryButton =
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
const couriers = data?.couriers || [];
const avgDays = couriers.length
? couriers.reduce((sum, courier) => sum + (courier.estimated_days || 0), 0) / couriers.length
: null;
const dispatches = data?.recent_dispatches || [];
return (
<div className="flex flex-col gap-5 min-w-0">
<LogisticsHeaderNav />
<div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">Shiprocket</h1>
{data?.mode && (
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge bg-muted text-foreground text-[11px] font-semibold">
{data.mode}
</span>
)}
{data && (
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
data.is_enabled ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'
}`}>
{data.is_enabled ? 'Enabled' : 'Disabled'}
</span>
)}
</div>
<button type="button" onClick={fetchData} disabled={loading} className={secondaryButton}>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
Refresh
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Wallet</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight truncate">
{loading ? '—' : inr(data?.wallet_balance_inr ?? 0)}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Wallet className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Active shipments</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">
{loading ? '—' : data?.active_shipments_count ?? 0}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Package className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Couriers</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">
{loading ? '—' : couriers.length}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Truck className="w-4 h-4" />
</span>
</div>
</div>
<div className={`${dataCardShell} p-4`}>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-[13px] text-muted-foreground">Avg estimate</p>
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight">
{loading ? '—' : avgDays === null ? '—' : `${avgDays.toFixed(1)} days`}
</p>
</div>
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
<Clock className="w-4 h-4" />
</span>
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
<div className={`lg:col-span-4 ${dataCardShell} p-4`}>
<h2 className="text-[13px] font-semibold text-foreground mb-4">Rate check</h2>
<form onSubmit={handleCalculateRate} className="space-y-3">
<div>
<label className={labelClass}>Pickup pincode</label>
<div className="relative">
<MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
<input
type="text"
inputMode="numeric"
maxLength={6}
value={pickupPincode}
onChange={(e) => setPickupPincode(e.target.value.replace(/\D/g, '').slice(0, 6))}
className={`${fieldClass} pl-8`}
/>
</div>
</div>
<div>
<label className={labelClass}>Delivery pincode</label>
<div className="relative">
<MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
<input
type="text"
inputMode="numeric"
maxLength={6}
value={deliveryPincode}
onChange={(e) => setDeliveryPincode(e.target.value.replace(/\D/g, '').slice(0, 6))}
className={`${fieldClass} pl-8`}
/>
</div>
</div>
<div>
<div className="flex items-center justify-between mb-1.5">
<label className={labelClass + ' mb-0'}>Weight</label>
<span className="text-[12px] font-semibold text-foreground">{weightKg.toFixed(1)} kg</span>
</div>
<input
type="range"
min="0.1"
max="5.0"
step="0.1"
value={weightKg}
onChange={(e) => setWeightKg(parseFloat(e.target.value))}
className="w-full accent-primary cursor-pointer"
/>
</div>
<button type="submit" className={`${primaryButton} w-full`}>
Calculate rates
</button>
</form>
</div>
<div className={`lg:col-span-8 ${dataCardShell}`}>
<div className="px-4 py-3 border-b border-border">
<h2 className="text-[13px] font-semibold text-foreground">Couriers</h2>
</div>
{loading ? (
<div className="py-16 flex justify-center">
<Loader2 className="w-6 h-6 animate-spin text-primary" />
</div>
) : (
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[640px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Courier</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Mode</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Days</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Rate</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Rating</th>
</tr>
</thead>
<tbody>
{(calculatedRates || []).length === 0 ? (
<tr>
<td colSpan={5} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No couriers</td>
</tr>
) : (calculatedRates || []).map((courier) => (
<tr key={courier.id} className="border-b border-border last:border-b-0 hover:bg-muted/10">
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">{courier.name}</td>
<td className="px-4 py-2.5">
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge bg-primary/10 text-primary text-[11px] font-semibold">
{courier.mode}
</span>
</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">{courier.estimated_days}</td>
<td className="px-4 py-2.5 text-right text-[13px] font-semibold text-foreground">{inr(courier.rate_inr)}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">{courier.rating}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
<div className={dataCardShell}>
<div className="px-4 py-3 border-b border-border">
<h2 className="text-[13px] font-semibold text-foreground">Recent dispatches</h2>
</div>
{loading ? (
<div className="py-16 flex justify-center">
<Loader2 className="w-6 h-6 animate-spin text-primary" />
</div>
) : (
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[760px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Tracking</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Order</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Courier</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">City</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Status</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Dispatched</th>
</tr>
</thead>
<tbody>
{dispatches.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No dispatches</td>
</tr>
) : dispatches.map((dispatch) => (
<tr key={dispatch.tracking_id} className="border-b border-border last:border-b-0 hover:bg-muted/10">
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">{dispatch.tracking_id}</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground">{dispatch.order_id}</td>
<td className="px-4 py-2.5 text-[13px] text-foreground">{dispatch.courier}</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground">{dispatch.destination_city || '—'}</td>
<td className="px-4 py-2.5">
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge bg-primary/10 text-primary text-[11px] font-semibold">
{dispatch.status}
</span>
</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground">{dateLabel(dispatch.dispatch_date)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
}