feat(front) react version start
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import { Outlet, useNavigate, useLocation } from '@tanstack/react-router'
|
||||
import { Box, Paper, Tabs, Tab, useTheme } from '@mui/material'
|
||||
import { useState } from 'react'
|
||||
import TopBar from './TopBar'
|
||||
import Sidebar from './Sidebar'
|
||||
|
||||
export default function AppShell() {
|
||||
const theme = useTheme()
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex', minHeight: '100vh' }}>
|
||||
<TopBar
|
||||
onCollapseClick={() => setCollapsed((p) => !p)}
|
||||
collapsed={collapsed}
|
||||
/>
|
||||
<Sidebar collapsed={collapsed} />
|
||||
<Box
|
||||
component="main"
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
p: { xs: 2, md: 3 },
|
||||
mt: '64px',
|
||||
minWidth: 0,
|
||||
width: {
|
||||
md: `calc(100% - ${collapsed ? 72 : 240}px)`,
|
||||
},
|
||||
transition: theme.transitions.create('width', {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
}}
|
||||
>
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
display: { md: 'none' },
|
||||
mb: 2,
|
||||
borderRadius: 3,
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
bgcolor: 'background.paper',
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
value={location.pathname}
|
||||
onChange={(_e, path) => navigate({ to: path })}
|
||||
variant="fullWidth"
|
||||
textColor="primary"
|
||||
indicatorColor="primary"
|
||||
>
|
||||
<Tab label="Campañas" value="/campaigns" />
|
||||
<Tab label="Sesiones" value="/sessions" />
|
||||
<Tab label="Archivos" value="/media" />
|
||||
</Tabs>
|
||||
</Paper>
|
||||
<Outlet />
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Outlet } from '@tanstack/react-router'
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { ThemeProvider as MuiThemeProvider, createTheme } from '@mui/material/styles'
|
||||
import CssBaseline from '@mui/material/CssBaseline'
|
||||
import { queryClient } from '../lib/queryClient'
|
||||
import { ThemeProvider, useThemeMode } from './ThemeContext'
|
||||
|
||||
function ThemedRoot() {
|
||||
const { mode } = useThemeMode()
|
||||
const theme = useMemo(
|
||||
() =>
|
||||
createTheme({
|
||||
shape: {
|
||||
borderRadius: 16,
|
||||
},
|
||||
palette: {
|
||||
mode,
|
||||
primary: { main: '#6366f1' },
|
||||
background: {
|
||||
default: mode === 'dark' ? '#09090b' : '#fafafa',
|
||||
paper: mode === 'dark' ? '#18181b' : '#ffffff',
|
||||
},
|
||||
text: {
|
||||
primary: mode === 'dark' ? '#e4e4e7' : '#18181b',
|
||||
secondary: mode === 'dark' ? '#a1a1aa' : '#52525b',
|
||||
disabled: mode === 'dark' ? '#71717a' : '#a1a1aa',
|
||||
},
|
||||
divider: mode === 'dark' ? '#27272a' : '#e4e4e7',
|
||||
action: {
|
||||
hover: mode === 'dark' ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.04)',
|
||||
selected: mode === 'dark' ? 'rgba(99,102,241,0.16)' : 'rgba(99,102,241,0.12)',
|
||||
},
|
||||
},
|
||||
components: {
|
||||
MuiCard: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
border: '1px solid #27272a',
|
||||
backgroundImage: 'none',
|
||||
boxShadow: 'none',
|
||||
borderRadius: 20,
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiAppBar: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
backgroundColor: '#18181b',
|
||||
borderBottom: '1px solid #27272a',
|
||||
boxShadow: 'none',
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiDrawer: {
|
||||
styleOverrides: {
|
||||
paper: {
|
||||
backgroundColor: '#18181b',
|
||||
borderRight: '1px solid #27272a',
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiButton: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
textTransform: 'none',
|
||||
borderRadius: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiOutlinedInput: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
borderRadius: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiDialog: {
|
||||
styleOverrides: {
|
||||
paper: {
|
||||
borderRadius: 20,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
[mode]
|
||||
)
|
||||
|
||||
return (
|
||||
<MuiThemeProvider theme={theme}>
|
||||
<CssBaseline />
|
||||
<Outlet />
|
||||
</MuiThemeProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Root() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<ThemedRoot />
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
Drawer,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
Toolbar,
|
||||
} from '@mui/material'
|
||||
import CampaignIcon from '@mui/icons-material/Campaign'
|
||||
import ChatIcon from '@mui/icons-material/Chat'
|
||||
import PermMediaIcon from '@mui/icons-material/PermMedia'
|
||||
import { Link, useLocation } from '@tanstack/react-router'
|
||||
|
||||
const DRAWER_WIDTH = 240
|
||||
const COLLAPSED_WIDTH = 72
|
||||
|
||||
const items = [
|
||||
{ path: '/campaigns', label: 'Campañas', icon: <CampaignIcon /> },
|
||||
{ path: '/sessions', label: 'Sesiones', icon: <ChatIcon /> },
|
||||
{ path: '/media', label: 'Archivos', icon: <PermMediaIcon /> },
|
||||
]
|
||||
|
||||
export default function Sidebar({ collapsed }) {
|
||||
const location = useLocation()
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
sx={{
|
||||
display: { xs: 'none', md: 'block' },
|
||||
width: collapsed ? COLLAPSED_WIDTH : DRAWER_WIDTH,
|
||||
flexShrink: 0,
|
||||
'& .MuiDrawer-paper': {
|
||||
boxSizing: 'border-box',
|
||||
width: collapsed ? COLLAPSED_WIDTH : DRAWER_WIDTH,
|
||||
overflowX: 'hidden',
|
||||
transition: (theme) =>
|
||||
theme.transitions.create('width', {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
},
|
||||
}}
|
||||
open
|
||||
>
|
||||
<Toolbar />
|
||||
<List>
|
||||
{items.map((item) => (
|
||||
<ListItem key={item.path} disablePadding>
|
||||
<ListItemButton
|
||||
component={Link}
|
||||
to={item.path}
|
||||
selected={location.pathname === item.path}
|
||||
sx={{ minHeight: 48 }}
|
||||
>
|
||||
<ListItemIcon
|
||||
sx={{
|
||||
minWidth: 0,
|
||||
mr: collapsed ? 'auto' : 2,
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{item.icon}
|
||||
</ListItemIcon>
|
||||
{!collapsed && <ListItemText primary={item.label} />}
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createContext, useContext, useState, useMemo } from 'react'
|
||||
|
||||
const ThemeContext = createContext({
|
||||
mode: 'dark',
|
||||
toggleTheme: () => {},
|
||||
})
|
||||
|
||||
export function ThemeProvider({ children }) {
|
||||
const [mode, setMode] = useState('dark')
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
mode,
|
||||
toggleTheme: () => {
|
||||
const next = mode === 'dark' ? 'light' : 'dark'
|
||||
setMode(next)
|
||||
document.documentElement.classList.toggle('dark', next === 'dark')
|
||||
},
|
||||
}),
|
||||
[mode]
|
||||
)
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||
}
|
||||
|
||||
export function useThemeMode() {
|
||||
return useContext(ThemeContext)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
AppBar,
|
||||
Toolbar,
|
||||
Typography,
|
||||
IconButton,
|
||||
Box,
|
||||
Button,
|
||||
useTheme,
|
||||
} from '@mui/material'
|
||||
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'
|
||||
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
|
||||
import Brightness4Icon from '@mui/icons-material/Brightness4'
|
||||
import Brightness7Icon from '@mui/icons-material/Brightness7'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { supabase } from '../lib/supabase'
|
||||
import { useThemeMode } from './ThemeContext'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export default function TopBar({
|
||||
onCollapseClick,
|
||||
collapsed,
|
||||
}) {
|
||||
const theme = useTheme()
|
||||
const navigate = useNavigate()
|
||||
const { mode, toggleTheme } = useThemeMode()
|
||||
const [email, setEmail] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
supabase.auth.getSession().then(({ data: { session } }) => {
|
||||
if (session?.user?.email) setEmail(session.user.email)
|
||||
})
|
||||
const { data: { subscription } } = supabase.auth.onAuthStateChange(
|
||||
(_event, session) => {
|
||||
setEmail(session?.user?.email || '')
|
||||
}
|
||||
)
|
||||
return () => subscription.unsubscribe()
|
||||
}, [])
|
||||
|
||||
const handleLogout = async () => {
|
||||
await supabase.auth.signOut()
|
||||
navigate({ to: '/login' })
|
||||
}
|
||||
|
||||
return (
|
||||
<AppBar
|
||||
position="fixed"
|
||||
sx={{
|
||||
width: { md: `calc(100% - ${collapsed ? 72 : 240}px)` },
|
||||
ml: { md: `${collapsed ? 72 : 240}px` },
|
||||
transition: theme.transitions.create(['width', 'margin'], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
<IconButton
|
||||
color="inherit"
|
||||
onClick={onCollapseClick}
|
||||
sx={{ mr: 2, display: { xs: 'none', md: 'flex' } }}
|
||||
>
|
||||
{collapsed ? <ChevronRightIcon /> : <ChevronLeftIcon />}
|
||||
</IconButton>
|
||||
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
|
||||
Panel de Campañas
|
||||
</Typography>
|
||||
{email && (
|
||||
<Typography variant="caption" sx={{ mr: 2, display: { xs: 'none', sm: 'block' } }}>
|
||||
{email}
|
||||
</Typography>
|
||||
)}
|
||||
<IconButton color="inherit" onClick={toggleTheme} sx={{ mr: 1 }}>
|
||||
{mode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />}
|
||||
</IconButton>
|
||||
<Button color="inherit" onClick={handleLogout}>
|
||||
Cerrar Sesión
|
||||
</Button>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
Card,
|
||||
CardContent,
|
||||
TextField,
|
||||
Button,
|
||||
Typography,
|
||||
Alert,
|
||||
} from '@mui/material'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { supabase } from '../../lib/supabase'
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const handleLogin = async (e) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
const { error: loginError } = await supabase.auth.signInWithPassword({
|
||||
email: email.trim(),
|
||||
password: password.trim(),
|
||||
})
|
||||
setLoading(false)
|
||||
if (loginError) {
|
||||
setError(loginError.message)
|
||||
return
|
||||
}
|
||||
navigate({ to: '/campaigns' })
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
minHeight: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
p: 3,
|
||||
}}
|
||||
>
|
||||
<Card sx={{ width: '100%', maxWidth: 420 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h5" component="h1" gutterBottom>
|
||||
Panel de Campañas
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary" gutterBottom>
|
||||
Inicia sesión para gestionar campañas, sesiones y archivos.
|
||||
</Typography>
|
||||
<Box component="form" onSubmit={handleLogin} sx={{ mt: 3 }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Correo"
|
||||
type="email"
|
||||
margin="normal"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Contraseña"
|
||||
type="password"
|
||||
margin="normal"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
sx={{ mt: 2 }}
|
||||
disabled={loading}
|
||||
>
|
||||
Entrar
|
||||
</Button>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
Card,
|
||||
CardContent,
|
||||
Typography,
|
||||
Button,
|
||||
Chip,
|
||||
} from '@mui/material'
|
||||
import { useDeleteCampaign } from './api'
|
||||
|
||||
function formatDate(d) {
|
||||
try {
|
||||
return new Date(d).toLocaleString()
|
||||
} catch {
|
||||
return d
|
||||
}
|
||||
}
|
||||
|
||||
export default function CampaignCard({ campaign, hasMedia, onEdit }) {
|
||||
const deleteMutation = useDeleteCampaign()
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!window.confirm('¿Eliminar esta campaña?')) return
|
||||
deleteMutation.mutate(campaign.id)
|
||||
}
|
||||
|
||||
const statusColor = campaign.active === false ? 'error' : 'success'
|
||||
const statusText = campaign.active === false ? 'Inactiva' : 'Activa'
|
||||
const keywordsStr = Array.isArray(campaign.keywords)
|
||||
? campaign.keywords.join(', ')
|
||||
: ''
|
||||
|
||||
return (
|
||||
<Card sx={{ mb: 2 }}>
|
||||
<CardContent>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" noWrap>
|
||||
{campaign.name}
|
||||
</Typography>
|
||||
<Chip size="small" color={statusColor} label={statusText} />
|
||||
</Box>
|
||||
{campaign.send_welcome_photos && (
|
||||
<Typography variant="caption" color="primary" display="block" sx={{ mt: 0.5 }}>
|
||||
📸 Requiere Fotos de Bienvenida
|
||||
</Typography>
|
||||
)}
|
||||
{keywordsStr && (
|
||||
<Typography variant="caption" display="block" color="text.secondary" sx={{ mt: 0.5 }}>
|
||||
<strong>Palabras clave:</strong> {keywordsStr}
|
||||
</Typography>
|
||||
)}
|
||||
{campaign.promt && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
display="block"
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
mt: 0.5,
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: 2,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<strong>Instrucciones:</strong> {campaign.promt}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" display="block" color="text.disabled" sx={{ mt: 1, overflowWrap: 'anywhere' }}>
|
||||
Creada: {formatDate(campaign.created_at)} • ID: {campaign.id.split('-')[0]}...
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 1,
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
{hasMedia && (
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
href={`/gallery?campaign_id=${campaign.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Galería
|
||||
</Button>
|
||||
)}
|
||||
<Button size="small" variant="outlined" onClick={onEdit}>
|
||||
Editar
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
color="error"
|
||||
onClick={handleDelete}
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useState } from 'react'
|
||||
import { Box, Typography, Button, CircularProgress } from '@mui/material'
|
||||
import CreateCampaignForm from './CreateCampaignForm'
|
||||
import CampaignCard from './CampaignCard'
|
||||
import EditCampaignModal from './EditCampaignModal'
|
||||
import { useCampaigns, useMediaCampaignIds } from './api'
|
||||
|
||||
export default function CampaignsPage() {
|
||||
const { data: campaigns, isLoading } = useCampaigns()
|
||||
const { data: mediaIds } = useMediaCampaignIds()
|
||||
const [showInactive, setShowInactive] = useState(false)
|
||||
const [editing, setEditing] = useState(null)
|
||||
|
||||
const filtered = showInactive
|
||||
? campaigns
|
||||
: campaigns?.filter((c) => c.active !== false)
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<CreateCampaignForm />
|
||||
<Box sx={{ mt: 3 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
mb: 2,
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6">Lista de Campañas</Typography>
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
onClick={() => setShowInactive((p) => !p)}
|
||||
>
|
||||
{showInactive ? 'Ocultar Inactivas' : 'Mostrar Inactivas'}
|
||||
</Button>
|
||||
</Box>
|
||||
{filtered?.map((c) => (
|
||||
<CampaignCard
|
||||
key={c.id}
|
||||
campaign={c}
|
||||
hasMedia={mediaIds?.has(c.id)}
|
||||
onEdit={() => setEditing(c)}
|
||||
/>
|
||||
))}
|
||||
{filtered?.length === 0 && (
|
||||
<Typography color="text.secondary">No se encontraron campañas.</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<EditCampaignModal campaign={editing} onClose={() => setEditing(null)} />
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
TextField,
|
||||
Button,
|
||||
Typography,
|
||||
Box,
|
||||
Alert,
|
||||
} from '@mui/material'
|
||||
import { useCreateCampaign } from './api'
|
||||
|
||||
export default function CreateCampaignForm() {
|
||||
const [name, setName] = useState('')
|
||||
const [notes, setNotes] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const createMutation = useCreateCampaign()
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
setMsg('')
|
||||
setError('')
|
||||
if (!name.trim()) {
|
||||
setError('El nombre de la campaña es obligatorio.')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await createMutation.mutateAsync({ name: name.trim(), promt: notes.trim() })
|
||||
setName('')
|
||||
setNotes('')
|
||||
setMsg('¡Campaña creada!')
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Crear Campaña
|
||||
</Typography>
|
||||
<Box component="form" onSubmit={handleSubmit}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Nombre de campaña"
|
||||
margin="normal"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Instrucciones para IA (opcional)"
|
||||
margin="normal"
|
||||
multiline
|
||||
rows={2}
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
sx={{ mt: 1 }}
|
||||
disabled={createMutation.isPending}
|
||||
>
|
||||
Crear Campaña
|
||||
</Button>
|
||||
{msg && (
|
||||
<Alert severity="success" sx={{ mt: 2 }}>
|
||||
{msg}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
TextField,
|
||||
Button,
|
||||
Box,
|
||||
FormControlLabel,
|
||||
Checkbox,
|
||||
Alert,
|
||||
} from '@mui/material'
|
||||
import { useUpdateCampaign } from './api'
|
||||
|
||||
export default function EditCampaignModal({ campaign, onClose }) {
|
||||
const [name, setName] = useState('')
|
||||
const [keywords, setKeywords] = useState('')
|
||||
const [prompt, setPrompt] = useState('')
|
||||
const [welcomePhotos, setWelcomePhotos] = useState(false)
|
||||
const [active, setActive] = useState(true)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const updateMutation = useUpdateCampaign()
|
||||
|
||||
useEffect(() => {
|
||||
if (campaign) {
|
||||
setName(campaign.name || '')
|
||||
setKeywords(
|
||||
Array.isArray(campaign.keywords) ? campaign.keywords.join(', ') : ''
|
||||
)
|
||||
setPrompt(campaign.promt || '')
|
||||
setWelcomePhotos(campaign.send_welcome_photos === true)
|
||||
setActive(campaign.active !== false)
|
||||
setMsg('')
|
||||
setError('')
|
||||
}
|
||||
}, [campaign])
|
||||
|
||||
const handleSave = async () => {
|
||||
setMsg('')
|
||||
setError('')
|
||||
if (!name.trim()) {
|
||||
setError('El nombre es obligatorio.')
|
||||
return
|
||||
}
|
||||
const kwArr = keywords
|
||||
? keywords.split(',').map((k) => k.trim()).filter((k) => k.length > 0)
|
||||
: []
|
||||
try {
|
||||
await updateMutation.mutateAsync({
|
||||
id: campaign.id,
|
||||
name: name.trim(),
|
||||
keywords: kwArr,
|
||||
promt: prompt.trim(),
|
||||
send_welcome_photos: welcomePhotos,
|
||||
active,
|
||||
})
|
||||
setMsg('¡Guardado!')
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={!!campaign} onClose={onClose} fullWidth maxWidth="sm">
|
||||
<DialogTitle>Editar Campaña</DialogTitle>
|
||||
<DialogContent>
|
||||
<Box sx={{ pt: 1 }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Nombre"
|
||||
margin="dense"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Palabras clave (separadas por coma)"
|
||||
margin="dense"
|
||||
placeholder="ej. casa, piscina, jardín"
|
||||
value={keywords}
|
||||
onChange={(e) => setKeywords(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Instrucciones para IA"
|
||||
margin="dense"
|
||||
multiline
|
||||
rows={3}
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={welcomePhotos}
|
||||
onChange={(e) => setWelcomePhotos(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Requerir Fotos de Bienvenida"
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={active}
|
||||
onChange={(e) => setActive(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label="Campaña Activa"
|
||||
/>
|
||||
{msg && (
|
||||
<Alert severity="success" sx={{ mt: 1 }}>
|
||||
{msg}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mt: 1 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button onClick={handleSave} variant="contained" disabled={updateMutation.isPending}>
|
||||
Guardar Cambios
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { supabase } from '../../lib/supabase'
|
||||
|
||||
export function useCampaigns() {
|
||||
return useQuery({
|
||||
queryKey: ['campaigns'],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase
|
||||
.from('campaigns')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false })
|
||||
if (error) throw new Error(error.message)
|
||||
return data || []
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useMediaCampaignIds() {
|
||||
return useQuery({
|
||||
queryKey: ['mediaCampaignIds'],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase.from('media').select('campaign_id')
|
||||
if (error) throw new Error(error.message)
|
||||
return new Set(data?.map((m) => m.campaign_id) || [])
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateCampaign() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ name, promt }) => {
|
||||
const { error } = await supabase
|
||||
.from('campaigns')
|
||||
.insert([{ name, promt, active: true }])
|
||||
if (error) throw new Error(error.message)
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['campaigns'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateCampaign() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ id, name, keywords, promt, send_welcome_photos, active }) => {
|
||||
const { error } = await supabase
|
||||
.from('campaigns')
|
||||
.update({ name, keywords, promt, send_welcome_photos, active })
|
||||
.eq('id', id)
|
||||
if (error) throw new Error(error.message)
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['campaigns'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteCampaign() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async (id) => {
|
||||
const { error } = await supabase.from('campaigns').delete().eq('id', id)
|
||||
if (error) throw new Error(error.message)
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['campaigns'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Button,
|
||||
Typography,
|
||||
Alert,
|
||||
} from '@mui/material'
|
||||
import { useDeleteMedia } from './api'
|
||||
|
||||
export default function DeleteMediaModal({ media, onClose }) {
|
||||
const [msg, setMsg] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const deleteMutation = useDeleteMedia()
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setMsg('')
|
||||
setError('')
|
||||
try {
|
||||
await deleteMutation.mutateAsync({ id: media.id, url: media.url })
|
||||
setMsg('¡Eliminado con éxito!')
|
||||
setTimeout(() => onClose(), 600)
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={!!media} onClose={onClose} maxWidth="xs" fullWidth>
|
||||
<DialogTitle>Eliminar Archivo?</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Estás seguro de que quieres eliminar esta foto? Esta acción no se puede deshacer.
|
||||
</Typography>
|
||||
{msg && (
|
||||
<Alert severity="success" sx={{ mt: 2 }}>
|
||||
{msg}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button onClick={handleConfirm} variant="contained" color="error" disabled={deleteMutation.isPending}>
|
||||
Eliminar
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Card, CardContent, Typography, Box, IconButton } from '@mui/material'
|
||||
import CloseIcon from '@mui/icons-material/Close'
|
||||
|
||||
function formatDate(d) {
|
||||
try {
|
||||
return new Date(d).toLocaleString()
|
||||
} catch {
|
||||
return d
|
||||
}
|
||||
}
|
||||
|
||||
export default function MediaCard({ media, campaignName, onDelete }) {
|
||||
return (
|
||||
<Card sx={{ mb: 2, overflow: 'hidden' }}>
|
||||
<Box sx={{ position: 'relative' }}>
|
||||
<img
|
||||
src={media.url}
|
||||
alt={media.category || 'archivo'}
|
||||
loading="lazy"
|
||||
style={{ width: '100%', height: 'auto', display: 'block' }}
|
||||
/>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => onDelete(media)}
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 8,
|
||||
right: 8,
|
||||
bgcolor: 'rgba(0,0,0,0.5)',
|
||||
color: '#fff',
|
||||
'&:hover': { bgcolor: 'rgba(0,0,0,0.8)' },
|
||||
}}
|
||||
>
|
||||
<CloseIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Box>
|
||||
<CardContent>
|
||||
<Typography variant="caption" color="primary" sx={{ fontWeight: 700, textTransform: 'uppercase' }}>
|
||||
{media.category || 'foto'} • {media.type || 'desconocido'}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ fontWeight: 600 }} noWrap>
|
||||
{campaignName}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{formatDate(media.created_at)}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
Card,
|
||||
CardContent,
|
||||
Typography,
|
||||
TextField,
|
||||
Button,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
Divider,
|
||||
Grid,
|
||||
Alert,
|
||||
CircularProgress,
|
||||
} from '@mui/material'
|
||||
import { useCampaigns } from '../campaigns/api'
|
||||
import { useMedia, useUploadMedia } from './api'
|
||||
import MediaCard from './MediaCard'
|
||||
import DeleteMediaModal from './DeleteMediaModal'
|
||||
|
||||
export default function MediaPage() {
|
||||
const [campaignId, setCampaignId] = useState('')
|
||||
const [category, setCategory] = useState('')
|
||||
const [mediaType, setMediaType] = useState('')
|
||||
const [file, setFile] = useState(null)
|
||||
const [url, setUrl] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [deletingMedia, setDeletingMedia] = useState(null)
|
||||
|
||||
const { data: campaigns } = useCampaigns()
|
||||
const { data: mediaList, isLoading } = useMedia()
|
||||
const uploadMutation = useUploadMedia()
|
||||
|
||||
const activeCampaignIds = new Set(
|
||||
campaigns?.filter((c) => c.active !== false).map((c) => c.id) || []
|
||||
)
|
||||
const filteredMedia = mediaList?.filter((m) => activeCampaignIds.has(m.campaign_id))
|
||||
|
||||
const handleUpload = async (e) => {
|
||||
e.preventDefault()
|
||||
setMsg('')
|
||||
setError('')
|
||||
try {
|
||||
await uploadMutation.mutateAsync({
|
||||
campaignId,
|
||||
category: category.trim(),
|
||||
type: mediaType.trim(),
|
||||
file,
|
||||
url: url.trim(),
|
||||
})
|
||||
setCampaignId('')
|
||||
setCategory('')
|
||||
setMediaType('')
|
||||
setFile(null)
|
||||
setUrl('')
|
||||
setMsg('¡Archivo guardado con éxito!')
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Card sx={{ mb: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Subir Archivo
|
||||
</Typography>
|
||||
<Box component="form" onSubmit={handleUpload}>
|
||||
<FormControl fullWidth margin="normal" size="small">
|
||||
<InputLabel>Campaña</InputLabel>
|
||||
<Select
|
||||
value={campaignId}
|
||||
label="Campaña"
|
||||
onChange={(e) => setCampaignId(e.target.value)}
|
||||
>
|
||||
<MenuItem value="">
|
||||
<em>Seleccionar campaña</em>
|
||||
</MenuItem>
|
||||
{campaigns?.map((c) => (
|
||||
<MenuItem key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Categoría (ej. cocina, frente, baño)"
|
||||
margin="normal"
|
||||
size="small"
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Tipo (ej. foto, video)"
|
||||
margin="normal"
|
||||
size="small"
|
||||
value={mediaType}
|
||||
onChange={(e) => setMediaType(e.target.value)}
|
||||
/>
|
||||
<Typography variant="caption" sx={{ mt: 1, display: 'block', fontWeight: 600, textTransform: 'uppercase' }}>
|
||||
Fuente de archivo
|
||||
</Typography>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,video/*"
|
||||
onChange={(e) => setFile(e.target.files?.[0] || null)}
|
||||
style={{ marginTop: 8, marginBottom: 8 }}
|
||||
/>
|
||||
<Divider sx={{ my: 1 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ px: 1 }}>
|
||||
O
|
||||
</Typography>
|
||||
</Divider>
|
||||
<TextField
|
||||
fullWidth
|
||||
type="url"
|
||||
label="Pegar URL remota (ej. Google Drive, Imgur)"
|
||||
margin="normal"
|
||||
size="small"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
sx={{ mt: 1 }}
|
||||
disabled={uploadMutation.isPending}
|
||||
>
|
||||
Guardar Archivo
|
||||
</Button>
|
||||
{msg && (
|
||||
<Alert severity="success" sx={{ mt: 2 }}>
|
||||
{msg}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Lista de Archivos
|
||||
</Typography>
|
||||
{isLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : (
|
||||
<Grid container spacing={2}>
|
||||
{filteredMedia?.map((m) => {
|
||||
const campaign = campaigns?.find((c) => c.id === m.campaign_id)
|
||||
return (
|
||||
<Grid item xs={12} sm={6} md={4} lg={3} key={m.id}>
|
||||
<MediaCard
|
||||
media={m}
|
||||
campaignName={campaign?.name || 'Campaña desconocida'}
|
||||
onDelete={(media) => setDeletingMedia(media)}
|
||||
/>
|
||||
</Grid>
|
||||
)
|
||||
})}
|
||||
{filteredMedia?.length === 0 && (
|
||||
<Grid item xs={12}>
|
||||
<Typography color="text.secondary">
|
||||
No se encontraron archivos de campañas activas.
|
||||
</Typography>
|
||||
</Grid>
|
||||
)}
|
||||
</Grid>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<DeleteMediaModal
|
||||
media={deletingMedia}
|
||||
onClose={() => setDeletingMedia(null)}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { supabase, STORAGE_BUCKET } from '../../lib/supabase'
|
||||
|
||||
export function useMedia() {
|
||||
return useQuery({
|
||||
queryKey: ['media'],
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase
|
||||
.from('media')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(100)
|
||||
if (error) throw new Error(error.message)
|
||||
return data || []
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUploadMedia() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ campaignId, category, type, file, url }) => {
|
||||
if (!campaignId) throw new Error('Select a campaign first.')
|
||||
if (!file && !url) throw new Error('Please select a file OR paste a URL.')
|
||||
if (file && url) throw new Error('Please select EITHER a file OR a URL, not both.')
|
||||
|
||||
let finalUrl = ''
|
||||
|
||||
if (url) {
|
||||
try {
|
||||
new URL(url)
|
||||
finalUrl = url
|
||||
} catch {
|
||||
throw new Error('Please provide a valid URL (include http/https).')
|
||||
}
|
||||
} else {
|
||||
const ext = file.name.split('.').pop()
|
||||
const filePath = `${campaignId}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`
|
||||
const { error: uploadError } = await supabase.storage
|
||||
.from(STORAGE_BUCKET)
|
||||
.upload(filePath, file, { cacheControl: '3600', upsert: false })
|
||||
if (uploadError) throw new Error('Upload error: ' + uploadError.message)
|
||||
const { data: publicUrlData } = supabase.storage
|
||||
.from(STORAGE_BUCKET)
|
||||
.getPublicUrl(filePath)
|
||||
finalUrl = publicUrlData.publicUrl
|
||||
}
|
||||
|
||||
const { error: insertError } = await supabase.from('media').insert([
|
||||
{
|
||||
campaign_id: campaignId,
|
||||
url: finalUrl,
|
||||
category,
|
||||
type,
|
||||
},
|
||||
])
|
||||
if (insertError) throw new Error('DB insert error: ' + insertError.message)
|
||||
|
||||
return finalUrl
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['media'] })
|
||||
qc.invalidateQueries({ queryKey: ['mediaCampaignIds'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteMedia() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ id, url }) => {
|
||||
const { error: dbError } = await supabase
|
||||
.from('media')
|
||||
.delete()
|
||||
.eq('id', id)
|
||||
if (dbError) throw new Error(dbError.message)
|
||||
|
||||
if (url.includes(STORAGE_BUCKET)) {
|
||||
try {
|
||||
const parts = url.split(STORAGE_BUCKET + '/')
|
||||
if (parts.length >= 2) {
|
||||
const filePath = parts[1]
|
||||
await supabase.storage.from(STORAGE_BUCKET).remove([filePath])
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to delete from storage', e)
|
||||
}
|
||||
}
|
||||
return id
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['media'] })
|
||||
qc.invalidateQueries({ queryKey: ['mediaCampaignIds'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Button,
|
||||
Typography,
|
||||
Alert,
|
||||
} from '@mui/material'
|
||||
import { useBlockSession } from './api'
|
||||
|
||||
export default function BlockSessionModal({ session, onClose }) {
|
||||
const [msg, setMsg] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const blockMutation = useBlockSession()
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setMsg('')
|
||||
setError('')
|
||||
try {
|
||||
await blockMutation.mutateAsync({ phone: session.phone })
|
||||
setMsg('¡Sesión bloqueada!')
|
||||
setTimeout(() => onClose(), 600)
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={!!session} onClose={onClose} maxWidth="xs" fullWidth>
|
||||
<DialogTitle>Bloquear Sesión?</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Estás seguro de que quieres bloquear esta sesión? El número de teléfono será bloqueado.
|
||||
</Typography>
|
||||
{msg && (
|
||||
<Alert severity="success" sx={{ mt: 2 }}>
|
||||
{msg}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mt: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button onClick={handleConfirm} variant="contained" color="error" disabled={blockMutation.isPending}>
|
||||
Bloquear
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
Typography,
|
||||
Box,
|
||||
Chip,
|
||||
IconButton,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from '@mui/material'
|
||||
import MoreVertIcon from '@mui/icons-material/MoreVert'
|
||||
import { useDeleteSession, useUnblockSession } from './api'
|
||||
|
||||
function formatDate(d) {
|
||||
try {
|
||||
return new Date(d).toLocaleString()
|
||||
} catch {
|
||||
return d
|
||||
}
|
||||
}
|
||||
|
||||
export default function SessionCard({ session, onBlock }) {
|
||||
const [anchor, setAnchor] = useState(null)
|
||||
const deleteMutation = useDeleteSession()
|
||||
const unblockMutation = useUnblockSession()
|
||||
|
||||
const handleDelete = async () => {
|
||||
setAnchor(null)
|
||||
if (!window.confirm(`¿Eliminar la sesión de ${session.phone || 'desconocido'} y todo su historial de chat?`)) return
|
||||
deleteMutation.mutate({ id: session.id, phone: session.phone })
|
||||
}
|
||||
|
||||
const handleUnblock = async () => {
|
||||
setAnchor(null)
|
||||
if (!window.confirm(`Desbloquear sesión para ${session.phone}?`)) return
|
||||
unblockMutation.mutate({ phone: session.phone })
|
||||
}
|
||||
|
||||
const statusColor = session.finished ? 'success' : 'warning'
|
||||
const statusText = session.finished ? 'Finalizada' : 'Activa'
|
||||
|
||||
return (
|
||||
<Card sx={{ mb: 2 }}>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
|
||||
<Typography variant="subtitle1" sx={{ fontWeight: 600, overflowWrap: 'anywhere' }}>
|
||||
{session.name || `Teléfono: ${session.phone || 'desconocido'}`}
|
||||
{session.name && session.phone && (
|
||||
<Typography component="span" variant="caption" color="text.secondary" sx={{ ml: 1 }}>
|
||||
({session.phone})
|
||||
</Typography>
|
||||
)}
|
||||
</Typography>
|
||||
<Chip size="small" color={statusColor} label={statusText} />
|
||||
{session.block && (
|
||||
<Chip size="small" color="error" label="Bloqueada" />
|
||||
)}
|
||||
</Box>
|
||||
<Typography variant="caption" display="block" color="text.secondary" sx={{ mt: 0.5 }}>
|
||||
<strong>Resumen:</strong> {session.summary || 'Aún no hay resumen.'}
|
||||
</Typography>
|
||||
<Typography variant="caption" display="block" color="text.disabled" sx={{ mt: 1, overflowWrap: 'anywhere' }}>
|
||||
Campaña: {session.campaign_id?.split('-')[0] || 'N/A'}...
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2, mt: 0.5, flexWrap: 'wrap' }}>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
Iniciada: {formatDate(session.created_at)}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
Última interacción: {session.last_interaction ? formatDate(session.last_interaction) : 'Ninguna'}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Typography variant="caption" display="block" color="text.disabled" sx={{ mt: 0.5, overflowWrap: 'anywhere' }}>
|
||||
ID de sesión: {session.id}
|
||||
</Typography>
|
||||
</Box>
|
||||
<IconButton onClick={(e) => setAnchor(e.currentTarget)}>
|
||||
<MoreVertIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</CardContent>
|
||||
<Menu anchorEl={anchor} open={Boolean(anchor)} onClose={() => setAnchor(null)}>
|
||||
{session.block ? (
|
||||
<MenuItem onClick={handleUnblock} sx={{ color: 'error.main' }}>
|
||||
Desbloquear
|
||||
</MenuItem>
|
||||
) : (
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
setAnchor(null)
|
||||
onBlock(session)
|
||||
}}
|
||||
sx={{ color: 'error.main' }}
|
||||
>
|
||||
Bloquear
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem onClick={handleDelete} sx={{ color: 'error.main' }}>
|
||||
Eliminar
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
Card,
|
||||
CardContent,
|
||||
Typography,
|
||||
TextField,
|
||||
Button,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
CircularProgress,
|
||||
} from '@mui/material'
|
||||
import { useCampaigns } from '../campaigns/api'
|
||||
import { useSessions } from './api'
|
||||
import SessionCard from './SessionCard'
|
||||
import BlockSessionModal from './BlockSessionModal'
|
||||
|
||||
export default function SessionsPage() {
|
||||
const [campaignFilter, setCampaignFilter] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [blockingSession, setBlockingSession] = useState(null)
|
||||
const { data: campaigns } = useCampaigns()
|
||||
const { data: sessions, isLoading, refetch } = useSessions(campaignFilter)
|
||||
|
||||
const filtered = search
|
||||
? sessions?.filter(
|
||||
(s) =>
|
||||
(s.phone && s.phone.toLowerCase().includes(search.toLowerCase())) ||
|
||||
(s.name && s.name.toLowerCase().includes(search.toLowerCase())) ||
|
||||
(s.summary && s.summary.toLowerCase().includes(search.toLowerCase()))
|
||||
)
|
||||
: sessions
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Card sx={{ mb: 3 }}>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Sesiones
|
||||
</Typography>
|
||||
<FormControl fullWidth margin="normal" size="small">
|
||||
<InputLabel>Filtrar por campaña</InputLabel>
|
||||
<Select
|
||||
value={campaignFilter}
|
||||
label="Filtrar por campaña"
|
||||
onChange={(e) => setCampaignFilter(e.target.value)}
|
||||
>
|
||||
<MenuItem value="">Todas las campañas</MenuItem>
|
||||
{campaigns?.map((c) => (
|
||||
<MenuItem key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Button
|
||||
fullWidth
|
||||
variant="contained"
|
||||
onClick={() => refetch()}
|
||||
sx={{ mt: 1 }}
|
||||
>
|
||||
Actualizar Sesiones
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
Lista de Sesiones
|
||||
</Typography>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Buscar por teléfono, nombre o resumen..."
|
||||
margin="normal"
|
||||
size="small"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ mt: 2 }}>
|
||||
{filtered?.length === 0 && (
|
||||
<Typography color="text.secondary">
|
||||
{sessions?.length === 0
|
||||
? 'No se encontraron sesiones.'
|
||||
: 'Ninguna sesión coincide con la búsqueda.'}
|
||||
</Typography>
|
||||
)}
|
||||
{filtered?.map((s) => (
|
||||
<SessionCard
|
||||
key={s.id}
|
||||
session={s}
|
||||
onBlock={(session) => setBlockingSession(session)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<BlockSessionModal
|
||||
session={blockingSession}
|
||||
onClose={() => setBlockingSession(null)}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { supabase } from '../../lib/supabase'
|
||||
|
||||
export function useSessions(campaignFilter = '') {
|
||||
return useQuery({
|
||||
queryKey: ['sessions', campaignFilter],
|
||||
queryFn: async () => {
|
||||
let query = supabase
|
||||
.from('sessions')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(100)
|
||||
if (campaignFilter) {
|
||||
query = query.eq('campaign_id', campaignFilter)
|
||||
}
|
||||
const { data, error } = await query
|
||||
if (error) throw new Error(error.message)
|
||||
return data || []
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useBlockSession() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ phone }) => {
|
||||
const { error } = await supabase
|
||||
.from('sessions')
|
||||
.update({ block: true })
|
||||
.eq('phone', phone)
|
||||
if (error) throw new Error(error.message)
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['sessions'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUnblockSession() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ phone }) => {
|
||||
const { error } = await supabase
|
||||
.from('sessions')
|
||||
.update({ block: false })
|
||||
.eq('phone', phone)
|
||||
if (error) throw new Error(error.message)
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['sessions'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteSession() {
|
||||
const qc = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async ({ id, phone }) => {
|
||||
const { error: historyError } = await supabase
|
||||
.from('n8n_chat_histories')
|
||||
.delete()
|
||||
.eq('session_id', id)
|
||||
if (historyError) throw new Error(historyError.message)
|
||||
const { error: sessionError } = await supabase
|
||||
.from('sessions')
|
||||
.delete()
|
||||
.eq('id', id)
|
||||
if (sessionError) throw new Error(sessionError.message)
|
||||
return { id, phone }
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['sessions'] })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@variant dark (&:where(.dark, .dark *));
|
||||
|
||||
html,
|
||||
body {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
html.dark {
|
||||
background-color: #09090b;
|
||||
color: #e4e4e7;
|
||||
}
|
||||
|
||||
html:not(.dark) {
|
||||
background-color: #fafafa;
|
||||
color: #18181b;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { QueryClient } from '@tanstack/react-query'
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
const SUPABASE_URL = 'https://rehavit.beroth.moe/supabase'
|
||||
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzc2NTU4OTc2LCJleHAiOjE5MzQyMzg5NzZ9.eFvvIQUstht8TxNffqAcqfmgS7W2JMZsDxkV41XBPOA'
|
||||
|
||||
export const STORAGE_BUCKET = 'campaign-media'
|
||||
|
||||
export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY)
|
||||
@@ -0,0 +1,11 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { RouterProvider } from '@tanstack/react-router'
|
||||
import { router } from './routes'
|
||||
import './index.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
</React.StrictMode>
|
||||
)
|
||||
@@ -0,0 +1,67 @@
|
||||
import { createRouter, createRootRoute, createRoute, redirect } from '@tanstack/react-router'
|
||||
import Root from './components/Root'
|
||||
import AppShell from './components/AppShell'
|
||||
import LoginPage from './features/auth/LoginPage'
|
||||
import CampaignsPage from './features/campaigns/CampaignsPage'
|
||||
import SessionsPage from './features/sessions/SessionsPage'
|
||||
import MediaPage from './features/media/MediaPage'
|
||||
import { supabase } from './lib/supabase'
|
||||
|
||||
const rootRoute = createRootRoute({
|
||||
component: Root,
|
||||
})
|
||||
|
||||
const indexRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/',
|
||||
beforeLoad: async () => {
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
throw redirect({ to: session ? '/campaigns' : '/login' })
|
||||
},
|
||||
})
|
||||
|
||||
const loginRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: '/login',
|
||||
component: LoginPage,
|
||||
beforeLoad: async () => {
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
if (session) throw redirect({ to: '/campaigns' })
|
||||
},
|
||||
})
|
||||
|
||||
const appLayoutRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
id: '_app',
|
||||
component: AppShell,
|
||||
beforeLoad: async () => {
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
if (!session) throw redirect({ to: '/login' })
|
||||
},
|
||||
})
|
||||
|
||||
const campaignsRoute = createRoute({
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
path: '/campaigns',
|
||||
component: CampaignsPage,
|
||||
})
|
||||
|
||||
const sessionsRoute = createRoute({
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
path: '/sessions',
|
||||
component: SessionsPage,
|
||||
})
|
||||
|
||||
const mediaRoute = createRoute({
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
path: '/media',
|
||||
component: MediaPage,
|
||||
})
|
||||
|
||||
const routeTree = rootRoute.addChildren([
|
||||
indexRoute,
|
||||
loginRoute,
|
||||
appLayoutRoute.addChildren([campaignsRoute, sessionsRoute, mediaRoute]),
|
||||
])
|
||||
|
||||
export const router = createRouter({ routeTree })
|
||||
Reference in New Issue
Block a user