File size: 7,085 Bytes
1b4b6d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca81162
1b4b6d2
 
 
ca81162
1b4b6d2
 
 
 
 
 
 
 
 
 
ca81162
1b4b6d2
 
 
 
 
 
 
ca81162
1b4b6d2
 
ca81162
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
1d5dce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348ea76
 
 
 
 
1d5dce6
 
 
 
348ea76
 
 
 
 
 
 
 
 
 
 
 
 
1d5dce6
 
 
 
 
 
 
 
 
 
 
 
348ea76
 
ca81162
1b4b6d2
 
ca81162
bdc2d18
348ea76
 
 
 
 
 
 
 
 
 
bdc2d18
 
 
348ea76
bdc2d18
1b4b6d2
4364975
 
1b4b6d2
 
 
 
ca81162
1b4b6d2
ca81162
1b4b6d2
 
 
348ea76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
"""Usage accounting and entitlement enforcement."""
from __future__ import annotations

import json
from typing import Any

from utils.db import safe_execute, safe_query
from utils.plans import get_plan_for_user, ttl_cache
from utils.db import is_sqlite


EVENT_PROJECT = "project_created"
EVENT_AI_CALL = "ai_call"
EVENT_EXPORT = "export"


def log_usage(
    user_id: int | None,
    event_type: str,
    quantity: int = 1,
    project_id: int | None = None,
    metadata: dict[str, Any] | None = None,
) -> None:
    safe_execute(
        """
        INSERT INTO qto_usage_logs (user_id, project_id, event_type, quantity, metadata)
        VALUES (%s, %s, %s, %s, %s)
        """,
        (
            user_id,
            project_id,
            event_type,
            quantity,
            json.dumps(metadata or {}, ensure_ascii=False, default=str),
        ),
    )


@ttl_cache(ttl_seconds=60)
def monthly_usage(user_id: int, event_type: str, feature: str = "qto") -> int:
    if is_sqlite():
        df = safe_query(
            """
            SELECT quantity, metadata
            FROM qto_usage_logs
            WHERE user_id=%s
              AND event_type=%s
              AND created_at >= date('now', 'start of month')
            """,
            (user_id, event_type),
        )
    else:
        df = safe_query(
            """
            SELECT quantity, metadata
            FROM qto_usage_logs
            WHERE user_id=%s
              AND event_type=%s
              AND created_at >= DATE_FORMAT(CURRENT_DATE, '%%Y-%%m-01')
            """,
            (user_id, event_type),
        )
    
    if df.empty:
        return 0
        
    total = 0
    for _, row in df.iterrows():
        try:
            meta = json.loads(row["metadata"] or "{}")
            row_feature = meta.get("feature", "qto")
            if row_feature == feature:
                total += int(row["quantity"] or 0)
        except Exception:
            pass
            
    return total


def lifetime_usage(user_id: int, event_type: str, feature: str = "qto") -> int:
    """Total count of an event for a feature over the account's whole lifetime
    (no monthly reset). Used for the one-time free project each new user gets."""
    df = safe_query(
        "SELECT quantity, metadata FROM qto_usage_logs WHERE user_id=%s AND event_type=%s",
        (user_id, event_type),
    )
    if df.empty:
        return 0
    total = 0
    for _, row in df.iterrows():
        try:
            meta = json.loads(row["metadata"] or "{}")
            if meta.get("feature", "qto") == feature:
                total += int(row["quantity"] or 0)
        except Exception:
            pass
    return total


# Every new user gets this many free projects PER TOOL, once (lifetime), before
# they ever subscribe — so they can try each tool on a real project for free.
FREE_PROJECTS_PER_FEATURE = 1


