sare26 commited on
Commit
8ba5f23
·
verified ·
1 Parent(s): b592ec1

Update artifacts/api-server/src/routes/me/index.ts

Browse files
artifacts/api-server/src/routes/me/index.ts CHANGED
@@ -49,6 +49,60 @@ router.get("/", async (req: Request, res: Response) => {
49
  }
50
 
51
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  await db.insert(usersTable).values({
53
  id: userId,
54
  email: userEmail?.toLowerCase() ?? null,
@@ -81,7 +135,8 @@ router.get("/", async (req: Request, res: Response) => {
81
  currentPeriodEnd: sub?.currentPeriodEnd?.toISOString() ?? null,
82
  paypalSubscriptionId: null,
83
  hasAccess
84
- }
 
85
  });
86
  } catch (error) {
87
  return res.json({
 
49
  }
50
 
51
  try {
52
+ // ========== 🆕 البحث عن مستخدم قديم بنفس البريد ==========
53
+ if (userEmail) {
54
+ const { data: legacyUser } = await supabase
55
+ .from('users')
56
+ .select('id, clerk_id, supabase_id')
57
+ .eq('email', userEmail.toLowerCase())
58
+ .not('clerk_id', 'is', null)
59
+ .maybeSingle();
60
+
61
+ if (legacyUser) {
62
+ console.log(`🔗 ربط المستخدم ${userEmail}: القديم=${legacyUser.id} ← الجديد=${userId}`);
63
+
64
+ // تحديث المستخدم القديم ليرتبط بالجديد
65
+ await supabase
66
+ .from('users')
67
+ .update({
68
+ supabase_id: userId,
69
+ updated_at: now.toISOString()
70
+ })
71
+ .eq('id', legacyUser.id);
72
+
73
+ // 🎯 استخدم اشتراك المستخدم القديم
74
+ const [existingSub] = await db
75
+ .select()
76
+ .from(subscriptionsTable)
77
+ .where(eq(subscriptionsTable.userId, legacyUser.id));
78
+
79
+ if (existingSub) {
80
+ // تحديث معرف المستخدم في الاشتراك للجديد
81
+ await db
82
+ .update(subscriptionsTable)
83
+ .set({ userId })
84
+ .where(eq(subscriptionsTable.userId, legacyUser.id));
85
+
86
+ const status: string = existingSub?.status ?? "none";
87
+ const hasAccess = status === "trialing" && existingSub?.trialEnd && new Date(existingSub.trialEnd) > now
88
+ ? true : status === "active" ? true : false;
89
+
90
+ return res.json({
91
+ userId, email: userEmail,
92
+ subscription: {
93
+ status,
94
+ trialEnd: existingSub?.trialEnd?.toISOString() ?? null,
95
+ currentPeriodEnd: existingSub?.currentPeriodEnd?.toISOString() ?? null,
96
+ paypalSubscriptionId: null,
97
+ hasAccess
98
+ },
99
+ isReturningUser: true // 🆕
100
+ });
101
+ }
102
+ }
103
+ }
104
+
105
+ // ========== مستخدم جديد (لا يوجد له حساب قديم) ==========
106
  await db.insert(usersTable).values({
107
  id: userId,
108
  email: userEmail?.toLowerCase() ?? null,
 
135
  currentPeriodEnd: sub?.currentPeriodEnd?.toISOString() ?? null,
136
  paypalSubscriptionId: null,
137
  hasAccess
138
+ },
139
+ isReturningUser: false // 🆕
140
  });
141
  } catch (error) {
142
  return res.json({