feat: full locations CRUD + legal policies in settings
Backend: - CRUD completo para countries, regions y cities - GET /settings/policy/:key — página HTML pública para políticas - GET/PATCH /settings/policies/:key — admin endpoints protegidos Admin: - /locations: árbol interactivo País → Región → Ciudad con add/edit/delete - /settings: editor de Política de Privacidad y Términos con enlace público copiable - Sidebar: Ciudades → Ubicaciones Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
5c740420e9
commit
39c4301d1b
@@ -0,0 +1,263 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { toast } from 'sonner';
|
||||
import { Plus, Pencil, Trash2, ChevronDown, ChevronRight, Globe, Map, MapPin } from 'lucide-react';
|
||||
|
||||
interface City { id: string; name: string; latitude?: number; longitude?: number; }
|
||||
interface Region { id: string; name: string; cities: City[]; }
|
||||
interface Country { id: string; name: string; regions: Region[]; }
|
||||
|
||||
type EditingItem = { type: 'country' | 'region' | 'city'; id: string; name: string } | null;
|
||||
type AddingItem = { type: 'country' } | { type: 'region'; countryId: string } | { type: 'city'; regionId: string } | null;
|
||||
|
||||
export default function LocationsPage() {
|
||||
const [countries, setCountries] = useState<Country[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [expandedCountries, setExpandedCountries] = useState<Set<string>>(new Set());
|
||||
const [expandedRegions, setExpandedRegions] = useState<Set<string>>(new Set());
|
||||
const [editing, setEditing] = useState<EditingItem>(null);
|
||||
const [adding, setAdding] = useState<AddingItem>(null);
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
api.get<Country[]>('/locations/countries')
|
||||
.then(setCountries)
|
||||
.catch(() => toast.error('Error al cargar ubicaciones'))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const startAdd = (item: AddingItem) => { setAdding(item); setEditing(null); setInputValue(''); };
|
||||
const startEdit = (item: EditingItem) => { setEditing(item); setAdding(null); setInputValue(item?.name || ''); };
|
||||
const cancel = () => { setAdding(null); setEditing(null); setInputValue(''); };
|
||||
|
||||
const saveAdd = async () => {
|
||||
if (!inputValue.trim() || !adding) return;
|
||||
try {
|
||||
if (adding.type === 'country') {
|
||||
await api.post('/locations/countries', { name: inputValue.trim() });
|
||||
} else if (adding.type === 'region') {
|
||||
await api.post('/locations/regions', { country_id: adding.countryId, name: inputValue.trim() });
|
||||
} else if (adding.type === 'city') {
|
||||
await api.post('/locations/cities', { region_id: adding.regionId, name: inputValue.trim() });
|
||||
}
|
||||
toast.success('Creado correctamente');
|
||||
cancel();
|
||||
load();
|
||||
} catch (e: any) { toast.error(e?.message || 'Error al crear'); }
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!inputValue.trim() || !editing) return;
|
||||
try {
|
||||
if (editing.type === 'country') {
|
||||
await api.patch(`/locations/countries/${editing.id}`, { name: inputValue.trim() });
|
||||
} else if (editing.type === 'region') {
|
||||
await api.patch(`/locations/regions/${editing.id}`, { name: inputValue.trim() });
|
||||
} else if (editing.type === 'city') {
|
||||
await api.patch(`/locations/cities/${editing.id}`, { name: inputValue.trim() });
|
||||
}
|
||||
toast.success('Actualizado correctamente');
|
||||
cancel();
|
||||
load();
|
||||
} catch (e: any) { toast.error(e?.message || 'Error al actualizar'); }
|
||||
};
|
||||
|
||||
const remove = async (type: 'country' | 'region' | 'city', id: string, name: string) => {
|
||||
if (!confirm(`¿Eliminar "${name}"? Se eliminarán todos los datos anidados.`)) return;
|
||||
try {
|
||||
if (type === 'country') await api.delete(`/locations/countries/${id}`);
|
||||
else if (type === 'region') await api.delete(`/locations/regions/${id}`);
|
||||
else await api.delete(`/locations/cities/${id}`);
|
||||
toast.success('Eliminado correctamente');
|
||||
load();
|
||||
} catch (e: any) { toast.error(e?.message || 'Error al eliminar'); }
|
||||
};
|
||||
|
||||
const InlineForm = ({ onSave, onCancel }: { onSave: () => void; onCancel: () => void }) => (
|
||||
<div className="flex gap-2 mt-2">
|
||||
<Input
|
||||
autoFocus
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') onSave(); if (e.key === 'Escape') onCancel(); }}
|
||||
placeholder="Nombre..."
|
||||
className="h-8 text-sm"
|
||||
/>
|
||||
<Button size="sm" onClick={onSave} className="h-8">Guardar</Button>
|
||||
<Button size="sm" variant="ghost" onClick={onCancel} className="h-8">Cancelar</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (loading) return <div className="flex items-center justify-center py-16 text-muted-foreground">Cargando...</div>;
|
||||
|
||||
const totalRegions = countries.reduce((a, c) => a + c.regions.length, 0);
|
||||
const totalCities = countries.reduce((a, c) => a + c.regions.reduce((b, r) => b + r.cities.length, 0), 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Ubicaciones</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">
|
||||
{countries.length} países · {totalRegions} regiones · {totalCities} ciudades
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => startAdd({ type: 'country' })}>
|
||||
<Plus className="mr-1 h-4 w-4" />Añadir País
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{adding?.type === 'country' && (
|
||||
<Card>
|
||||
<CardContent className="pt-4">
|
||||
<p className="text-sm font-medium mb-1 flex items-center gap-1"><Globe size={14} /> Nuevo país</p>
|
||||
<InlineForm onSave={saveAdd} onCancel={cancel} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{countries.length === 0 && (
|
||||
<Card><CardContent className="py-12 text-center text-muted-foreground">No hay países. Agrega uno para comenzar.</CardContent></Card>
|
||||
)}
|
||||
|
||||
{countries.map((country) => {
|
||||
const isCountryOpen = expandedCountries.has(country.id);
|
||||
return (
|
||||
<Card key={country.id}>
|
||||
<CardContent className="pt-4">
|
||||
{/* Country row */}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
className="flex items-center gap-2 flex-1 text-left hover:opacity-80"
|
||||
onClick={() => setExpandedCountries(prev => {
|
||||
const s = new Set(prev);
|
||||
s.has(country.id) ? s.delete(country.id) : s.add(country.id);
|
||||
return s;
|
||||
})}
|
||||
>
|
||||
{isCountryOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
<Globe size={16} className="text-blue-500" />
|
||||
{editing?.type === 'country' && editing.id === country.id ? null : (
|
||||
<span className="font-semibold">{country.name}</span>
|
||||
)}
|
||||
<Badge variant="secondary" className="text-xs">{country.regions.length} regiones</Badge>
|
||||
</button>
|
||||
{!(editing?.type === 'country' && editing.id === country.id) && (
|
||||
<div className="flex gap-1">
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => startEdit({ type: 'country', id: country.id, name: country.name })}>
|
||||
<Pencil size={13} />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => remove('country', country.id, country.name)}>
|
||||
<Trash2 size={13} />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editing?.type === 'country' && editing.id === country.id && (
|
||||
<InlineForm onSave={saveEdit} onCancel={cancel} />
|
||||
)}
|
||||
|
||||
{isCountryOpen && (
|
||||
<div className="ml-6 mt-3 space-y-2">
|
||||
{country.regions.map((region) => {
|
||||
const isRegionOpen = expandedRegions.has(region.id);
|
||||
return (
|
||||
<div key={region.id} className="border rounded-lg p-3">
|
||||
{/* Region row */}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
className="flex items-center gap-2 flex-1 text-left hover:opacity-80"
|
||||
onClick={() => setExpandedRegions(prev => {
|
||||
const s = new Set(prev);
|
||||
s.has(region.id) ? s.delete(region.id) : s.add(region.id);
|
||||
return s;
|
||||
})}
|
||||
>
|
||||
{isRegionOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
<Map size={14} className="text-green-500" />
|
||||
{!(editing?.type === 'region' && editing.id === region.id) && (
|
||||
<span className="font-medium text-sm">{region.name}</span>
|
||||
)}
|
||||
<Badge variant="outline" className="text-xs">{region.cities.length} ciudades</Badge>
|
||||
</button>
|
||||
{!(editing?.type === 'region' && editing.id === region.id) && (
|
||||
<div className="flex gap-1">
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6" onClick={() => startEdit({ type: 'region', id: region.id, name: region.name })}>
|
||||
<Pencil size={12} />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" className="h-6 w-6 text-destructive" onClick={() => remove('region', region.id, region.name)}>
|
||||
<Trash2 size={12} />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editing?.type === 'region' && editing.id === region.id && (
|
||||
<InlineForm onSave={saveEdit} onCancel={cancel} />
|
||||
)}
|
||||
|
||||
{isRegionOpen && (
|
||||
<div className="ml-5 mt-2">
|
||||
<div className="flex flex-wrap gap-1 mb-2">
|
||||
{region.cities.map((city) => (
|
||||
<div key={city.id} className="group flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs">
|
||||
{editing?.type === 'city' && editing.id === city.id ? null : (
|
||||
<>
|
||||
<MapPin size={10} className="text-orange-400" />
|
||||
<span>{city.name}</span>
|
||||
<button className="opacity-0 group-hover:opacity-100 ml-1" onClick={() => startEdit({ type: 'city', id: city.id, name: city.name })}>
|
||||
<Pencil size={10} />
|
||||
</button>
|
||||
<button className="opacity-0 group-hover:opacity-100 text-destructive" onClick={() => remove('city', city.id, city.name)}>
|
||||
<Trash2 size={10} />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{editing?.type === 'city' && region.cities.some(c => c.id === editing.id) && (
|
||||
<InlineForm onSave={saveEdit} onCancel={cancel} />
|
||||
)}
|
||||
{adding?.type === 'city' && adding.regionId === region.id ? (
|
||||
<InlineForm onSave={saveAdd} onCancel={cancel} />
|
||||
) : (
|
||||
<Button size="sm" variant="outline" className="h-6 text-xs mt-1" onClick={() => startAdd({ type: 'city', regionId: region.id })}>
|
||||
<Plus size={11} className="mr-1" />Ciudad
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{adding?.type === 'region' && adding.countryId === country.id ? (
|
||||
<div className="border rounded-lg p-3">
|
||||
<p className="text-xs text-muted-foreground mb-1 flex items-center gap-1"><Map size={12} /> Nueva región</p>
|
||||
<InlineForm onSave={saveAdd} onCancel={cancel} />
|
||||
</div>
|
||||
) : (
|
||||
<Button size="sm" variant="outline" onClick={() => startAdd({ type: 'region', countryId: country.id })}>
|
||||
<Plus size={13} className="mr-1" />Región
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,79 +2,125 @@
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { api } from '@/lib/api';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { toast } from 'sonner';
|
||||
import { Save } from 'lucide-react';
|
||||
import { Save, ExternalLink, Copy, FileText, Shield } from 'lucide-react';
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api/v1';
|
||||
const PUBLIC_BASE = API_BASE.replace('/api/v1', '');
|
||||
|
||||
const POLICY_ITEMS = [
|
||||
{
|
||||
key: 'privacy',
|
||||
label: 'Política de Privacidad',
|
||||
icon: Shield,
|
||||
description: 'Cómo se recopilan, usan y protegen los datos personales de los usuarios.',
|
||||
},
|
||||
{
|
||||
key: 'terms',
|
||||
label: 'Términos y Condiciones',
|
||||
icon: FileText,
|
||||
description: 'Condiciones de uso de la plataforma ProsApp.',
|
||||
},
|
||||
];
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [settings, setSettings] = useState<Record<string, any> | null>(null);
|
||||
const [editValue, setEditValue] = useState('');
|
||||
const [policies, setPolicies] = useState<Record<string, string>>({ privacy: '', terms: '' });
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
api.get<Record<string, any>>('/settings')
|
||||
.then((data) => {
|
||||
setSettings(data);
|
||||
setEditValue(JSON.stringify(data, null, 2));
|
||||
})
|
||||
.catch(() => setError('Error al cargar configuración'))
|
||||
api.get<{ privacy: string | null; terms: string | null }>('/settings/policies')
|
||||
.then((data) => setPolicies({ privacy: data.privacy || '', terms: data.terms || '' }))
|
||||
.catch(() => toast.error('Error al cargar políticas'))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
const savePolicy = async (key: string) => {
|
||||
setSaving(key);
|
||||
try {
|
||||
const parsed = JSON.parse(editValue);
|
||||
await api.patch('/settings', parsed);
|
||||
setSettings(parsed);
|
||||
toast.success('Configuración guardada');
|
||||
await api.patch(`/settings/policies/${key}`, { content: policies[key] });
|
||||
toast.success('Política guardada');
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message || 'Error al guardar');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
setSaving(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="flex items-center justify-center py-16 text-muted-foreground">Cargando...</div>;
|
||||
}
|
||||
const copyLink = (key: string) => {
|
||||
const url = `${API_BASE}/settings/policy/${key}`;
|
||||
navigator.clipboard.writeText(url);
|
||||
toast.success('Enlace copiado');
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-destructive">
|
||||
<p>{error}</p>
|
||||
<Button variant="outline" size="sm" onClick={load} className="mt-2">Reintentar</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (loading) return <div className="flex items-center justify-center py-16 text-muted-foreground">Cargando...</div>;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-2xl font-bold">Configuración</h1>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Configuración global (JSON)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<textarea
|
||||
className="flex min-h-[300px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
/>
|
||||
<Button onClick={save} disabled={saving}>
|
||||
<Save className="mr-1 h-4 w-4" />
|
||||
{saving ? 'Guardando...' : 'Guardar'}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Configuración</h1>
|
||||
<p className="text-muted-foreground text-sm mt-1">Gestiona las políticas legales y ajustes globales de ProsApp.</p>
|
||||
</div>
|
||||
|
||||
{/* Policies */}
|
||||
<div className="space-y-6">
|
||||
<h2 className="text-lg font-semibold">Documentos legales</h2>
|
||||
{POLICY_ITEMS.map(({ key, label, icon: Icon, description }) => {
|
||||
const publicUrl = `${API_BASE}/settings/policy/${key}`;
|
||||
return (
|
||||
<Card key={key}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Icon size={18} className="text-muted-foreground" />
|
||||
{label}
|
||||
</CardTitle>
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<textarea
|
||||
className="w-full min-h-[260px] rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 font-mono resize-y"
|
||||
placeholder={`Escribe aquí el contenido de ${label.toLowerCase()}...\n\nPuedes usar texto plano. Se mostrará con formato en la página pública.`}
|
||||
value={policies[key]}
|
||||
onChange={(e) => setPolicies((p) => ({ ...p, [key]: e.target.value }))}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Button
|
||||
onClick={() => savePolicy(key)}
|
||||
disabled={saving === key}
|
||||
>
|
||||
<Save className="mr-1 h-4 w-4" />
|
||||
{saving === key ? 'Guardando...' : 'Guardar'}
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-1 flex-1 min-w-0">
|
||||
<code className="text-xs bg-muted px-2 py-1.5 rounded border truncate flex-1 min-w-0">
|
||||
{publicUrl}
|
||||
</code>
|
||||
<Button size="icon" variant="outline" className="h-8 w-8 shrink-0" onClick={() => copyLink(key)}>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
<a href={publicUrl} target="_blank" rel="noopener noreferrer">
|
||||
<Button size="icon" variant="outline" className="h-8 w-8 shrink-0">
|
||||
<ExternalLink size={14} />
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Enlace público para compartir con usuarios o incluir en la app mobile/web.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ const menu = [
|
||||
{ href: '/users', label: 'Usuarios', icon: Users },
|
||||
{ href: '/professionals', label: 'Profesionales', icon: Briefcase },
|
||||
{ href: '/services', label: 'Servicios', icon: ClipboardList },
|
||||
{ href: '/cities', label: 'Ciudades', icon: MapPin },
|
||||
{ href: '/locations', label: 'Ubicaciones', icon: MapPin },
|
||||
{ href: '/professions', label: 'Profesiones', icon: Wrench },
|
||||
{ href: '/comments', label: 'Comentarios', icon: Star },
|
||||
{ href: '/sms', label: 'SMS', icon: MessageSquare },
|
||||
|
||||
Reference in New Issue
Block a user