payments with stripe

Signed-off-by: Omar Sánchez Pizarro <omar.sanchez@pistacero.net>
This commit is contained in:
Omar Sánchez Pizarro
2026-01-21 02:20:13 +01:00
parent 626e3342d0
commit cc6ffdc5a5
16 changed files with 1441 additions and 44 deletions

View File

@@ -1,7 +1,7 @@
<template>
<div class="min-h-screen bg-gray-100 dark:bg-gray-900" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
<!-- Sidebar - Solo mostrar si no estamos en login -->
<template v-if="$route.path !== '/login'">
<!-- Sidebar - Solo mostrar si no estamos en login o register -->
<template v-if="!isPublicRoute">
<!-- Sidebar -->
<aside
class="fixed top-0 left-0 z-40 h-screen transition-all duration-300 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 shadow-lg"
@@ -83,9 +83,9 @@
</template>
<!-- Main Content -->
<div class="transition-all duration-300" :class="$route.path === '/login' ? '' : (sidebarCollapsed ? 'ml-20' : 'ml-64')">
<!-- Header - Solo mostrar si no estamos en login -->
<header v-if="$route.path !== '/login'" class="sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
<div class="transition-all duration-300" :class="isPublicRoute ? '' : (sidebarCollapsed ? 'ml-20' : 'ml-64')">
<!-- Header - Solo mostrar si no estamos en login o register -->
<header v-if="!isPublicRoute" class="sticky top-0 z-30 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
<div class="flex items-center justify-between h-16 px-6">
<!-- Breadcrumbs -->
<div class="flex items-center space-x-2">
@@ -138,13 +138,13 @@
</header>
<!-- Page Content -->
<main :class="$route.path === '/login' ? '' : 'p-6 pb-20'">
<main :class="isPublicRoute ? '' : 'p-6 pb-20'">
<router-view />
</main>
</div>
<!-- Footer Fixed - Solo mostrar si no estamos en login -->
<footer v-if="$route.path !== '/login'" class="fixed bottom-0 left-0 right-0 z-30 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 py-3 shadow-sm" :class="sidebarCollapsed ? 'ml-20' : 'ml-64'">
<!-- Footer Fixed - Solo mostrar si no estamos en login o register -->
<footer v-if="!isPublicRoute" class="fixed bottom-0 left-0 right-0 z-30 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 py-3 shadow-sm" :class="sidebarCollapsed ? 'ml-20' : 'ml-64'">
<div class="px-6">
<p class="text-center text-sm text-gray-600 dark:text-gray-400">
© {{ new Date().getFullYear() }} Wallabicher. Todos los derechos reservados.
@@ -180,7 +180,7 @@ import {
} from '@heroicons/vue/24/outline';
import pushNotificationService from './services/pushNotifications';
import authService from './services/auth';
import { useRouter } from 'vue-router';
import { useRouter, useRoute } from 'vue-router';
import api from './services/api';
import ToastContainer from './components/ToastContainer.vue';
@@ -198,6 +198,7 @@ const allNavItems = [
];
const router = useRouter();
const route = useRoute();
const wsConnected = ref(false);
const sidebarCollapsed = ref(false);
const darkMode = ref(false);
@@ -209,6 +210,10 @@ let ws = null;
const isDark = computed(() => darkMode.value);
const isAuthenticated = computed(() => authService.hasCredentials());
// Rutas públicas que no deben mostrar el sidebar/header
const publicRoutes = ['/login', '/register'];
const isPublicRoute = computed(() => publicRoutes.includes(route.path));
// Filtrar navItems según el rol del usuario
const navItems = computed(() => {
return allNavItems.filter(item => {
@@ -339,7 +344,7 @@ onMounted(async () => {
authService.clearSession();
currentUser.value = authService.getUsername() || null;
isAdmin.value = authService.isAdmin();
if (router.currentRoute.value.path !== '/login') {
if (!publicRoutes.includes(router.currentRoute.value.path)) {
router.push('/login');
}
} else {

View File

@@ -13,11 +13,13 @@ import Logs from './views/Logs.vue';
import RateLimiter from './views/RateLimiter.vue';
import Sessions from './views/Sessions.vue';
import Login from './views/Login.vue';
import Register from './views/Register.vue';
import './style.css';
import authService from './services/auth';
const routes = [
{ path: '/login', component: Login, name: 'login' },
{ path: '/register', component: Register, name: 'register' },
{ path: '/', component: Dashboard, meta: { requiresAuth: true } }, // Redirige a /dashboard
{ path: '/articles', component: Articles, meta: { requiresAuth: true } },
{ path: '/articles/:platform/:id', component: ArticleDetail, meta: { requiresAuth: true } },
@@ -38,8 +40,8 @@ const router = createRouter({
// Guard de navegación para verificar autenticación
router.beforeEach(async (to, from, next) => {
// Si la ruta es /login y ya está autenticado, redirigir al dashboard
if (to.path === '/login') {
// Si la ruta es /login o /register y ya está autenticado, redirigir al dashboard
if (to.path === '/login' || to.path === '/register') {
if (authService.hasCredentials()) {
const isValid = await authService.validateSession();
if (isValid) {

View File

@@ -193,5 +193,26 @@ export default {
const response = await api.put(`/subscription/${username}`, subscriptionData);
return response.data;
},
// Métodos genéricos para rutas adicionales
async post(url, data) {
const response = await api.post(url, data);
return response.data;
},
async get(url, config) {
const response = await api.get(url, config);
return response.data;
},
async put(url, data) {
const response = await api.put(url, data);
return response.data;
},
async delete(url) {
const response = await api.delete(url);
return response.data;
},
};

View File

@@ -217,6 +217,12 @@
<!-- Footer -->
<div class="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
<p class="text-sm text-center text-gray-600 dark:text-gray-400 mb-2">
¿No tienes cuenta?
<router-link to="/register" class="text-primary-600 dark:text-primary-400 hover:underline font-semibold">
Regístrate gratis
</router-link>
</p>
<p class="text-xs text-center text-gray-500 dark:text-gray-400">
¿Necesitas ayuda? Contacta con el administrador del sistema
</p>
@@ -265,7 +271,14 @@ async function handleLogin() {
window.dispatchEvent(new CustomEvent('auth-login'));
} catch (error) {
console.error('Error en login:', error);
loginError.value = error.message || 'Usuario o contraseña incorrectos';
// Verificar si el error es de pago pendiente
if (error.response?.data?.status === 'pending_payment') {
loginError.value = 'Tu cuenta está pendiente de pago. Por favor, completa el proceso de pago para activar tu cuenta. Si ya pagaste, espera unos minutos y vuelve a intentar.';
} else {
loginError.value = error.response?.data?.message || error.message || 'Usuario o contraseña incorrectos';
}
authService.clearSession();
} finally {
loginLoading.value = false;

View File

@@ -0,0 +1,394 @@
<template>
<div class="fixed inset-0 bg-gradient-to-br from-primary-50 via-teal-50 to-cyan-50 dark:from-gray-950 dark:via-gray-900 dark:to-primary-950 overflow-y-auto">
<div class="min-h-screen flex items-center justify-center p-4 py-12">
<!-- Logo flotante en la esquina -->
<div class="absolute top-4 left-4">
<img src="/logo.jpg" alt="Wallabicher" class="w-12 h-12 rounded-xl shadow-lg" />
</div>
<div class="w-full max-w-6xl">
<!-- Header -->
<div class="text-center mb-8">
<h1 class="text-4xl sm:text-5xl font-bold text-gray-900 dark:text-white mb-2">
Crea tu cuenta en
<span class="bg-gradient-to-r from-primary-600 via-teal-600 to-cyan-600 bg-clip-text text-transparent">
Wallabicher
</span>
</h1>
<p class="text-lg text-gray-600 dark:text-gray-400 mb-2">
Elige el plan perfecto para ti y empieza a monitorizar marketplaces
</p>
<p class="text-sm text-gray-500 dark:text-gray-500 flex items-center justify-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"></path>
</svg>
Haz clic en un plan para seleccionarlo
</p>
</div>
<div class="grid lg:grid-cols-3 gap-6 mb-8">
<!-- Planes -->
<div
v-for="plan in plans"
:key="plan.id"
@click="selectPlan(plan.id)"
:class="[
'group relative p-6 rounded-2xl border-2 cursor-pointer transition-all duration-300 transform hover:-translate-y-2 hover:shadow-xl',
selectedPlan === plan.id
? 'border-primary-500 dark:border-primary-400 shadow-2xl scale-105 bg-white dark:bg-gray-800 ring-4 ring-primary-100 dark:ring-primary-900/50'
: 'border-gray-200 dark:border-gray-700 hover:border-primary-300 dark:hover:border-primary-700 bg-white/80 dark:bg-gray-800/80 hover:bg-white dark:hover:bg-gray-800'
]"
>
<!-- Badge popular -->
<div v-if="plan.id === 'basic'" class="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 bg-gradient-to-r from-primary-600 to-teal-600 text-white text-xs font-semibold rounded-full">
Más Popular
</div>
<!-- Checkmark si está seleccionado -->
<div v-if="selectedPlan === plan.id" class="absolute top-4 right-4 w-8 h-8 bg-primary-600 rounded-full flex items-center justify-center shadow-lg animate-scale-in">
<svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
</div>
<!-- Indicador de clickeable si NO está seleccionado -->
<div v-else class="absolute top-4 right-4 w-8 h-8 border-2 border-gray-300 dark:border-gray-600 rounded-full flex items-center justify-center group-hover:border-primary-500 dark:group-hover:border-primary-400 transition-colors">
<svg class="w-4 h-4 text-gray-400 group-hover:text-primary-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
</svg>
</div>
<div class="text-center mb-6">
<h3 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">{{ plan.name }}</h3>
<p class="text-sm text-gray-600 dark:text-gray-400 mb-4">{{ plan.description }}</p>
<div class="mb-4">
<div v-if="billingPeriod === 'monthly'">
<span class="text-3xl font-bold text-gray-900 dark:text-white">
{{ plan.price.monthly.toFixed(2) }}
</span>
<span class="text-gray-600 dark:text-gray-400">/mes</span>
</div>
<div v-else>
<span class="text-3xl font-bold text-gray-900 dark:text-white">
{{ plan.price.yearly.toFixed(2) }}
</span>
<span class="text-gray-600 dark:text-gray-400">/año</span>
<div class="text-sm text-primary-600 dark:text-primary-400 mt-1">
{{ (plan.price.yearly / 12).toFixed(2) }}/mes
</div>
</div>
</div>
</div>
<ul class="space-y-2 mb-4">
<li v-for="(feature, idx) in plan.features.slice(0, 4)" :key="idx" class="flex items-start text-sm">
<svg class="w-5 h-5 text-primary-600 dark:text-primary-400 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
<span class="text-gray-700 dark:text-gray-300">{{ feature }}</span>
</li>
</ul>
</div>
</div>
<!-- Formulario de registro -->
<div class="max-w-md mx-auto bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8 border border-gray-200 dark:border-gray-700">
<h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-2 text-center">
Completa tu registro
</h2>
<div class="text-center mb-6 p-3 bg-primary-50 dark:bg-primary-900/20 rounded-lg border border-primary-200 dark:border-primary-800">
<p class="text-sm text-gray-600 dark:text-gray-400">
Plan seleccionado:
<span class="font-bold text-primary-600 dark:text-primary-400">
{{ plans.find(p => p.id === selectedPlan)?.name || 'Gratis' }}
</span>
</p>
</div>
<!-- Toggle mensual/anual -->
<div class="flex justify-center mb-6">
<div class="inline-flex items-center bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
<button
@click="billingPeriod = 'monthly'"
:class="[
'px-4 py-2 rounded-md text-sm font-medium transition-all',
billingPeriod === 'monthly'
? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
: 'text-gray-700 dark:text-gray-300'
]"
>
Mensual
</button>
<button
@click="billingPeriod = 'yearly'"
:class="[
'px-4 py-2 rounded-md text-sm font-medium transition-all',
billingPeriod === 'yearly'
? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
: 'text-gray-700 dark:text-gray-300'
]"
>
Anual
<span class="ml-1 text-xs text-primary-600 dark:text-primary-400">-17%</span>
</button>
</div>
</div>
<form @submit.prevent="handleRegister" class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Nombre de usuario
</label>
<input
v-model="formData.username"
type="text"
required
minlength="3"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="usuario123"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Email
</label>
<input
v-model="formData.email"
type="email"
required
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="tu@email.com"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Contraseña
</label>
<input
v-model="formData.password"
type="password"
required
minlength="6"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="••••••••"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Confirmar contraseña
</label>
<input
v-model="formData.confirmPassword"
type="password"
required
minlength="6"
class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="••••••••"
/>
</div>
<div v-if="error" class="bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-400 px-4 py-3 rounded-lg text-sm">
{{ error }}
</div>
<button
type="submit"
:disabled="loading"
class="w-full py-3 px-4 bg-gradient-to-r from-primary-600 to-teal-600 hover:from-primary-700 hover:to-teal-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
>
<span v-if="!loading">
{{ selectedPlan === 'free' ? 'Crear cuenta gratis' : `Continuar al pago (${getPlanPrice()})` }}
</span>
<span v-else>Procesando...</span>
</button>
</form>
<div class="mt-6 text-center">
<p class="text-sm text-gray-600 dark:text-gray-400">
¿Ya tienes cuenta?
<router-link to="/login" class="text-primary-600 dark:text-primary-400 hover:underline font-semibold">
Inicia sesión
</router-link>
</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import api from '../services/api';
export default {
name: 'Register',
setup() {
const router = useRouter();
const plans = ref([]);
const selectedPlan = ref('free');
const billingPeriod = ref('monthly');
const loading = ref(false);
const error = ref('');
const formData = ref({
username: '',
email: '',
password: '',
confirmPassword: '',
});
const getPlanPrice = () => {
const plan = plans.value.find(p => p.id === selectedPlan.value);
if (!plan) return '0.00';
return billingPeriod.value === 'yearly'
? plan.price.yearly.toFixed(2)
: plan.price.monthly.toFixed(2);
};
const selectPlan = (planId) => {
selectedPlan.value = planId;
error.value = '';
};
const handleRegister = async () => {
error.value = '';
// Validaciones
if (formData.value.password !== formData.value.confirmPassword) {
error.value = 'Las contraseñas no coinciden';
return;
}
if (formData.value.password.length < 6) {
error.value = 'La contraseña debe tener al menos 6 caracteres';
return;
}
if (formData.value.username.length < 3) {
error.value = 'El nombre de usuario debe tener al menos 3 caracteres';
return;
}
loading.value = true;
try {
// 1. Registrar usuario
const registerResponse = await api.post('/users/register', {
username: formData.value.username,
email: formData.value.email,
password: formData.value.password,
planId: selectedPlan.value,
});
if (!registerResponse.success) {
throw new Error(registerResponse.error || 'Error al registrar usuario');
}
// 2. Si es plan gratuito, hacer login y redirigir al dashboard
if (selectedPlan.value === 'free') {
const loginResponse = await api.post('/users/login', {
username: formData.value.username,
password: formData.value.password,
});
if (loginResponse.token) {
localStorage.setItem('token', loginResponse.token);
localStorage.setItem('username', loginResponse.username);
localStorage.setItem('role', loginResponse.role || 'user');
router.push('/');
}
} else {
// 3. Si es plan de pago, crear sesión de checkout directamente (sin login)
// El usuario se activará cuando se complete el pago
try {
const checkoutResponse = await api.post('/payments/create-checkout-session', {
planId: selectedPlan.value,
billingPeriod: billingPeriod.value,
username: formData.value.username,
email: formData.value.email,
});
if (checkoutResponse.url) {
// Guardar info para después del pago
sessionStorage.setItem('pendingUsername', formData.value.username);
// Redirigir a Stripe Checkout
window.location.href = checkoutResponse.url;
} else {
throw new Error('No se pudo crear la sesión de pago');
}
} catch (checkoutError) {
// Si falla el checkout, mostrar error pero el usuario YA está creado
console.error('Error creando sesión de checkout:', checkoutError);
error.value = 'Usuario creado, pero hubo un error al procesar el pago. Por favor, intenta iniciar sesión y actualizar tu suscripción desde el panel.';
// Opcional: podríamos eliminar el usuario aquí si queremos ser más estrictos
// Pero es mejor dejarlo para que pueda intentar pagar después desde el dashboard
}
}
} catch (err) {
console.error('Error en registro:', err);
error.value = err.response?.data?.message || err.response?.data?.error || err.message || 'Error al registrar usuario';
} finally {
loading.value = false;
}
};
onMounted(async () => {
try {
// Cargar planes
const response = await api.get('/subscription/plans');
plans.value = response.plans || [];
// Preseleccionar el plan de la URL si existe
const urlParams = new URLSearchParams(window.location.search);
const planFromUrl = urlParams.get('plan');
if (planFromUrl && plans.value.find(p => p.id === planFromUrl)) {
selectedPlan.value = planFromUrl;
}
} catch (err) {
console.error('Error cargando planes:', err);
}
});
return {
plans,
selectedPlan,
billingPeriod,
formData,
loading,
error,
selectPlan,
handleRegister,
getPlanPrice,
};
},
};
</script>
<style scoped>
@keyframes scale-in {
0% {
transform: scale(0);
opacity: 0;
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
opacity: 1;
}
}
.animate-scale-in {
animation: scale-in 0.3s ease-out;
}
</style>

View File

@@ -45,6 +45,51 @@
</div>
</div>
<!-- Actions -->
<div v-if="subscription.subscription.planId !== 'free'" class="flex flex-wrap gap-3 pb-6 border-b border-gray-200 dark:border-gray-700">
<button
v-if="!subscription.subscription.cancelAtPeriodEnd"
@click="openCancelModal"
class="btn btn-outline-danger"
:disabled="actionLoading"
>
Cancelar suscripción
</button>
<button
v-else
@click="reactivateSubscription"
class="btn btn-primary"
:disabled="actionLoading"
>
Reactivar suscripción
</button>
<button
@click="openCustomerPortal"
class="btn btn-outline"
:disabled="actionLoading"
>
Gestionar pago
</button>
</div>
<!-- Cancel Warning -->
<div v-if="subscription.subscription.cancelAtPeriodEnd" class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
<div class="flex items-start space-x-3">
<svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
</svg>
<div>
<p class="text-sm font-semibold text-yellow-800 dark:text-yellow-300">
Suscripción cancelada
</p>
<p class="text-sm text-yellow-700 dark:text-yellow-400 mt-1">
Tu suscripción se mantendrá activa hasta {{ formatDate(subscription.subscription.currentPeriodEnd) }}.
Después se cambiará al plan gratuito automáticamente.
</p>
</div>
</div>
</div>
<!-- Usage Stats -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
@@ -99,19 +144,19 @@
<div class="card">
<div class="card-header">
<h3 class="card-title">Planes Disponibles</h3>
<p class="card-subtitle">Información de los planes disponibles</p>
<p class="card-subtitle">Cambia tu plan en cualquier momento</p>
</div>
<!-- Mensaje informativo -->
<div class="mb-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
<div class="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div class="flex items-start">
<svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400 mr-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg class="w-5 h-5 text-blue-600 dark:text-blue-400 mr-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<div>
<h4 class="text-sm font-semibold text-yellow-800 dark:text-yellow-300 mb-1">Cambio de plan temporalmente deshabilitado</h4>
<p class="text-sm text-yellow-700 dark:text-yellow-400">
El cambio de plan no está disponible por el momento. Si necesitas cambiar tu plan, contacta con el administrador.
<h4 class="text-sm font-semibold text-blue-800 dark:text-blue-300 mb-1">Actualiza tu plan</h4>
<p class="text-sm text-blue-700 dark:text-blue-400">
Puedes cambiar a un plan superior en cualquier momento. Para planes de pago, serás redirigido a Stripe Checkout. El cambio a plan gratuito es inmediato.
</p>
</div>
</div>
@@ -125,13 +170,18 @@
<div
v-for="plan in plans"
:key="plan.id"
class="p-6 rounded-xl border-2 transition-all duration-300 opacity-75"
class="p-6 rounded-xl border-2 transition-all duration-300 hover:shadow-xl"
:class="
plan.id === subscription?.subscription?.planId
? 'border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/20'
: 'border-gray-200 dark:border-gray-800'
? 'border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/20 shadow-lg'
: 'border-gray-200 dark:border-gray-800 hover:border-primary-300 dark:hover:border-primary-700 hover:-translate-y-1'
"
>
<!-- Badge de plan popular -->
<div v-if="plan.id === 'basic'" class="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 bg-gradient-to-r from-primary-600 to-teal-600 text-white text-xs font-semibold rounded-full">
Más Popular
</div>
<div class="text-center mb-4">
<h4 class="text-xl font-bold text-gray-900 dark:text-gray-100 mb-1">{{ plan.name }}</h4>
<p class="text-sm text-gray-600 dark:text-gray-400 mb-4">{{ plan.description }}</p>
@@ -140,11 +190,14 @@
{{ plan.price.monthly.toFixed(2) }}
</span>
<span class="text-gray-600 dark:text-gray-400">/mes</span>
<p v-if="plan.price.yearly > 0" class="text-xs text-primary-600 dark:text-primary-400 mt-1">
o {{ plan.price.yearly.toFixed(2) }}/año (ahorra 17%)
</p>
</div>
</div>
<ul class="space-y-2 mb-6">
<li v-for="feature in plan.features.slice(0, 3)" :key="feature" class="flex items-start text-sm">
<li v-for="feature in plan.features.slice(0, 4)" :key="feature" class="flex items-start text-sm">
<svg class="w-4 h-4 text-primary-600 dark:text-primary-400 mr-2 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
</svg>
@@ -154,14 +207,26 @@
<button
v-if="plan.id !== subscription?.subscription?.planId"
class="w-full btn btn-primary opacity-50 cursor-not-allowed"
disabled
title="Cambio de plan temporalmente deshabilitado"
@click="upgradePlan(plan.id)"
:disabled="upgrading"
class="w-full btn transition-all duration-300"
:class="plan.id === 'free'
? 'btn-outline'
: 'btn-primary shadow-lg hover:shadow-xl'"
>
No disponible
<span v-if="!upgrading">
{{ plan.id === 'free' ? 'Cambiar a gratuito' : 'Seleccionar plan' }}
</span>
<span v-else class="flex items-center justify-center">
<svg class="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Procesando...
</span>
</button>
<div v-else class="w-full text-center py-2 px-4 bg-primary-100 dark:bg-primary-900/50 text-primary-700 dark:text-primary-400 rounded-lg font-semibold">
Plan Actual
<div v-else class="w-full text-center py-3 px-4 bg-gradient-to-r from-primary-100 to-teal-100 dark:from-primary-900/50 dark:to-teal-900/50 text-primary-700 dark:text-primary-400 rounded-lg font-semibold border-2 border-primary-300 dark:border-primary-700">
Plan Actual
</div>
</div>
</div>
@@ -178,6 +243,8 @@ const plans = ref([]);
const loading = ref(true);
const loadingPlans = ref(true);
const upgrading = ref(false);
const actionLoading = ref(false);
const showCancelModal = ref(false);
function formatDate(date) {
if (!date) return 'N/A';
@@ -238,27 +305,120 @@ async function loadPlans() {
async function upgradePlan(planId) {
if (upgrading.value) return;
if (!confirm(`¿Estás seguro de que quieres cambiar a el plan ${plans.value.find(p => p.id === planId)?.name || planId}?`)) {
return;
}
const selectedPlan = plans.value.find(p => p.id === planId);
if (!selectedPlan) return;
// Si es plan de pago, crear sesión de checkout
if (planId !== 'free') {
// Preguntar período de facturación
const billingPeriodChoice = confirm('¿Deseas facturación anual? (17% de descuento)\n\nAceptar = Anual\nCancelar = Mensual');
const chosenBillingPeriod = billingPeriodChoice ? 'yearly' : 'monthly';
try {
upgrading.value = true;
const response = await api.post('/payments/create-checkout-session', {
planId,
billingPeriod: chosenBillingPeriod,
});
if (response.url) {
// Redirigir a Stripe Checkout
window.location.href = response.url;
}
} catch (error) {
console.error('Error creando sesión de checkout:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al crear la sesión de pago';
alert(errorMessage);
} finally {
upgrading.value = false;
}
} else {
// Plan gratuito
if (!confirm(`¿Estás seguro de que quieres cambiar al plan ${selectedPlan.name}?`)) {
return;
}
try {
upgrading.value = true;
await api.updateSubscription({ planId });
await loadSubscription();
} catch (error) {
console.error('Error actualizando plan:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al actualizar el plan';
alert(errorMessage);
} finally {
upgrading.value = false;
}
}
}
function openCancelModal() {
if (confirm('¿Estás seguro de que quieres cancelar tu suscripción? Se mantendrá activa hasta el final del período de facturación.')) {
cancelSubscription();
}
}
async function cancelSubscription() {
try {
upgrading.value = true;
await api.updateSubscription({ planId });
// Plan actualizado correctamente
actionLoading.value = true;
await api.post('/payments/cancel-subscription');
alert('Suscripción cancelada. Se mantendrá activa hasta el final del período.');
await loadSubscription();
} catch (error) {
console.error('Error actualizando plan:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al actualizar el plan';
console.error('Error cancelando suscripción:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al cancelar la suscripción';
alert(errorMessage);
} finally {
upgrading.value = false;
actionLoading.value = false;
}
}
async function reactivateSubscription() {
try {
actionLoading.value = true;
await api.post('/payments/reactivate-subscription');
alert('Suscripción reactivada correctamente.');
await loadSubscription();
} catch (error) {
console.error('Error reactivando suscripción:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al reactivar la suscripción';
alert(errorMessage);
} finally {
actionLoading.value = false;
}
}
async function openCustomerPortal() {
try {
actionLoading.value = true;
const response = await api.post('/payments/create-portal-session');
if (response.url) {
window.location.href = response.url;
}
} catch (error) {
console.error('Error abriendo portal de cliente:', error);
const errorMessage = error.response?.data?.message || error.response?.data?.error || 'Error al abrir el portal de gestión';
alert(errorMessage);
} finally {
actionLoading.value = false;
}
}
onMounted(() => {
loadSubscription();
loadPlans();
// Verificar si venimos de un pago exitoso
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('payment_success') === 'true') {
alert('¡Pago procesado exitosamente! Tu suscripción ha sido activada.');
// Limpiar URL
window.history.replaceState({}, document.title, window.location.pathname);
} else if (urlParams.get('payment_cancelled') === 'true') {
alert('Pago cancelado. Puedes intentarlo de nuevo cuando quieras.');
// Limpiar URL
window.history.replaceState({}, document.title, window.location.pathname);
}
});
</script>