-
Notifications
You must be signed in to change notification settings - Fork 3
/
planUtils.ts
70 lines (60 loc) · 1.8 KB
/
planUtils.ts
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
import type { Env } from './api/auth';
export interface CheckUserPlanResult {
id: string;
username: string;
plan_type: string;
expired: boolean;
message: string;
}
interface queryResult {
id: string;
username: string;
created_at: string;
plan_type: string;
plan_started_at: string;
plan_expired_at: string;
}
export async function checkUserPlan(userId: string, env: Env) {
// Get user plan information
const userQuery = await env.D1.prepare(
"SELECT id, username, plan_type, plan_expired_at FROM users WHERE id = ?"
).bind(userId).first() as queryResult;
if (!userQuery) {
throw new Error('User not found');
}
const { id, username, plan_type, plan_expired_at } = userQuery;
// Convert plan_expired_at to Date object
const expiredAtDate = new Date(plan_expired_at);
const currentTime = new Date();
// Check if plan is FREE
if (plan_type === 'FREE') {
return {
id: id,
username: username,
plan_type: 'FREE',
expired: false,
message: 'Plan is FREE, cannot perform this action'
} as CheckUserPlanResult;
}
// Check if plan is expired
if (expiredAtDate < currentTime) {
// If plan is expired, downgrade to FREE
await env.D1.prepare(
"UPDATE users SET plan_type =? WHERE id = ?"
).bind('FREE', userId).run();
return {
id: id,
username: username,
plan_type: 'FREE',
expired: true,
message: 'Plan expired, downgraded to FREE'
} as CheckUserPlanResult;
}
return {
id: id,
username: username,
plan_type: plan_type,
expired: false,
message: 'Plan is valid'
} as CheckUserPlanResult;
}