-
-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathbanner.functions.ts
More file actions
374 lines (327 loc) · 10.8 KB
/
banner.functions.ts
File metadata and controls
374 lines (327 loc) · 10.8 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { createServerFn } from '@tanstack/react-start'
import { db } from '~/db/client'
import { banners, bannerDismissals } from '~/db/schema'
import { eq, and, gte, lte, or, sql } from 'drizzle-orm'
import * as v from 'valibot'
import { loadUser } from './auth.server'
import { requireAdmin } from './feed.server'
import type { BannerScope, BannerStyle } from '~/db/schema'
export type ActiveBanner = {
id: string
title: string
content: string | null
linkUrl: string | null
linkText: string | null
style: BannerStyle
scope: BannerScope
pathPrefixes: string[]
priority: number
startsAt: number | null
expiresAt: number | null
}
export type BannerWithMeta = ActiveBanner & {
isActive: boolean
createdAt: number
updatedAt: number
}
// Server function to get active banners for a given path
export const getActiveBanners = createServerFn({ method: 'POST' })
.inputValidator(
v.object({
pathname: v.string(),
}),
)
.handler(async ({ data }): Promise<ActiveBanner[]> => {
const now = new Date()
// Get all active banners that are within their schedule
const activeBanners = await db.query.banners.findMany({
where: and(
eq(banners.isActive, true),
// Either no start date or starts_at <= now
or(sql`${banners.startsAt} IS NULL`, lte(banners.startsAt, now)),
// Either no end date or expires_at >= now
or(sql`${banners.expiresAt} IS NULL`, gte(banners.expiresAt, now)),
),
orderBy: (b, { desc }) => [desc(b.priority), desc(b.createdAt)],
})
// Filter banners based on scope and current path
const filteredBanners = activeBanners.filter((banner) => {
if (banner.scope === 'global') {
return true
}
// For targeted banners, check if pathname matches any path prefix
if (banner.scope === 'targeted') {
return banner.pathPrefixes.some((prefix) =>
data.pathname.startsWith(prefix),
)
}
return false
})
return filteredBanners.map((banner) => ({
id: banner.id,
title: banner.title,
content: banner.content,
linkUrl: banner.linkUrl,
linkText: banner.linkText,
style: banner.style,
scope: banner.scope,
pathPrefixes: banner.pathPrefixes,
priority: banner.priority,
startsAt: banner.startsAt?.getTime() ?? null,
expiresAt: banner.expiresAt?.getTime() ?? null,
}))
})
// Server function to get dismissed banner IDs for the current user
export const getDismissedBannerIds = createServerFn({ method: 'GET' }).handler(
async (): Promise<string[]> => {
const user = await loadUser()
if (!user) {
return []
}
const dismissals = await db.query.bannerDismissals.findMany({
where: eq(bannerDismissals.userId, user.userId),
columns: {
bannerId: true,
},
})
return dismissals.map((d) => d.bannerId)
},
)
// Server function to dismiss a banner for the current user
export const dismissBanner = createServerFn({ method: 'POST' })
.inputValidator(
v.object({
bannerId: v.pipe(v.string(), v.uuid()),
}),
)
.handler(async ({ data }): Promise<{ success: boolean }> => {
const user = await loadUser()
if (!user) {
// For anonymous users, we can't store in DB - client will use localStorage
return { success: false }
}
// Check if already dismissed
const existing = await db.query.bannerDismissals.findFirst({
where: and(
eq(bannerDismissals.userId, user.userId),
eq(bannerDismissals.bannerId, data.bannerId),
),
})
if (existing) {
return { success: true }
}
// Create dismissal record
await db.insert(bannerDismissals).values({
userId: user.userId,
bannerId: data.bannerId,
})
return { success: true }
})
// ============================================
// Admin CRUD Operations
// ============================================
// List all banners (admin)
export const listBanners = createServerFn({ method: 'POST' })
.inputValidator(
v.object({
includeInactive: v.optional(v.boolean()),
}),
)
.handler(async ({ data }): Promise<BannerWithMeta[]> => {
await requireAdmin()
const whereClause = data.includeInactive
? undefined
: eq(banners.isActive, true)
const allBanners = await db.query.banners.findMany({
where: whereClause,
orderBy: (b, { desc }) => [desc(b.priority), desc(b.createdAt)],
})
return allBanners.map((banner) => ({
id: banner.id,
title: banner.title,
content: banner.content,
linkUrl: banner.linkUrl,
linkText: banner.linkText,
style: banner.style,
scope: banner.scope,
pathPrefixes: banner.pathPrefixes,
priority: banner.priority,
isActive: banner.isActive,
startsAt: banner.startsAt?.getTime() ?? null,
expiresAt: banner.expiresAt?.getTime() ?? null,
createdAt: banner.createdAt.getTime(),
updatedAt: banner.updatedAt.getTime(),
}))
})
// Get single banner by ID (admin)
export const getBanner = createServerFn({ method: 'POST' })
.inputValidator(v.object({ id: v.pipe(v.string(), v.uuid()) }))
.handler(async ({ data }): Promise<BannerWithMeta | null> => {
await requireAdmin()
const banner = await db.query.banners.findFirst({
where: eq(banners.id, data.id),
})
if (!banner) {
return null
}
return {
id: banner.id,
title: banner.title,
content: banner.content,
linkUrl: banner.linkUrl,
linkText: banner.linkText,
style: banner.style,
scope: banner.scope,
pathPrefixes: banner.pathPrefixes,
priority: banner.priority,
isActive: banner.isActive,
startsAt: banner.startsAt?.getTime() ?? null,
expiresAt: banner.expiresAt?.getTime() ?? null,
createdAt: banner.createdAt.getTime(),
updatedAt: banner.updatedAt.getTime(),
}
})
// Create new banner (admin)
export const createBanner = createServerFn({ method: 'POST' })
.inputValidator(
v.object({
title: v.pipe(v.string(), v.minLength(1, 'Title is required')),
content: v.optional(v.string()),
linkUrl: v.union([
v.optional(v.pipe(v.string(), v.url())),
v.literal(''),
]),
linkText: v.optional(v.string()),
style: v.optional(
v.picklist(['info', 'warning', 'success', 'promo']),
'info',
),
scope: v.optional(v.picklist(['global', 'targeted']), 'global'),
pathPrefixes: v.optional(v.array(v.string()), []),
isActive: v.optional(v.boolean(), true),
startsAt: v.optional(v.number()),
expiresAt: v.optional(v.number()),
priority: v.optional(v.number(), 0),
}),
)
.handler(async ({ data }): Promise<{ id: string }> => {
await requireAdmin()
const [newBanner] = await db
.insert(banners)
.values({
title: data.title,
content: data.content || null,
linkUrl: data.linkUrl || null,
linkText: data.linkText || null,
style: data.style,
scope: data.scope,
pathPrefixes: data.pathPrefixes,
isActive: data.isActive,
startsAt: data.startsAt ? new Date(data.startsAt) : null,
expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,
priority: data.priority,
})
.returning()
return { id: newBanner.id }
})
// Update banner (admin)
export const updateBanner = createServerFn({ method: 'POST' })
.inputValidator(
v.object({
id: v.pipe(v.string(), v.uuid()),
title: v.optional(v.pipe(v.string(), v.minLength(1))),
content: v.optional(v.string()),
linkUrl: v.union([
v.optional(v.pipe(v.string(), v.url())),
v.literal(''),
]),
linkText: v.optional(v.string()),
style: v.optional(v.picklist(['info', 'warning', 'success', 'promo'])),
scope: v.optional(v.picklist(['global', 'targeted'])),
pathPrefixes: v.optional(v.array(v.string())),
isActive: v.optional(v.boolean()),
startsAt: v.optional(v.nullable(v.number())),
expiresAt: v.optional(v.nullable(v.number())),
priority: v.optional(v.number()),
}),
)
.handler(async ({ data }): Promise<{ success: boolean }> => {
await requireAdmin()
const existing = await db.query.banners.findFirst({
where: eq(banners.id, data.id),
})
if (!existing) {
throw new Error('Banner not found')
}
const updates: {
title?: string
content?: string | null
linkUrl?: string | null
linkText?: string | null
style?: BannerStyle
scope?: BannerScope
pathPrefixes?: string[]
isActive?: boolean
startsAt?: Date | null
expiresAt?: Date | null
priority?: number
updatedAt: Date
} = {
updatedAt: new Date(),
}
if (data.title !== undefined) updates.title = data.title
if (data.content !== undefined) updates.content = data.content || null
if (data.linkUrl !== undefined) updates.linkUrl = data.linkUrl || null
if (data.linkText !== undefined) updates.linkText = data.linkText || null
if (data.style !== undefined) updates.style = data.style
if (data.scope !== undefined) updates.scope = data.scope
if (data.pathPrefixes !== undefined)
updates.pathPrefixes = data.pathPrefixes
if (data.isActive !== undefined) updates.isActive = data.isActive
if (data.startsAt !== undefined) {
updates.startsAt = data.startsAt ? new Date(data.startsAt) : null
}
if (data.expiresAt !== undefined) {
updates.expiresAt = data.expiresAt ? new Date(data.expiresAt) : null
}
if (data.priority !== undefined) updates.priority = data.priority
await db.update(banners).set(updates).where(eq(banners.id, data.id))
return { success: true }
})
// Delete banner (admin)
export const deleteBanner = createServerFn({ method: 'POST' })
.inputValidator(v.object({ id: v.pipe(v.string(), v.uuid()) }))
.handler(async ({ data }): Promise<{ success: boolean }> => {
await requireAdmin()
const existing = await db.query.banners.findFirst({
where: eq(banners.id, data.id),
})
if (!existing) {
throw new Error('Banner not found')
}
// Delete banner (cascades to dismissals)
await db.delete(banners).where(eq(banners.id, data.id))
return { success: true }
})
// Toggle banner active state (admin)
export const toggleBannerActive = createServerFn({ method: 'POST' })
.inputValidator(
v.object({
id: v.pipe(v.string(), v.uuid()),
isActive: v.boolean(),
}),
)
.handler(async ({ data }): Promise<{ success: boolean }> => {
await requireAdmin()
const existing = await db.query.banners.findFirst({
where: eq(banners.id, data.id),
})
if (!existing) {
throw new Error('Banner not found')
}
await db
.update(banners)
.set({ isActive: data.isActive, updatedAt: new Date() })
.where(eq(banners.id, data.id))
return { success: true }
})