basel00omar commited on
Commit
d00aac8
·
1 Parent(s): aba072e

fix: complete payment activation flow - redirect to billing after payment, show activation spinner, poll until subscription is live, show success screen with unlocked projects

Browse files
frontend/src/App.jsx CHANGED
@@ -23,12 +23,25 @@ export default function App() {
23
  const [page, setPage] = useState('dashboard');
24
  const [pageParams, setPageParams] = useState(null);
25
  const [selectedProject, setSelectedProject] = useState(null);
26
- const [isArabic, setIsArabic] = useState(false); // Default to English as requested
27
  const [isDark, setIsDark] = useState(true);
28
  const [showAuth, setShowAuth] = useState(false);
29
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
30
  const [moduleProjectName, setModuleProjectName] = useState({ programme: '', cashflow: '' });
31
  const [activeModules, setActiveModules] = useState({ programme: false, cashflow: false });
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  useEffect(() => {
34
  if (token) {
@@ -528,7 +541,7 @@ export default function App() {
528
  )}
529
  {page === 'market' && <MarketPrices token={token} isArabic={isArabic} />}
530
  {page === 'compare' && <PlanComparison token={token} isArabic={isArabic} />}
531
- {page === 'billing' && <Billing token={token} isArabic={isArabic} user={user} onLogout={handleLogout} />}
532
  {page === 'qs_assistant' && <QsAssistant token={token} isArabic={isArabic} />}
533
  {page === 'admin' && <Admin token={token} isArabic={isArabic} />}
534
  </main>
 
23
  const [page, setPage] = useState('dashboard');
24
  const [pageParams, setPageParams] = useState(null);
25
  const [selectedProject, setSelectedProject] = useState(null);
26
+ const [isArabic, setIsArabic] = useState(false);
27
  const [isDark, setIsDark] = useState(true);
28
  const [showAuth, setShowAuth] = useState(false);
29
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
30
  const [moduleProjectName, setModuleProjectName] = useState({ programme: '', cashflow: '' });
31
  const [activeModules, setActiveModules] = useState({ programme: false, cashflow: false });
32
+ const [paymentSuccess, setPaymentSuccess] = useState(false);
33
+
34
+ useEffect(() => {
35
+ // Detect return from Dodo payment page
36
+ const params = new URLSearchParams(window.location.search);
37
+ if (params.get('payment_success') === '1') {
38
+ setPaymentSuccess(true);
39
+ // Clean the URL
40
+ window.history.replaceState({}, '', window.location.pathname);
41
+ // Navigate to billing page to show activated subscription
42
+ setPage('billing');
43
+ }
44
+ }, []);
45
 
46
  useEffect(() => {
47
  if (token) {
 
541
  )}
542
  {page === 'market' && <MarketPrices token={token} isArabic={isArabic} />}
543
  {page === 'compare' && <PlanComparison token={token} isArabic={isArabic} />}
544
+ {page === 'billing' && <Billing token={token} isArabic={isArabic} user={user} onLogout={handleLogout} paymentSuccess={paymentSuccess} onPaymentSuccessHandled={() => setPaymentSuccess(false)} />}
545
  {page === 'qs_assistant' && <QsAssistant token={token} isArabic={isArabic} />}
546
  {page === 'admin' && <Admin token={token} isArabic={isArabic} />}
547
  </main>
frontend/src/components/Billing.jsx CHANGED
@@ -1,16 +1,68 @@
1
- import React, { useState, useEffect } from 'react';
2
- import { CreditCard, Check, AlertCircle, Sparkles, Layers, Briefcase, DollarSign } from 'lucide-react';
3
 
4
- export default function Billing({ token, isArabic, user, onLogout }) {
5
  const [details, setDetails] = useState(null);
6
  const [loading, setLoading] = useState(false);
7
  const [deleting, setDeleting] = useState(false);
8
  const [message, setMessage] = useState('');
9
  const [activeTab, setActiveTab] = useState('qto');
10
-
 
 
 
 
 
 
 
11
  const [isEditingName, setIsEditingName] = useState(false);
12
  const [editedName, setEditedName] = useState(user?.name || '');
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  useEffect(() => {
15
  fetchSubscriptionDetails(activeTab);
16
  }, [activeTab]);
@@ -42,6 +94,10 @@ export default function Billing({ token, isArabic, user, onLogout }) {
42
  const data = await res.json();
43
  if (res.ok && data.checkout_url) {
44
  window.open(data.checkout_url, '_blank');
 
 
 
 
45
  } else {
46
  throw new Error(data.detail || 'Could not generate checkout link.');
47
  }
@@ -52,6 +108,7 @@ export default function Billing({ token, isArabic, user, onLogout }) {
52
  }
53
  };
54
 
 
55
  const handleSaveName = async () => {
56
  setLoading(true);
57
  try {
@@ -120,6 +177,53 @@ export default function Billing({ token, isArabic, user, onLogout }) {
120
  }
121
  };
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if (loading && !details) {
124
  return (
125
  <div style={{ textAlign: 'center', padding: '50px' }}>
 
1
+ import React, { useState, useEffect, useRef } from 'react';
2
+ import { CreditCard, Check, AlertCircle, Sparkles, Layers, Briefcase, DollarSign, CheckCircle, Loader } from 'lucide-react';
3
 
4
+ export default function Billing({ token, isArabic, user, onLogout, paymentSuccess, onPaymentSuccessHandled }) {
5
  const [details, setDetails] = useState(null);
6
  const [loading, setLoading] = useState(false);
7
  const [deleting, setDeleting] = useState(false);
8
  const [message, setMessage] = useState('');
9
  const [activeTab, setActiveTab] = useState('qto');
10
+
11
+ // Payment activation state
12
+ const [activating, setActivating] = useState(false);
13
+ const [activated, setActivated] = useState(false);
14
+ const [activatedPlan, setActivatedPlan] = useState(null);
15
+ const pollRef = useRef(null);
16
+ const pollCountRef = useRef(0);
17
+
18
  const [isEditingName, setIsEditingName] = useState(false);
19
  const [editedName, setEditedName] = useState(user?.name || '');
20
 
21
+ // When paymentSuccess prop arrives, start polling for activation
22
+ useEffect(() => {
23
+ if (paymentSuccess) {
24
+ setActivating(true);
25
+ pollCountRef.current = 0;
26
+ startPolling();
27
+ }
28
+ }, [paymentSuccess]);
29
+
30
+ const startPolling = () => {
31
+ // Poll every 2.5 seconds for up to 40 seconds (16 attempts)
32
+ pollRef.current = setInterval(async () => {
33
+ pollCountRef.current += 1;
34
+ if (pollCountRef.current > 16) {
35
+ clearInterval(pollRef.current);
36
+ // Even if not confirmed, refresh and stop
37
+ setActivating(false);
38
+ fetchSubscriptionDetails(activeTab);
39
+ if (onPaymentSuccessHandled) onPaymentSuccessHandled();
40
+ return;
41
+ }
42
+ try {
43
+ // Check all 3 features for any new active subscription
44
+ const features = ['qto', 'cashflow', 'programme'];
45
+ for (const feat of features) {
46
+ const res = await fetch(`/api/billing/subscription?feature=${feat}`, {
47
+ headers: { 'Authorization': `Bearer ${token}` }
48
+ });
49
+ const data = await res.json();
50
+ if (res.ok && data.subscription_status === 'active' && data.plan_tier > 0) {
51
+ // Found an active subscription!
52
+ clearInterval(pollRef.current);
53
+ setActivating(false);
54
+ setActivated(true);
55
+ setActivatedPlan({ feature: feat, plan: data.plan_name, tier: data.plan_tier, limit: data.project_limit });
56
+ fetchSubscriptionDetails(feat);
57
+ setActiveTab(feat);
58
+ if (onPaymentSuccessHandled) onPaymentSuccessHandled();
59
+ return;
60
+ }
61
+ }
62
+ } catch (e) { /* ignore */ }
63
+ }, 2500);
64
+ };
65
+
66
  useEffect(() => {
67
  fetchSubscriptionDetails(activeTab);
68
  }, [activeTab]);
 
94
  const data = await res.json();
95
  if (res.ok && data.checkout_url) {
96
  window.open(data.checkout_url, '_blank');
97
+ // Show a tip to the user to come back after payment
98
+ setMessage(isArabic
99
+ ? '✅ تم فتح صفحة الدفع. بعد إتمام الدفع، ارجع لهذه الصفحة وسيتم تفعيل اشتراكك تلقائياً!'
100
+ : '✅ Payment page opened. After completing payment, return here and your subscription will activate automatically!');
101
  } else {
102
  throw new Error(data.detail || 'Could not generate checkout link.');
103
  }
 
108
  }
109
  };
110
 
111
+
112
  const handleSaveName = async () => {
113
  setLoading(true);
114
  try {
 
177
  }
178
  };
179
 
180
+ // === ACTIVATING OVERLAY ===
181
+ if (activating) {
182
+ return (
183
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '60vh', textAlign: 'center', padding: '40px' }}>
184
+ <div style={{ width: '80px', height: '80px', border: '6px solid var(--border-color)', borderTopColor: 'var(--primary)', borderRadius: '50%', animation: 'spin 1s linear infinite', marginBottom: '30px' }} />
185
+ <h2 style={{ fontSize: '1.8rem', fontWeight: 800, color: 'var(--text-primary)', marginBottom: '12px' }}>
186
+ {isArabic ? '⚡ جاري تفعيل اشتراكك...' : '⚡ Activating your subscription...'}
187
+ </h2>
188
+ <p style={{ color: 'var(--text-secondary)', fontSize: '1rem', maxWidth: '400px' }}>
189
+ {isArabic
190
+ ? 'تم استلام الدفع بنجاح. نحن الآن نفعّل اشتراكك ونفتح المشاريع لحسابك.'
191
+ : 'Payment received. We are now activating your subscription and unlocking your projects.'}
192
+ </p>
193
+ <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginTop: '16px' }}>
194
+ {isArabic ? 'قد يستغرق هذا بضع ثوانٍ...' : 'This may take a few seconds...'}
195
+ </p>
196
+ </div>
197
+ );
198
+ }
199
+
200
+ // === SUCCESS OVERLAY ===
201
+ if (activated && activatedPlan) {
202
+ return (
203
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '60vh', textAlign: 'center', padding: '40px' }}>
204
+ <div style={{ width: '100px', height: '100px', borderRadius: '50%', background: 'linear-gradient(135deg, var(--success), #059669)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '30px', boxShadow: '0 0 40px rgba(16, 185, 129, 0.4)' }}>
205
+ <Check size={50} color="white" strokeWidth={3} />
206
+ </div>
207
+ <h2 style={{ fontSize: '2rem', fontWeight: 800, color: 'var(--success)', marginBottom: '12px' }}>
208
+ {isArabic ? '🎉 تم تفعيل اشتراكك!' : '🎉 Subscription Activated!'}
209
+ </h2>
210
+ <p style={{ color: 'var(--text-secondary)', fontSize: '1.1rem', marginBottom: '8px' }}>
211
+ {isArabic ? `خطتك الجديدة: ${activatedPlan.plan}` : `Your plan: ${activatedPlan.plan}`}
212
+ </p>
213
+ <p style={{ color: 'var(--text-primary)', fontSize: '1rem', fontWeight: 700, marginBottom: '30px' }}>
214
+ {isArabic ? `تم فتح ${activatedPlan.limit} مشاريع لحسابك!` : `${activatedPlan.limit} projects unlocked for your account!`}
215
+ </p>
216
+ <button
217
+ onClick={() => setActivated(false)}
218
+ className="btn btn-primary"
219
+ style={{ padding: '14px 40px', fontSize: '1rem', fontWeight: 700, borderRadius: '12px' }}
220
+ >
221
+ {isArabic ? 'ابدأ الآن! 🚀' : 'Start Now! 🚀'}
222
+ </button>
223
+ </div>
224
+ );
225
+ }
226
+
227
  if (loading && !details) {
228
  return (
229
  <div style={{ textAlign: 'center', padding: '50px' }}>
utils/payments.py CHANGED
@@ -76,7 +76,7 @@ def create_checkout_session(user: dict, tier: int | str, feature: str = "qto") -
76
  kwargs = {
77
  "product_cart": [{"product_id": product_id, "quantity": 1}],
78
  "customer": {"email": user["email"]},
79
- "return_url": app_base_url(),
80
  }
81
  if str(tier).isdigit():
82
  from utils.db import safe_query
 
76
  kwargs = {
77
  "product_cart": [{"product_id": product_id, "quantity": 1}],
78
  "customer": {"email": user["email"]},
79
+ "return_url": app_base_url() + "/?payment_success=1",
80
  }
81
  if str(tier).isdigit():
82
  from utils.db import safe_query