ifixkart-admin/app/(admin)/integrations/shipping/page.tsx

396 lines
17 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import {
Truck,
ShieldCheck,
Server,
Lock,
RefreshCw,
CheckCircle2,
AlertCircle,
MapPin,
Package,
DollarSign,
Key,
Calendar,
} from 'lucide-react';
import { toast } from 'sonner';
import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav';
import { integrationService } from '@/services/api/integrationService';
export default function ShippingIntegrationsPage() {
const [creds, setCreds] = useState<any>({
email: '',
pickup_location: 'Primary',
pickup_pin: '',
api_url: 'https://apiv2.shiprocket.in/v1/external',
source: 'unconfigured',
is_locked_by_config: false,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// Auth test
const [authEmail, setAuthEmail] = useState('');
const [authPassword, setAuthPassword] = useState('');
const [authing, setAuthing] = useState(false);
// Serviceability check
const [pickupPin, setPickupPin] = useState('');
const [deliveryPin, setDeliveryPin] = useState('');
const [weight, setWeight] = useState(0.5);
const [isCod, setIsCod] = useState(false);
const [checkingService, setCheckingService] = useState(false);
const [serviceResults, setServiceResults] = useState<any[]>([]);
const fetchShippingConfig = async () => {
setLoading(true);
try {
const data = await integrationService.getShiprocketCredentials();
setCreds(data);
if (data.pickup_pin) setPickupPin(data.pickup_pin);
if (data.email) setAuthEmail(data.email);
} catch (err: any) {
toast.error('Failed to load Shiprocket credentials');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchShippingConfig();
}, []);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
await integrationService.saveShiprocketCredentials(creds);
toast.success('Shiprocket credentials saved successfully');
} catch (err: any) {
toast.error(err.message || 'Failed to save Shiprocket credentials');
} finally {
setSaving(false);
}
};
const handleAuthTest = async (e: React.FormEvent) => {
e.preventDefault();
if (!authEmail.trim() || !authPassword.trim()) {
toast.error('Email and password are required for Shiprocket login');
return;
}
setAuthing(true);
try {
const res = await integrationService.authShiprocket({
email: authEmail.trim(),
password: authPassword.trim(),
});
if (res.status === 'SUCCESS') {
toast.success('Shiprocket Authentication Successful! Session token generated.');
} else {
toast.error(`Auth failed: ${res.detail || JSON.stringify(res)}`);
}
} catch (err: any) {
toast.error(err.message || 'Shiprocket authentication failed');
} finally {
setAuthing(false);
}
};
const handleCheckServiceability = async (e: React.FormEvent) => {
e.preventDefault();
if (!pickupPin.trim() || !deliveryPin.trim()) {
toast.error('Both Pickup and Delivery Pincodes are required');
return;
}
setCheckingService(true);
try {
const res = await integrationService.checkShiprocketServiceability({
pickup_pin: pickupPin.trim(),
delivery_pin: deliveryPin.trim(),
weight,
cod: isCod,
});
if (res.status === 'SUCCESS') {
const couriers = res.data?.data?.available_courier_companies || [];
setServiceResults(couriers);
toast.success(`Serviceability confirmed! ${couriers.length} couriers available.`);
} else {
toast.error(`Serviceability check failed: ${res.detail || 'Pincode not serviceable'}`);
}
} catch (err: any) {
toast.error(err.message || 'Courier serviceability check failed');
} finally {
setCheckingService(false);
}
};
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<IntegrationsHeaderNav activeTab="shipping" />
{/* Top Banner */}
<div className="p-4 rounded-xl bg-purple-50 dark:bg-purple-950/30 border border-purple-200 dark:border-purple-900/50 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-base font-semibold text-purple-900 dark:text-purple-100 flex items-center gap-2">
<Truck className="w-4 h-4 text-purple-600" />
Shiprocket Logistics & Courier Partner Integration
</h2>
<p className="text-xs text-purple-700 dark:text-purple-300 mt-0.5">
Automated courier rate comparison, pickup dispatch, label printing, and real-time pincode serviceability calculator.
</p>
</div>
{creds.is_locked_by_config ? (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs font-semibold">
<ShieldCheck className="w-3.5 h-3.5 text-blue-600" />
Configured via Config.py
</span>
) : (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-200 text-xs font-semibold">
<Server className="w-3.5 h-3.5 text-purple-600" />
Database Configuration
</span>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
{/* Credentials Form (Cols 1-6) */}
<div className="lg:col-span-6 rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<Key className="w-4 h-4 text-purple-600" />
Shiprocket Logistics Settings
</h3>
</div>
<form onSubmit={handleSave} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Shiprocket Account Email
</label>
<input
type="email"
disabled={creds.is_locked_by_config}
value={creds.email || ''}
onChange={(e) => setCreds({ ...creds, email: e.target.value })}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-60 focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Primary Pickup Hub
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.pickup_location || 'Primary'}
onChange={(e) => setCreds({ ...creds, pickup_location: e.target.value })}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-60 focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Warehouse Pincode
</label>
<input
type="text"
disabled={creds.is_locked_by_config}
value={creds.pickup_pin || ''}
onChange={(e) => setCreds({ ...creds, pickup_pin: e.target.value })}
placeholder="e.g. 600001"
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-60 focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
</div>
{!creds.is_locked_by_config && (
<button
type="submit"
disabled={saving}
className="w-full py-2.5 px-4 rounded-lg bg-purple-600 hover:bg-purple-700 text-white text-xs font-semibold shadow-sm transition"
>
{saving ? 'Saving...' : 'Save Shiprocket Settings'}
</button>
)}
</form>
{/* Quick Login Authenticator */}
<div className="mt-6 pt-5 border-t border-gray-100 dark:border-gray-800">
<h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-2">
Refresh Authentication Token
</h4>
<form onSubmit={handleAuthTest} className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<input
type="email"
placeholder="Account email"
value={authEmail}
onChange={(e) => setAuthEmail(e.target.value)}
className="w-full px-3 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
<input
type="password"
placeholder="Account password"
value={authPassword}
onChange={(e) => setAuthPassword(e.target.value)}
className="w-full px-3 py-1.5 text-xs rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
/>
</div>
<button
type="submit"
disabled={authing}
className="w-full py-2 px-3 rounded-lg bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 text-xs font-semibold transition flex items-center justify-center gap-1.5"
>
<RefreshCw className={`w-3.5 h-3.5 ${authing ? 'animate-spin' : ''}`} />
{authing ? 'Authenticating...' : 'Authenticate & Generate Token'}
</button>
</form>
</div>
</div>
{/* Real-time Courier Serviceability Checker (Cols 7-12) */}
<div className="lg:col-span-6 rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm flex flex-col justify-between">
<div>
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-2">
<MapPin className="w-4 h-4 text-purple-600" />
Pincode Serviceability & Rate Calculator
</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
Check real-time courier partner availability, estimated delivery days, and freight tariffs.
</p>
<form onSubmit={handleCheckServiceability} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Pickup Pincode
</label>
<input
type="text"
value={pickupPin}
onChange={(e) => setPickupPin(e.target.value)}
placeholder="e.g. 600001"
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Destination Pincode
</label>
<input
type="text"
value={deliveryPin}
onChange={(e) => setDeliveryPin(e.target.value)}
placeholder="e.g. 560001"
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 items-center">
<div>
<label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
Weight (kg)
</label>
<input
type="number"
step="0.1"
value={weight}
onChange={(e) => setWeight(parseFloat(e.target.value) || 0.5)}
className="w-full px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-500 focus:outline-none"
/>
</div>
<div className="pt-4">
<label className="flex items-center gap-2 cursor-pointer text-xs font-medium text-gray-700 dark:text-gray-300">
<input
type="checkbox"
checked={isCod}
onChange={(e) => setIsCod(e.target.checked)}
className="rounded border-gray-300 text-purple-600 focus:ring-purple-500 w-4 h-4"
/>
Cash On Delivery (COD)
</label>
</div>
</div>
<button
type="submit"
disabled={checkingService}
className="w-full py-2.5 px-4 rounded-lg bg-purple-600 hover:bg-purple-700 text-white text-xs font-semibold shadow-sm transition flex items-center justify-center gap-2"
>
<Truck className={`w-3.5 h-3.5 ${checkingService ? 'animate-bounce' : ''}`} />
{checkingService ? 'Checking Couriers...' : 'Calculate Serviceability'}
</button>
</form>
</div>
<div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-800 text-xs text-gray-500">
Couriers: Bluedart, Delhivery, Ekart, DTDC, Shadowfax
</div>
</div>
</div>
{/* Available Couriers Table */}
{serviceResults.length > 0 && (
<div className="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-6 shadow-sm">
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-4">
<CheckCircle2 className="w-4 h-4 text-emerald-600" />
Available Courier Partners ({serviceResults.length})
</h3>
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="bg-gray-50 dark:bg-gray-800/50 text-gray-500 uppercase font-medium border-y border-gray-100 dark:border-gray-800">
<tr>
<th className="py-2.5 px-3">Courier Name</th>
<th className="py-2.5 px-3">Estimated Delivery</th>
<th className="py-2.5 px-3">Rating</th>
<th className="py-2.5 px-3">Freight Charge</th>
<th className="py-2.5 px-3">COD Eligible</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
{serviceResults.map((c: any, idx: number) => (
<tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
<td className="py-2.5 px-3 font-semibold text-gray-900 dark:text-white">
{c.courier_name || 'Standard Courier'}
</td>
<td className="py-2.5 px-3 text-gray-600 dark:text-gray-300">
{c.estimated_delivery_days ? `${c.estimated_delivery_days} Days` : '2-4 Days'}
</td>
<td className="py-2.5 px-3">
<span className="inline-flex px-2 py-0.5 rounded text-[10px] font-semibold bg-amber-100 dark:bg-amber-950 text-amber-800 dark:text-amber-300">
★ {c.rating || '4.5'}
</span>
</td>
<td className="py-2.5 px-3 font-mono font-medium text-emerald-600 dark:text-emerald-400">
₹{c.rate || c.freight_charge || '60'}
</td>
<td className="py-2.5 px-3">
<span
className={`inline-flex px-2 py-0.5 rounded-full text-[10px] font-semibold ${
c.cod === 1 || c.is_cod
? 'bg-emerald-100 dark:bg-emerald-950 text-emerald-800 dark:text-emerald-300'
: 'bg-gray-100 dark:bg-gray-800 text-gray-500'
}`}
>
{c.cod === 1 || c.is_cod ? 'Yes' : 'Prepaid Only'}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}