Compare commits
28 Commits
5842ca2dfc
...
feature/ph
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56c30e4904 | ||
|
|
51cd021f85 | ||
|
|
fc6dd5623a | ||
|
|
1531f41226 | ||
|
|
37a64fa1ef | ||
|
|
c4daeb1870 | ||
|
|
79aab68acd | ||
|
|
11a5a66c8b | ||
|
|
ab292de06c | ||
|
|
8a9dd44c50 | ||
|
|
219dae83c6 | ||
|
|
066b81dd2a | ||
|
|
8171014a7e | ||
|
|
46b5b5f1b2 | ||
|
|
a267fc0715 | ||
|
|
9ec8908091 | ||
|
|
0d468ef15a | ||
|
|
8fc483251e | ||
|
|
1d39f3f00a | ||
|
|
b20fab8ec1 | ||
|
|
437b0c7516 | ||
|
|
4de9128430 | ||
|
|
f195b6a72a | ||
|
|
ab6b6cc4be | ||
|
|
d0e6b342b5 | ||
|
|
461f3211dd | ||
|
|
abbf6dbabb | ||
|
|
a10e89ab08 |
Binary file not shown.
@@ -19,21 +19,9 @@ class PlanAdmin(admin.ModelAdmin):
|
||||
('Plan Info', {
|
||||
'fields': ('name', 'slug', 'price', 'billing_cycle', 'features', 'is_active')
|
||||
}),
|
||||
('User / Site Limits', {
|
||||
('Account Management Limits', {
|
||||
'fields': ('max_users', 'max_sites', 'max_industries', 'max_author_profiles')
|
||||
}),
|
||||
('Planner Limits', {
|
||||
'fields': ('max_keywords', 'max_clusters', 'daily_cluster_limit', 'daily_keyword_import_limit', 'monthly_cluster_ai_credits')
|
||||
}),
|
||||
('Writer Limits', {
|
||||
'fields': ('daily_content_tasks', 'daily_ai_requests', 'monthly_word_count_limit', 'monthly_content_ai_credits')
|
||||
}),
|
||||
('Image Limits', {
|
||||
'fields': ('monthly_image_count', 'monthly_image_ai_credits', 'max_images_per_task', 'image_model_choices')
|
||||
}),
|
||||
('AI Controls', {
|
||||
'fields': ('daily_ai_request_limit', 'monthly_ai_credit_limit')
|
||||
}),
|
||||
('Billing & Credits', {
|
||||
'fields': ('included_credits', 'extra_credit_price', 'allow_credit_topup', 'auto_credit_topup_threshold', 'auto_credit_topup_amount', 'credits_per_month')
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Generated manually for Phase 0: Remove plan operation limit fields (credit-only system)
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('igny8_core_auth', '0013_remove_ai_cost_per_request'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
# Remove Planner Limits
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='max_keywords',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='max_clusters',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='max_content_ideas',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='daily_cluster_limit',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='daily_keyword_import_limit',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='monthly_cluster_ai_credits',
|
||||
),
|
||||
# Remove Writer Limits
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='daily_content_tasks',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='daily_ai_requests',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='monthly_word_count_limit',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='monthly_content_ai_credits',
|
||||
),
|
||||
# Remove Image Generation Limits
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='monthly_image_count',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='daily_image_generation_limit',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='monthly_image_ai_credits',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='max_images_per_task',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='image_model_choices',
|
||||
),
|
||||
# Remove AI Request Controls
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='daily_ai_request_limit',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='plan',
|
||||
name='monthly_ai_credit_limit',
|
||||
),
|
||||
]
|
||||
|
||||
@@ -93,8 +93,8 @@ class Account(models.Model):
|
||||
|
||||
class Plan(models.Model):
|
||||
"""
|
||||
Subscription plan model with comprehensive limits and features.
|
||||
Plans define limits for users, sites, content generation, AI usage, and billing.
|
||||
Subscription plan model - Phase 0: Credit-only system.
|
||||
Plans define credits, billing, and account management limits only.
|
||||
"""
|
||||
BILLING_CYCLE_CHOICES = [
|
||||
('monthly', 'Monthly'),
|
||||
@@ -110,7 +110,7 @@ class Plan(models.Model):
|
||||
is_active = models.BooleanField(default=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
# User / Site / Scope Limits
|
||||
# Account Management Limits (kept - not operation limits)
|
||||
max_users = models.IntegerField(default=1, validators=[MinValueValidator(1)], help_text="Total users allowed per account")
|
||||
max_sites = models.IntegerField(
|
||||
default=1,
|
||||
@@ -120,32 +120,7 @@ class Plan(models.Model):
|
||||
max_industries = models.IntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)], help_text="Optional limit for industries/sectors")
|
||||
max_author_profiles = models.IntegerField(default=5, validators=[MinValueValidator(0)], help_text="Limit for saved writing styles")
|
||||
|
||||
# Planner Limits
|
||||
max_keywords = models.IntegerField(default=1000, validators=[MinValueValidator(0)], help_text="Total keywords allowed (global limit)")
|
||||
max_clusters = models.IntegerField(default=100, validators=[MinValueValidator(0)], help_text="Total clusters allowed (global)")
|
||||
max_content_ideas = models.IntegerField(default=300, validators=[MinValueValidator(0)], help_text="Total content ideas allowed (global limit)")
|
||||
daily_cluster_limit = models.IntegerField(default=10, validators=[MinValueValidator(0)], help_text="Max clusters that can be created per day")
|
||||
daily_keyword_import_limit = models.IntegerField(default=100, validators=[MinValueValidator(0)], help_text="SeedKeywords import limit per day")
|
||||
monthly_cluster_ai_credits = models.IntegerField(default=50, validators=[MinValueValidator(0)], help_text="AI credits allocated for clustering")
|
||||
|
||||
# Writer Limits
|
||||
daily_content_tasks = models.IntegerField(default=10, validators=[MinValueValidator(0)], help_text="Max number of content tasks (blogs) per day")
|
||||
daily_ai_requests = models.IntegerField(default=50, validators=[MinValueValidator(0)], help_text="Total AI executions (content + idea + image) allowed per day")
|
||||
monthly_word_count_limit = models.IntegerField(default=50000, validators=[MinValueValidator(0)], help_text="Monthly word limit (for generated content)")
|
||||
monthly_content_ai_credits = models.IntegerField(default=200, validators=[MinValueValidator(0)], help_text="AI credit pool for content generation")
|
||||
|
||||
# Image Generation Limits
|
||||
monthly_image_count = models.IntegerField(default=100, validators=[MinValueValidator(0)], help_text="Max images per month")
|
||||
daily_image_generation_limit = models.IntegerField(default=25, validators=[MinValueValidator(0)], help_text="Max images that can be generated per day")
|
||||
monthly_image_ai_credits = models.IntegerField(default=100, validators=[MinValueValidator(0)], help_text="AI credit pool for image generation")
|
||||
max_images_per_task = models.IntegerField(default=4, validators=[MinValueValidator(1)], help_text="Max images per content task")
|
||||
image_model_choices = models.JSONField(default=list, blank=True, help_text="Allowed image models (e.g., ['dalle3', 'hidream'])")
|
||||
|
||||
# AI Request Controls
|
||||
daily_ai_request_limit = models.IntegerField(default=100, validators=[MinValueValidator(0)], help_text="Global daily AI request cap")
|
||||
monthly_ai_credit_limit = models.IntegerField(default=500, validators=[MinValueValidator(0)], help_text="Unified credit ceiling per month (all AI functions)")
|
||||
|
||||
# Billing & Add-ons
|
||||
# Billing & Credits (Phase 0: Credit-only system)
|
||||
included_credits = models.IntegerField(default=0, validators=[MinValueValidator(0)], help_text="Monthly credits included")
|
||||
extra_credit_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.01, help_text="Price per additional credit")
|
||||
allow_credit_topup = models.BooleanField(default=True, help_text="Can user purchase more credits?")
|
||||
|
||||
@@ -11,10 +11,10 @@ class PlanSerializer(serializers.ModelSerializer):
|
||||
model = Plan
|
||||
fields = [
|
||||
'id', 'name', 'slug', 'price', 'billing_cycle', 'features', 'is_active',
|
||||
'max_users', 'max_sites', 'max_keywords', 'max_clusters', 'max_content_ideas',
|
||||
'monthly_word_count_limit', 'monthly_ai_credit_limit', 'monthly_image_count',
|
||||
'daily_content_tasks', 'daily_ai_request_limit', 'daily_image_generation_limit',
|
||||
'included_credits', 'image_model_choices', 'credits_per_month'
|
||||
'max_users', 'max_sites', 'max_industries', 'max_author_profiles',
|
||||
'included_credits', 'extra_credit_price', 'allow_credit_topup',
|
||||
'auto_credit_topup_threshold', 'auto_credit_topup_amount',
|
||||
'stripe_product_id', 'stripe_price_id', 'credits_per_month'
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ from .views import (
|
||||
SiteUserAccessViewSet, PlanViewSet, SiteViewSet, SectorViewSet,
|
||||
IndustryViewSet, SeedKeywordViewSet
|
||||
)
|
||||
from .serializers import RegisterSerializer, LoginSerializer, ChangePasswordSerializer, UserSerializer
|
||||
from .serializers import RegisterSerializer, LoginSerializer, ChangePasswordSerializer, UserSerializer, RefreshTokenSerializer
|
||||
from .models import User
|
||||
from .utils import generate_access_token, get_token_expiry, decode_token
|
||||
import jwt
|
||||
|
||||
router = DefaultRouter()
|
||||
# Main structure: Groups, Users, Accounts, Subscriptions, Site User Access
|
||||
@@ -78,7 +80,7 @@ class LoginView(APIView):
|
||||
password = serializer.validated_data['password']
|
||||
|
||||
try:
|
||||
user = User.objects.get(email=email)
|
||||
user = User.objects.select_related('account', 'account__plan').get(email=email)
|
||||
except User.DoesNotExist:
|
||||
return error_response(
|
||||
error='Invalid credentials',
|
||||
@@ -107,9 +109,17 @@ class LoginView(APIView):
|
||||
user_data = user_serializer.data
|
||||
except Exception as e:
|
||||
# Fallback if serializer fails (e.g., missing account_id column)
|
||||
# Log the error for debugging but don't fail the login
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.warning(f"UserSerializer failed for user {user.id}: {e}", exc_info=True)
|
||||
|
||||
# Ensure username is properly set (use email prefix if username is empty/default)
|
||||
username = user.username if user.username and user.username != 'user' else user.email.split('@')[0]
|
||||
|
||||
user_data = {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'username': username,
|
||||
'email': user.email,
|
||||
'role': user.role,
|
||||
'account': None,
|
||||
@@ -119,12 +129,10 @@ class LoginView(APIView):
|
||||
return success_response(
|
||||
data={
|
||||
'user': user_data,
|
||||
'tokens': {
|
||||
'access': access_token,
|
||||
'refresh': refresh_token,
|
||||
'access_expires_at': access_expires_at.isoformat(),
|
||||
'refresh_expires_at': refresh_expires_at.isoformat(),
|
||||
}
|
||||
'access': access_token,
|
||||
'refresh': refresh_token,
|
||||
'access_expires_at': access_expires_at.isoformat(),
|
||||
'refresh_expires_at': refresh_expires_at.isoformat(),
|
||||
},
|
||||
message='Login successful',
|
||||
request=request
|
||||
@@ -180,6 +188,84 @@ class ChangePasswordView(APIView):
|
||||
)
|
||||
|
||||
|
||||
@extend_schema(
|
||||
tags=['Authentication'],
|
||||
summary='Refresh Token',
|
||||
description='Refresh access token using refresh token'
|
||||
)
|
||||
class RefreshTokenView(APIView):
|
||||
"""Refresh access token endpoint."""
|
||||
permission_classes = [permissions.AllowAny]
|
||||
|
||||
def post(self, request):
|
||||
serializer = RefreshTokenSerializer(data=request.data)
|
||||
if not serializer.is_valid():
|
||||
return error_response(
|
||||
error='Validation failed',
|
||||
errors=serializer.errors,
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
request=request
|
||||
)
|
||||
|
||||
refresh_token = serializer.validated_data['refresh']
|
||||
|
||||
try:
|
||||
# Decode and validate refresh token
|
||||
payload = decode_token(refresh_token)
|
||||
|
||||
# Verify it's a refresh token
|
||||
if payload.get('type') != 'refresh':
|
||||
return error_response(
|
||||
error='Invalid token type',
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get user
|
||||
user_id = payload.get('user_id')
|
||||
account_id = payload.get('account_id')
|
||||
|
||||
try:
|
||||
user = User.objects.select_related('account', 'account__plan').get(id=user_id)
|
||||
except User.DoesNotExist:
|
||||
return error_response(
|
||||
error='User not found',
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get account
|
||||
account = None
|
||||
if account_id:
|
||||
try:
|
||||
from .models import Account
|
||||
account = Account.objects.get(id=account_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not account:
|
||||
account = getattr(user, 'account', None)
|
||||
|
||||
# Generate new access token
|
||||
access_token = generate_access_token(user, account)
|
||||
access_expires_at = get_token_expiry('access')
|
||||
|
||||
return success_response(
|
||||
data={
|
||||
'access': access_token,
|
||||
'access_expires_at': access_expires_at.isoformat()
|
||||
},
|
||||
request=request
|
||||
)
|
||||
|
||||
except jwt.InvalidTokenError:
|
||||
return error_response(
|
||||
error='Invalid or expired refresh token',
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
request=request
|
||||
)
|
||||
|
||||
|
||||
@extend_schema(exclude=True) # Exclude from public API documentation - internal authenticated endpoint
|
||||
class MeView(APIView):
|
||||
"""Get current user information."""
|
||||
@@ -201,6 +287,7 @@ urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('register/', csrf_exempt(RegisterView.as_view()), name='auth-register'),
|
||||
path('login/', csrf_exempt(LoginView.as_view()), name='auth-login'),
|
||||
path('refresh/', csrf_exempt(RefreshTokenView.as_view()), name='auth-refresh'),
|
||||
path('change-password/', ChangePasswordView.as_view(), name='auth-change-password'),
|
||||
path('me/', MeView.as_view(), name='auth-me'),
|
||||
]
|
||||
|
||||
@@ -933,12 +933,10 @@ class AuthViewSet(viewsets.GenericViewSet):
|
||||
return success_response(
|
||||
data={
|
||||
'user': user_serializer.data,
|
||||
'tokens': {
|
||||
'access': access_token,
|
||||
'refresh': refresh_token,
|
||||
'access_expires_at': access_expires_at.isoformat(),
|
||||
'refresh_expires_at': refresh_expires_at.isoformat(),
|
||||
}
|
||||
'access': access_token,
|
||||
'refresh': refresh_token,
|
||||
'access_expires_at': access_expires_at.isoformat(),
|
||||
'refresh_expires_at': refresh_expires_at.isoformat(),
|
||||
},
|
||||
message='Login successful',
|
||||
request=request
|
||||
|
||||
@@ -3,6 +3,7 @@ Celery configuration for IGNY8
|
||||
"""
|
||||
import os
|
||||
from celery import Celery
|
||||
from celery.schedules import crontab
|
||||
|
||||
# Set the default Django settings module for the 'celery' program.
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8_core.settings')
|
||||
@@ -18,6 +19,13 @@ app.config_from_object('django.conf:settings', namespace='CELERY')
|
||||
# Load task modules from all registered Django apps.
|
||||
app.autodiscover_tasks()
|
||||
|
||||
# Celery Beat schedule for periodic tasks
|
||||
app.conf.beat_schedule = {
|
||||
'replenish-monthly-credits': {
|
||||
'task': 'igny8_core.modules.billing.tasks.replenish_monthly_credits',
|
||||
'schedule': crontab(hour=0, minute=0, day_of_month=1), # First day of month at midnight
|
||||
},
|
||||
}
|
||||
|
||||
@app.task(bind=True, ignore_result=True)
|
||||
def debug_task(self):
|
||||
|
||||
99
backend/igny8_core/modules/billing/tasks.py
Normal file
99
backend/igny8_core/modules/billing/tasks.py
Normal file
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
Celery tasks for billing operations
|
||||
"""
|
||||
import logging
|
||||
from celery import shared_task
|
||||
from django.utils import timezone
|
||||
from django.db import transaction
|
||||
from igny8_core.auth.models import Account
|
||||
from .services import CreditService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@shared_task(name='igny8_core.modules.billing.tasks.replenish_monthly_credits')
|
||||
def replenish_monthly_credits():
|
||||
"""
|
||||
Replenish monthly credits for all active accounts.
|
||||
Runs on the first day of each month at midnight.
|
||||
|
||||
For each active account with a plan:
|
||||
- Adds plan.included_credits to account.credits
|
||||
- Creates a CreditTransaction record
|
||||
- Logs the replenishment
|
||||
"""
|
||||
logger.info("=" * 80)
|
||||
logger.info("MONTHLY CREDIT REPLENISHMENT TASK STARTED")
|
||||
logger.info(f"Timestamp: {timezone.now()}")
|
||||
logger.info("=" * 80)
|
||||
|
||||
# Get all active accounts with plans
|
||||
accounts = Account.objects.filter(
|
||||
status='active',
|
||||
plan__isnull=False
|
||||
).select_related('plan')
|
||||
|
||||
total_accounts = accounts.count()
|
||||
logger.info(f"Found {total_accounts} active accounts with plans")
|
||||
|
||||
replenished = 0
|
||||
skipped = 0
|
||||
errors = 0
|
||||
|
||||
for account in accounts:
|
||||
try:
|
||||
plan = account.plan
|
||||
|
||||
# Get monthly credits from plan
|
||||
monthly_credits = plan.included_credits or plan.credits_per_month or 0
|
||||
|
||||
if monthly_credits <= 0:
|
||||
logger.info(f"Account {account.id} ({account.name}): Plan has no included credits, skipping")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Add credits using CreditService
|
||||
with transaction.atomic():
|
||||
new_balance = CreditService.add_credits(
|
||||
account=account,
|
||||
amount=monthly_credits,
|
||||
transaction_type='subscription',
|
||||
description=f"Monthly credit replenishment - {plan.name} plan",
|
||||
metadata={
|
||||
'plan_id': plan.id,
|
||||
'plan_name': plan.name,
|
||||
'monthly_credits': monthly_credits,
|
||||
'replenishment_date': timezone.now().isoformat()
|
||||
}
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Account {account.id} ({account.name}): "
|
||||
f"Added {monthly_credits} credits (balance: {new_balance})"
|
||||
)
|
||||
replenished += 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Account {account.id} ({account.name}): "
|
||||
f"Failed to replenish credits: {str(e)}",
|
||||
exc_info=True
|
||||
)
|
||||
errors += 1
|
||||
|
||||
logger.info("=" * 80)
|
||||
logger.info("MONTHLY CREDIT REPLENISHMENT TASK COMPLETED")
|
||||
logger.info(f"Total accounts: {total_accounts}")
|
||||
logger.info(f"Replenished: {replenished}")
|
||||
logger.info(f"Skipped: {skipped}")
|
||||
logger.info(f"Errors: {errors}")
|
||||
logger.info("=" * 80)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'total_accounts': total_accounts,
|
||||
'replenished': replenished,
|
||||
'skipped': skipped,
|
||||
'errors': errors
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ class CreditBalanceViewSet(viewsets.ViewSet):
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get plan credits per month
|
||||
plan_credits_per_month = account.plan.credits_per_month if account.plan else 0
|
||||
# Get plan credits per month (use get_effective_credits_per_month for Phase 0 compatibility)
|
||||
plan_credits_per_month = account.plan.get_effective_credits_per_month() if account.plan else 0
|
||||
|
||||
# Calculate credits used this month
|
||||
now = timezone.now()
|
||||
@@ -207,7 +207,10 @@ class CreditUsageViewSet(AccountModelViewSet):
|
||||
|
||||
@action(detail=False, methods=['get'], url_path='limits', url_name='limits')
|
||||
def limits(self, request):
|
||||
"""Get plan limits and current usage statistics"""
|
||||
"""
|
||||
Get account limits and credit usage statistics (Phase 0: Credit-only system).
|
||||
Returns account management limits and credit usage only.
|
||||
"""
|
||||
# Try multiple ways to get account
|
||||
account = getattr(request, 'account', None)
|
||||
|
||||
@@ -225,13 +228,7 @@ class CreditUsageViewSet(AccountModelViewSet):
|
||||
except (AttributeError, UserModel.DoesNotExist, Exception) as e:
|
||||
account = None
|
||||
|
||||
# Debug logging
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.info(f'Limits endpoint - User: {getattr(request, "user", None)}, Account: {account}, Account has plan: {account.plan if account else False}')
|
||||
|
||||
if not account:
|
||||
logger.warning(f'No account found in limits endpoint')
|
||||
# Return empty limits instead of error - frontend will show "no data" message
|
||||
return success_response(data={'limits': []}, request=request)
|
||||
|
||||
@@ -241,115 +238,16 @@ class CreditUsageViewSet(AccountModelViewSet):
|
||||
return success_response(data={'limits': []}, request=request)
|
||||
|
||||
# Import models
|
||||
from igny8_core.modules.planner.models import Keywords, Clusters, ContentIdeas
|
||||
from igny8_core.modules.writer.models import Tasks, Images
|
||||
from igny8_core.auth.models import User, Site
|
||||
|
||||
# Get current month boundaries
|
||||
now = timezone.now()
|
||||
start_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
start_of_day = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
# Calculate usage statistics
|
||||
limits_data = []
|
||||
|
||||
# Planner Limits
|
||||
keywords_count = Keywords.objects.filter(account=account).count()
|
||||
clusters_count = Clusters.objects.filter(account=account).count()
|
||||
content_ideas_count = ContentIdeas.objects.filter(account=account).count()
|
||||
clusters_today = Clusters.objects.filter(account=account, created_at__gte=start_of_day).count()
|
||||
|
||||
limits_data.extend([
|
||||
{
|
||||
'title': 'Keywords',
|
||||
'limit': plan.max_keywords or 0,
|
||||
'used': keywords_count,
|
||||
'available': max(0, (plan.max_keywords or 0) - keywords_count),
|
||||
'unit': 'keywords',
|
||||
'category': 'planner',
|
||||
'percentage': (keywords_count / (plan.max_keywords or 1)) * 100 if plan.max_keywords else 0
|
||||
},
|
||||
{
|
||||
'title': 'Clusters',
|
||||
'limit': plan.max_clusters or 0,
|
||||
'used': clusters_count,
|
||||
'available': max(0, (plan.max_clusters or 0) - clusters_count),
|
||||
'unit': 'clusters',
|
||||
'category': 'planner',
|
||||
'percentage': (clusters_count / (plan.max_clusters or 1)) * 100 if plan.max_clusters else 0
|
||||
},
|
||||
{
|
||||
'title': 'Content Ideas',
|
||||
'limit': plan.max_content_ideas or 0,
|
||||
'used': content_ideas_count,
|
||||
'available': max(0, (plan.max_content_ideas or 0) - content_ideas_count),
|
||||
'unit': 'ideas',
|
||||
'category': 'planner',
|
||||
'percentage': (content_ideas_count / (plan.max_content_ideas or 1)) * 100 if plan.max_content_ideas else 0
|
||||
},
|
||||
{
|
||||
'title': 'Daily Cluster Limit',
|
||||
'limit': plan.daily_cluster_limit or 0,
|
||||
'used': clusters_today,
|
||||
'available': max(0, (plan.daily_cluster_limit or 0) - clusters_today),
|
||||
'unit': 'per day',
|
||||
'category': 'planner',
|
||||
'percentage': (clusters_today / (plan.daily_cluster_limit or 1)) * 100 if plan.daily_cluster_limit else 0
|
||||
},
|
||||
])
|
||||
|
||||
# Writer Limits
|
||||
tasks_today = Tasks.objects.filter(account=account, created_at__gte=start_of_day).count()
|
||||
tasks_month = Tasks.objects.filter(account=account, created_at__gte=start_of_month)
|
||||
word_count_month = tasks_month.aggregate(total=Sum('word_count'))['total'] or 0
|
||||
|
||||
limits_data.extend([
|
||||
{
|
||||
'title': 'Monthly Word Count',
|
||||
'limit': plan.monthly_word_count_limit or 0,
|
||||
'used': word_count_month,
|
||||
'available': max(0, (plan.monthly_word_count_limit or 0) - word_count_month),
|
||||
'unit': 'words',
|
||||
'category': 'writer',
|
||||
'percentage': (word_count_month / (plan.monthly_word_count_limit or 1)) * 100 if plan.monthly_word_count_limit else 0
|
||||
},
|
||||
{
|
||||
'title': 'Daily Content Tasks',
|
||||
'limit': plan.daily_content_tasks or 0,
|
||||
'used': tasks_today,
|
||||
'available': max(0, (plan.daily_content_tasks or 0) - tasks_today),
|
||||
'unit': 'per day',
|
||||
'category': 'writer',
|
||||
'percentage': (tasks_today / (plan.daily_content_tasks or 1)) * 100 if plan.daily_content_tasks else 0
|
||||
},
|
||||
])
|
||||
|
||||
# Image Limits
|
||||
images_month = Images.objects.filter(account=account, created_at__gte=start_of_month).count()
|
||||
images_today = Images.objects.filter(account=account, created_at__gte=start_of_day).count()
|
||||
|
||||
limits_data.extend([
|
||||
{
|
||||
'title': 'Monthly Images',
|
||||
'limit': plan.monthly_image_count or 0,
|
||||
'used': images_month,
|
||||
'available': max(0, (plan.monthly_image_count or 0) - images_month),
|
||||
'unit': 'images',
|
||||
'category': 'images',
|
||||
'percentage': (images_month / (plan.monthly_image_count or 1)) * 100 if plan.monthly_image_count else 0
|
||||
},
|
||||
{
|
||||
'title': 'Daily Image Generation',
|
||||
'limit': plan.daily_image_generation_limit or 0,
|
||||
'used': images_today,
|
||||
'available': max(0, (plan.daily_image_generation_limit or 0) - images_today),
|
||||
'unit': 'per day',
|
||||
'category': 'images',
|
||||
'percentage': (images_today / (plan.daily_image_generation_limit or 1)) * 100 if plan.daily_image_generation_limit else 0
|
||||
},
|
||||
])
|
||||
|
||||
# AI Credits
|
||||
# Credit Usage (Phase 0: Credit-only system)
|
||||
credits_used_month = CreditUsageLog.objects.filter(
|
||||
account=account,
|
||||
created_at__gte=start_of_month
|
||||
@@ -358,64 +256,89 @@ class CreditUsageViewSet(AccountModelViewSet):
|
||||
# Get credits by operation type
|
||||
cluster_credits = CreditUsageLog.objects.filter(
|
||||
account=account,
|
||||
operation_type='clustering',
|
||||
operation_type__in=['clustering'],
|
||||
created_at__gte=start_of_month
|
||||
).aggregate(total=Sum('credits_used'))['total'] or 0
|
||||
|
||||
content_credits = CreditUsageLog.objects.filter(
|
||||
account=account,
|
||||
operation_type='content',
|
||||
operation_type__in=['content', 'content_generation'],
|
||||
created_at__gte=start_of_month
|
||||
).aggregate(total=Sum('credits_used'))['total'] or 0
|
||||
|
||||
image_credits = CreditUsageLog.objects.filter(
|
||||
account=account,
|
||||
operation_type='image',
|
||||
operation_type__in=['images', 'image_generation', 'image_prompt_extraction'],
|
||||
created_at__gte=start_of_month
|
||||
).aggregate(total=Sum('credits_used'))['total'] or 0
|
||||
|
||||
plan_credits = plan.monthly_ai_credit_limit or plan.credits_per_month or 0
|
||||
idea_credits = CreditUsageLog.objects.filter(
|
||||
account=account,
|
||||
operation_type__in=['ideas', 'idea_generation'],
|
||||
created_at__gte=start_of_month
|
||||
).aggregate(total=Sum('credits_used'))['total'] or 0
|
||||
|
||||
# Use included_credits from plan (Phase 0: Credit-only)
|
||||
plan_credits = plan.included_credits or plan.credits_per_month or 0
|
||||
|
||||
limits_data.extend([
|
||||
{
|
||||
'title': 'Monthly AI Credits',
|
||||
'title': 'Monthly Credits',
|
||||
'limit': plan_credits,
|
||||
'used': credits_used_month,
|
||||
'available': max(0, plan_credits - credits_used_month),
|
||||
'unit': 'credits',
|
||||
'category': 'ai',
|
||||
'category': 'credits',
|
||||
'percentage': (credits_used_month / plan_credits * 100) if plan_credits else 0
|
||||
},
|
||||
{
|
||||
'title': 'Content AI Credits',
|
||||
'limit': plan.monthly_content_ai_credits or 0,
|
||||
'used': content_credits,
|
||||
'available': max(0, (plan.monthly_content_ai_credits or 0) - content_credits),
|
||||
'title': 'Current Balance',
|
||||
'limit': None, # No limit - shows current balance
|
||||
'used': None,
|
||||
'available': account.credits,
|
||||
'unit': 'credits',
|
||||
'category': 'ai',
|
||||
'percentage': (content_credits / (plan.monthly_content_ai_credits or 1)) * 100 if plan.monthly_content_ai_credits else 0
|
||||
'category': 'credits',
|
||||
'percentage': None
|
||||
},
|
||||
{
|
||||
'title': 'Image AI Credits',
|
||||
'limit': plan.monthly_image_ai_credits or 0,
|
||||
'used': image_credits,
|
||||
'available': max(0, (plan.monthly_image_ai_credits or 0) - image_credits),
|
||||
'unit': 'credits',
|
||||
'category': 'ai',
|
||||
'percentage': (image_credits / (plan.monthly_image_ai_credits or 1)) * 100 if plan.monthly_image_ai_credits else 0
|
||||
},
|
||||
{
|
||||
'title': 'Cluster AI Credits',
|
||||
'limit': plan.monthly_cluster_ai_credits or 0,
|
||||
'title': 'Clustering Credits',
|
||||
'limit': None,
|
||||
'used': cluster_credits,
|
||||
'available': max(0, (plan.monthly_cluster_ai_credits or 0) - cluster_credits),
|
||||
'available': None,
|
||||
'unit': 'credits',
|
||||
'category': 'ai',
|
||||
'percentage': (cluster_credits / (plan.monthly_cluster_ai_credits or 1)) * 100 if plan.monthly_cluster_ai_credits else 0
|
||||
'category': 'credits',
|
||||
'percentage': None
|
||||
},
|
||||
{
|
||||
'title': 'Content Generation Credits',
|
||||
'limit': None,
|
||||
'used': content_credits,
|
||||
'available': None,
|
||||
'unit': 'credits',
|
||||
'category': 'credits',
|
||||
'percentage': None
|
||||
},
|
||||
{
|
||||
'title': 'Image Generation Credits',
|
||||
'limit': None,
|
||||
'used': image_credits,
|
||||
'available': None,
|
||||
'unit': 'credits',
|
||||
'category': 'credits',
|
||||
'percentage': None
|
||||
},
|
||||
{
|
||||
'title': 'Idea Generation Credits',
|
||||
'limit': None,
|
||||
'used': idea_credits,
|
||||
'available': None,
|
||||
'unit': 'credits',
|
||||
'category': 'credits',
|
||||
'percentage': None
|
||||
},
|
||||
])
|
||||
|
||||
# General Limits
|
||||
# Account Management Limits (kept - not operation limits)
|
||||
users_count = User.objects.filter(account=account).count()
|
||||
sites_count = Site.objects.filter(account=account).count()
|
||||
|
||||
@@ -426,7 +349,7 @@ class CreditUsageViewSet(AccountModelViewSet):
|
||||
'used': users_count,
|
||||
'available': max(0, (plan.max_users or 0) - users_count),
|
||||
'unit': 'users',
|
||||
'category': 'general',
|
||||
'category': 'account',
|
||||
'percentage': (users_count / (plan.max_users or 1)) * 100 if plan.max_users else 0
|
||||
},
|
||||
{
|
||||
@@ -435,7 +358,7 @@ class CreditUsageViewSet(AccountModelViewSet):
|
||||
'used': sites_count,
|
||||
'available': max(0, (plan.max_sites or 0) - sites_count),
|
||||
'unit': 'sites',
|
||||
'category': 'general',
|
||||
'category': 'account',
|
||||
'percentage': (sites_count / (plan.max_sites or 1)) * 100 if plan.max_sites else 0
|
||||
},
|
||||
])
|
||||
|
||||
@@ -1,37 +1,39 @@
|
||||
# Generated manually for Phase 0: Module Enable Settings
|
||||
# Using RunSQL to create table directly to avoid model resolution issues with new unified API model
|
||||
|
||||
from django.db import migrations, models
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('igny8_core_modules_system', '0006_alter_systemstatus_unique_together_and_more'),
|
||||
('system', '0006_alter_systemstatus_unique_together_and_more'),
|
||||
('igny8_core_auth', '0008_passwordresettoken_alter_industry_options_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ModuleEnableSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('planner_enabled', models.BooleanField(default=True, help_text='Enable Planner module')),
|
||||
('writer_enabled', models.BooleanField(default=True, help_text='Enable Writer module')),
|
||||
('thinker_enabled', models.BooleanField(default=True, help_text='Enable Thinker module')),
|
||||
('automation_enabled', models.BooleanField(default=True, help_text='Enable Automation module')),
|
||||
('site_builder_enabled', models.BooleanField(default=True, help_text='Enable Site Builder module')),
|
||||
('linker_enabled', models.BooleanField(default=True, help_text='Enable Linker module')),
|
||||
('optimizer_enabled', models.BooleanField(default=True, help_text='Enable Optimizer module')),
|
||||
('publisher_enabled', models.BooleanField(default=True, help_text='Enable Publisher module')),
|
||||
('account', models.ForeignKey(on_delete=models.CASCADE, to='igny8_core_auth.account', db_column='tenant_id')),
|
||||
],
|
||||
options={
|
||||
'db_table': 'igny8_module_enable_settings',
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='moduleenablesettings',
|
||||
constraint=models.UniqueConstraint(fields=('account',), name='unique_account_module_enable_settings'),
|
||||
# Create table using raw SQL to avoid model resolution issues
|
||||
# The model state is automatically discovered from models.py
|
||||
migrations.RunSQL(
|
||||
sql="""
|
||||
CREATE TABLE IF NOT EXISTS igny8_module_enable_settings (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
planner_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
writer_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
thinker_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
automation_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
site_builder_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
linker_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
optimizer_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
publisher_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
tenant_id BIGINT NOT NULL REFERENCES igny8_tenants(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS igny8_module_enable_settings_tenant_id_idx ON igny8_module_enable_settings(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS igny8_module_enable_settings_account_created_idx ON igny8_module_enable_settings(tenant_id, created_at);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS unique_account_module_enable_settings ON igny8_module_enable_settings(tenant_id);
|
||||
""",
|
||||
reverse_sql="DROP TABLE IF EXISTS igny8_module_enable_settings CASCADE;",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@@ -235,6 +235,15 @@ class ModuleSettingsViewSet(AccountModelViewSet):
|
||||
|
||||
def retrieve(self, request, pk=None):
|
||||
"""Get setting by key (pk can be key string)"""
|
||||
# Special case: if pk is "enable", this is likely a routing conflict
|
||||
# The correct endpoint is /settings/modules/enable/ which should go to ModuleEnableSettingsViewSet
|
||||
if pk == 'enable':
|
||||
return error_response(
|
||||
error='Use /api/v1/system/settings/modules/enable/ endpoint for module enable settings',
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
request=request
|
||||
)
|
||||
|
||||
queryset = self.get_queryset()
|
||||
try:
|
||||
# Try to get by ID first
|
||||
@@ -287,58 +296,124 @@ class ModuleEnableSettingsViewSet(AccountModelViewSet):
|
||||
ViewSet for managing module enable/disable settings
|
||||
Unified API Standard v1.0 compliant
|
||||
One record per account
|
||||
Read access: All authenticated users
|
||||
Write access: Admins/Owners only
|
||||
"""
|
||||
queryset = ModuleEnableSettings.objects.all()
|
||||
serializer_class = ModuleEnableSettingsSerializer
|
||||
permission_classes = [IsAuthenticatedAndActive, HasTenantAccess, IsAdminOrOwner]
|
||||
authentication_classes = [JWTAuthentication, CSRFExemptSessionAuthentication]
|
||||
throttle_scope = 'system'
|
||||
throttle_classes = [DebugScopedRateThrottle]
|
||||
|
||||
def get_permissions(self):
|
||||
"""
|
||||
Allow read access to all authenticated users,
|
||||
but restrict write access to admins/owners
|
||||
"""
|
||||
if self.action in ['list', 'retrieve', 'get_current']:
|
||||
permission_classes = [IsAuthenticatedAndActive, HasTenantAccess]
|
||||
else:
|
||||
permission_classes = [IsAuthenticatedAndActive, HasTenantAccess, IsAdminOrOwner]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
def get_queryset(self):
|
||||
"""Get module enable settings for current account"""
|
||||
# Return queryset filtered by account - but list() will handle get_or_create
|
||||
queryset = super().get_queryset()
|
||||
# Filter by account if available
|
||||
account = getattr(self.request, 'account', None)
|
||||
if not account:
|
||||
user = getattr(self.request, 'user', None)
|
||||
if user:
|
||||
account = getattr(user, 'account', None)
|
||||
if account:
|
||||
queryset = queryset.filter(account=account)
|
||||
return queryset
|
||||
|
||||
def list(self, request):
|
||||
"""Get or create module enable settings for current account"""
|
||||
account = getattr(request, 'account', None)
|
||||
if not account:
|
||||
user = getattr(request, 'user', None)
|
||||
if user:
|
||||
account = getattr(user, 'account', None)
|
||||
|
||||
if not account:
|
||||
return error_response(
|
||||
error='Account not found',
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get or create settings for account
|
||||
settings = ModuleEnableSettings.get_or_create_for_account(account)
|
||||
serializer = self.get_serializer(settings)
|
||||
return success_response(data=serializer.data, request=request)
|
||||
@action(detail=False, methods=['get', 'put'], url_path='current', url_name='current')
|
||||
def get_current(self, request):
|
||||
"""Get or update current account's module enable settings"""
|
||||
if request.method == 'GET':
|
||||
return self.list(request)
|
||||
else:
|
||||
return self.update(request, pk=None)
|
||||
|
||||
def retrieve(self, request, pk=None):
|
||||
"""Get module enable settings for current account"""
|
||||
account = getattr(request, 'account', None)
|
||||
if not account:
|
||||
user = getattr(request, 'user', None)
|
||||
if user:
|
||||
account = getattr(user, 'account', None)
|
||||
|
||||
if not account:
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Get or create module enable settings for current account"""
|
||||
try:
|
||||
account = getattr(request, 'account', None)
|
||||
if not account:
|
||||
user = getattr(request, 'user', None)
|
||||
if user and hasattr(user, 'account'):
|
||||
account = user.account
|
||||
|
||||
if not account:
|
||||
return error_response(
|
||||
error='Account not found',
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
request=request
|
||||
)
|
||||
|
||||
# Check if table exists (migration might not have been run)
|
||||
try:
|
||||
# Get or create settings for account (one per account)
|
||||
try:
|
||||
settings = ModuleEnableSettings.objects.get(account=account)
|
||||
except ModuleEnableSettings.DoesNotExist:
|
||||
# Create default settings for account
|
||||
settings = ModuleEnableSettings.objects.create(account=account)
|
||||
|
||||
serializer = self.get_serializer(settings)
|
||||
return success_response(data=serializer.data, request=request)
|
||||
except Exception as db_error:
|
||||
# Check if it's a "table does not exist" error
|
||||
error_str = str(db_error)
|
||||
if 'does not exist' in error_str.lower() or 'relation' in error_str.lower():
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.error(f"ModuleEnableSettings table does not exist. Migration 0007_add_module_enable_settings needs to be run: {error_str}")
|
||||
return error_response(
|
||||
error='Module enable settings table not found. Please run migration: python manage.py migrate igny8_core_modules_system 0007',
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
request=request
|
||||
)
|
||||
# Re-raise other database errors
|
||||
raise
|
||||
except Exception as e:
|
||||
import traceback
|
||||
error_trace = traceback.format_exc()
|
||||
return error_response(
|
||||
error='Account not found',
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
error=f'Failed to load module enable settings: {str(e)}',
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
request=request
|
||||
)
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
"""Get module enable settings for current account"""
|
||||
try:
|
||||
account = getattr(request, 'account', None)
|
||||
if not account:
|
||||
user = getattr(request, 'user', None)
|
||||
if user:
|
||||
account = getattr(user, 'account', None)
|
||||
|
||||
if not account:
|
||||
return error_response(
|
||||
error='Account not found',
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get or create settings for account
|
||||
settings, created = ModuleEnableSettings.objects.get_or_create(account=account)
|
||||
serializer = self.get_serializer(settings)
|
||||
return success_response(data=serializer.data, request=request)
|
||||
except Exception as e:
|
||||
return error_response(
|
||||
error=f'Failed to load module enable settings: {str(e)}',
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get or create settings for account
|
||||
settings = ModuleEnableSettings.get_or_create_for_account(account)
|
||||
serializer = self.get_serializer(settings)
|
||||
return success_response(data=serializer.data, request=request)
|
||||
|
||||
def update(self, request, pk=None):
|
||||
"""Update module enable settings for current account"""
|
||||
|
||||
@@ -16,8 +16,8 @@ router.register(r'strategies', StrategyViewSet, basename='strategy')
|
||||
router.register(r'settings/system', SystemSettingsViewSet, basename='system-settings')
|
||||
router.register(r'settings/account', AccountSettingsViewSet, basename='account-settings')
|
||||
router.register(r'settings/user', UserSettingsViewSet, basename='user-settings')
|
||||
# Register ModuleSettingsViewSet first
|
||||
router.register(r'settings/modules', ModuleSettingsViewSet, basename='module-settings')
|
||||
router.register(r'settings/modules/enable', ModuleEnableSettingsViewSet, basename='module-enable-settings')
|
||||
router.register(r'settings/ai', AISettingsViewSet, basename='ai-settings')
|
||||
|
||||
# Custom URL patterns for integration settings - matching reference plugin structure
|
||||
@@ -50,7 +50,20 @@ integration_image_gen_settings_viewset = IntegrationSettingsViewSet.as_view({
|
||||
'get': 'get_image_generation_settings',
|
||||
})
|
||||
|
||||
# Custom view for module enable settings to avoid URL routing conflict with ModuleSettingsViewSet
|
||||
# This must be defined as a custom path BEFORE router.urls to ensure it matches first
|
||||
# The update method handles pk=None correctly, so we can use as_view
|
||||
module_enable_viewset = ModuleEnableSettingsViewSet.as_view({
|
||||
'get': 'list',
|
||||
'put': 'update',
|
||||
'patch': 'partial_update',
|
||||
})
|
||||
|
||||
urlpatterns = [
|
||||
# Module enable settings endpoint - MUST come before router.urls to avoid conflict
|
||||
# When /settings/modules/enable/ is called, it would match ModuleSettingsViewSet with pk='enable'
|
||||
# So we define it as a custom path first
|
||||
path('settings/modules/enable/', module_enable_viewset, name='module-enable-settings'),
|
||||
path('', include(router.urls)),
|
||||
# Public health check endpoint (API Standard v1.0 requirement)
|
||||
path('ping/', ping, name='system-ping'),
|
||||
|
||||
@@ -411,9 +411,9 @@ frontend/
|
||||
<Route path="/reference/seed-keywords" element={<SeedKeywords />} />
|
||||
<Route path="/reference/industries" element={<ReferenceIndustries />} />
|
||||
|
||||
{/* Automation & Schedules */}
|
||||
{/* Automation */}
|
||||
<Route path="/automation" element={<AutomationDashboard />} />
|
||||
<Route path="/schedules" element={<Schedules />} />
|
||||
{/* Note: Schedules functionality is integrated into Automation Dashboard */}
|
||||
|
||||
{/* Settings */}
|
||||
<Route path="/settings" element={<GeneralSettings />} />
|
||||
|
||||
@@ -644,9 +644,12 @@ class KeywordViewSet(SiteSectorModelViewSet):
|
||||
"data": {
|
||||
"user": { ... },
|
||||
"access": "eyJ0eXAiOiJKV1QiLCJhbGc...",
|
||||
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGc..."
|
||||
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGc...",
|
||||
"access_expires_at": "2025-01-XXT...",
|
||||
"refresh_expires_at": "2025-01-XXT..."
|
||||
},
|
||||
"message": "Login successful"
|
||||
"message": "Login successful",
|
||||
"request_id": "550e8400-e29b-41d4-a716-446655440000"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -278,11 +278,10 @@ frontend/src/
|
||||
│ ├── Billing/ # Existing
|
||||
│ ├── Settings/ # Existing
|
||||
│ ├── Automation/ # EXISTING (placeholder) - IMPLEMENT
|
||||
│ │ ├── Dashboard.tsx # Automation overview
|
||||
│ │ ├── Dashboard.tsx # Automation overview (includes schedules functionality)
|
||||
│ │ ├── Rules.tsx # Automation rules management
|
||||
│ │ ├── Workflows.tsx # Workflow templates
|
||||
│ │ └── History.tsx # Automation execution history
|
||||
│ ├── Schedules.tsx # EXISTING (placeholder) - IMPLEMENT
|
||||
│ ├── Linker/ # NEW
|
||||
│ │ ├── Dashboard.tsx
|
||||
│ │ ├── Candidates.tsx
|
||||
@@ -653,7 +652,7 @@ docker-data/
|
||||
| **Implement Automation Service** | `domain/automation/services/` | TODO | HIGH |
|
||||
| **Implement Automation API** | `modules/automation/` | TODO | HIGH |
|
||||
| **Implement Automation UI** | `frontend/src/pages/Automation/` | TODO | HIGH |
|
||||
| **Implement Schedules UI** | `frontend/src/pages/Schedules.tsx` | TODO | HIGH |
|
||||
| **Note**: Schedules functionality will be integrated into Automation UI, not as a separate page | - | - | - |
|
||||
|
||||
### 9.2 Phase 1: Site Builder
|
||||
|
||||
|
||||
@@ -234,7 +234,7 @@ CREDIT_COSTS = {
|
||||
|------|-------|--------------|
|
||||
| **Automation Dashboard** | `frontend/src/pages/Automation/Dashboard.tsx` | EXISTING (placeholder) |
|
||||
| **Rules Management** | `frontend/src/pages/Automation/Rules.tsx` | NEW |
|
||||
| **Schedules Page** | `frontend/src/pages/Schedules.tsx` | EXISTING (placeholder) |
|
||||
| **Schedules (within Automation)** | Integrated into Automation Dashboard | Part of automation menu |
|
||||
| **Automation API Client** | `frontend/src/services/automation.api.ts` | NEW |
|
||||
|
||||
### 2.6 Testing
|
||||
|
||||
@@ -462,13 +462,11 @@ urlpatterns = router.urls
|
||||
- Test rule
|
||||
- Manual execution
|
||||
|
||||
#### Schedules Page
|
||||
#### Schedules (Part of Automation Menu)
|
||||
|
||||
| Task | File | Dependencies | Implementation |
|
||||
|------|------|--------------|----------------|
|
||||
| **Schedules Page** | `frontend/src/pages/Schedules.tsx` | EXISTING (placeholder) | View scheduled task history |
|
||||
**Note**: Schedules functionality will be integrated into the Automation menu group, not as a separate page.
|
||||
|
||||
**Schedules Page Features**:
|
||||
**Schedules Features** (within Automation Dashboard):
|
||||
- List scheduled tasks
|
||||
- Filter by status, rule, date
|
||||
- View execution results
|
||||
@@ -553,11 +551,11 @@ export const automationApi = {
|
||||
|
||||
- [ ] Implement `frontend/src/pages/Automation/Dashboard.tsx`
|
||||
- [ ] Create `frontend/src/pages/Automation/Rules.tsx`
|
||||
- [ ] Implement `frontend/src/pages/Schedules.tsx`
|
||||
- [ ] Integrate schedules functionality into Automation Dashboard (not as separate page)
|
||||
- [ ] Create `frontend/src/services/automation.api.ts`
|
||||
- [ ] Create rule creation wizard
|
||||
- [ ] Create rule editor
|
||||
- [ ] Create schedule history table
|
||||
- [ ] Create schedule history table (within Automation Dashboard)
|
||||
|
||||
### Testing Tasks
|
||||
|
||||
|
||||
@@ -50,7 +50,6 @@ const SeedKeywords = lazy(() => import("./pages/Reference/SeedKeywords"));
|
||||
const ReferenceIndustries = lazy(() => import("./pages/Reference/Industries"));
|
||||
|
||||
// Other Pages - Lazy loaded
|
||||
const Schedules = lazy(() => import("./pages/Schedules"));
|
||||
const AutomationDashboard = lazy(() => import("./pages/Automation/Dashboard"));
|
||||
|
||||
// Settings - Lazy loaded
|
||||
@@ -294,11 +293,6 @@ export default function App() {
|
||||
</ModuleGuard>
|
||||
</Suspense>
|
||||
} />
|
||||
<Route path="/schedules" element={
|
||||
<Suspense fallback={null}>
|
||||
<Schedules />
|
||||
</Suspense>
|
||||
} />
|
||||
|
||||
{/* Settings */}
|
||||
<Route path="/settings" element={
|
||||
|
||||
@@ -21,7 +21,6 @@ import { useAuthStore } from "../../store/authStore";
|
||||
* - /settings (including /settings/sites)
|
||||
* - /dashboard
|
||||
* - /analytics
|
||||
* - /schedules
|
||||
* - /thinker
|
||||
* - /signin, /signup
|
||||
*/
|
||||
@@ -37,7 +36,6 @@ const SITE_SWITCHER_HIDDEN_PATHS = [
|
||||
'/settings',
|
||||
'/dashboard',
|
||||
'/analytics',
|
||||
'/schedules',
|
||||
'/thinker',
|
||||
];
|
||||
|
||||
|
||||
@@ -51,11 +51,6 @@ export const routes: RouteConfig[] = [
|
||||
{ path: '/thinker/profile', label: 'Profile', breadcrumb: 'Profile' },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/schedules',
|
||||
label: 'Schedules',
|
||||
icon: 'Schedules',
|
||||
},
|
||||
];
|
||||
|
||||
export const getBreadcrumbs = (pathname: string): Array<{ label: string; path: string }> => {
|
||||
|
||||
@@ -24,36 +24,63 @@ const LayoutContent: React.FC = () => {
|
||||
const [debugEnabled, setDebugEnabled] = useState(false);
|
||||
const lastUserRefresh = useRef<number>(0);
|
||||
|
||||
// Initialize site store on mount - only once
|
||||
// Initialize site store on mount - only once, but only if authenticated
|
||||
useEffect(() => {
|
||||
if (!hasLoadedSite.current && !isLoadingSite.current) {
|
||||
hasLoadedSite.current = true;
|
||||
isLoadingSite.current = true;
|
||||
trackLoading('site-loading', true);
|
||||
// Only load sites if user is authenticated AND has a token
|
||||
if (!isAuthenticated) return;
|
||||
|
||||
// Check if token exists - if not, wait a bit for Zustand persist to write it
|
||||
const checkTokenAndLoad = () => {
|
||||
const authState = useAuthStore.getState();
|
||||
if (!authState?.token) {
|
||||
// Token not available yet - wait a bit and retry (Zustand persist might still be writing)
|
||||
setTimeout(() => {
|
||||
const retryAuthState = useAuthStore.getState();
|
||||
if (retryAuthState?.token && !hasLoadedSite.current && !isLoadingSite.current) {
|
||||
loadSites();
|
||||
}
|
||||
}, 100); // Wait 100ms for persist to write
|
||||
return;
|
||||
}
|
||||
|
||||
// Add timeout to prevent infinite loading
|
||||
// Match API timeout (30s) + buffer for network delays
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (isLoadingSite.current) {
|
||||
console.error('AppLayout: Site loading timeout after 35 seconds');
|
||||
trackLoading('site-loading', false);
|
||||
isLoadingSite.current = false;
|
||||
addError(new Error('Site loading timeout - check network connection'), 'AppLayout.loadActiveSite');
|
||||
}
|
||||
}, 35000); // 35 seconds to match API timeout (30s) + buffer
|
||||
|
||||
loadActiveSite()
|
||||
.catch((error) => {
|
||||
console.error('AppLayout: Error loading active site:', error);
|
||||
addError(error, 'AppLayout.loadActiveSite');
|
||||
})
|
||||
.finally(() => {
|
||||
clearTimeout(timeoutId);
|
||||
trackLoading('site-loading', false);
|
||||
isLoadingSite.current = false;
|
||||
});
|
||||
}
|
||||
}, []); // Empty deps - only run once on mount
|
||||
loadSites();
|
||||
};
|
||||
|
||||
const loadSites = () => {
|
||||
if (!hasLoadedSite.current && !isLoadingSite.current) {
|
||||
hasLoadedSite.current = true;
|
||||
isLoadingSite.current = true;
|
||||
trackLoading('site-loading', true);
|
||||
|
||||
// Add timeout to prevent infinite loading
|
||||
// Match API timeout (30s) + buffer for network delays
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (isLoadingSite.current) {
|
||||
console.error('AppLayout: Site loading timeout after 35 seconds');
|
||||
trackLoading('site-loading', false);
|
||||
isLoadingSite.current = false;
|
||||
addError(new Error('Site loading timeout - check network connection'), 'AppLayout.loadActiveSite');
|
||||
}
|
||||
}, 35000); // 35 seconds to match API timeout (30s) + buffer
|
||||
|
||||
loadActiveSite()
|
||||
.catch((error) => {
|
||||
// Don't log 403 errors as they're expected when not authenticated
|
||||
if (error.status !== 403) {
|
||||
console.error('AppLayout: Error loading active site:', error);
|
||||
addError(error, 'AppLayout.loadActiveSite');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
clearTimeout(timeoutId);
|
||||
trackLoading('site-loading', false);
|
||||
isLoadingSite.current = false;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
checkTokenAndLoad();
|
||||
}, [isAuthenticated]); // Run when authentication state changes
|
||||
|
||||
// Load sectors when active site changes (by ID, not object reference)
|
||||
useEffect(() => {
|
||||
@@ -114,6 +141,19 @@ const LayoutContent: React.FC = () => {
|
||||
// Throttle: only refresh if last refresh was more than 30 seconds ago (unless forced)
|
||||
if (!force && now - lastUserRefresh.current < 30000) return;
|
||||
|
||||
// Check if token exists before making API call
|
||||
const authState = useAuthStore.getState();
|
||||
if (!authState?.token) {
|
||||
// Token not available yet - wait a bit for Zustand persist to write it
|
||||
setTimeout(() => {
|
||||
const retryAuthState = useAuthStore.getState();
|
||||
if (retryAuthState?.token && retryAuthState?.isAuthenticated) {
|
||||
refreshUserData(force);
|
||||
}
|
||||
}, 100); // Wait 100ms for persist to write
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
lastUserRefresh.current = now;
|
||||
await refreshUser();
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
PlugInIcon,
|
||||
TaskIcon,
|
||||
BoltIcon,
|
||||
TimeIcon,
|
||||
DocsIcon,
|
||||
PageIcon,
|
||||
DollarLineIcon,
|
||||
@@ -21,7 +20,6 @@ import SidebarWidget from "./SidebarWidget";
|
||||
import { APP_VERSION } from "../config/version";
|
||||
import { useAuthStore } from "../store/authStore";
|
||||
import { useSettingsStore } from "../store/settingsStore";
|
||||
import { isModuleEnabled } from "../config/modules.config";
|
||||
import ApiStatusIndicator from "../components/sidebar/ApiStatusIndicator";
|
||||
|
||||
type NavItem = {
|
||||
@@ -39,8 +37,8 @@ type MenuSection = {
|
||||
const AppSidebar: React.FC = () => {
|
||||
const { isExpanded, isMobileOpen, isHovered, setIsHovered } = useSidebar();
|
||||
const location = useLocation();
|
||||
const { user } = useAuthStore();
|
||||
const { moduleEnableSettings, isModuleEnabled: checkModuleEnabled } = useSettingsStore();
|
||||
const { user, isAuthenticated } = useAuthStore();
|
||||
const { moduleEnableSettings, isModuleEnabled: checkModuleEnabled, loadModuleEnableSettings, loading: settingsLoading } = useSettingsStore();
|
||||
|
||||
// Show admin menu only for users in aws-admin account
|
||||
const isAwsAdminAccount = Boolean(
|
||||
@@ -48,11 +46,11 @@ const AppSidebar: React.FC = () => {
|
||||
user?.role === 'developer' // Also show for developers as fallback
|
||||
);
|
||||
|
||||
// Helper to check if module is enabled
|
||||
const moduleEnabled = (moduleName: string): boolean => {
|
||||
// Helper to check if module is enabled - memoized to prevent infinite loops
|
||||
const moduleEnabled = useCallback((moduleName: string): boolean => {
|
||||
if (!moduleEnableSettings) return true; // Default to enabled if not loaded
|
||||
return checkModuleEnabled(moduleName);
|
||||
};
|
||||
}, [moduleEnableSettings, checkModuleEnabled]);
|
||||
|
||||
const [openSubmenu, setOpenSubmenu] = useState<{
|
||||
sectionIndex: number;
|
||||
@@ -68,6 +66,16 @@ const AppSidebar: React.FC = () => {
|
||||
[location.pathname]
|
||||
);
|
||||
|
||||
// Load module enable settings on mount (only once) - but only if user is authenticated
|
||||
useEffect(() => {
|
||||
// Only load if user is authenticated and settings aren't already loaded
|
||||
if (user && isAuthenticated && !moduleEnableSettings && !settingsLoading) {
|
||||
loadModuleEnableSettings().catch((error) => {
|
||||
console.warn('Failed to load module enable settings:', error);
|
||||
});
|
||||
}
|
||||
}, [user, isAuthenticated]); // Only run when user/auth state changes
|
||||
|
||||
// Define menu sections with useMemo to prevent recreation on every render
|
||||
// Filter out disabled modules based on module enable settings
|
||||
const menuSections: MenuSection[] = useMemo(() => {
|
||||
@@ -135,12 +143,6 @@ const AppSidebar: React.FC = () => {
|
||||
});
|
||||
}
|
||||
|
||||
workflowItems.push({
|
||||
icon: <TimeIcon />,
|
||||
name: "Schedules",
|
||||
path: "/schedules",
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
label: "OVERVIEW",
|
||||
@@ -196,7 +198,7 @@ const AppSidebar: React.FC = () => {
|
||||
],
|
||||
},
|
||||
];
|
||||
}, [moduleEnableSettings, moduleEnabled]);
|
||||
}, [moduleEnabled]);
|
||||
|
||||
// Admin section - only shown for users in aws-admin account
|
||||
const adminSection: MenuSection = useMemo(() => ({
|
||||
@@ -282,14 +284,6 @@ const AppSidebar: React.FC = () => {
|
||||
: menuSections;
|
||||
}, [isAwsAdminAccount, menuSections, adminSection]);
|
||||
|
||||
// Load module enable settings on mount
|
||||
useEffect(() => {
|
||||
const { loadModuleEnableSettings } = useSettingsStore.getState();
|
||||
if (!moduleEnableSettings) {
|
||||
loadModuleEnableSettings();
|
||||
}
|
||||
}, [moduleEnableSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
const currentPath = location.pathname;
|
||||
let foundMatch = false;
|
||||
@@ -305,9 +299,15 @@ const AppSidebar: React.FC = () => {
|
||||
});
|
||||
|
||||
if (shouldOpen) {
|
||||
setOpenSubmenu({
|
||||
sectionIndex,
|
||||
itemIndex,
|
||||
setOpenSubmenu((prev) => {
|
||||
// Only update if different to prevent infinite loops
|
||||
if (prev?.sectionIndex === sectionIndex && prev?.itemIndex === itemIndex) {
|
||||
return prev;
|
||||
}
|
||||
return {
|
||||
sectionIndex,
|
||||
itemIndex,
|
||||
};
|
||||
});
|
||||
foundMatch = true;
|
||||
}
|
||||
@@ -330,10 +330,16 @@ const AppSidebar: React.FC = () => {
|
||||
// scrollHeight should work even when height is 0px due to overflow-hidden
|
||||
const scrollHeight = element.scrollHeight;
|
||||
if (scrollHeight > 0) {
|
||||
setSubMenuHeight((prevHeights) => ({
|
||||
...prevHeights,
|
||||
[key]: scrollHeight,
|
||||
}));
|
||||
setSubMenuHeight((prevHeights) => {
|
||||
// Only update if height changed to prevent infinite loops
|
||||
if (prevHeights[key] === scrollHeight) {
|
||||
return prevHeights;
|
||||
}
|
||||
return {
|
||||
...prevHeights,
|
||||
[key]: scrollHeight,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
}, 50);
|
||||
|
||||
@@ -5,6 +5,19 @@ import { fetchCreditBalance, CreditBalance } from '../../services/api';
|
||||
import { Card } from '../../components/ui/card';
|
||||
import Badge from '../../components/ui/badge/Badge';
|
||||
|
||||
// Credit costs per operation (Phase 0: Credit-only system)
|
||||
const CREDIT_COSTS: Record<string, { cost: number | string; description: string }> = {
|
||||
clustering: { cost: 10, description: 'Per clustering request' },
|
||||
idea_generation: { cost: 15, description: 'Per cluster → ideas request' },
|
||||
content_generation: { cost: '1 per 100 words', description: 'Per 100 words generated' },
|
||||
image_prompt_extraction: { cost: 2, description: 'Per content piece' },
|
||||
image_generation: { cost: 5, description: 'Per image generated' },
|
||||
linking: { cost: 8, description: 'Per content piece' },
|
||||
optimization: { cost: '1 per 200 words', description: 'Per 200 words optimized' },
|
||||
site_structure_generation: { cost: 50, description: 'Per site blueprint' },
|
||||
site_page_generation: { cost: 20, description: 'Per page generated' },
|
||||
};
|
||||
|
||||
export default function Credits() {
|
||||
const toast = useToast();
|
||||
const [balance, setBalance] = useState<CreditBalance | null>(null);
|
||||
@@ -88,6 +101,35 @@ export default function Credits() {
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Credit Costs Reference */}
|
||||
<div className="mt-8">
|
||||
<Card className="p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Credit Costs per Operation</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
Understanding how credits are consumed for each operation type
|
||||
</p>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{Object.entries(CREDIT_COSTS).map(([operation, info]) => (
|
||||
<div key={operation} className="flex items-start justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="flex-1">
|
||||
<div className="font-medium text-gray-900 dark:text-white capitalize">
|
||||
{operation.replace(/_/g, ' ')}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
{info.description}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 text-right">
|
||||
<Badge variant="light" color="primary" className="font-semibold">
|
||||
{typeof info.cost === 'number' ? `${info.cost} credits` : info.cost}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,19 @@ import { fetchCreditUsage, CreditUsageLog, fetchUsageLimits, LimitCard } from '.
|
||||
import { Card } from '../../components/ui/card';
|
||||
import Badge from '../../components/ui/badge/Badge';
|
||||
|
||||
// Credit costs per operation (Phase 0: Credit-only system)
|
||||
const CREDIT_COSTS: Record<string, { cost: number | string; description: string }> = {
|
||||
clustering: { cost: 10, description: 'Per clustering request' },
|
||||
idea_generation: { cost: 15, description: 'Per cluster → ideas request' },
|
||||
content_generation: { cost: '1 per 100 words', description: 'Per 100 words generated' },
|
||||
image_prompt_extraction: { cost: 2, description: 'Per content piece' },
|
||||
image_generation: { cost: 5, description: 'Per image generated' },
|
||||
linking: { cost: 8, description: 'Per content piece' },
|
||||
optimization: { cost: '1 per 200 words', description: 'Per 200 words optimized' },
|
||||
site_structure_generation: { cost: 50, description: 'Per site blueprint' },
|
||||
site_page_generation: { cost: 20, description: 'Per page generated' },
|
||||
};
|
||||
|
||||
export default function Usage() {
|
||||
const toast = useToast();
|
||||
const [usageLogs, setUsageLogs] = useState<CreditUsageLog[]>([]);
|
||||
@@ -33,13 +46,8 @@ export default function Usage() {
|
||||
try {
|
||||
setLimitsLoading(true);
|
||||
const response = await fetchUsageLimits();
|
||||
console.log('Usage limits response:', response);
|
||||
setLimits(response.limits || []);
|
||||
if (!response.limits || response.limits.length === 0) {
|
||||
console.warn('No limits data received from API');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Error loading usage limits:', error);
|
||||
toast.error(`Failed to load usage limits: ${error.message}`);
|
||||
setLimits([]);
|
||||
} finally {
|
||||
@@ -47,120 +55,82 @@ export default function Usage() {
|
||||
}
|
||||
};
|
||||
|
||||
const groupedLimits = {
|
||||
planner: limits.filter(l => l.category === 'planner'),
|
||||
writer: limits.filter(l => l.category === 'writer'),
|
||||
images: limits.filter(l => l.category === 'images'),
|
||||
ai: limits.filter(l => l.category === 'ai'),
|
||||
general: limits.filter(l => l.category === 'general'),
|
||||
};
|
||||
|
||||
// Debug info
|
||||
console.log('[Usage Component] Render state:', {
|
||||
limitsLoading,
|
||||
limitsCount: limits.length,
|
||||
groupedLimits,
|
||||
plannerCount: groupedLimits.planner.length,
|
||||
writerCount: groupedLimits.writer.length,
|
||||
imagesCount: groupedLimits.images.length,
|
||||
aiCount: groupedLimits.ai.length,
|
||||
generalCount: groupedLimits.general.length,
|
||||
});
|
||||
// Filter limits to show only credits and account management (Phase 0: Credit-only system)
|
||||
const creditLimits = limits.filter(l => l.category === 'credits');
|
||||
const accountLimits = limits.filter(l => l.category === 'account');
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<PageMeta title="Usage" description="Monitor your plan limits and usage statistics" />
|
||||
<PageMeta title="Usage" description="Monitor your credit usage and account limits" />
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Acoount Limits Usage 12</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">Monitor your plan limits and usage statistics</p>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Credit Usage & Limits</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-1">Monitor your credit usage and account management limits</p>
|
||||
</div>
|
||||
|
||||
{/* Debug Info - Remove in production */}
|
||||
{import.meta.env.DEV && (
|
||||
<Card className="p-4 mb-4 bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800">
|
||||
<div className="text-xs text-gray-600 dark:text-gray-400">
|
||||
<strong>Debug:</strong> Loading={limitsLoading ? 'Yes' : 'No'}, Limits={limits.length},
|
||||
Planner={groupedLimits.planner.length}, Writer={groupedLimits.writer.length},
|
||||
Images={groupedLimits.images.length}, AI={groupedLimits.ai.length}, General={groupedLimits.general.length}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
{/* Credit Costs Reference */}
|
||||
<Card className="p-6 mb-6">
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Credit Costs per Operation</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{Object.entries(CREDIT_COSTS).map(([operation, info]) => (
|
||||
<div key={operation} className="flex items-start justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="flex-1">
|
||||
<div className="font-medium text-gray-900 dark:text-white capitalize">
|
||||
{operation.replace(/_/g, ' ')}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
{info.description}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 text-right">
|
||||
<Badge variant="light" color="primary" className="font-semibold">
|
||||
{typeof info.cost === 'number' ? `${info.cost} credits` : info.cost}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Limit Cards by Category */}
|
||||
{/* Credit Limits */}
|
||||
{limitsLoading ? (
|
||||
<Card className="p-6 mb-8">
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="text-gray-500">Loading limits...</div>
|
||||
</div>
|
||||
</Card>
|
||||
) : limits.length === 0 ? (
|
||||
<Card className="p-6 mb-8">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400">
|
||||
<p className="mb-2 font-medium">No usage limits data available.</p>
|
||||
<p className="text-sm">The API endpoint may not be responding or your account may not have a plan configured.</p>
|
||||
<p className="text-xs mt-2 text-gray-400">Check browser console for errors. Endpoint: /v1/billing/credits/usage/limits/</p>
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-6 mb-8">
|
||||
{/* Planner Limits */}
|
||||
{groupedLimits.planner.length > 0 && (
|
||||
{/* Credit Usage Limits */}
|
||||
{creditLimits.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Planner Limits</h2>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Credit Usage</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{groupedLimits.planner.map((limit, idx) => (
|
||||
{creditLimits.map((limit, idx) => (
|
||||
<LimitCardComponent key={idx} limit={limit} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Writer Limits */}
|
||||
{groupedLimits.writer.length > 0 && (
|
||||
{/* Account Management Limits */}
|
||||
{accountLimits.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Writer Limits</h2>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Account Management</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{groupedLimits.writer.map((limit, idx) => (
|
||||
{accountLimits.map((limit, idx) => (
|
||||
<LimitCardComponent key={idx} limit={limit} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Image Limits */}
|
||||
{groupedLimits.images.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Image Generation Limits</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{groupedLimits.images.map((limit, idx) => (
|
||||
<LimitCardComponent key={idx} limit={limit} />
|
||||
))}
|
||||
{creditLimits.length === 0 && accountLimits.length === 0 && (
|
||||
<Card className="p-6">
|
||||
<div className="text-center text-gray-500 dark:text-gray-400">
|
||||
<p className="mb-2 font-medium">No limits data available.</p>
|
||||
<p className="text-sm">Your account may not have a plan configured.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Credits */}
|
||||
{groupedLimits.ai.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">AI Credits</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{groupedLimits.ai.map((limit, idx) => (
|
||||
<LimitCardComponent key={idx} limit={limit} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* General Limits */}
|
||||
{groupedLimits.general.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">General Limits</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
{groupedLimits.general.map((limit, idx) => (
|
||||
<LimitCardComponent key={idx} limit={limit} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -219,22 +189,20 @@ export default function Usage() {
|
||||
function LimitCardComponent({ limit }: { limit: LimitCard }) {
|
||||
const getCategoryColor = (category: string) => {
|
||||
switch (category) {
|
||||
case 'planner': return 'blue';
|
||||
case 'writer': return 'green';
|
||||
case 'images': return 'purple';
|
||||
case 'ai': return 'orange';
|
||||
case 'general': return 'gray';
|
||||
case 'credits': return 'primary';
|
||||
case 'account': return 'gray';
|
||||
default: return 'gray';
|
||||
}
|
||||
};
|
||||
|
||||
const getUsageStatus = (percentage: number) => {
|
||||
const getUsageStatus = (percentage: number | null) => {
|
||||
if (percentage === null) return 'info';
|
||||
if (percentage >= 90) return 'danger';
|
||||
if (percentage >= 75) return 'warning';
|
||||
return 'success';
|
||||
};
|
||||
|
||||
const percentage = Math.min(limit.percentage, 100);
|
||||
const percentage = limit.percentage !== null && limit.percentage !== undefined ? Math.min(limit.percentage, 100) : null;
|
||||
const status = getUsageStatus(percentage);
|
||||
const color = getCategoryColor(limit.category);
|
||||
|
||||
@@ -242,12 +210,16 @@ function LimitCardComponent({ limit }: { limit: LimitCard }) {
|
||||
? 'bg-red-500'
|
||||
: status === 'warning'
|
||||
? 'bg-yellow-500'
|
||||
: status === 'info'
|
||||
? 'bg-blue-500'
|
||||
: 'bg-green-500';
|
||||
|
||||
const statusTextColor = status === 'danger'
|
||||
? 'text-red-600 dark:text-red-400'
|
||||
: status === 'warning'
|
||||
? 'text-yellow-600 dark:text-yellow-400'
|
||||
: status === 'info'
|
||||
? 'text-blue-600 dark:text-blue-400'
|
||||
: 'text-green-600 dark:text-green-400';
|
||||
|
||||
return (
|
||||
@@ -258,26 +230,44 @@ function LimitCardComponent({ limit }: { limit: LimitCard }) {
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-2xl font-bold text-gray-900 dark:text-white">{limit.used.toLocaleString()}</span>
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">/ {limit.limit.toLocaleString()}</span>
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">{limit.unit}</span>
|
||||
{limit.limit !== null && limit.limit !== undefined ? (
|
||||
<>
|
||||
<span className="text-2xl font-bold text-gray-900 dark:text-white">{limit.used.toLocaleString()}</span>
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">/ {limit.limit.toLocaleString()}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{limit.available !== null && limit.available !== undefined ? limit.available.toLocaleString() : limit.used.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
{limit.unit && (
|
||||
<span className="text-xs text-gray-400 dark:text-gray-500">{limit.unit}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
|
||||
<div
|
||||
className={`h-2 rounded-full ${statusColorClass}`}
|
||||
style={{ width: `${percentage}%` }}
|
||||
/>
|
||||
{percentage !== null && (
|
||||
<div className="mt-2">
|
||||
<div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
|
||||
<div
|
||||
className={`h-2 rounded-full ${statusColorClass}`}
|
||||
style={{ width: `${percentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className={statusTextColor}>
|
||||
{limit.available.toLocaleString()} available
|
||||
</span>
|
||||
<span className="text-gray-500 dark:text-gray-400">
|
||||
{percentage.toFixed(1)}% used
|
||||
</span>
|
||||
{limit.available !== null && limit.available !== undefined ? (
|
||||
<span className={statusTextColor}>
|
||||
{limit.available.toLocaleString()} available
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-500 dark:text-gray-400">Current value</span>
|
||||
)}
|
||||
{percentage !== null && (
|
||||
<span className="text-gray-500 dark:text-gray-400">
|
||||
{percentage.toFixed(1)}% used
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -76,7 +76,7 @@ export default function Help() {
|
||||
},
|
||||
{
|
||||
question: "How do I set up automation?",
|
||||
answer: "Go to Dashboard > Automation Setup section. Enable automation for each step (Keywords, Ideas, Content, Images) and configure settings like how many keywords to process per cycle. Advanced settings are available in Schedules page."
|
||||
answer: "Go to Dashboard > Automation Setup section. Enable automation for each step (Keywords, Ideas, Content, Images) and configure settings like how many keywords to process per cycle. Advanced scheduling settings are available in the Automation menu."
|
||||
},
|
||||
{
|
||||
question: "Can I edit AI-generated content?",
|
||||
@@ -539,7 +539,7 @@ export default function Help() {
|
||||
|
||||
<div className="mt-6 p-4 bg-brand-50 dark:bg-brand-900/10 rounded-lg border border-brand-200 dark:border-brand-800">
|
||||
<p className="text-sm text-brand-800 dark:text-brand-300">
|
||||
<strong>Note:</strong> Configure automation in Dashboard > Automation Setup. For advanced scheduling, go to Schedules page.
|
||||
<strong>Note:</strong> Configure automation in Dashboard > Automation Setup. For advanced scheduling, go to the Automation menu.
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -78,9 +78,16 @@ function getActiveSectorId(): number | null {
|
||||
}
|
||||
}
|
||||
|
||||
// Get auth token from store
|
||||
// Get auth token from store - try Zustand store first, then localStorage as fallback
|
||||
const getAuthToken = (): string | null => {
|
||||
try {
|
||||
// First try to get from Zustand store directly (faster, no parsing)
|
||||
const authState = useAuthStore.getState();
|
||||
if (authState?.token) {
|
||||
return authState.token;
|
||||
}
|
||||
|
||||
// Fallback to localStorage (for cases where store hasn't initialized yet)
|
||||
const authStorage = localStorage.getItem('auth-storage');
|
||||
if (authStorage) {
|
||||
const parsed = JSON.parse(authStorage);
|
||||
@@ -92,9 +99,16 @@ const getAuthToken = (): string | null => {
|
||||
return null;
|
||||
};
|
||||
|
||||
// Get refresh token from store
|
||||
// Get refresh token from store - try Zustand store first, then localStorage as fallback
|
||||
const getRefreshToken = (): string | null => {
|
||||
try {
|
||||
// First try to get from Zustand store directly (faster, no parsing)
|
||||
const authState = useAuthStore.getState();
|
||||
if (authState?.refreshToken) {
|
||||
return authState.refreshToken;
|
||||
}
|
||||
|
||||
// Fallback to localStorage (for cases where store hasn't initialized yet)
|
||||
const authStorage = localStorage.getItem('auth-storage');
|
||||
if (authStorage) {
|
||||
const parsed = JSON.parse(authStorage);
|
||||
@@ -148,9 +162,14 @@ export async function fetchAPI(endpoint: string, options?: RequestInit & { timeo
|
||||
if (errorData?.detail?.includes('Authentication credentials') ||
|
||||
errorData?.message?.includes('Authentication credentials') ||
|
||||
errorData?.error?.includes('Authentication credentials')) {
|
||||
// Token is invalid - clear auth state and force re-login
|
||||
const { logout } = useAuthStore.getState();
|
||||
logout();
|
||||
// Only logout if we actually have a token stored (means it's invalid)
|
||||
// If no token, it might be a race condition after login - don't logout
|
||||
const authState = useAuthStore.getState();
|
||||
if (authState?.token || authState?.isAuthenticated) {
|
||||
// Token exists but is invalid - clear auth state and force re-login
|
||||
const { logout } = useAuthStore.getState();
|
||||
logout();
|
||||
}
|
||||
// Don't throw here - let the error handling below show the error
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -175,13 +194,14 @@ export async function fetchAPI(endpoint: string, options?: RequestInit & { timeo
|
||||
|
||||
if (refreshResponse.ok) {
|
||||
const refreshData = await refreshResponse.json();
|
||||
if (refreshData.success && refreshData.access) {
|
||||
const accessToken = refreshData.data?.access || refreshData.access;
|
||||
if (refreshData.success && accessToken) {
|
||||
// Update token in store
|
||||
try {
|
||||
const authStorage = localStorage.getItem('auth-storage');
|
||||
if (authStorage) {
|
||||
const parsed = JSON.parse(authStorage);
|
||||
parsed.state.token = refreshData.access;
|
||||
parsed.state.token = accessToken;
|
||||
localStorage.setItem('auth-storage', JSON.stringify(parsed));
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -191,7 +211,7 @@ export async function fetchAPI(endpoint: string, options?: RequestInit & { timeo
|
||||
// Retry original request with new token
|
||||
const newHeaders = {
|
||||
...headers,
|
||||
'Authorization': `Bearer ${refreshData.access}`,
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
};
|
||||
|
||||
const retryResponse = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
|
||||
@@ -60,14 +60,17 @@ export const useAuthStore = create<AuthState>()(
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.message || 'Login failed');
|
||||
throw new Error(data.error || data.message || 'Login failed');
|
||||
}
|
||||
|
||||
// Store user and JWT tokens
|
||||
// Store user and JWT tokens (handle both old and new API formats)
|
||||
const responseData = data.data || data;
|
||||
// Support both formats: new (access/refresh at top level) and old (tokens.access/refresh)
|
||||
const tokens = responseData.tokens || {};
|
||||
set({
|
||||
user: data.user,
|
||||
token: data.tokens?.access || null,
|
||||
refreshToken: data.tokens?.refresh || null,
|
||||
user: responseData.user || data.user,
|
||||
token: responseData.access || tokens.access || data.access || null,
|
||||
refreshToken: responseData.refresh || tokens.refresh || data.refresh || null,
|
||||
isAuthenticated: true,
|
||||
loading: false
|
||||
});
|
||||
@@ -119,8 +122,8 @@ export const useAuthStore = create<AuthState>()(
|
||||
// Store user and JWT tokens
|
||||
set({
|
||||
user: data.user,
|
||||
token: data.tokens?.access || null,
|
||||
refreshToken: data.tokens?.refresh || null,
|
||||
token: data.data?.access || data.access || null,
|
||||
refreshToken: data.data?.refresh || data.refresh || null,
|
||||
isAuthenticated: true,
|
||||
loading: false
|
||||
});
|
||||
@@ -168,8 +171,8 @@ export const useAuthStore = create<AuthState>()(
|
||||
throw new Error(data.message || 'Token refresh failed');
|
||||
}
|
||||
|
||||
// Update access token
|
||||
set({ token: data.access });
|
||||
// Update access token (API returns access at top level of data)
|
||||
set({ token: data.data?.access || data.access });
|
||||
|
||||
// Also refresh user data to get latest account/plan information
|
||||
// This ensures account/plan changes are reflected immediately
|
||||
|
||||
Reference in New Issue
Block a user