Fix and UI imporvements

This commit is contained in:
Urtzi Alfaro
2025-12-09 10:21:41 +01:00
parent 667e6e0404
commit 508f4569b9
22 changed files with 833 additions and 953 deletions

View File

@@ -33,6 +33,7 @@
"i18next": "^23.7.0",
"i18next-icu": "^2.4.1",
"immer": "^10.0.3",
"leaflet": "^1.9.4",
"lucide-react": "^0.294.0",
"papaparse": "^5.4.1",
"react": "^18.2.0",
@@ -43,6 +44,7 @@
"react-hook-form": "^7.48.0",
"react-hot-toast": "^2.4.1",
"react-i18next": "^13.5.0",
"react-leaflet": "^4.2.1",
"react-router-dom": "^6.20.0",
"recharts": "^2.10.0",
"tailwind-merge": "^2.1.0",
@@ -4038,6 +4040,17 @@
"integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",
"license": "MIT"
},
"node_modules/@react-leaflet/core": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-2.1.0.tgz",
"integrity": "sha512-Qk7Pfu8BSarKGqILj4x7bCSZ1pjuAPZ+qmRwH5S7mDS91VSbVVsJSrW4qA+GPrro8t69gFYVMWb1Zc4yFmPiVg==",
"license": "Hippocratic-2.1",
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
},
"node_modules/@remix-run/router": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
@@ -11597,6 +11610,13 @@
"node": ">=14.0.0"
}
},
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause",
"peer": true
},
"node_modules/leven": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@@ -13415,6 +13435,20 @@
"dev": true,
"license": "MIT"
},
"node_modules/react-leaflet": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-4.2.1.tgz",
"integrity": "sha512-p9chkvhcKrWn/H/1FFeVSqLdReGwn2qmiobOQGO3BifX+/vV/39qhY8dGqbdcPh1e6jxh/QHriLXr7a4eLFK4Q==",
"license": "Hippocratic-2.1",
"dependencies": {
"@react-leaflet/core": "^2.1.0"
},
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
},
"node_modules/react-refresh": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",

View File

@@ -54,6 +54,7 @@
"i18next": "^23.7.0",
"i18next-icu": "^2.4.1",
"immer": "^10.0.3",
"leaflet": "^1.9.4",
"lucide-react": "^0.294.0",
"papaparse": "^5.4.1",
"react": "^18.2.0",
@@ -64,6 +65,7 @@
"react-hook-form": "^7.48.0",
"react-hot-toast": "^2.4.1",
"react-i18next": "^13.5.0",
"react-leaflet": "^4.2.1",
"react-router-dom": "^6.20.0",
"recharts": "^2.10.0",
"tailwind-merge": "^2.1.0",

View File

