first
This commit is contained in:
commit
8538ab969a
434 changed files with 44051 additions and 0 deletions
3
packages/database/biome.json
Normal file
3
packages/database/biome.json
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"extends": ["../../biome.json"]
|
||||
}
|
||||
15
packages/database/drizzle/client.ts
Normal file
15
packages/database/drizzle/client.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { drizzle } from "drizzle-orm/node-postgres";
|
||||
import * as schema from "./schema/postgres";
|
||||
|
||||
// Check the drizzle documentation for more information on how to connect to your preferred database provider
|
||||
// https://orm.drizzle.team/docs/get-started-postgresql
|
||||
|
||||
const databaseUrl = process.env.DATABASE_URL as string;
|
||||
|
||||
if (!databaseUrl) {
|
||||
throw new Error("DATABASE_URL is not set");
|
||||
}
|
||||
|
||||
export const db = drizzle(databaseUrl, {
|
||||
schema,
|
||||
});
|
||||
9
packages/database/drizzle/drizzle.config.ts
Normal file
9
packages/database/drizzle/drizzle.config.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "postgresql",
|
||||
schema: "./drizzle/schema/postgres.ts",
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL as string,
|
||||
},
|
||||
});
|
||||
4
packages/database/drizzle/index.ts
Normal file
4
packages/database/drizzle/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export * from "./client";
|
||||
export * from "./zod";
|
||||
export * from "./queries";
|
||||
export * from "./schema";
|
||||
88
packages/database/drizzle/queries/ai-chats.ts
Normal file
88
packages/database/drizzle/queries/ai-chats.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import { eq } from "drizzle-orm";
|
||||
import { db } from "../client";
|
||||
import { aiChat } from "../schema/postgres";
|
||||
|
||||
export async function getAiChatsByUserId({
|
||||
limit,
|
||||
offset,
|
||||
userId,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
userId: string;
|
||||
}) {
|
||||
return await db.query.aiChat.findMany({
|
||||
where: (aiChat, { eq }) => eq(aiChat.userId, userId),
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAiChatsByOrganizationId({
|
||||
limit,
|
||||
offset,
|
||||
organizationId,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
organizationId: string;
|
||||
}) {
|
||||
return await db.query.aiChat.findMany({
|
||||
where: (aiChat, { eq }) => eq(aiChat.organizationId, organizationId),
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAiChatById(id: string) {
|
||||
return db.query.aiChat.findFirst({
|
||||
where: (aiChat, { eq }) => eq(aiChat.id, id),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAiChat({
|
||||
organizationId,
|
||||
userId,
|
||||
title,
|
||||
}: {
|
||||
organizationId?: string;
|
||||
userId: string;
|
||||
title?: string;
|
||||
}) {
|
||||
const [{ id }] = await db
|
||||
.insert(aiChat)
|
||||
.values({
|
||||
organizationId,
|
||||
userId,
|
||||
title,
|
||||
})
|
||||
.returning({ id: aiChat.id });
|
||||
|
||||
const createdChat = await getAiChatById(id);
|
||||
|
||||
if (!createdChat) {
|
||||
throw new Error("Failed to create chat");
|
||||
}
|
||||
|
||||
return createdChat;
|
||||
}
|
||||
|
||||
export async function updateAiChat({
|
||||
id,
|
||||
title,
|
||||
messages,
|
||||
}: {
|
||||
id: string;
|
||||
title?: string;
|
||||
messages?: typeof aiChat.$inferInsert.messages;
|
||||
}) {
|
||||
return await db
|
||||
.update(aiChat)
|
||||
.set({ title, messages })
|
||||
.where(eq(aiChat.id, id))
|
||||
.returning();
|
||||
}
|
||||
|
||||
export async function deleteAiChat(id: string) {
|
||||
return await db.delete(aiChat).where(eq(aiChat.id, id));
|
||||
}
|
||||
4
packages/database/drizzle/queries/index.ts
Normal file
4
packages/database/drizzle/queries/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export * from "./organizations";
|
||||
export * from "./users";
|
||||
export * from "./ai-chats";
|
||||
export * from "./purchases";
|
||||
105
packages/database/drizzle/queries/organizations.ts
Normal file
105
packages/database/drizzle/queries/organizations.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { and, eq } from "drizzle-orm";
|
||||
import type { z } from "zod";
|
||||
import { db } from "../client";
|
||||
import { member, organization } from "../schema/postgres";
|
||||
import type { OrganizationUpdateSchema } from "../zod";
|
||||
|
||||
export async function getOrganizations({
|
||||
limit,
|
||||
offset,
|
||||
query,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
query?: string;
|
||||
}) {
|
||||
return db.query.organization.findMany({
|
||||
where: query
|
||||
? (org, { like }) => like(org.name, `%${query}%`)
|
||||
: undefined,
|
||||
limit,
|
||||
offset,
|
||||
extras: {
|
||||
membersCount: db
|
||||
.$count(member, eq(member.organizationId, organization.id))
|
||||
.as("membersCount"),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function countAllOrganizations() {
|
||||
return db.$count(organization);
|
||||
}
|
||||
|
||||
export async function getOrganizationById(id: string) {
|
||||
return db.query.organization.findFirst({
|
||||
where: (org, { eq }) => eq(org.id, id),
|
||||
with: {
|
||||
members: true,
|
||||
invitations: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getInvitationById(id: string) {
|
||||
return db.query.invitation.findFirst({
|
||||
where: (invitation, { eq }) => eq(invitation.id, id),
|
||||
with: {
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrganizationBySlug(slug: string) {
|
||||
return db.query.organization.findFirst({
|
||||
where: (org, { eq }) => eq(org.slug, slug),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrganizationMembership(
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
) {
|
||||
return db.query.member.findFirst({
|
||||
where: (member, { eq }) =>
|
||||
and(
|
||||
eq(member.organizationId, organizationId),
|
||||
eq(member.userId, userId),
|
||||
),
|
||||
with: {
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrganizationWithPurchasesAndMembersCount(
|
||||
organizationId: string,
|
||||
) {
|
||||
return db.query.organization.findFirst({
|
||||
where: (org, { eq }) => eq(org.id, organizationId),
|
||||
with: {
|
||||
purchases: true,
|
||||
},
|
||||
extras: {
|
||||
membersCount: db
|
||||
.$count(member, eq(member.organizationId, organization.id))
|
||||
.as("membersCount"),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPendingInvitationByEmail(email: string) {
|
||||
return db.query.invitation.findFirst({
|
||||
where: (invitation, { eq }) =>
|
||||
and(eq(invitation.email, email), eq(invitation.status, "pending")),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateOrganization(
|
||||
updatedOrganization: z.infer<typeof OrganizationUpdateSchema>,
|
||||
) {
|
||||
return db
|
||||
.update(organization)
|
||||
.set(updatedOrganization)
|
||||
.where(eq(organization.id, updatedOrganization.id));
|
||||
}
|
||||
59
packages/database/drizzle/queries/purchases.ts
Normal file
59
packages/database/drizzle/queries/purchases.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { eq } from "drizzle-orm";
|
||||
import type { z } from "zod";
|
||||
import { db } from "../client";
|
||||
import { purchase } from "../schema/postgres";
|
||||
import type { PurchaseInsertSchema, PurchaseUpdateSchema } from "../zod";
|
||||
|
||||
export async function getPurchasesByOrganizationId(organizationId: string) {
|
||||
return db.query.purchase.findMany({
|
||||
where: (purchase, { eq }) =>
|
||||
eq(purchase.organizationId, organizationId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPurchasesByUserId(userId: string) {
|
||||
return db.query.purchase.findMany({
|
||||
where: (purchase, { eq }) => eq(purchase.userId, userId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPurchaseById(id: string) {
|
||||
return db.query.purchase.findFirst({
|
||||
where: (purchase, { eq }) => eq(purchase.id, id),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPurchaseBySubscriptionId(subscriptionId: string) {
|
||||
return db.query.purchase.findFirst({
|
||||
where: (purchase, { eq }) =>
|
||||
eq(purchase.subscriptionId, subscriptionId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPurchase(
|
||||
insertedPurchase: z.infer<typeof PurchaseInsertSchema>,
|
||||
) {
|
||||
const [{ id }] = await db
|
||||
.insert(purchase)
|
||||
.values(insertedPurchase)
|
||||
.returning({ id: purchase.id });
|
||||
|
||||
return getPurchaseById(id);
|
||||
}
|
||||
|
||||
export async function updatePurchase(
|
||||
updatedPurchase: z.infer<typeof PurchaseUpdateSchema>,
|
||||
) {
|
||||
const [{ id }] = await db
|
||||
.update(purchase)
|
||||
.set(updatedPurchase)
|
||||
.returning({ id: purchase.id });
|
||||
|
||||
return getPurchaseById(id);
|
||||
}
|
||||
|
||||
export async function deletePurchaseBySubscriptionId(subscriptionId: string) {
|
||||
await db
|
||||
.delete(purchase)
|
||||
.where(eq(purchase.subscriptionId, subscriptionId));
|
||||
}
|
||||
112
packages/database/drizzle/queries/users.ts
Normal file
112
packages/database/drizzle/queries/users.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import { eq } from "drizzle-orm";
|
||||
import type { z } from "zod";
|
||||
import { db } from "../client";
|
||||
import { account, user } from "../schema/postgres";
|
||||
import type { UserUpdateSchema } from "../zod";
|
||||
|
||||
export async function getUsers({
|
||||
limit,
|
||||
offset,
|
||||
query,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
query?: string;
|
||||
}) {
|
||||
return await db.query.user.findMany({
|
||||
where: (user, { like }) => like(user.name, `%${query}%`),
|
||||
limit,
|
||||
offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function countAllUsers() {
|
||||
return db.$count(user);
|
||||
}
|
||||
|
||||
export async function getUserById(id: string) {
|
||||
return await db.query.user.findFirst({
|
||||
where: (user, { eq }) => eq(user.id, id),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserByEmail(email: string) {
|
||||
return await db.query.user.findFirst({
|
||||
where: (user, { eq }) => eq(user.email, email),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUser({
|
||||
email,
|
||||
name,
|
||||
role,
|
||||
emailVerified,
|
||||
onboardingComplete,
|
||||
}: {
|
||||
email: string;
|
||||
name: string;
|
||||
role: "admin" | "user";
|
||||
emailVerified: boolean;
|
||||
onboardingComplete: boolean;
|
||||
}) {
|
||||
const [{ id }] = await db
|
||||
.insert(user)
|
||||
.values({
|
||||
email,
|
||||
name,
|
||||
role,
|
||||
emailVerified,
|
||||
onboardingComplete,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning({
|
||||
id: user.id,
|
||||
});
|
||||
|
||||
const newUser = await getUserById(id);
|
||||
|
||||
return newUser;
|
||||
}
|
||||
|
||||
export async function getAccountById(id: string) {
|
||||
return await db.query.account.findFirst({
|
||||
where: (account, { eq }) => eq(account.id, id),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUserAccount({
|
||||
userId,
|
||||
providerId,
|
||||
accountId,
|
||||
hashedPassword,
|
||||
}: {
|
||||
userId: string;
|
||||
providerId: string;
|
||||
accountId: string;
|
||||
hashedPassword?: string;
|
||||
}) {
|
||||
const [{ id }] = await db
|
||||
.insert(account)
|
||||
.values({
|
||||
userId,
|
||||
accountId,
|
||||
providerId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
password: hashedPassword,
|
||||
})
|
||||
.returning({
|
||||
id: account.id,
|
||||
});
|
||||
|
||||
const newAccount = await getAccountById(id);
|
||||
|
||||
return newAccount;
|
||||
}
|
||||
|
||||
export async function updateUser(
|
||||
updatedUser: z.infer<typeof UserUpdateSchema>,
|
||||
) {
|
||||
return db.update(user).set(updatedUser).where(eq(user.id, updatedUser.id));
|
||||
}
|
||||
1
packages/database/drizzle/schema/index.ts
Normal file
1
packages/database/drizzle/schema/index.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from "./sqlite";
|
||||
226
packages/database/drizzle/schema/mysql.ts
Normal file
226
packages/database/drizzle/schema/mysql.ts
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
import { createId as cuid } from "@paralleldrive/cuid2";
|
||||
import { relations } from "drizzle-orm";
|
||||
import {
|
||||
boolean,
|
||||
int,
|
||||
json,
|
||||
mysqlEnum,
|
||||
mysqlTable,
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
varchar,
|
||||
} from "drizzle-orm/mysql-core";
|
||||
|
||||
// Enums
|
||||
export const purchaseTypeEnum = mysqlEnum("PurchaseType", [
|
||||
"SUBSCRIPTION",
|
||||
"ONE_TIME",
|
||||
]);
|
||||
|
||||
// Tables
|
||||
export const user = mysqlTable("user", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: boolean("emailVerified").notNull().default(false),
|
||||
image: text("image"),
|
||||
createdAt: timestamp("createdAt").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updatedAt").notNull().defaultNow(),
|
||||
username: text("username").unique(),
|
||||
role: text("role"),
|
||||
banned: boolean("banned"),
|
||||
banReason: text("banReason"),
|
||||
banExpires: timestamp("banExpires"),
|
||||
onboardingComplete: boolean("onboardingComplete").default(false).notNull(),
|
||||
paymentsCustomerId: text("paymentsCustomerId"),
|
||||
locale: text("locale"),
|
||||
});
|
||||
|
||||
export const session = mysqlTable(
|
||||
"session",
|
||||
{
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
ipAddress: text("ipAddress"),
|
||||
userAgent: text("userAgent"),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
impersonatedBy: text("impersonatedBy"),
|
||||
activeOrganizationId: text("activeOrganizationId"),
|
||||
token: text("token").notNull(),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
updatedAt: timestamp("updatedAt").notNull(),
|
||||
},
|
||||
(table) => [uniqueIndex("session_token_idx").on(table.token)],
|
||||
);
|
||||
|
||||
export const account = mysqlTable("account", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
accountId: text("accountId").notNull(),
|
||||
providerId: text("providerId").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accessToken: text("accessToken"),
|
||||
refreshToken: text("refreshToken"),
|
||||
idToken: text("idToken"),
|
||||
expiresAt: timestamp("expiresAt"),
|
||||
password: text("password"),
|
||||
accessTokenExpiresAt: timestamp("accessTokenExpiresAt"),
|
||||
refreshTokenExpiresAt: timestamp("refreshTokenExpiresAt"),
|
||||
scope: text("scope"),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
updatedAt: timestamp("updatedAt").notNull(),
|
||||
});
|
||||
|
||||
export const verification = mysqlTable("verification", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
createdAt: timestamp("createdAt"),
|
||||
updatedAt: timestamp("updatedAt"),
|
||||
});
|
||||
|
||||
export const passkey = mysqlTable("passkey", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name"),
|
||||
publicKey: text("publicKey").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
credentialID: text("credentialID").notNull(),
|
||||
counter: int("counter").notNull(),
|
||||
deviceType: text("deviceType").notNull(),
|
||||
backedUp: boolean("backedUp").notNull(),
|
||||
transports: text("transports"),
|
||||
createdAt: timestamp("createdAt"),
|
||||
});
|
||||
|
||||
export const twoFactor = mysqlTable("twoFactor", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
secret: text("secret").notNull(),
|
||||
backupCodes: text("backupCodes").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const organization = mysqlTable(
|
||||
"organization",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
slug: text("slug"),
|
||||
logo: text("logo"),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
metadata: text("metadata"),
|
||||
paymentsCustomerId: text("paymentsCustomerId"),
|
||||
},
|
||||
(table) => [uniqueIndex("organization_slug_idx").on(table.slug)],
|
||||
);
|
||||
|
||||
export const member = mysqlTable(
|
||||
"member",
|
||||
{
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
role: text("role").notNull(),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("member_user_org_idx").on(
|
||||
table.userId,
|
||||
table.organizationId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const invitation = mysqlTable("invitation", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
email: text("email").notNull(),
|
||||
role: text("role"),
|
||||
status: text("status").notNull(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
inviterId: text("inviterId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const purchase = mysqlTable("purchase", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
type: purchaseTypeEnum.notNull(),
|
||||
customerId: text("customerId").notNull(),
|
||||
subscriptionId: text("subscriptionId").unique(),
|
||||
productId: text("productId").notNull(),
|
||||
status: text("status"),
|
||||
createdAt: timestamp("createdAt").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updatedAt"),
|
||||
});
|
||||
|
||||
export const aiChat = mysqlTable("aiChat", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, { onDelete: "cascade" }),
|
||||
title: text("title"),
|
||||
messages: json("messages"),
|
||||
createdAt: timestamp("createdAt").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updatedAt"),
|
||||
});
|
||||
|
||||
// Relations
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
passkeys: many(passkey),
|
||||
invitations: many(invitation),
|
||||
purchases: many(purchase),
|
||||
memberships: many(member),
|
||||
aiChats: many(aiChat),
|
||||
twoFactors: many(twoFactor),
|
||||
}));
|
||||
|
||||
export const organizationRelations = relations(organization, ({ many }) => ({
|
||||
members: many(member),
|
||||
invitations: many(invitation),
|
||||
purchases: many(purchase),
|
||||
aiChats: many(aiChat),
|
||||
}));
|
||||
235
packages/database/drizzle/schema/postgres.ts
Normal file
235
packages/database/drizzle/schema/postgres.ts
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import { createId as cuid } from "@paralleldrive/cuid2";
|
||||
import { relations } from "drizzle-orm";
|
||||
import {
|
||||
boolean,
|
||||
integer,
|
||||
json,
|
||||
pgEnum,
|
||||
pgTable,
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
varchar,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
// Enums
|
||||
export const purchaseTypeEnum = pgEnum("PurchaseType", [
|
||||
"SUBSCRIPTION",
|
||||
"ONE_TIME",
|
||||
]);
|
||||
|
||||
// Tables
|
||||
export const user = pgTable("user", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: boolean("emailVerified").notNull().default(false),
|
||||
image: text("image"),
|
||||
createdAt: timestamp("createdAt").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updatedAt").notNull().defaultNow(),
|
||||
username: text("username").unique(),
|
||||
role: text("role"),
|
||||
banned: boolean("banned"),
|
||||
banReason: text("banReason"),
|
||||
banExpires: timestamp("banExpires"),
|
||||
onboardingComplete: boolean("onboardingComplete").default(false).notNull(),
|
||||
paymentsCustomerId: text("paymentsCustomerId"),
|
||||
locale: text("locale"),
|
||||
});
|
||||
|
||||
export const session = pgTable(
|
||||
"session",
|
||||
{
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
ipAddress: text("ipAddress"),
|
||||
userAgent: text("userAgent"),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
impersonatedBy: text("impersonatedBy"),
|
||||
activeOrganizationId: text("activeOrganizationId"),
|
||||
token: text("token").notNull(),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
updatedAt: timestamp("updatedAt").notNull(),
|
||||
},
|
||||
(table) => [uniqueIndex("session_token_idx").on(table.token)],
|
||||
);
|
||||
|
||||
export const account = pgTable("account", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
accountId: text("accountId").notNull(),
|
||||
providerId: text("providerId").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accessToken: text("accessToken"),
|
||||
refreshToken: text("refreshToken"),
|
||||
idToken: text("idToken"),
|
||||
expiresAt: timestamp("expiresAt"),
|
||||
password: text("password"),
|
||||
accessTokenExpiresAt: timestamp("accessTokenExpiresAt"),
|
||||
refreshTokenExpiresAt: timestamp("refreshTokenExpiresAt"),
|
||||
scope: text("scope"),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
updatedAt: timestamp("updatedAt").notNull(),
|
||||
});
|
||||
|
||||
export const verification = pgTable("verification", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
createdAt: timestamp("createdAt"),
|
||||
updatedAt: timestamp("updatedAt"),
|
||||
});
|
||||
|
||||
export const passkey = pgTable("passkey", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name"),
|
||||
publicKey: text("publicKey").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
credentialID: text("credentialID").notNull(),
|
||||
counter: integer("counter").notNull(),
|
||||
deviceType: text("deviceType").notNull(),
|
||||
backedUp: boolean("backedUp").notNull(),
|
||||
transports: text("transports"),
|
||||
createdAt: timestamp("createdAt"),
|
||||
});
|
||||
|
||||
export const twoFactor = pgTable("twoFactor", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
secret: text("secret").notNull(),
|
||||
backupCodes: text("backupCodes").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const organization = pgTable(
|
||||
"organization",
|
||||
{
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
slug: text("slug"),
|
||||
logo: text("logo"),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
metadata: text("metadata"),
|
||||
paymentsCustomerId: text("paymentsCustomerId"),
|
||||
},
|
||||
|
||||
(table) => [uniqueIndex("organization_slug_idx").on(table.slug)],
|
||||
);
|
||||
|
||||
export const member = pgTable(
|
||||
"member",
|
||||
{
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
role: text("role").notNull(),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("member_user_org_idx").on(
|
||||
table.userId,
|
||||
table.organizationId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const invitation = pgTable("invitation", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
email: text("email").notNull(),
|
||||
role: text("role"),
|
||||
status: text("status").notNull(),
|
||||
expiresAt: timestamp("expiresAt").notNull(),
|
||||
inviterId: text("inviterId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const purchase = pgTable("purchase", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
type: purchaseTypeEnum("type").notNull(),
|
||||
customerId: text("customerId").notNull(),
|
||||
subscriptionId: text("subscriptionId").unique(),
|
||||
productId: text("productId").notNull(),
|
||||
status: text("status"),
|
||||
createdAt: timestamp("createdAt").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updatedAt"),
|
||||
});
|
||||
|
||||
export const aiChat = pgTable("aiChat", {
|
||||
id: varchar("id", { length: 255 })
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, { onDelete: "cascade" }),
|
||||
title: text("title"),
|
||||
messages:
|
||||
json("messages").$type<
|
||||
{
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
}[]
|
||||
>(),
|
||||
createdAt: timestamp("createdAt").defaultNow().notNull(),
|
||||
updatedAt: timestamp("updatedAt"),
|
||||
});
|
||||
|
||||
// Relations
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
passkeys: many(passkey),
|
||||
invitations: many(invitation),
|
||||
purchases: many(purchase),
|
||||
memberships: many(member),
|
||||
aiChats: many(aiChat),
|
||||
twoFactors: many(twoFactor),
|
||||
}));
|
||||
|
||||
export const organizationRelations = relations(organization, ({ many }) => ({
|
||||
members: many(member),
|
||||
invitations: many(invitation),
|
||||
purchases: many(purchase),
|
||||
aiChats: many(aiChat),
|
||||
}));
|
||||
235
packages/database/drizzle/schema/sqlite.ts
Normal file
235
packages/database/drizzle/schema/sqlite.ts
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import { createId as cuid } from "@paralleldrive/cuid2";
|
||||
import { relations, sql } from "drizzle-orm";
|
||||
import {
|
||||
blob,
|
||||
integer,
|
||||
sqliteTable,
|
||||
text,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
// Tables
|
||||
export const user = sqliteTable("user", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
email: text("email").notNull().unique(),
|
||||
emailVerified: integer("emailVerified", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
image: text("image"),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: integer("updatedAt", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
username: text("username").unique(),
|
||||
role: text("role"),
|
||||
banned: integer("banned", { mode: "boolean" }),
|
||||
banReason: text("banReason"),
|
||||
banExpires: integer("banExpires", { mode: "timestamp" }),
|
||||
onboardingComplete: integer("onboardingComplete", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
paymentsCustomerId: text("paymentsCustomerId"),
|
||||
locale: text("locale"),
|
||||
});
|
||||
|
||||
export const session = sqliteTable(
|
||||
"session",
|
||||
{
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(),
|
||||
ipAddress: text("ipAddress"),
|
||||
userAgent: text("userAgent"),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
impersonatedBy: text("impersonatedBy"),
|
||||
activeOrganizationId: text("activeOrganizationId"),
|
||||
token: text("token").notNull(),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" }).notNull(),
|
||||
updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(),
|
||||
},
|
||||
(table) => [uniqueIndex("session_token_idx").on(table.token)],
|
||||
);
|
||||
|
||||
export const account = sqliteTable("account", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
accountId: text("accountId").notNull(),
|
||||
providerId: text("providerId").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
accessToken: text("accessToken"),
|
||||
refreshToken: text("refreshToken"),
|
||||
idToken: text("idToken"),
|
||||
expiresAt: integer("expiresAt", { mode: "timestamp" }),
|
||||
password: text("password"),
|
||||
accessTokenExpiresAt: integer("accessTokenExpiresAt", {
|
||||
mode: "timestamp",
|
||||
}),
|
||||
refreshTokenExpiresAt: integer("refreshTokenExpiresAt", {
|
||||
mode: "timestamp",
|
||||
}),
|
||||
scope: text("scope"),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" }).notNull(),
|
||||
updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(),
|
||||
});
|
||||
|
||||
export const verification = sqliteTable("verification", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
identifier: text("identifier").notNull(),
|
||||
value: text("value").notNull(),
|
||||
expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" }),
|
||||
updatedAt: integer("updatedAt", { mode: "timestamp" }),
|
||||
});
|
||||
|
||||
export const passkey = sqliteTable("passkey", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name"),
|
||||
publicKey: text("publicKey").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
credentialID: text("credentialID").notNull(),
|
||||
counter: integer("counter").notNull(),
|
||||
deviceType: text("deviceType").notNull(),
|
||||
backedUp: integer("backedUp", { mode: "boolean" }).notNull(),
|
||||
transports: text("transports"),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" }),
|
||||
});
|
||||
|
||||
export const twoFactor = sqliteTable("twoFactor", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
secret: text("secret").notNull(),
|
||||
backupCodes: text("backupCodes").notNull(),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const organization = sqliteTable(
|
||||
"organization",
|
||||
{
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
slug: text("slug"),
|
||||
logo: text("logo"),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" }).notNull(),
|
||||
metadata: text("metadata"),
|
||||
paymentsCustomerId: text("paymentsCustomerId"),
|
||||
},
|
||||
(table) => [uniqueIndex("organization_slug_idx").on(table.slug)],
|
||||
);
|
||||
|
||||
export const member = sqliteTable(
|
||||
"member",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
role: text("role").notNull(),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" }).notNull(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("member_user_org_idx").on(
|
||||
table.userId,
|
||||
table.organizationId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const invitation = sqliteTable("invitation", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
email: text("email").notNull(),
|
||||
role: text("role"),
|
||||
status: text("status").notNull(),
|
||||
expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(),
|
||||
inviterId: text("inviterId")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export const purchase = sqliteTable("purchase", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
type: text({ enum: ["SUBSCRIPTION", "ONE_TIME"] }).notNull(),
|
||||
customerId: text("customerId").notNull(),
|
||||
subscriptionId: text("subscriptionId").unique(),
|
||||
productId: text("productId").notNull(),
|
||||
status: text("status"),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: integer("updatedAt", { mode: "timestamp" }).default(
|
||||
sql`CURRENT_TIMESTAMP`,
|
||||
),
|
||||
});
|
||||
|
||||
export const aiChat = sqliteTable("aiChat", {
|
||||
id: text("id")
|
||||
.$defaultFn(() => cuid())
|
||||
.primaryKey(),
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, { onDelete: "cascade" }),
|
||||
title: text("title"),
|
||||
messages: blob("messages", { mode: "json" }),
|
||||
createdAt: integer("createdAt", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: integer("updatedAt", { mode: "timestamp" }).default(
|
||||
sql`CURRENT_TIMESTAMP`,
|
||||
),
|
||||
});
|
||||
|
||||
// Relations
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
passkeys: many(passkey),
|
||||
invitations: many(invitation),
|
||||
purchases: many(purchase),
|
||||
memberships: many(member),
|
||||
aiChats: many(aiChat),
|
||||
twoFactors: many(twoFactor),
|
||||
}));
|
||||
|
||||
export const organizationRelations = relations(organization, ({ many }) => ({
|
||||
members: many(member),
|
||||
invitations: many(invitation),
|
||||
purchases: many(purchase),
|
||||
aiChats: many(aiChat),
|
||||
}));
|
||||
40
packages/database/drizzle/zod.ts
Normal file
40
packages/database/drizzle/zod.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import {
|
||||
createInsertSchema,
|
||||
createSelectSchema,
|
||||
createUpdateSchema,
|
||||
} from "drizzle-zod";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
account,
|
||||
aiChat,
|
||||
invitation,
|
||||
member,
|
||||
organization,
|
||||
passkey,
|
||||
purchase,
|
||||
session,
|
||||
user,
|
||||
verification,
|
||||
} from "./schema";
|
||||
|
||||
export const AiChatSchema = createSelectSchema(aiChat);
|
||||
export const UserSchema = createSelectSchema(user);
|
||||
export const UserUpdateSchema = createUpdateSchema(user, {
|
||||
id: z.string(),
|
||||
});
|
||||
export const OrganizationSchema = createSelectSchema(organization);
|
||||
export const OrganizationUpdateSchema = createUpdateSchema(organization, {
|
||||
id: z.string(),
|
||||
});
|
||||
export const MemberSchema = createSelectSchema(member);
|
||||
export const InvitationSchema = createSelectSchema(invitation);
|
||||
export const PurchaseSchema = createSelectSchema(purchase);
|
||||
export type Purchase = typeof purchase.$inferSelect;
|
||||
export const PurchaseInsertSchema = createInsertSchema(purchase);
|
||||
export const PurchaseUpdateSchema = createUpdateSchema(purchase, {
|
||||
id: z.string(),
|
||||
});
|
||||
export const SessionSchema = createSelectSchema(session);
|
||||
export const AccountSchema = createSelectSchema(account);
|
||||
export const VerificationSchema = createSelectSchema(verification);
|
||||
export const PasskeySchema = createSelectSchema(passkey);
|
||||
1
packages/database/index.ts
Normal file
1
packages/database/index.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from "./prisma";
|
||||
32
packages/database/package.json
Normal file
32
packages/database/package.json
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"dependencies": {
|
||||
"@paralleldrive/cuid2": "^2.2.2",
|
||||
"@prisma/client": "^6.9.0",
|
||||
"@repo/config": "workspace:*",
|
||||
"drizzle-orm": "^0.44.2",
|
||||
"drizzle-zod": "^0.8.2",
|
||||
"pg": "^8.16.0",
|
||||
"zod": "^3.25.55"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.9.4",
|
||||
"@repo/tsconfig": "workspace:*",
|
||||
"@types/node": "22.15.30",
|
||||
"dotenv-cli": "^8.0.0",
|
||||
"drizzle-kit": "^0.31.1",
|
||||
"prisma": "^6.9.0",
|
||||
"prisma-json-types-generator": "^3.4.2",
|
||||
"zod-prisma-types": "^3.2.4"
|
||||
},
|
||||
"main": "./index.ts",
|
||||
"name": "@repo/database",
|
||||
"scripts": {
|
||||
"generate": "prisma generate --no-hints --schema=./prisma/schema.prisma",
|
||||
"push": "dotenv -c -e ../../.env -- prisma db push --skip-generate --schema=./prisma/schema.prisma",
|
||||
"migrate": "dotenv -c -e ../../.env -- prisma migrate dev --schema=./prisma/schema.prisma",
|
||||
"studio": "dotenv -c -e ../../.env -- prisma studio --schema=./prisma/schema.prisma",
|
||||
"type-check": "tsc --noEmit"
|
||||
},
|
||||
"types": "./**/.tsx",
|
||||
"version": "0.0.0"
|
||||
}
|
||||
18
packages/database/prisma/client.ts
Normal file
18
packages/database/prisma/client.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const prismaClientSingleton = () => {
|
||||
return new PrismaClient();
|
||||
};
|
||||
|
||||
declare global {
|
||||
var prisma: undefined | ReturnType<typeof prismaClientSingleton>;
|
||||
}
|
||||
|
||||
// biome-ignore lint/suspicious/noRedeclare: <explanation>
|
||||
const prisma = globalThis.prisma ?? prismaClientSingleton();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalThis.prisma = prisma;
|
||||
}
|
||||
|
||||
export { prisma as db };
|
||||
7
packages/database/prisma/index.ts
Normal file
7
packages/database/prisma/index.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export * from "./client";
|
||||
export * from "./zod";
|
||||
export * from "./queries";
|
||||
|
||||
declare global {
|
||||
namespace PrismaJson {}
|
||||
}
|
||||
92
packages/database/prisma/queries/ai-chats.ts
Normal file
92
packages/database/prisma/queries/ai-chats.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { db } from "../client";
|
||||
import type { AiChat } from "../zod";
|
||||
|
||||
export async function getAiChatsByUserId({
|
||||
limit,
|
||||
offset,
|
||||
userId,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
userId: string;
|
||||
}) {
|
||||
return await db.aiChat.findMany({
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
take: limit,
|
||||
skip: offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAiChatsByOrganizationId({
|
||||
limit,
|
||||
offset,
|
||||
organizationId,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
organizationId: string;
|
||||
}) {
|
||||
return await db.aiChat.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
},
|
||||
take: limit,
|
||||
skip: offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAiChatById(id: string) {
|
||||
return await db.aiChat.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAiChat({
|
||||
organizationId,
|
||||
userId,
|
||||
title,
|
||||
}: {
|
||||
organizationId?: string;
|
||||
userId: string;
|
||||
title?: string;
|
||||
}) {
|
||||
return await db.aiChat.create({
|
||||
data: {
|
||||
organizationId,
|
||||
userId,
|
||||
title,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAiChat({
|
||||
id,
|
||||
title,
|
||||
messages,
|
||||
}: {
|
||||
id: string;
|
||||
title?: string;
|
||||
messages?: AiChat["messages"];
|
||||
}) {
|
||||
return await db.aiChat.update({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
data: {
|
||||
title,
|
||||
messages,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAiChat(id: string) {
|
||||
return await db.aiChat.delete({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
4
packages/database/prisma/queries/index.ts
Normal file
4
packages/database/prisma/queries/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export * from "./ai-chats";
|
||||
export * from "./organizations";
|
||||
export * from "./purchases";
|
||||
export * from "./users";
|
||||
128
packages/database/prisma/queries/organizations.ts
Normal file
128
packages/database/prisma/queries/organizations.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import type { z } from "zod";
|
||||
import { db } from "../client";
|
||||
import type { OrganizationUpdateInputSchema } from "../zod";
|
||||
|
||||
export async function getOrganizations({
|
||||
limit,
|
||||
offset,
|
||||
query,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
query?: string;
|
||||
}) {
|
||||
return db.organization
|
||||
.findMany({
|
||||
where: {
|
||||
name: { contains: query, mode: "insensitive" },
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
take: limit,
|
||||
skip: offset,
|
||||
})
|
||||
.then((res) =>
|
||||
res.map((org) => ({
|
||||
...org,
|
||||
membersCount: org._count.members,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export async function countAllOrganizations() {
|
||||
return db.organization.count();
|
||||
}
|
||||
|
||||
export async function getOrganizationById(id: string) {
|
||||
return db.organization.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
members: true,
|
||||
invitations: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getInvitationById(id: string) {
|
||||
return db.invitation.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrganizationBySlug(slug: string) {
|
||||
return db.organization.findUnique({
|
||||
where: { slug },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrganizationMembership(
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
) {
|
||||
return db.member.findUnique({
|
||||
where: {
|
||||
organizationId_userId: {
|
||||
organizationId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getOrganizationWithPurchasesAndMembersCount(
|
||||
organizationId: string,
|
||||
) {
|
||||
const organization = await db.organization.findUnique({
|
||||
where: {
|
||||
id: organizationId,
|
||||
},
|
||||
include: {
|
||||
purchases: true,
|
||||
_count: {
|
||||
select: {
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return organization
|
||||
? {
|
||||
...organization,
|
||||
membersCount: organization._count.members,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function getPendingInvitationByEmail(email: string) {
|
||||
return db.invitation.findFirst({
|
||||
where: {
|
||||
email,
|
||||
status: "pending",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateOrganization(
|
||||
organization: z.infer<typeof OrganizationUpdateInputSchema> & {
|
||||
id: string;
|
||||
},
|
||||
) {
|
||||
return db.organization.update({
|
||||
where: {
|
||||
id: organization.id,
|
||||
},
|
||||
data: organization,
|
||||
});
|
||||
}
|
||||
69
packages/database/prisma/queries/purchases.ts
Normal file
69
packages/database/prisma/queries/purchases.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import type { z } from "zod";
|
||||
import { db } from "../client";
|
||||
import type {
|
||||
PurchaseUncheckedCreateInputSchema,
|
||||
PurchaseUncheckedUpdateInputSchema,
|
||||
} from "../zod";
|
||||
|
||||
export async function getPurchaseById(id: string) {
|
||||
return db.purchase.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPurchasesByOrganizationId(organizationId: string) {
|
||||
return db.purchase.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPurchasesByUserId(userId: string) {
|
||||
return db.purchase.findMany({
|
||||
where: {
|
||||
userId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPurchaseBySubscriptionId(subscriptionId: string) {
|
||||
return db.purchase.findFirst({
|
||||
where: {
|
||||
subscriptionId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPurchase(
|
||||
purchase: z.infer<typeof PurchaseUncheckedCreateInputSchema>,
|
||||
) {
|
||||
const created = await db.purchase.create({
|
||||
data: purchase,
|
||||
});
|
||||
|
||||
return getPurchaseById(created.id);
|
||||
}
|
||||
|
||||
export async function updatePurchase(
|
||||
purchase: z.infer<typeof PurchaseUncheckedUpdateInputSchema> & {
|
||||
id: string;
|
||||
},
|
||||
) {
|
||||
const updated = await db.purchase.update({
|
||||
where: {
|
||||
id: purchase.id,
|
||||
},
|
||||
data: purchase,
|
||||
});
|
||||
|
||||
return getPurchaseById(updated.id);
|
||||
}
|
||||
|
||||
export async function deletePurchaseBySubscriptionId(subscriptionId: string) {
|
||||
await db.purchase.delete({
|
||||
where: {
|
||||
subscriptionId,
|
||||
},
|
||||
});
|
||||
}
|
||||
113
packages/database/prisma/queries/users.ts
Normal file
113
packages/database/prisma/queries/users.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import type { z } from "zod";
|
||||
import { db } from "../client";
|
||||
import type { UserUncheckedUpdateInputSchema } from "../zod";
|
||||
|
||||
export async function getUsers({
|
||||
limit,
|
||||
offset,
|
||||
query,
|
||||
}: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
query?: string;
|
||||
}) {
|
||||
return await db.user.findMany({
|
||||
where: query
|
||||
? {
|
||||
name: {
|
||||
contains: query,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
take: limit,
|
||||
skip: offset,
|
||||
});
|
||||
}
|
||||
|
||||
export async function countAllUsers() {
|
||||
return await db.user.count();
|
||||
}
|
||||
|
||||
export async function getUserById(id: string) {
|
||||
return await db.user.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserByEmail(email: string) {
|
||||
return await db.user.findUnique({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUser({
|
||||
email,
|
||||
name,
|
||||
role,
|
||||
emailVerified,
|
||||
onboardingComplete,
|
||||
}: {
|
||||
email: string;
|
||||
name: string;
|
||||
role: "admin" | "user";
|
||||
emailVerified: boolean;
|
||||
onboardingComplete: boolean;
|
||||
}) {
|
||||
return await db.user.create({
|
||||
data: {
|
||||
email,
|
||||
name,
|
||||
role,
|
||||
emailVerified,
|
||||
onboardingComplete,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAccountById(id: string) {
|
||||
return await db.account.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUserAccount({
|
||||
userId,
|
||||
providerId,
|
||||
accountId,
|
||||
hashedPassword,
|
||||
}: {
|
||||
userId: string;
|
||||
providerId: string;
|
||||
accountId: string;
|
||||
hashedPassword?: string;
|
||||
}) {
|
||||
return await db.account.create({
|
||||
data: {
|
||||
userId,
|
||||
accountId,
|
||||
providerId,
|
||||
password: hashedPassword,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateUser(
|
||||
user: z.infer<typeof UserUncheckedUpdateInputSchema> & { id: string },
|
||||
) {
|
||||
return await db.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: user,
|
||||
});
|
||||
}
|
||||
212
packages/database/prisma/schema.prisma
Normal file
212
packages/database/prisma/schema.prisma
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
generator zod {
|
||||
provider = "zod-prisma-types"
|
||||
output = "./zod"
|
||||
createInputTypes = true
|
||||
addIncludeType = false
|
||||
addSelectType = false
|
||||
}
|
||||
|
||||
generator json {
|
||||
provider = "prisma-json-types-generator"
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
email String
|
||||
emailVerified Boolean
|
||||
image String?
|
||||
createdAt DateTime
|
||||
updatedAt DateTime
|
||||
username String?
|
||||
role String?
|
||||
banned Boolean?
|
||||
banReason String?
|
||||
banExpires DateTime?
|
||||
onboardingComplete Boolean @default(false)
|
||||
paymentsCustomerId String?
|
||||
locale String?
|
||||
twoFactorEnabled Boolean?
|
||||
sessions Session[]
|
||||
accounts Account[]
|
||||
passkeys Passkey[]
|
||||
invitations Invitation[]
|
||||
purchases Purchase[]
|
||||
members Member[]
|
||||
twofactors TwoFactor[]
|
||||
aiChats AiChat[]
|
||||
|
||||
@@unique([email])
|
||||
@@unique([username])
|
||||
@@map("user")
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
expiresAt DateTime
|
||||
ipAddress String?
|
||||
userAgent String?
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
impersonatedBy String?
|
||||
|
||||
activeOrganizationId String?
|
||||
|
||||
token String
|
||||
createdAt DateTime
|
||||
updatedAt DateTime
|
||||
|
||||
@@unique([token])
|
||||
@@map("session")
|
||||
}
|
||||
|
||||
model Account {
|
||||
id String @id @default(cuid())
|
||||
accountId String
|
||||
providerId String
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
accessToken String? @db.Text
|
||||
refreshToken String? @db.Text
|
||||
idToken String? @db.Text
|
||||
expiresAt DateTime?
|
||||
password String?
|
||||
|
||||
accessTokenExpiresAt DateTime?
|
||||
refreshTokenExpiresAt DateTime?
|
||||
scope String?
|
||||
createdAt DateTime
|
||||
updatedAt DateTime
|
||||
|
||||
@@map("account")
|
||||
}
|
||||
|
||||
model Verification {
|
||||
id String @id @default(cuid())
|
||||
identifier String
|
||||
value String @db.Text
|
||||
expiresAt DateTime
|
||||
|
||||
createdAt DateTime?
|
||||
updatedAt DateTime?
|
||||
|
||||
@@map("verification")
|
||||
}
|
||||
|
||||
model Passkey {
|
||||
id String @id @default(cuid())
|
||||
name String?
|
||||
publicKey String
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
credentialID String
|
||||
counter Int
|
||||
deviceType String
|
||||
backedUp Boolean
|
||||
transports String?
|
||||
createdAt DateTime?
|
||||
|
||||
@@map("passkey")
|
||||
}
|
||||
|
||||
model TwoFactor {
|
||||
id String @id @default(cuid())
|
||||
secret String
|
||||
backupCodes String
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("twoFactor")
|
||||
}
|
||||
|
||||
model Organization {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String?
|
||||
logo String?
|
||||
createdAt DateTime
|
||||
metadata String?
|
||||
paymentsCustomerId String?
|
||||
members Member[]
|
||||
invitations Invitation[]
|
||||
purchases Purchase[]
|
||||
aiChats AiChat[]
|
||||
|
||||
@@unique([slug])
|
||||
@@map("organization")
|
||||
}
|
||||
|
||||
model Member {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
role String
|
||||
createdAt DateTime
|
||||
|
||||
@@unique([organizationId, userId])
|
||||
@@map("member")
|
||||
}
|
||||
|
||||
model Invitation {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
email String
|
||||
role String?
|
||||
status String
|
||||
expiresAt DateTime
|
||||
inviterId String
|
||||
user User @relation(fields: [inviterId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("invitation")
|
||||
}
|
||||
|
||||
enum PurchaseType {
|
||||
SUBSCRIPTION
|
||||
ONE_TIME
|
||||
}
|
||||
|
||||
model Purchase {
|
||||
id String @id @default(cuid())
|
||||
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
organizationId String?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
userId String?
|
||||
type PurchaseType
|
||||
customerId String
|
||||
subscriptionId String? @unique
|
||||
productId String
|
||||
status String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([subscriptionId])
|
||||
@@map("purchase")
|
||||
}
|
||||
|
||||
model AiChat {
|
||||
id String @id @default(cuid())
|
||||
organizationId String?
|
||||
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
userId String?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
title String?
|
||||
/// [Array<{role: "user" | "assistant"; content: string;}>]
|
||||
messages Json @default("[]") /// @zod.custom.use(z.array(z.object({ role: z.enum(['user', 'assistant']), content: z.string() })))
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("ai_chat")
|
||||
}
|
||||
7633
packages/database/prisma/zod/index.ts
Normal file
7633
packages/database/prisma/zod/index.ts
Normal file
File diff suppressed because it is too large
Load diff
5
packages/database/tsconfig.json
Normal file
5
packages/database/tsconfig.json
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"extends": "@repo/tsconfig/base.json",
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": ["dist", "build", "node_modules", "prisma/zod/**/*.ts"]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue