File size: 9,447 Bytes
a24a2b4
1b4b6d2
 
578576e
1b4b6d2
 
 
bdc2d18
369b6c9
1b4b6d2
 
 
369b6c9
 
 
 
 
 
 
db74bd0
 
8b6ba96
db74bd0
8b6ba96
578576e
 
 
8b6ba96
 
 
0d6b4f2
8b6ba96
db74bd0
bdc2d18
 
 
 
 
 
 
 
 
 
9e60280
 
 
 
 
 
 
bdc2d18
 
 
6d00451
 
 
 
 
 
 
369b6c9
 
bdc2d18
33c6070
9e60280
369b6c9
 
 
33c6070
6d00451
369b6c9
 
bdc2d18
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
ca81162
1b4b6d2
 
 
aba072e
578576e
 
 
 
aba072e
 
578576e
aba072e
0d6b4f2
aba072e
ca81162
 
1b4b6d2
bdc2d18
 
 
1b4b6d2
ca81162
 
 
1b4b6d2
6d00451
 
 
 
 
 
 
348ea76
1d5dce6
 
 
 
 
 
348ea76
1b4b6d2
 
 
 
 
 
1d5dce6
 
348ea76
 
6d00451
1b4b6d2
 
 
 
 
 
 
 
 
 
ca45135
 
 
1d5dce6
1b4b6d2
 
 
 
 
 
fa156f3
1b4b6d2
 
 
 
 
1d5dce6
 
 
fa156f3
1b4b6d2
a24a2b4
 
1b4b6d2
348ea76
 
 
 
 
a24a2b4
 
 
348ea76
 
a24a2b4
348ea76
 
fa156f3
 
bdc2d18
 
 
fa156f3
 
348ea76
fa156f3
1b4b6d2
 
 
ca75569
 
 
 
 
 
 
 
 
 
1b4b6d2
b92e226
33c6070
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
206
207
208
209
210
import logging
from fastapi import APIRouter, Depends, HTTPException, Query
from api.auth import get_current_user
from utils.payments import create_checkout_session, auto_sync_user_subscriptions, force_activate_subscription, sync_user_addons
from utils.plans import PLANS, get_active_subscription, get_plan_for_user
from utils.usage import monthly_usage, EVENT_AI_CALL, EVENT_EXPORT, EVENT_PROJECT
from utils.settings import get_setting
from utils.db import safe_query, safe_execute
from utils.features import FEATURES, get_credits, count_projects

router = APIRouter()


@router.get("/feature-access")
async def feature_access(feature: str = Query(...), current_user: dict = Depends(get_current_user)):
    """Whether the user can use a per-project tool (programme / cashflow)."""
    if feature not in FEATURES:
        raise HTTPException(status_code=404, detail="Unknown feature.")
    
    user_id = current_user["id"]
    role = current_user["role"]
    email = current_user["email"]
    is_admin = role == "admin"

    # Auto-sync from Dodo API β€” so even if webhook was missed, subscription activates on next Dashboard load.
    # (Add-on reconciliation is done only in /subscription to avoid concurrent double-grants, since that
    # endpoint runs once per load and sync_user_addons already grants add-ons for ALL tools in one pass.)
    try:
        auto_sync_user_subscriptions(user_id, email)
    except Exception:
        logging.getLogger("qto.billing").exception("feature-access auto_sync failed for user %s", user_id)

    plan = get_plan_for_user(user_id, role, feature)

    # Per-tool add-on allowance (qto -> extra_projects_allowance,
    # programme -> programme_credits, cashflow -> cashflow_credits).
    from utils.features import extra_projects_for
    extra_projects = 0 if is_admin else extra_projects_for(user_id, feature)

    # "used" is the SAME monthly count the creation gate (check_limit) uses, so
    # the "X / limit" shown on the dashboard always matches when the button flips.
    projects = monthly_usage(user_id, EVENT_PROJECT, feature)

    # Single source of truth for entitlement β€” includes the one-time free project
    # every new user gets per tool (same as the QTO /subscription endpoint).
    from utils.usage import project_entitlement
    ent = project_entitlement({"id": user_id, "role": role}, feature)
    free_left = ent.get("free_left", 0)
    limit = 999999 if is_admin else (plan.projects + extra_projects + free_left)
    can_create = ent["can_create"]
    # Keep access to previously-saved projects even after the monthly quota
    # resets or the subscription lapses (viewing history must not disappear).
    total_saved = count_projects(user_id, feature)
    has_had_trial = False
    try:
        df_past = safe_query("SELECT id FROM qto_subscriptions WHERE user_id=%s AND feature=%s LIMIT 1", (user_id, feature))
        has_had_trial = not df_past.empty
    except:
        pass
        
    return {
        "feature": feature,
        "access": is_admin or can_create or total_saved > 0,
        "credits": extra_projects,
        "free_projects": free_left,
        "projects": projects,
        "limit": limit,
        "can_create": can_create,
        "plan_tier": plan.tier,
        "has_had_trial": has_had_trial,
    }

@router.post("/activate")
async def activate_after_payment(feature: str = Query("qto"), current_user: dict = Depends(get_current_user)):
    """Called by the frontend the moment the user returns from Dodo checkout.

    Synchronous + uncached: pulls the subscription straight from Dodo, writes it,
    clears the plan caches, and returns the confirmed status. This is the
    authoritative activation path β€” it does not depend on the webhook arriving.
    """
    result = force_activate_subscription(current_user["id"], current_user["email"], feature)
    return result


