feat: add portal database schema

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 20:26:18 +02:00
1 parent 763098b129
commit 7acaacb92e
17 files changed
+4410 -111

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
import "server-only";
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import { env } from "@/config/env";
import * as schema from "./schema";
export const pool = new Pool({ connectionString: env.DATABASE_URL });
export const db: NodePgDatabase<typeof schema> = drizzle({ client: pool, schema });
+24
View File
@@ -0,0 +1,24 @@
import { index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
import { editorialAccounts } from "./editorials";
export const albumGrants = pgTable(
"album_grants",
{
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
immichAlbumId: text("immich_album_id").notNull(),
grantedAt: timestamp("granted_at", { withTimezone: true }).notNull().defaultNow(),
revokedAt: timestamp("revoked_at", { withTimezone: true }),
grantedByUserId: uuid("granted_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
},
(table) => [
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
index("album_grants_immich_album_id_idx").on(table.immichAlbumId),
],
);
+16
View File
@@ -0,0 +1,16 @@
import { jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
export const auditEvents = pgTable("audit_events", {
id: uuid("id").defaultRandom().primaryKey(),
eventType: text("event_type").notNull(),
actorUserId: uuid("actor_user_id").references(() => users.id, { onDelete: "restrict" }),
actorType: text("actor_type").notNull().default("system"),
entityType: text("entity_type").notNull(),
entityId: text("entity_id").notNull(),
previousValues: jsonb("previous_values"),
newValues: jsonb("new_values"),
occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
requestId: uuid("request_id"),
});
+55
View File
@@ -0,0 +1,55 @@
import { boolean, pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
export const portalRoles = ["ADMIN", "EDITORIAL"] as const;
export const portalRole = pgEnum("portal_role", portalRoles);
export const users = pgTable("user", {
id: uuid("id").defaultRandom().primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").notNull().default(false),
image: text("image"),
role: portalRole("role").notNull().default("EDITORIAL"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
export const accounts = pgTable("account", {
id: uuid("id").defaultRandom().primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at", { withTimezone: true }),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at", { withTimezone: true }),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
export const sessions = pgTable("session", {
id: uuid("id").defaultRandom().primaryKey(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
});
export const verifications = pgTable("verification", {
id: uuid("id").defaultRandom().primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
+91
View File
@@ -0,0 +1,91 @@
import { sql } from "drizzle-orm";
import {
check,
customType,
integer,
jsonb,
pgEnum,
pgTable,
text,
timestamp,
uniqueIndex,
uuid,
varchar,
} from "drizzle-orm/pg-core";
import { users } from "./auth";
import { editorialAccounts } from "./editorials";
import { usages } from "./usages";
export const reportStatuses = ["draft", "final", "cancelled"] as const;
export const reportStatus = pgEnum("report_status", reportStatuses);
const bytea = customType<{ data: Buffer; driverData: Buffer }>({
dataType() {
return "bytea";
},
});
export const billingReports = pgTable(
"billing_reports",
{
id: uuid("id").defaultRandom().primaryKey(),
reportNumber: integer("report_number").notNull(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
periodStartsAt: timestamp("period_starts_at", { withTimezone: true }).notNull(),
periodEndsAt: timestamp("period_ends_at", { withTimezone: true }).notNull(),
billingAddressSnapshot: jsonb("billing_address_snapshot").notNull(),
invoiceNumber: text("invoice_number"),
netTotalCents: integer("net_total_cents").notNull(),
status: reportStatus("status").notNull().default("draft"),
pdf: bytea("pdf"),
pdfSha256: varchar("pdf_sha256", { length: 64 }),
createdByUserId: uuid("created_by_user_id")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
finalizedAt: timestamp("finalized_at", { withTimezone: true }),
cancelledAt: timestamp("cancelled_at", { withTimezone: true }),
cancellationReason: text("cancellation_reason"),
cancelledByUserId: uuid("cancelled_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
},
(table) => [
uniqueIndex("billing_reports_report_number_unique").on(table.reportNumber),
uniqueIndex("billing_reports_invoice_number_unique").on(table.invoiceNumber),
check("billing_reports_pdf_sha256_hex_check", sql`${table.pdfSha256} ~ '^[0-9a-f]{64}$'`),
check(
"billing_reports_final_pdf_check",
sql`${table.status} <> 'final' OR (${table.pdf} IS NOT NULL AND ${table.pdfSha256} IS NOT NULL)`,
),
],
);
export const billingReportItems = pgTable(
"billing_report_items",
{
id: uuid("id").defaultRandom().primaryKey(),
billingReportId: uuid("billing_report_id")
.notNull()
.references(() => billingReports.id, { onDelete: "restrict" }),
usageId: uuid("usage_id")
.notNull()
.references(() => usages.id, { onDelete: "restrict" }),
immichAssetIdSnapshot: text("immich_asset_id_snapshot").notNull(),
filenameSnapshot: text("filename_snapshot").notNull(),
albumNameSnapshot: text("album_name_snapshot").notNull(),
purposeSnapshot: text("purpose_snapshot").notNull(),
internalReferenceSnapshot: text("internal_reference_snapshot"),
priceCents: integer("price_cents").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("billing_report_items_report_usage_unique").on(
table.billingReportId,
table.usageId,
),
],
);
+78
View File
@@ -0,0 +1,78 @@
import { relations } from "drizzle-orm";
import { type AnyPgColumn, integer, pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth";
export const accountStatuses = [
"pending_email",
"pending_approval",
"active",
"suspended",
"rejected",
] as const;
export const accountStatus = pgEnum("account_status", accountStatuses);
export const editorialAccounts = pgTable("editorial_accounts", {
id: uuid("id").defaultRandom().primaryKey(),
userId: uuid("user_id")
.notNull()
.unique()
.references(() => users.id, { onDelete: "restrict" }),
name: text("name").notNull(),
contactName: text("contact_name").notNull(),
loginEmail: text("login_email").notNull().unique(),
status: accountStatus("status").notNull().default("pending_email"),
currentPriceCents: integer("current_price_cents"),
currentBillingAddressVersionId: uuid("current_billing_address_version_id").references(
(): AnyPgColumn => billingAddressVersions.id,
{ onDelete: "restrict" },
),
emailVerifiedAt: timestamp("email_verified_at", { withTimezone: true }),
acceptedTermsVersion: text("accepted_terms_version"),
acceptedTermsAt: timestamp("accepted_terms_at", { withTimezone: true }),
privacyAcknowledgedAt: timestamp("privacy_acknowledged_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
export const billingAddressVersions = pgTable("billing_address_versions", {
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
companyName: text("company_name").notNull(),
contactName: text("contact_name").notNull(),
addressLine1: text("address_line_1").notNull(),
addressLine2: text("address_line_2"),
postalCode: text("postal_code").notNull(),
city: text("city").notNull(),
countryCode: text("country_code").notNull(),
validFrom: timestamp("valid_from", { withTimezone: true }).notNull().defaultNow(),
supersededById: uuid("superseded_by_id").references((): AnyPgColumn => billingAddressVersions.id, {
onDelete: "restrict",
}),
createdByUserId: uuid("created_by_user_id").references(() => users.id, {
onDelete: "restrict",
}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const editorialAccountsRelations = relations(editorialAccounts, ({ one, many }) => ({
user: one(users, {
fields: [editorialAccounts.userId],
references: [users.id],
}),
billingAddressVersions: many(billingAddressVersions),
}));
export const billingAddressVersionsRelations = relations(billingAddressVersions, ({ one }) => ({
editorialAccount: one(editorialAccounts, {
fields: [billingAddressVersions.editorialAccountId],
references: [editorialAccounts.id],
}),
supersededBy: one(billingAddressVersions, {
fields: [billingAddressVersions.supersededById],
references: [billingAddressVersions.id],
relationName: "supersededBillingAddressVersion",
}),
}));
+6
View File
@@ -0,0 +1,6 @@
export * from "./albums";
export * from "./audit";
export * from "./auth";
export * from "./billing";
export * from "./editorials";
export * from "./usages";
+63
View File
@@ -0,0 +1,63 @@
import { integer, pgEnum, pgTable, text, timestamp, uniqueIndex, uuid, bigint } from "drizzle-orm/pg-core";
import { editorialAccounts } from "./editorials";
import { billingReports } from "./billing";
export const usageBillingStatuses = ["open", "billed", "reopened"] as const;
export const usageBillingStatus = pgEnum("usage_billing_status", usageBillingStatuses);
export const downloadStatuses = [
"authorized",
"streaming",
"completed",
"failed_before_delivery",
"interrupted",
] as const;
export const downloadStatus = pgEnum("download_status", downloadStatuses);
export const usages = pgTable("usages", {
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
immichAssetId: text("immich_asset_id").notNull(),
filenameSnapshot: text("filename_snapshot").notNull(),
immichAlbumIdSnapshot: text("immich_album_id_snapshot").notNull(),
albumNameSnapshot: text("album_name_snapshot").notNull(),
purpose: text("purpose").notNull(),
internalReference: text("internal_reference"),
priceCents: integer("price_cents").notNull(),
billingStatus: usageBillingStatus("billing_status").notNull().default("open"),
billingReportId: uuid("billing_report_id").references(() => billingReports.id, {
onDelete: "restrict",
}),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const downloadEvents = pgTable(
"download_events",
{
id: uuid("id").defaultRandom().primaryKey(),
editorialAccountId: uuid("editorial_account_id")
.notNull()
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
usageId: uuid("usage_id")
.notNull()
.references(() => usages.id, { onDelete: "restrict" }),
immichAssetId: text("immich_asset_id").notNull(),
authorizedAt: timestamp("authorized_at", { withTimezone: true }).notNull().defaultNow(),
startedAt: timestamp("started_at", { withTimezone: true }),
completedAt: timestamp("completed_at", { withTimezone: true }),
status: downloadStatus("status").notNull().default("authorized"),
transferredBytes: bigint("transferred_bytes", { mode: "number" }),
repeatDownloadNote: text("repeat_download_note"),
requestId: uuid("request_id").notNull(),
idempotencyKey: text("idempotency_key").notNull(),
},
(table) => [
uniqueIndex("download_events_editorial_idempotency_key_unique").on(
table.editorialAccountId,
table.idempotencyKey,
),
],
);