this repo has no description
1"use server";
2
3import { eq } from "drizzle-orm";
4
5import { group, member } from "@/db/schema";
6import { getUserId } from "@/lib/auth";
7import { db } from "@/lib/db";
8import { generateInvite } from "@/lib/invite";
9
10export type GroupWithMembers = Awaited<ReturnType<typeof getGroups>>[number];
11
12export async function createGroup(name: string, description?: string) {
13 const userId = await getUserId();
14 if (!userId) return null;
15
16 const invite = await generateInvite();
17 const [res] = await db
18 .insert(group)
19 .values({ userId, invite, name, description })
20 .returning();
21
22 return res;
23}
24
25export async function getGroups() {
26 const userId = await getUserId();
27 if (!userId) return [];
28
29 return await db.query.group.findMany({
30 where: (group, { exists, eq, or, and }) =>
31 or(
32 eq(group.userId, userId),
33 exists(
34 db
35 .select()
36 .from(member)
37 .where(
38 and(eq(member.groupId, group.id), eq(member.userId, userId)),
39 ),
40 ),
41 ),
42 with: {
43 owner: true,
44 members: {
45 with: {
46 user: true,
47 redemptions: {
48 with: {
49 voucher: true,
50 },
51 },
52 },
53 },
54 },
55 });
56}
57
58export async function getGroup(id: number) {
59 const groups = await getGroups();
60 return groups.find((g) => g.id === id) || null;
61}
62
63export async function isGroupOwner(id: number) {
64 const userId = await getUserId();
65 const groupData = await getGroup(id);
66
67 if (!userId || !groupData) return false;
68 return groupData.userId === userId;
69}
70
71export async function deleteGroup(id: number) {
72 if (!(await isGroupOwner(id))) return false;
73 const res = await db.delete(group).where(eq(group.id, id));
74 return res.rowCount > 0;
75}
76
77export async function updateGroup(
78 id: number,
79 name: string,
80 description?: string,
81) {
82 if (!(await isGroupOwner(id))) return null;
83
84 const [res] = await db
85 .update(group)
86 .set({ name, description })
87 .where(eq(group.id, id))
88 .returning();
89
90 return res;
91}