@router.get("/subscription")
async def get_subscription_details(feature: str = Query("qto"), current_user: dict = Depends(get_current_user)):
    user_id = current_user["id"]
    role = current_user["role"]
    email = current_user["email"]

    # Auto-sync on every load: pull subscriptions AND add-ons from Dodo and
    # reconcile any missing ones. This is the authoritative recovery path β€” it
    # does not rely on the webhook OR on the post-payment redirect reaching the
    # app (which it doesn't, since the app is embedded in an iframe).
    try:
        auto_sync_user_subscriptions(user_id, email)
        sync_user_addons(user_id, email)
    except Exception:
        logging.getLogger("qto.billing").exception("subscription reconcile failed for user %s", user_id)

    sub = get_active_subscription(user_id, feature)
    plan = get_plan_for_user(user_id, role, feature)
    
    # Extra projects (per-tool add-on allowance)
    from utils.features import extra_projects_for
    extra_projects = extra_projects_for(user_id, feature)
        
    usage_projects = monthly_usage(user_id, EVENT_PROJECT, feature)
    usage_exports = monthly_usage(user_id, EVENT_EXPORT, feature)
    usage_ai = monthly_usage(user_id, EVENT_AI_CALL, feature)
    
    has_had_trial = False
    try:
        df_past = safe_query("SELECT id FROM qto_subscriptions WHERE user_id=%s AND feature=%s LIMIT 1", (user_id, feature))
        has_had_trial = not df_past.empty
    except:
        pass

    is_admin = role == "admin"
    # Single source of truth for entitlement (monthly room OR add-on credit OR
    # the one-time free project every new user gets before subscribing).
    from utils.usage import project_entitlement
    ent = project_entitlement({"id": user_id, "role": role}, feature)
    free_left = ent.get("free_left", 0)
    can_create = ent["can_create"]

    return {
        "plan_name": plan.name,
        "plan_tier": plan.tier,
        "subscription_status": sub.get("status") if sub else "inactive",
        "current_period_end": sub.get("current_period_end") if sub else None,
        "extra_projects": extra_projects,
        "free_projects": free_left,
        "project_limit": plan.projects + extra_projects + free_left,
        "can_create": can_create,
        "monthly_base": plan.projects,
        "has_had_trial": has_had_trial,
        "usage": {
            "projects": usage_projects,
            "exports": usage_exports,
            "ai_calls": usage_ai
        },
        "plans_catalog": [
            {
                "tier": tier,
                "name": p.name,
                "price_aed": p.monthly_price_aed,
                "projects_limit": p.projects,
                "ai_calls": p.ai_calls,
                "exports": p.exports
            } for tier, p in PLANS.items() if tier > 1   # tier 1 (Starter) retired -> 3 paid tiers
        ]
    }

@router.get("/checkout")
async def get_checkout_url(
    tier: str = Query(...), # e.g. "1", "2", "3", "4", "addon"
    feature: str = Query("qto"), # "qto", "programme", "cashflow"
    current_user: dict = Depends(get_current_user)
):
    try:
        # Map tier back to int if it's a digit
        req_tier = int(tier) if tier.isdigit() else tier
        # Starter (tier 1, 50 AED) has been retired β€” only 3 paid tiers remain.
        if req_tier == 1:
            raise HTTPException(status_code=400, detail="The Starter plan is no longer available. Please choose Professional, Business or Studio.")
        url = create_checkout_session(current_user, req_tier, feature)
        return {"checkout_url": url}
    except HTTPException:
        raise
    except Exception as e:
        # DANGER ZONE: never grant a subscription/credit for free when Dodo is
        # actually configured. Doing so on a transient Dodo error used to create
        # phantom "manual" subscriptions (e.g. a tier-2 plan the user never paid
        # for). The mock path is ONLY for local/dev where no Dodo key exists.
        if get_setting("DODO_PAYMENTS_API_KEY"):
            logging.getLogger("qto.billing").exception(
                "checkout failed tier=%s feature=%s user=%s: %s", tier, feature, current_user.get("id"), e
            )
            raise HTTPException(
                status_code=502,
                detail=f"Could not start checkout ({type(e).__name__}: {str(e)[:200]}).",
            )
        # --- Local/dev only (no Dodo key): mock checkout so tests can run ---
        user_id = current_user["id"]
        if tier == "addon":
            from utils.features import FEATURE_EXTRA_COL
            col = FEATURE_EXTRA_COL.get(feature, "extra_projects_allowance")
            safe_execute(f"UPDATE qto_users SET {col} = COALESCE({col}, 0) + 1 WHERE id=%s", (user_id,))
        elif str(tier).isdigit():
            safe_execute("INSERT INTO qto_subscriptions (user_id, feature, plan_tier, provider, provider_subscription_id, status) VALUES (%s, %s, %s, 'manual', 'mock_123', 'active')", (user_id, feature, int(tier)))

        return {"checkout_url": "/"}

@router.get("/portal")
async def get_portal_url(current_user: dict = Depends(get_current_user)):
    try:
        from utils.payments import create_portal_session
        url = create_portal_session(current_user["id"])
        return {"portal_url": url}
    except Exception as e:
        # Fallback to static URL if no subscription
        portal_url = get_setting("DODO_CUSTOMER_PORTAL_URL")
        if portal_url:
            return {"portal_url": portal_url}
        raise HTTPException(status_code=400, detail=str(e))