-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
177 lines (170 loc) · 5.29 KB
/
index.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
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
"use server"
import { z } from "zod"
import { authAction } from "./safe-action-client"
import { db } from "~/db/client"
import { eq } from "drizzle-orm"
import { accounts, profiles, myShows } from "~/db/schema"
import { ERR } from "~/lib/utils"
import { revalidatePath } from "next/cache"
import {
getAccount,
getAccountWithProfiles,
getProfile,
getAccountWithActiveProfile,
getMyShowsFromTmdb,
} from "~/lib/server-fetchers"
import { stripe } from "~/lib/stripe"
import { headers } from "next/headers"
import { redirect } from "next/navigation"
import type { Stripe } from "stripe"
import { planTuple } from "~/lib/configs"
import { MediaTuple } from "~/lib/types"
export const createProfile = authAction(
z.object({
name: z.string().min(2).max(20),
}),
async (input, { userId }) => {
const account = await getAccountWithProfiles()
if (account.profiles.length === 4) throw new Error(ERR.not_allowed)
const takenProfileSlots = account.profiles.map((profile) =>
Number(profile.id.at(-1)),
)
const openProfileSlot = [1, 2, 3, 4].find(
(el) => !takenProfileSlots.includes(el),
)
if (!openProfileSlot) throw new Error(ERR.undefined)
await db.insert(profiles).values({
id: `${userId}-${openProfileSlot}`,
accountId: userId,
name: input.name,
profileImgPath: `https://api.dicebear.com/6.x/bottts-neutral/svg?seed=${input.name}`,
})
revalidatePath("/manage-profile")
return { message: "Profile Created" }
},
)
export const deleteProfile = authAction(
z.object({
profileId: z.string(),
}),
async (input) => {
const account = await getAccountWithProfiles()
if (account.activeProfileId === input.profileId)
return { message: "Cannot delete active profile" }
if (!account.profiles.find((profile) => profile.id === input.profileId))
throw new Error(ERR.unauthorized)
await db.delete(profiles).where(eq(profiles.id, input.profileId))
revalidatePath("/manage-profile")
return { message: "Profile Deleted" }
},
)
export const updateProfile = authAction(
z.object({
profileId: z.string(),
name: z.string().min(2).max(20),
}),
async (input, { userId }) => {
const profile = await getProfile(input.profileId)
if (userId !== profile.accountId) throw new Error(ERR.unauthorized)
await db
.update(profiles)
.set({
name: input.name,
profileImgPath: `https://api.dicebear.com/6.x/bottts-neutral/svg?seed=${input.name}`,
})
.where(eq(profiles.id, input.profileId))
revalidatePath("/manage-profile")
return { message: "Profile Updated" }
},
)
export const switchProfile = authAction(
z.object({
profileId: z.string(),
}),
async (input, { userId }) => {
const profile = await getProfile(input.profileId)
if (profile.accountId !== userId) throw new Error(ERR.unauthorized)
await db
.update(accounts)
.set({
activeProfileId: input.profileId,
})
.where(eq(accounts.id, userId))
revalidatePath("/")
return { message: "You have switched active profile" }
},
)
export const toggleMyShow = authAction(
z.object({
id: z.number(),
isSaved: z.boolean(),
movieOrTv: z.enum(MediaTuple),
}),
async (input) => {
const account = await getAccount()
if (!input.isSaved) {
await db.insert(myShows).values({
id: input.id,
mediaType: input.movieOrTv,
profileId: account.activeProfileId,
})
return { isSaved: true }
} else {
await db.delete(myShows).where(eq(myShows.id, input.id))
return { isSaved: false }
}
},
)
export const createCheckoutSession = authAction(
z.object({
stripeProductId: z.string(),
planName: z.enum(planTuple),
}),
async (input, { userId }) => {
const account = await getAccount()
const siteUrl = headers().get("origin")!
let checkoutSession: Stripe.Checkout.Session | Stripe.BillingPortal.Session
if (input.planName !== "free" && account.membership === "free")
checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
billing_address_collection: "auto",
customer_email: account.email,
line_items: [
{
price: input.stripeProductId,
quantity: 1,
},
],
success_url: `${siteUrl}/subscription/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${siteUrl}/subscription`,
metadata: {
userId,
planName: input.planName,
},
})
else
checkoutSession = await stripe.billingPortal.sessions.create({
customer: account.stripeCustomerId!,
return_url: `${siteUrl}/subscription`,
})
redirect(checkoutSession.url!)
},
)
export const getMyShowsInfinite = authAction(
z.object({
index: z.number().min(0),
limit: z.number().min(2).max(50),
}),
async (input) => {
const account = await getAccountWithActiveProfile()
const shows = await db.query.myShows.findMany({
where: eq(myShows.profileId, account.activeProfileId),
limit: input.limit + 1,
offset: input.index * input.limit,
})
const hasNextPage = shows.length > input.limit ? true : false
if (hasNextPage) shows.pop()
const filteredShows = await getMyShowsFromTmdb(shows)
return { shows: filteredShows, hasNextPage }
},
)