.cabinet-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
.cabinet-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid #e0e0e0;
padding-bottom: 20px;
margin-bottom: 30px;
}
.subscription-block, .payment-history {
background: #f8f9fa;
padding: 25px;
border-radius: 12px;
margin-bottom: 25px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.subscription-active {
border: 2px solid #28a745;
background: white;
padding: 20px;
border-radius: 8px;
}
.subscription-inactive {
border: 2px solid #dc3545;
background: #fff5f5;
padding: 20px;
border-radius: 8px;
}
.status-badge {
display: inline-block;
padding: 8px 16px;
border-radius: 20px;
font-weight: 600;
margin-bottom: 15px;
font-size: 14px;
}
.status-active { background: #28a745; color: white; }
.status-inactive { background: #dc3545; color: white; }
.status-canceled { background: #ffc107; color: #212529; }
.subscription-details {
margin: 15px 0;
}
.subscription-details p {
margin: 8px 0;
font-size: 16px;
}
.btn-cancel {
background: #dc3545;
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
cursor: pointer;
font-weight: 600;
margin-top: 15px;
transition: background 0.2s;
}
.btn-cancel:hover {
background: #c82333;
}
.btn-subscribe {
background: #007bff;
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
cursor: pointer;
font-weight: 600;
}
.payment-item {
border-bottom: 1px solid #e0e0e0;
padding: 15px 0;
}
.payment-item:last-child {
border-bottom: none;
}
class PowerYogaCabinet {
constructor() {
this.projectId = parseInt(document.querySelector('#allrecords').dataset.tildaProjectId);
this.init();
}
async init() {
await this.loadUserData();
await this.loadSubscriptionData();
this.setupEventListeners();
}
loadUserData() {
// Получаем данные пользователя из localStorage Tilda Members
const lsUser = window.localStorage.getItem('tilda_members_profile' + this.projectId);
if (lsUser) {
const user = JSON.parse(lsUser);
document.getElementById('userName').textContent = user.name || user.email;
return user;
}
return null;
}
async loadSubscriptionData() {
const user = this.loadUserData();
if (!user) return;
try {
// Запрос к вашему API для получения данных о подписке
const response = await fetch('/api/subscription-status', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: user.email,
userId: user.id
})
});
const subscriptionData = await response.json();
this.displaySubscriptionInfo(subscriptionData);
} catch (error) {
console.error('Ошибка загрузки данных подписки:', error);
this.displayErrorMessage();
}
}
displaySubscriptionInfo(data) {
const container = document.getElementById('subscriptionStatus');
if (!data.hasActiveSubscription) {
container.innerHTML = `
Подписка неактивна
У вас нет активной подписки на Power Yoga Online
`;
return;
}
container.innerHTML = `
Подписка активна
Тариф: ${this.getSubscriptionTypeName(data.subscriptionType)}
Сумма подписки: ${data.amount}₽
Последний платеж: ${this.formatDate(data.lastPaymentDate)} - ${data.lastPaymentAmount}₽
Следующий платеж: ${this.formatDate(data.nextPaymentDate)}
`;
if (data.paymentHistory) {
this.displayPaymentHistory(data.paymentHistory);
}
}
displayPaymentHistory(payments) {
const container = document.getElementById('paymentList');
if (!payments || payments.length === 0) {
container.innerHTML = '
История платежей пуста
';
return;
}
const historyHTML = payments.map(payment => `
${this.formatDate(payment.date)}
${payment.description}
${payment.amount}₽
${payment.status === 'success' ? 'Успешно' : 'Ошибка'}
`).join('');
container.innerHTML = historyHTML;
}
async cancelSubscription(subscriptionId) {
if (!confirm('Вы уверены, что хотите отменить подписку? После отмены доступ к платным материалам будет заблокирован.')) {
return;
}
try {
const response = await fetch('/api/cancel-subscription', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
subscriptionId: subscriptionId,
email: this.loadUserData().email
})
});
const result = await response.json();
if (result.success) {
alert('Подписка успешно отменена. Спасибо за то, что были с нами!');
location.reload(); // Перезагружаем страницу для обновления данных
} else {
alert('Произошла ошибка при отмене подписки: ' + result.message);
}
} catch (error) {
alert('Произошла ошибка. Попробуйте позже или обратитесь в поддержку.');
console.error('Ошибка отмены подписки:', error);
}
}
getSubscriptionTypeName(type) {
const types = {
'monthly': 'Power Yoga Online - Monthly (Месячная)',
'quarterly': 'Power Yoga Online - Quarterly (Квартальная)'
};
return types[type] || type;
}
formatDate(dateString) {
if (!dateString) return 'Не указано';
const date = new Date(dateString);
return date.toLocaleDateString('ru-RU', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
}
displayErrorMessage() {
document.getElementById('subscriptionStatus').innerHTML = `
Не удалось загрузить информацию о подписке. Попробуйте обновить страницу.
`;
}
setupEventListeners() {
// Обновление данных каждые 30 секунд
setInterval(() => {
this.loadSubscriptionData();
}, 30000);
}
}
// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
window.poweryogaCabinet = new PowerYogaCabinet();
});