def project_entitlement(user: dict, feature: str = "qto") -> dict:
    """Single source of truth for 'can this user create a project right now?'.

    Monthly model: the tier gives `base` projects PER MONTH (resets monthly).
    Add-ons are ONE-TIME credits consumed only when creating beyond the monthly
    base — they are not a permanent bump. On top of that, an unsubscribed user
    (no paid tier) gets ONE free project per tool for their whole lifetime, so a
    user can create when they still have monthly room OR hold an unused add-on
    credit OR still have their free project.
    """
    user_id = int(user.get("id"))
    role = user.get("role")
    is_admin = role == "admin"
    plan = get_plan_for_user(user_id, role, feature)
    base = plan.projects
    from utils.features import extra_projects_for
    try:
        credits = 0 if is_admin else extra_projects_for(user_id, feature)
    except Exception as e:
        print(f"Error fetching extra projects: {e}")
        credits = 0
    used = monthly_usage(user_id, EVENT_PROJECT, feature)

    # One-time free project for users without a paid plan (base == 0).
    free_base = FREE_PROJECTS_PER_FEATURE if (base == 0 and not is_admin) else 0
    free_used = lifetime_usage(user_id, EVENT_PROJECT, feature) if free_base else 0
    free_left = max(free_base - free_used, 0)

    can_create = is_admin or (used < base) or (credits > 0) or (free_left > 0)
    return {
        "base": base, "used": used, "credits": credits,
        "free_base": free_base, "free_left": free_left,
        "can_create": can_create, "is_admin": is_admin,
    }


def check_limit(user: dict, event_type: str, amount: int = 1, feature: str = "qto") -> tuple[bool, str]:
    user_id = int(user.get("id"))
    role = user.get("role")
    plan = get_plan_for_user(user_id, role, feature)

    if event_type == EVENT_PROJECT:
        ent = project_entitlement(user, feature)
        if ent["can_create"]:
            return True, "OK"
        return False, (
            f"Monthly project limit reached for {feature}: {ent['used']}/{ent['base']} this month, "
            f"and you have 0 extra projects left. Add a project or upgrade your plan."
        )

    # AI calls / exports still scale with any unused add-ons the user holds.
    from utils.features import extra_projects_for
    try:
        extra_projects = extra_projects_for(user_id, feature)
    except Exception:
        extra_projects = 0
    limits = {
        EVENT_AI_CALL: plan.ai_calls + (extra_projects * 20),
        EVENT_EXPORT: plan.exports + (extra_projects * 5),
    }
    limit = limits.get(event_type)
    if limit is None:
        return True, "OK"
    used = monthly_usage(user_id, event_type, feature)
    if used + amount > limit:
        return False, f"Plan limit reached for {event_type} ({feature}): {used}/{limit}"
    return True, "OK"


def settle_project_creation(user: dict, feature: str = "qto", metadata: dict | None = None) -> None:
    """Log a newly-created project AND spend one add-on credit if it went beyond
    the monthly tier quota. Call this INSTEAD of log_usage at creation time.
    """
    user_id = int(user.get("id"))
    role = user.get("role")
    md = dict(metadata or {})
    if feature != "qto":
        md.setdefault("feature", feature)

    # Count what existed BEFORE this project (fresh, not the 60s-cached value).
    monthly_usage.clear()
    used_before = monthly_usage(user_id, EVENT_PROJECT, feature)

    log_usage(user_id, EVENT_PROJECT, metadata=md)
    monthly_usage.clear()

    if role != "admin":
        plan = get_plan_for_user(user_id, role, feature)
        if used_before >= plan.projects:
            # Monthly quota was already full → this one is covered by a one-time add-on.
            from utils.features import consume_extra_project
            consume_extra_project(user_id, feature, 1)


def check_file_size(user: dict, size_bytes: int) -> tuple[bool, str]:
    plan = get_plan_for_user(int(user.get("id")), user.get("role"))
    max_bytes = plan.max_file_mb * 1024 * 1024
    if size_bytes > max_bytes:
        return False, f"File exceeds plan limit: {plan.max_file_mb} MB"
    return True, "OK"