feat: add geolocation fields to session and implement geo stats endpoint

- Added country, city, countryCode, latitude, and longitude fields to the Session model.
- Updated geoip service to fetch and store geolocation data based on user IP.
- Created a new admin endpoint to retrieve geolocation statistics, including user counts by country and city.
- Enhanced admin page to display geolocation statistics with expandable city details.
- Introduced caching for geolocation data to optimize performance.
This commit is contained in:
Jose Selesan
2026-06-10 10:18:31 -03:00
parent 00f0cf511f
commit dc8a10a612
15 changed files with 389 additions and 30 deletions

View File

@@ -1,11 +1,30 @@
import { apiClient } from '@/lib/api-client';
import { useQuery } from '@tanstack/react-query';
import { Link, useLocation } from '@tanstack/react-router';
import { Building2, CalendarDays, Crosshair, Users } from 'lucide-react';
import {
Building2,
CalendarDays,
ChevronDown,
ChevronRight,
Crosshair,
Globe,
Users,
} from 'lucide-react';
import { Fragment, useState } from 'react';
import { AdminLayout } from './admin-layout';
function countryFlag(countryCode: string): string {
if (countryCode === 'LOCAL' || countryCode === 'XX') return '';
const codePoints = countryCode
.toUpperCase()
.split('')
.map((c) => 0x1f1e6 + c.charCodeAt(0) - 65);
return String.fromCodePoint(...codePoints);
}
export function AdminPage() {
const location = useLocation();
const [expandedCountry, setExpandedCountry] = useState<string | null>(null);
const complexesQuery = useQuery({
queryKey: ['admin-complexes'],
@@ -17,6 +36,11 @@ export function AdminPage() {
queryFn: () => apiClient.admin.listUsers(),
});
const geoQuery = useQuery({
queryKey: ['admin-geo-stats'],
queryFn: () => apiClient.admin.getGeoStats(),
});
const stats = {
totalComplexes: complexesQuery.data?.length ?? 0,
totalUsers: usersQuery.data?.length ?? 0,
@@ -125,6 +149,106 @@ export function AdminPage() {
</Link>
</div>
</div>
<div>
<h2 className="mb-3 text-lg font-semibold">Usuarios por país / ciudad</h2>
{geoQuery.isLoading && <p className="text-sm text-muted-foreground">Cargando...</p>}
{geoQuery.data && geoQuery.data.countries.length === 0 && (
<div className="rounded-2xl border border-border/60 bg-card p-8 text-center shadow-sm">
<Globe className="mx-auto mb-2 size-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
Aún no hay datos de geolocalización. Aparecerán a medida que los usuarios inicien
sesión.
</p>
</div>
)}
{geoQuery.data && geoQuery.data.countries.length > 0 && (
<div className="overflow-hidden rounded-2xl border border-border/60 bg-card shadow-sm">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border/60">
<th className="w-8 px-4 py-3" />
<th className="px-4 py-3 text-left font-medium text-muted-foreground">País</th>
<th className="px-4 py-3 text-right font-medium text-muted-foreground">
Usuarios
</th>
</tr>
</thead>
<tbody>
{geoQuery.data.countries.map((country) => {
const isExpanded = expandedCountry === country.countryCode;
const flag = countryFlag(country.countryCode);
return (
<Fragment key={country.countryCode}>
<tr
className={`cursor-pointer border-b border-border/40 transition-colors hover:bg-accent/50 ${isExpanded ? 'bg-accent/30' : ''}`}
onClick={() => setExpandedCountry(isExpanded ? null : country.countryCode)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setExpandedCountry(isExpanded ? null : country.countryCode);
}
}}
tabIndex={0}
role="button"
>
<td className="px-4 py-3">
{country.cities.length > 1 ||
country.cities[0]?.city !== country.country ? (
<button type="button" className="text-muted-foreground">
{isExpanded ? (
<ChevronDown className="size-4" />
) : (
<ChevronRight className="size-4" />
)}
</button>
) : (
<span className="inline-block w-4" />
)}
</td>
<td className="px-4 py-3">
<span className="mr-2">{flag}</span>
{country.country}
</td>
<td className="px-4 py-3 text-right font-medium">{country.totalUsers}</td>
</tr>
{isExpanded && (
<tr>
<td colSpan={3} className="bg-accent/20 p-0">
<table className="w-full text-xs">
<tbody>
{country.cities.map((city) => (
<tr key={city.city} className="border-b border-border/20">
<td className="w-8 px-4 py-2" />
<td className="px-4 py-2 text-muted-foreground">{city.city}</td>
<td className="px-4 py-2 text-right font-medium">
{city.userCount}
</td>
</tr>
))}
</tbody>
</table>
</td>
</tr>
)}
</Fragment>
);
})}
</tbody>
</table>
<div className="border-t border-border/40 px-4 py-2 text-xs text-muted-foreground">
{geoQuery.data.totalUniqueCountries}{' '}
{geoQuery.data.totalUniqueCountries === 1 ? 'país' : 'países'} · solo sesiones activas
con geolocalización resuelta
</div>
</div>
)}
</div>
</AdminLayout>
);
}

View File

@@ -2,6 +2,7 @@ import type {
AdminBlockUserInput,
AdminComplexListItem,
AdminCreatePlanInput,
AdminGeoStats,
AdminGlobalStats,
AdminUpdatePlanInput,
AdminUser,
@@ -77,6 +78,11 @@ export async function getGlobalStats() {
return response.data;
}
export async function getGeoStats() {
const response = await http.get<AdminGeoStats>('/api/admin/geo-stats');
return response.data;
}
export async function getUserSessions(userId: string) {
const response = await http.get<AdminUserSession[]>(`/api/admin/users/${userId}/sessions`);
return response.data;