|
|
from datetime import datetime
|
|
|
import json
|
|
|
import os
|
|
|
|
|
|
|
|
|
SUBSCRIPTIONS_FILE = 'data/subscriptions.json'
|
|
|
|
|
|
|
|
|
os.makedirs(os.path.dirname(SUBSCRIPTIONS_FILE), exist_ok=True)
|
|
|
|
|
|
|
|
|
if not os.path.exists(SUBSCRIPTIONS_FILE):
|
|
|
with open(SUBSCRIPTIONS_FILE, 'w') as f:
|
|
|
json.dump({}, f)
|
|
|
|
|
|
|
|
|
class Subscription:
|
|
|
def __init__(self, user_id, plan_id, start_date, end_date, is_active=True):
|
|
|
self.user_id = user_id
|
|
|
self.plan_id = plan_id
|
|
|
self.start_date = start_date
|
|
|
self.end_date = end_date
|
|
|
self.is_active = is_active
|
|
|
self.created_at = datetime.now().isoformat()
|
|
|
|
|
|
@staticmethod
|
|
|
def get_by_user_id(user_id):
|
|
|
"""Get subscription by user ID"""
|
|
|
try:
|
|
|
with open(SUBSCRIPTIONS_FILE, 'r') as f:
|
|
|
subscriptions = json.load(f)
|
|
|
|
|
|
user_subscription = subscriptions.get(str(user_id))
|
|
|
if user_subscription:
|
|
|
return Subscription(
|
|
|
user_id=user_subscription['user_id'],
|
|
|
plan_id=user_subscription['plan_id'],
|
|
|
start_date=user_subscription['start_date'],
|
|
|
end_date=user_subscription['end_date'],
|
|
|
is_active=user_subscription['is_active']
|
|
|
)
|
|
|
return None
|
|
|
except Exception:
|
|
|
return None
|
|
|
|
|
|
@staticmethod
|
|
|
def create_or_update(user_id, plan_id, start_date, end_date, is_active=True):
|
|
|
"""Create or update subscription"""
|
|
|
try:
|
|
|
|
|
|
if os.path.exists(SUBSCRIPTIONS_FILE):
|
|
|
with open(SUBSCRIPTIONS_FILE, 'r') as f:
|
|
|
subscriptions = json.load(f)
|
|
|
else:
|
|
|
subscriptions = {}
|
|
|
|
|
|
|
|
|
subscriptions[str(user_id)] = {
|
|
|
'user_id': user_id,
|
|
|
'plan_id': plan_id,
|
|
|
'start_date': start_date,
|
|
|
'end_date': end_date,
|
|
|
'is_active': is_active,
|
|
|
'created_at': datetime.now().isoformat()
|
|
|
}
|
|
|
|
|
|
|
|
|
with open(SUBSCRIPTIONS_FILE, 'w') as f:
|
|
|
json.dump(subscriptions, f, indent=2)
|
|
|
|
|
|
return Subscription(user_id, plan_id, start_date, end_date, is_active)
|
|
|
except Exception as e:
|
|
|
print(f"Error creating/updating subscription: {e}")
|
|
|
return None
|
|
|
|
|
|
@staticmethod
|
|
|
def cancel(user_id):
|
|
|
"""Cancel subscription for user"""
|
|
|
try:
|
|
|
|
|
|
if os.path.exists(SUBSCRIPTIONS_FILE):
|
|
|
with open(SUBSCRIPTIONS_FILE, 'r') as f:
|
|
|
subscriptions = json.load(f)
|
|
|
else:
|
|
|
return False
|
|
|
|
|
|
|
|
|
if str(user_id) in subscriptions:
|
|
|
subscriptions[str(user_id)]['is_active'] = False
|
|
|
|
|
|
|
|
|
with open(SUBSCRIPTIONS_FILE, 'w') as f:
|
|
|
json.dump(subscriptions, f, indent=2)
|
|
|
|
|
|
return True
|
|
|
return False
|
|
|
except Exception as e:
|
|
|
print(f"Error canceling subscription: {e}")
|
|
|
return False |