@@ -1,9 +1,12 @@
/*
* Distribution Map Component for Enterprise Dashboard
* Shows delivery routes and shipment status across the network
* Shows delivery routes and shipment status across the network with real Leaflet map
*/
import React, { useState } from 'react';
import { MapContainer, TileLayer, Marker, Polyline, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';
import { Badge } from '../ui/Badge';
import { Button } from '../ui/Button';
@@ -22,6 +25,14 @@ import {
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
// Fix for default marker icons in Leaflet
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});
interface RoutePoint {
tenant_id: string;
name: string;
@@ -32,6 +43,7 @@ interface RoutePoint {
estimated_arrival?: string;
actual_arrival?: string;
sequence: number;
id?: string;
}
interface RouteData {
@@ -40,7 +52,7 @@ interface RouteData {
total_distance_km: number;
estimated_duration_minutes: number;
status: 'planned' | 'in_progress' | 'completed' | 'cancelled';
route_points?: RoutePoint[];
route_sequence?: RoutePoint[]; // Backend returns route_sequence, not route_points
}
interface ShipmentStatusData {
@@ -55,13 +67,22 @@ interface DistributionMapProps {
shipments?: ShipmentStatusData;
}
// Helper function to create custom markers
const createRouteMarker = (color: string, number: number) => {
return L.divIcon({
className: 'custom-route-marker',
html: `<div style="background-color: ${color}; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 3px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.3); font-size: 14px; font-weight: bold; color: white;">${number}</div>`,
iconSize: [32, 32],
iconAnchor: [16, 16]
});
};
const DistributionMap: React.FC<DistributionMapProps> = ({
routes = [],
shipments = { pending: 0, in_transit: 0, delivered: 0, failed: 0 }
}) => {
const { t } = useTranslation('dashboard');
const [selectedRoute, setSelectedRoute] = useState<RouteData | null>(null);
const [showAllRoutes, setShowAllRoutes] = useState(true);
const renderMapVisualization = () => {
if (!routes || routes.length === 0) {
@@ -87,9 +108,12 @@ const DistributionMap: React.FC<DistributionMapProps> = ({
);
}
// Find active routes (in_progress or planned for today)
// Find active routes with GPS data
const activeRoutes = routes.filter(route =>
route.status === 'in_progress' || route.status === 'planned'
(route.status === 'in_progress' || route.status === 'planned') &&
route.route_sequence &&
route.route_sequence.length > 0 &&
route.route_sequence.every(point => point.latitude && point.longitude)
);
if (activeRoutes.length === 0) {
@@ -115,113 +139,108 @@ const DistributionMap: React.FC<DistributionMapProps> = ({
);
}
// Enhanced visual representation with improved styling
// Calculate center point (average of all route points)
const allPoints = activeRoutes.flatMap(route => route.route_sequence || []);
const centerLat = allPoints.reduce((sum, p) => sum + p.latitude, 0) / allPoints.length;
const centerLng = allPoints.reduce((sum, p) => sum + p.longitude, 0) / allPoints.length;
// Real Leaflet map with routes
return (
<div className="relative h-64 lg:h-96 rounded-xl overflow-hidden border-2" style={{
background: 'linear-gradient(135deg, var(--color-info-50) 0%, var(--color-primary-50) 50%, var(--color-secondary-50) 100%)',
borderColor: 'var(--border-primary)'
}}>
{/* Bakery-themed pattern overlay */}
<div className="absolute inset-0 opacity-5 bg-pattern" />
<div className="relative h-96 rounded-xl overflow-hidden border-2" style={{ borderColor: 'var(--border-primary)' }}>
<MapContainer
center={[centerLat, centerLng]}
zoom={6}
style={{ height: '100%', width: '100%' }}
scrollWheelZoom={true}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{/* Central Info Display */}
<div className="absolute inset-0 flex items-center justify-center">
<div className="text-center">
<div
className="w-20 h-20 rounded-2xl flex items-center justify-center mb-3 mx-auto shadow-lg"
style={{
backgroundColor: 'var(--color-info-100)',
}}
>
<MapIcon className="w-10 h-10" style={{ color: 'var(--color-info-600)' }} />
</div>
<div className="text-2xl font-bold mb-1" style={{ color: 'var(--text-primary)' }}>
{t('enterprise.distribution_map')}
</div>
<div className="text-sm font-medium px-4 py-2 rounded-full inline-block" style={{
backgroundColor: 'var(--color-info-100)',
color: 'var(--color-info-900)'
}}>
{activeRoutes.length} {t('enterprise.active_routes')}
</div>
</div>
</div>
{/* Render each route */}
{activeRoutes.map((route, routeIdx) => {
const points = route.route_sequence || [];
const routeColor = route.status === 'in_progress' ? '#3b82f6' : '#f59e0b';
{/* Glassmorphism Route Info Cards */}
<div className="absolute top-4 left-4 right-4 flex flex-wrap gap-2">
{activeRoutes.slice(0, 3).map((route, index) => (
<div
key={route.id}
className="glass-effect p-3 rounded-lg shadow-md backdrop-blur-sm max-w-xs"
style={{
backgroundColor: 'rgba(255, 255, 255, 0.9)',
border: '1px solid var(--border-primary)'
}}
>
<div className="flex items-center gap-2">
<div
className="w-8 h-8 rounded-lg flex items-center justify-center"
style={{
backgroundColor: 'var(--color-info-100)',
// Create polyline coordinates
const polylinePositions: [number, number][] = points.map(p => [p.latitude, p.longitude]);
return (
<React.Fragment key={route.id}>
{/* Route polyline */}
<Polyline
positions={polylinePositions}
pathOptions={{
color: routeColor,
weight: 4,
opacity: 0.7
}}
>
<Route className="w-4 h-4" style={{ color: 'var(--color-info-600)' }} />
</div>
<div className="flex-1 min-w-0">
<div className="font-semibold text-sm truncate" style={{ color: 'var(--text-primary)' }}>
{t('enterprise.route')} {route.route_number}
</div>
<div className="text-xs" style={{ color: 'var(--text-secondary)' }}>
{route.total_distance_km.toFixed(1)} km {Math.ceil(route.estimated_duration_minutes / 60)}h
</div>
</div>
</div>
</div>
))}
{activeRoutes.length > 3 && (
<div
className="glass-effect p-3 rounded-lg shadow-md backdrop-blur-sm"
style={{
backgroundColor: 'rgba(255, 255, 255, 0.9)',
border: '1px solid var(--border-primary)'
}}
>
<div className="text-sm font-semibold" style={{ color: 'var(--text-secondary)' }}>
+{activeRoutes.length - 3} more
</div>
</div>
)}
</div>
/>
{/* Status Legend */}
{/* Route stop markers */}
{points.map((point, idx) => {
const markerColor = point.status === 'delivered' ? '#22c55e' :
point.status === 'in_transit' ? '#3b82f6' :
point.status === 'failed' ? '#ef4444' : '#f59e0b';
return (
<Marker
key={`${route.id}-${idx}`}
position={[point.latitude, point.longitude]}
icon={createRouteMarker(markerColor, point.sequence)}
>
<Popup>
<div className="min-w-[200px]">
<div className="font-semibold text-base mb-1">{point.name}</div>
<div className="text-sm text-gray-600 mb-2">{point.address}</div>
<div className="text-xs text-gray-500">
<div>Route: {route.route_number}</div>
<div>Stop {point.sequence} of {points.length}</div>
<div className="capitalize mt-1">Status: {point.status}</div>
</div>
</div>
</Popup>
</Marker>
);
})}
</React.Fragment>
);
})}
</MapContainer>
{/* Status Legend Overlay */}
<div
className="absolute bottom-4 right-4 glass-effect p-4 rounded-lg shadow-lg backdrop-blur-sm space-y-2"
className="absolute bottom-4 right-4 glass-effect p-4 rounded-lg shadow-lg backdrop-blur-sm space-y-2 z-[1000]"
style={{
backgroundColor: 'rgba(255, 255, 255, 0.95)',
border: '1px solid var(--border-primary)'
}}
>
<div className="text-xs font-semibold mb-2" style={{ color: 'var(--text-primary)' }}>
{activeRoutes.length} {t('enterprise.active_routes')}
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: 'var(--color-warning)' }}></div>
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#22c55e' }}></div>
<span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
{t('enterprise.pending')}: {shipments.pending}
{t('enterprise.delivered')}: {shipments.delivered}
</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: 'var(--color-info)' }}></div>
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#3b82f6' }}></div>
<span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
{t('enterprise.in_transit')}: {shipments.in_transit}
</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: 'var(--color-success)' }}></div>
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#f59e0b' }}></div>
<span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
{t('enterprise.delivered')}: {shipments.delivered}
{t('enterprise.pending')}: {shipments.pending}
</span>
</div>
{shipments.failed > 0 && (
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: 'var(--color-error)' }}></div>
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#ef4444' }}></div>
<span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
{t('enterprise.failed')}: {shipments.failed}
</span>
@@ -437,9 +456,9 @@ const DistributionMap: React.FC<DistributionMapProps> = ({
</div>
{/* Timeline of Stops */}
{route.route_points && route.route_points.length > 0 && (
{route.route_sequence && route.route_sequence.length > 0 && (
<div className="ml-6 border-l-2 pl-6 space-y-3" style={{ borderColor: 'var(--border-secondary)' }}>
{route.route_points.map((point, idx) => {
{route.route_sequence.map((point, idx) => {
const getPointStatusColor = (status: string) => {
switch (status) {
case 'delivered':

View File

@@ -189,6 +189,7 @@ export function useEventNotifications(config: UseNotificationsConfig = {}): UseE
notifications,
recentNotifications,
isLoading: isLoading || !isConnected,
isConnected, // Added this missing return property
clearNotifications,
};
}

View File

@@ -6,13 +6,12 @@ import {
Package,
MapPin,
Calendar,
ArrowRight,
Search,
Filter,
MoreVertical,
Clock,
CheckCircle,
AlertTriangle
AlertTriangle,
X
} from 'lucide-react';
import {
Button,
@@ -22,8 +21,10 @@ import {
CardHeader,
CardTitle,
Badge,
Input
Input,
Tabs,
} from '../../../../components/ui';
import { TabsList, TabsTrigger, TabsContent } from '../../../../components/ui/Tabs';
import { PageHeader } from '../../../../components/layout';
import { useTenant } from '../../../../stores/tenant.store';
import { useDistributionOverview } from '../../../../api/hooks/useEnterpriseDashboard';
@@ -118,69 +119,60 @@ const DistributionPage: React.FC = () => {
/>
{/* Main Content Areas */}
<div className="flex flex-col gap-6">
<div className="space-y-6">
{/* Tabs Navigation */}
<div className="flex border-b border-gray-200">
<button
className={`px-4 py-2 font-medium text-sm transition-colors border-b-2 ${activeTab === 'overview'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
onClick={() => setActiveTab('overview')}
>
Vista General
</button>
<button
className={`px-4 py-2 font-medium text-sm transition-colors border-b-2 ${activeTab === 'routes'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
onClick={() => setActiveTab('routes')}
>
Listado de Rutas
</button>
<button
className={`px-4 py-2 font-medium text-sm transition-colors border-b-2 ${activeTab === 'shipments'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}
onClick={() => setActiveTab('shipments')}
>
Listado de Envíos
</button>
</div>
<Tabs
value={activeTab}
onValueChange={(value: 'overview' | 'routes' | 'shipments') => setActiveTab(value)}
className="w-full"
>
<TabsList className="flex w-full">
<TabsTrigger value="overview" className="flex-1">
{t('operations:distribution.tabs.overview', 'Vista General')}
</TabsTrigger>
<TabsTrigger value="routes" className="flex-1">
{t('operations:distribution.tabs.routes', 'Listado de Rutas')}
</TabsTrigger>
<TabsTrigger value="shipments" className="flex-1">
{t('operations:distribution.tabs.shipments', 'Listado de Envíos')}
</TabsTrigger>
</TabsList>
{/* Content based on Active Tab */}
{activeTab === 'overview' && (
<div className="space-y-6">
{/* Content based on Active Tab */}
<TabsContent value="overview" className="space-y-6 mt-6">
{/* Map Section */}
<Card className="overflow-hidden border-none shadow-lg">
<CardHeader className="bg-white border-b sticky top-0 z-10">
<Card className="overflow-hidden">
<CardHeader className="sticky top-0 z-10">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="p-2 bg-blue-100 rounded-lg">
<MapPin className="w-5 h-5 text-blue-600" />
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-[var(--color-info-50)] dark:bg-[var(--color-info-900)]">
<MapPin className="w-5 h-5 text-[var(--color-info)] dark:text-[var(--color-info-300)]" />
</div>
<div>
<CardTitle>{t('operations:map.title', 'Mapa de Distribución')}</CardTitle>
<p className="text-sm text-gray-500">Visualización en tiempo real de la flota</p>
<CardTitle className="text-lg">
{t('operations:map.title', 'Mapa de Distribución')}
</CardTitle>
<p className="text-sm text-[var(--text-secondary)]">
{t('operations:map.description', 'Visualización en tiempo real de la flota')}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="flex items-center gap-1">
<Badge variant="outline" className="flex items-center gap-1 border-[var(--border-primary)]">
<div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
En Vivo
{t('operations:map.live', 'En Vivo')}
</Badge>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="p-4 bg-slate-50">
<DistributionMap
routes={distributionData?.route_sequences || []}
shipments={shipmentStatus}
/>
<div className="p-4 bg-[var(--bg-secondary)]">
<div className="aspect-video rounded-lg overflow-hidden bg-[var(--bg-tertiary)] flex items-center justify-center">
<DistributionMap
routes={distributionData?.route_sequences || []}
shipments={shipmentStatus}
/>
</div>
</div>
</CardContent>
</Card>
@@ -189,7 +181,9 @@ const DistributionPage: React.FC = () => {
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>Rutas en Progreso</CardTitle>
<CardTitle className="text-lg">
{t('operations:distribution.active_routes', 'Rutas en Progreso')}
</CardTitle>
</CardHeader>
<CardContent>
{distributionData?.route_sequences?.filter((r: any) => r.status === 'in_progress').length > 0 ? (
@@ -197,101 +191,190 @@ const DistributionPage: React.FC = () => {
{distributionData.route_sequences
.filter((r: any) => r.status === 'in_progress')
.map((route: any) => (
<div key={route.id} className="flex items-center justify-between p-3 bg-white border rounded-lg shadow-sm">
<div
key={route.id}
className="flex items-center justify-between p-4 bg-[var(--bg-secondary)] border rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
>
<div className="flex items-center gap-3">
<div className="p-2 bg-blue-50 rounded-full">
<Truck className="w-4 h-4 text-blue-600" />
<div className="p-2 rounded-full bg-[var(--color-info-50)] dark:bg-[var(--color-info-900)]">
<Truck
className="w-4 h-4 text-[var(--color-info)] dark:text-[var(--color-info-300)]"
/>
</div>
<div>
<p className="font-medium text-sm text-gray-900">Ruta {route.route_number}</p>
<p className="text-xs text-gray-500">{route.formatted_driver_name || 'Sin conductor asignado'}</p>
<p className="font-medium text-[var(--text-primary)]">
{t('operations:distribution.route_prefix', 'Ruta')} {route.route_number}
</p>
<p className="text-sm text-[var(--text-secondary)]">
{route.formatted_driver_name || t('operations:distribution.no_driver', 'Sin conductor asignado')}
</p>
</div>
</div>
<Badge variant="info">En Ruta</Badge>
<Badge variant="info">
{t('operations:distribution.status.in_progress', 'En Ruta')}
</Badge>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-gray-500">
No hay rutas en progreso actualmente.
<div className="text-center py-8 text-[var(--text-secondary)]">
{t('operations:distribution.no_active_routes', 'No hay rutas en progreso actualmente.')}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">
{t('operations:distribution.pending_deliveries', 'Entregas Pendientes')}
</CardTitle>
</CardHeader>
<CardContent>
{distributionData?.status_counts?.pending > 0 ? (
<div className="space-y-4">
<div className="flex items-center justify-between p-4 bg-[var(--bg-secondary)] border rounded-lg">
<div className="flex items-center gap-3">
<div className="p-2 rounded-full bg-[var(--color-warning-50)] dark:bg-[var(--color-warning-900)]">
<Package
className="w-4 h-4 text-[var(--color-warning)] dark:text-[var(--color-warning-300)]"
/>
</div>
<div>
<p className="font-medium text-[var(--text-primary)]">
{t('operations:distribution.pending_count', 'Entregas Pendientes')}
</p>
<p className="text-sm text-[var(--text-secondary)]">
{t('operations:distribution.pending_desc', 'Aún por distribuir')}
</p>
</div>
</div>
<Badge variant="warning">
{distributionData.status_counts.pending}
</Badge>
</div>
</div>
) : (
<div className="text-center py-8 text-[var(--text-secondary)]">
{t('operations:distribution.no_pending', 'No hay entregas pendientes.')}
</div>
)}
</CardContent>
</Card>
</div>
</div>
)}
</TabsContent>
{activeTab === 'routes' && (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Listado de Rutas</CardTitle>
<div className="flex gap-2">
<Input
placeholder="Buscar rutas..."
leftIcon={<Search className="w-4 h-4 text-gray-400" />}
className="w-64"
/>
<Button variant="outline" size="sm" leftIcon={<Filter className="w-4 h-4" />}>Filtros</Button>
<TabsContent value="routes" className="space-y-6 mt-6">
<Card>
<CardHeader>
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<CardTitle className="text-lg">
{t('operations:distribution.routes_list', 'Listado de Rutas')}
</CardTitle>
<p className="text-sm text-[var(--text-secondary)] mt-1">
{t('operations:distribution.routes_desc', 'Gestión y seguimiento de rutas de distribución')}
</p>
</div>
<div className="flex flex-col sm:flex-row gap-2">
<Input
placeholder={t('operations:distribution.search_routes', 'Buscar rutas...')}
leftIcon={<Search className="w-4 h-4 text-[var(--text-tertiary)]" />}
className="w-full sm:w-64"
/>
<Button variant="outline" size="sm" leftIcon={<Filter className="w-4 h-4" />}>
{t('operations:actions.filters', 'Filtros')}
</Button>
</div>
</div>
</div>
</CardHeader>
<CardContent>
{(distributionData?.route_sequences?.length || 0) > 0 ? (
<div className="overflow-x-auto">
<table className="w-full text-sm text-left">
<thead className="text-xs text-gray-700 uppercase bg-gray-50">
<tr>
<th className="px-4 py-3">Ruta</th>
<th className="px-4 py-3">Estado</th>
<th className="px-4 py-3">Distancia</th>
<th className="px-4 py-3">Duración Est.</th>
<th className="px-4 py-3">Paradas</th>
<th className="px-4 py-3 text-right">Acciones</th>
</tr>
</thead>
<tbody>
{distributionData.route_sequences.map((route: any) => (
<tr key={route.id} className="border-b hover:bg-gray-50">
<td className="px-4 py-3 font-medium">{route.route_number}</td>
<td className="px-4 py-3">
<Badge variant={
route.status === 'completed' ? 'success' :
route.status === 'in_progress' ? 'info' :
route.status === 'pending' ? 'warning' : 'default'
}>
{route.status}
</Badge>
</td>
<td className="px-4 py-3">{route.total_distance_km?.toFixed(1) || '-'} km</td>
<td className="px-4 py-3">{route.estimated_duration_minutes || '-'} min</td>
<td className="px-4 py-3">{route.route_points?.length || 0}</td>
<td className="px-4 py-3 text-right">
<Button variant="ghost" size="sm" leftIcon={<MoreVertical className="w-4 h-4" />} />
</td>
</CardHeader>
<CardContent>
{(distributionData?.route_sequences?.length || 0) > 0 ? (
<div className="overflow-x-auto">
<table className="w-full text-sm text-left">
<thead className="text-xs text-[var(--text-secondary)] uppercase bg-[var(--bg-secondary)] border-b">
<tr>
<th className="px-4 py-3">{t('operations:distribution.table.route', 'Ruta')}</th>
<th className="px-4 py-3">{t('operations:distribution.table.status', 'Estado')}</th>
<th className="px-4 py-3">{t('operations:distribution.table.distance', 'Distancia')}</th>
<th className="px-4 py-3">{t('operations:distribution.table.duration', 'Duración Est.')}</th>
<th className="px-4 py-3">{t('operations:distribution.table.stops', 'Paradas')}</th>
<th className="px-4 py-3 text-right">{t('operations:distribution.table.actions', 'Acciones')}</th>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="text-center py-12 bg-gray-50 rounded-lg border border-dashed">
<p className="text-gray-500">No se encontraron rutas para esta fecha.</p>
</div>
)}
</CardContent>
</Card>
)}
</thead>
<tbody className="divide-y divide-[var(--border-primary)]">
{distributionData.route_sequences.map((route: any) => (
<tr key={route.id} className="hover:bg-[var(--bg-secondary)] transition-colors">
<td className="px-4 py-3 font-medium text-[var(--text-primary)]">
{t('operations:distribution.route_prefix', 'Ruta')} {route.route_number}
</td>
<td className="px-4 py-3">
<Badge variant={
route.status === 'completed' ? 'success' :
route.status === 'in_progress' ? 'info' :
route.status === 'pending' ? 'warning' : 'default'
}>
{route.status}
</Badge>
</td>
<td className="px-4 py-3">
{route.total_distance_km?.toFixed(1) || '-'} km
</td>
<td className="px-4 py-3">
{route.estimated_duration_minutes || '-'} min
</td>
<td className="px-4 py-3">
{route.route_points?.length || 0}
</td>
<td className="px-4 py-3 text-right">
<Button
variant="ghost"
size="sm"
icon={MoreVertical}
aria-label={t('operations:actions.more_options', 'Más opciones')}
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="text-center py-12 border-2 border-dashed border-[var(--border-primary)] rounded-lg">
<p className="text-[var(--text-secondary)]">
{t('operations:distribution.no_routes_found', 'No se encontraron rutas para esta fecha.')}
</p>
</div>
)}
</CardContent>
</Card>
</TabsContent>
{/* Similar structure for Shipments tab, simplified for now */}
{activeTab === 'shipments' && (
<div className="text-center py-12 bg-gray-50 rounded-lg border border-dashed">
<Package className="w-12 h-12 text-gray-300 mx-auto mb-3" />
<h3 className="text-lg font-medium text-gray-900">Gestión de Envíos</h3>
<p className="text-gray-500">Funcionalidad de listado detallado de envíos próximamente.</p>
</div>
)}
{/* Similar structure for Shipments tab, simplified for now */}
<TabsContent value="shipments" className="space-y-6 mt-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">
{t('operations:distribution.shipments_list', 'Gestión de Envíos')}
</CardTitle>
<p className="text-sm text-[var(--text-secondary)]">
{t('operations:distribution.shipments_desc', 'Funcionalidad de listado detallado de envíos próximamente.')}
</p>
</CardHeader>
<CardContent>
<div className="text-center py-12 border-2 border-dashed border-[var(--border-primary)] rounded-lg">
<Package className="w-12 h-12 text-[var(--text-tertiary)] mx-auto mb-4" />
<h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
{t('operations:distribution.shipments_title', 'Gestión de Envíos')}
</h3>
<p className="text-[var(--text-secondary)]">
{t('operations:distribution.shipments_desc', 'Funcionalidad de listado detallado de envíos próximamente.')}
</p>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
</div>
);

View File

@@ -58,6 +58,7 @@ const DemoPage = () => {
const [creationError, setCreationError] = useState('');
const [estimatedProgress, setEstimatedProgress] = useState(0);
const [progressStartTime, setProgressStartTime] = useState<number | null>(null);
const [estimatedRemainingSeconds, setEstimatedRemainingSeconds] = useState<number | null>(null);
// BUG-010 FIX: State for partial status warning
const [partialWarning, setPartialWarning] = useState<{
@@ -227,19 +228,19 @@ const DemoPage = () => {
} catch (error) {
console.error('Error creating demo:', error);
setCreationError('Error al iniciar la demo. Por favor, inténtalo de nuevo.');
} finally {
setCreatingTier(null);
setProgressStartTime(null);
setEstimatedProgress(0);
// Reset progress
setCloneProgress({
parent: 0,
children: [0, 0, 0],
distribution: 0,
overall: 0
});
setCreationError('Error al iniciar la demo. Por favor, inténtalo de nuevo.');
}
// NOTE: State reset moved to navigation callback and error handlers
// to prevent modal from disappearing before redirect
};
const pollForSessionStatus = async (sessionId, tier, sessionData) => {
@@ -287,17 +288,33 @@ const DemoPage = () => {
const statusData = await statusResponse.json();
// Capture estimated remaining time from backend
if (statusData.estimated_remaining_seconds !== undefined) {
setEstimatedRemainingSeconds(statusData.estimated_remaining_seconds);
}
// Update progress based on actual backend status
updateProgressFromBackendStatus(statusData, tier);
// BUG-010 FIX: Handle ready status separately from partial
if (statusData.status === 'ready') {
// Full success - navigate immediately
// Full success - set to 100% and navigate after delay
clearInterval(progressInterval);
setCloneProgress(prev => ({ ...prev, overall: 100 }));
setTimeout(() => {
// Reset state before navigation
setCreatingTier(null);
setProgressStartTime(null);
setEstimatedProgress(0);
setCloneProgress({
parent: 0,
children: [0, 0, 0],
distribution: 0,
overall: 0
});
// Navigate to the main dashboard which will automatically route to enterprise or bakery dashboard based on subscription tier
navigate('/app/dashboard');
}, 1000);
}, 1500); // Increased from 1000ms to show 100% completion
return;
} else if (statusData.status === 'PARTIAL' || statusData.status === 'partial') {
// BUG-010 FIX: Show warning modal for partial status
@@ -313,6 +330,15 @@ const DemoPage = () => {
return;
} else if (statusData.status === 'FAILED' || statusData.status === 'failed') {
clearInterval(progressInterval);
setCreatingTier(null);
setProgressStartTime(null);
setEstimatedProgress(0);
setCloneProgress({
parent: 0,
children: [0, 0, 0],
distribution: 0,
overall: 0
});
setCreationError('Error al clonar los datos de demo. Por favor, inténtalo de nuevo.');
return;
}
@@ -343,6 +369,15 @@ const DemoPage = () => {
} catch (error) {
clearInterval(progressInterval);
console.error('Error polling for status:', error);
setCreatingTier(null);
setProgressStartTime(null);
setEstimatedProgress(0);
setCloneProgress({
parent: 0,
children: [0, 0, 0],
distribution: 0,
overall: 0
});
setCreationError('Error verificando el estado de la demo. Por favor, inténtalo de nuevo.');
} finally {
// Clean up abort controller reference
@@ -466,7 +501,9 @@ const DemoPage = () => {
if (progress.parent && progress.children && progress.distribution !== undefined) {
// This looks like an enterprise results structure from the end of cloning
// Calculate progress based on parent, children, and distribution status
if (progress.parent.overall_status === 'ready' || progress.parent.overall_status === 'partial') {
// FIX 1: Handle both "completed" and "ready" for parent status
const parentStatus = progress.parent.overall_status;
if (parentStatus === 'ready' || parentStatus === 'completed' || parentStatus === 'partial') {
parentProgress = 100;
} else if (progress.parent.overall_status === 'pending') {
parentProgress = 50; // Increased from 25 for better perceived progress
@@ -482,9 +519,11 @@ const DemoPage = () => {
if (progress.children && progress.children.length > 0) {
childrenProgressArray = progress.children.map((child: any) => {
if (child.status === 'ready' || child.status === 'completed') return 100;
if (child.status === 'partial') return 75;
if (child.status === 'pending') return 30;
// FIX 2: Handle both status types for children
const childStatus = child.status || child.overall_status;
if (childStatus === 'ready' || childStatus === 'completed') return 100;
if (childStatus === 'partial') return 75;
if (childStatus === 'pending') return 30;
return 0;
});
const avgChildrenProgress = childrenProgressArray.reduce((a, b) => a + b, 0) / childrenProgressArray.length;
@@ -499,15 +538,22 @@ const DemoPage = () => {
}
if (progress.distribution) {
if (progress.distribution.status === 'ready' || progress.distribution.status === 'completed') {
// FIX 3: Handle both status types for distribution
const distStatus = progress.distribution.status || progress.distribution.overall_status;
if (distStatus === 'ready' || distStatus === 'completed') {
distributionProgress = 100;
} else if (progress.distribution.status === 'pending') {
} else if (distStatus === 'pending') {
distributionProgress = 50;
} else {
distributionProgress = progress.distribution.status === 'failed' ? 100 : 75;
distributionProgress = distStatus === 'failed' ? 100 : 75;
}
backendProgress = Math.round(backendProgress * 0.8 + distributionProgress * 0.2);
}
// FIX 4: Allow 100% progress when all components complete
if (parentProgress === 100 && childrenProgressArray.every(p => p === 100) && distributionProgress === 100) {
backendProgress = 100;
}
} else {
// If it's not the enterprise result structure, fall back to service-based calculation
const services = progress || {};
@@ -525,8 +571,9 @@ const DemoPage = () => {
distributionProgress = backendProgress * 0.8;
}
// Use the maximum of backend progress and estimated progress to prevent backtracking
const overallProgress = Math.max(Math.min(95, backendProgress), estimatedProgress);
// FIX 5: Don't cap at 95% when backend reports 100%
const cappedBackendProgress = backendProgress === 100 ? 100 : Math.min(95, backendProgress);
const overallProgress = Math.max(cappedBackendProgress, estimatedProgress);
setCloneProgress({
parent: Math.max(parentProgress, estimatedProgress * 0.9),
@@ -681,61 +728,127 @@ const DemoPage = () => {
<Modal
isOpen={creatingTier !== null}
onClose={() => { }}
size="md"
size="lg"
>
<ModalHeader
title="Configurando Tu Demo"
title={
<div className="flex items-center gap-3">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-primary"></div>
<span>Configurando Tu Demo</span>
</div>
}
showCloseButton={false}
/>
<ModalBody padding="lg">
<div className="space-y-4">
<div className="flex justify-between text-sm">
<span>Progreso total</span>
<span>{cloneProgress.overall}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div
className="bg-primary h-2 rounded-full transition-all duration-300"
style={{ width: `${cloneProgress.overall}%` }}
></div>
</div>
<div className="text-center text-sm text-[var(--text-secondary)] mt-4">
{getLoadingMessage(creatingTier, cloneProgress.overall)}
</div>
{creatingTier === 'enterprise' && (
<div className="space-y-3 mt-4">
<div className="flex justify-between text-sm">
<span className="font-medium">Obrador Central</span>
<span>{cloneProgress.parent}%</span>
<div className="space-y-6">
{/* Overall Progress Section */}
<div className="text-center">
<div className="flex justify-between text-sm mb-2">
<span className="font-medium">Progreso Total</span>
<span className="font-semibold text-lg">{cloneProgress.overall}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3 overflow-hidden">
<div
className="bg-gradient-to-r from-blue-500 to-purple-600 h-3 rounded-full transition-all duration-500 relative overflow-hidden"
style={{ width: `${cloneProgress.overall}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent animate-shimmer"></div>
</div>
</div>
{estimatedRemainingSeconds !== null && estimatedRemainingSeconds > 0 && (
<div className="mt-3 text-sm text-[var(--text-secondary)]">
~{estimatedRemainingSeconds}s restantes
</div>
)}
<div className="mt-4 text-[var(--text-secondary)]">
{getLoadingMessage(creatingTier, cloneProgress.overall)}
</div>
</div>
{/* Enterprise Detailed Progress */}
{creatingTier === 'enterprise' && (
<div className="space-y-5 mt-6">
{/* Parent Tenant */}
<div className="bg-blue-50 dark:bg-blue-900/20 rounded-xl p-4 border border-blue-200 dark:border-blue-800">
<div className="flex justify-between items-center mb-2">
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full bg-blue-500"></div>
<span className="font-semibold text-blue-900 dark:text-blue-100">Obrador Central</span>
</div>
<span className="font-medium text-blue-700 dark:text-blue-300">{cloneProgress.parent}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5">
<div
className="bg-gradient-to-r from-blue-400 to-blue-600 h-2.5 rounded-full transition-all duration-500"
style={{ width: `${cloneProgress.parent}%` }}
></div>
</div>
</div>
{/* Child Outlets */}
<div className="grid grid-cols-3 gap-3">
{cloneProgress.children.map((progress, index) => (
<div key={index} className="text-center">
<div className="text-xs text-[var(--text-tertiary)] mb-1">Outlet {index + 1}</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5">
<div
key={index}
className="bg-green-50 dark:bg-green-900/20 rounded-lg p-3 border border-green-200 dark:border-green-800"
>
<div className="flex justify-between items-center mb-1">
<span className="text-xs font-medium text-green-700 dark:text-green-300">Outlet {index + 1}</span>
<span className="text-xs font-semibold text-green-700 dark:text-green-300">{progress}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div
className="bg-blue-500 h-1.5 rounded-full transition-all duration-300"
className="bg-gradient-to-r from-green-400 to-green-600 h-2 rounded-full transition-all duration-500"
style={{ width: `${progress}%` }}
></div>
</div>
<div className="text-xs mt-1">{progress}%</div>
</div>
))}
</div>
<div className="flex justify-between text-sm mt-2">
<span className="font-medium">Distribución</span>
<span>{cloneProgress.distribution}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5">
<div
className="bg-purple-500 h-1.5 rounded-full transition-all duration-300"
style={{ width: `${cloneProgress.distribution}%` }}
></div>
{/* Distribution System */}
<div className="bg-purple-50 dark:bg-purple-900/20 rounded-xl p-4 border border-purple-200 dark:border-purple-800">
<div className="flex justify-between items-center mb-2">
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full bg-purple-500"></div>
<span className="font-semibold text-purple-900 dark:text-purple-100">Distribución</span>
</div>
<span className="font-medium text-purple-700 dark:text-purple-300">{cloneProgress.distribution}%</span>
</div>
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5">
<div
className="bg-gradient-to-r from-purple-400 to-purple-600 h-2.5 rounded-full transition-all duration-500"
style={{ width: `${cloneProgress.distribution}%` }}
></div>
</div>
</div>
</div>
)}
{/* Professional Progress Indicator */}
{creatingTier === 'professional' && cloneProgress.overall < 100 && (
<div className="text-center py-3">
<div className="flex justify-center items-center gap-1">
<div className="w-2 h-2 bg-primary rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
<div className="w-2 h-2 bg-primary rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
<div className="w-2 h-2 bg-primary rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
</div>
<p className="text-sm text-[var(--text-tertiary)] mt-2">
Procesando servicios en paralelo...
</p>
</div>
)}
{/* Information Box */}
<div className="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-3 border border-gray-200 dark:border-gray-700">
<p className="text-xs text-[var(--text-tertiary)] text-center">
{creatingTier === 'enterprise'
? 'Creando obrador central, outlets y sistema de distribución...'
: 'Personalizando tu panadería con datos reales...'}
</p>
</div>
</div>
</ModalBody>
</Modal>