feat: add portal database schema
This commit is contained in:
1 parent
763098b129
commit
7acaacb92e
17 files changed
+4410
-111
No files matched your search
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "postgresql",
|
||||
schema: "./src/db/schema/index.ts",
|
||||
out: "./drizzle",
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL ?? "postgresql://portal:portal@localhost:5432/portal",
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
CREATE TYPE "public"."portal_role" AS ENUM('ADMIN', 'EDITORIAL');--> statement-breakpoint
|
||||
CREATE TYPE "public"."report_status" AS ENUM('draft', 'final', 'cancelled');--> statement-breakpoint
|
||||
CREATE TYPE "public"."account_status" AS ENUM('pending_email', 'pending_approval', 'active', 'suspended', 'rejected');--> statement-breakpoint
|
||||
CREATE TYPE "public"."download_status" AS ENUM('authorized', 'streaming', 'completed', 'failed_before_delivery', 'interrupted');--> statement-breakpoint
|
||||
CREATE TYPE "public"."usage_billing_status" AS ENUM('open', 'billed', 'reopened');--> statement-breakpoint
|
||||
CREATE TABLE "album_grants" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"immich_album_id" text NOT NULL,
|
||||
"granted_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"revoked_at" timestamp with time zone,
|
||||
"granted_by_user_id" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "audit_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"event_type" text NOT NULL,
|
||||
"actor_user_id" uuid,
|
||||
"actor_type" text DEFAULT 'system' NOT NULL,
|
||||
"entity_type" text NOT NULL,
|
||||
"entity_id" text NOT NULL,
|
||||
"previous_values" jsonb,
|
||||
"new_values" jsonb,
|
||||
"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"request_id" uuid
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "account" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"account_id" text NOT NULL,
|
||||
"provider_id" text NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"access_token" text,
|
||||
"refresh_token" text,
|
||||
"id_token" text,
|
||||
"access_token_expires_at" timestamp with time zone,
|
||||
"refresh_token_expires_at" timestamp with time zone,
|
||||
"scope" text,
|
||||
"password" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "session" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"token" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"ip_address" text,
|
||||
"user_agent" text,
|
||||
"user_id" uuid NOT NULL,
|
||||
CONSTRAINT "session_token_unique" UNIQUE("token")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "user" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"email" text NOT NULL,
|
||||
"email_verified" boolean DEFAULT false NOT NULL,
|
||||
"image" text,
|
||||
"role" "portal_role" DEFAULT 'EDITORIAL' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "user_email_unique" UNIQUE("email")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "verification" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"identifier" text NOT NULL,
|
||||
"value" text NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "billing_report_items" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"billing_report_id" uuid NOT NULL,
|
||||
"usage_id" uuid NOT NULL,
|
||||
"immich_asset_id_snapshot" text NOT NULL,
|
||||
"filename_snapshot" text NOT NULL,
|
||||
"album_name_snapshot" text NOT NULL,
|
||||
"purpose_snapshot" text NOT NULL,
|
||||
"internal_reference_snapshot" text,
|
||||
"price_cents" integer NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "billing_reports" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"report_number" integer NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"period_starts_at" timestamp with time zone NOT NULL,
|
||||
"period_ends_at" timestamp with time zone NOT NULL,
|
||||
"billing_address_snapshot" jsonb NOT NULL,
|
||||
"invoice_number" text,
|
||||
"net_total_cents" integer NOT NULL,
|
||||
"status" "report_status" DEFAULT 'draft' NOT NULL,
|
||||
"pdf" "bytea",
|
||||
"pdf_sha256" varchar(64),
|
||||
"created_by_user_id" uuid NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"finalized_at" timestamp with time zone,
|
||||
"cancelled_at" timestamp with time zone,
|
||||
"cancellation_reason" text,
|
||||
"cancelled_by_user_id" uuid,
|
||||
CONSTRAINT "billing_reports_pdf_sha256_hex_check" CHECK ("billing_reports"."pdf_sha256" ~ '^[0-9a-f]{64}$'),
|
||||
CONSTRAINT "billing_reports_final_pdf_check" CHECK ("billing_reports"."status" <> 'final' OR ("billing_reports"."pdf" IS NOT NULL AND "billing_reports"."pdf_sha256" IS NOT NULL))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "billing_address_versions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"company_name" text NOT NULL,
|
||||
"contact_name" text NOT NULL,
|
||||
"address_line_1" text NOT NULL,
|
||||
"address_line_2" text,
|
||||
"postal_code" text NOT NULL,
|
||||
"city" text NOT NULL,
|
||||
"country_code" text NOT NULL,
|
||||
"valid_from" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"superseded_by_id" uuid,
|
||||
"created_by_user_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "editorial_accounts" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"contact_name" text NOT NULL,
|
||||
"login_email" text NOT NULL,
|
||||
"status" "account_status" DEFAULT 'pending_email' NOT NULL,
|
||||
"current_price_cents" integer,
|
||||
"current_billing_address_version_id" uuid,
|
||||
"email_verified_at" timestamp with time zone,
|
||||
"accepted_terms_version" text,
|
||||
"accepted_terms_at" timestamp with time zone,
|
||||
"privacy_acknowledged_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "editorial_accounts_user_id_unique" UNIQUE("user_id"),
|
||||
CONSTRAINT "editorial_accounts_login_email_unique" UNIQUE("login_email")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "download_events" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"usage_id" uuid NOT NULL,
|
||||
"immich_asset_id" text NOT NULL,
|
||||
"authorized_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"started_at" timestamp with time zone,
|
||||
"completed_at" timestamp with time zone,
|
||||
"status" "download_status" DEFAULT 'authorized' NOT NULL,
|
||||
"transferred_bytes" bigint,
|
||||
"repeat_download_note" text,
|
||||
"request_id" uuid NOT NULL,
|
||||
"idempotency_key" text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "usages" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"editorial_account_id" uuid NOT NULL,
|
||||
"immich_asset_id" text NOT NULL,
|
||||
"filename_snapshot" text NOT NULL,
|
||||
"immich_album_id_snapshot" text NOT NULL,
|
||||
"album_name_snapshot" text NOT NULL,
|
||||
"purpose" text NOT NULL,
|
||||
"internal_reference" text,
|
||||
"price_cents" integer NOT NULL,
|
||||
"billing_status" "usage_billing_status" DEFAULT 'open' NOT NULL,
|
||||
"billing_report_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_granted_by_user_id_user_id_fk" FOREIGN KEY ("granted_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "audit_events" ADD CONSTRAINT "audit_events_actor_user_id_user_id_fk" FOREIGN KEY ("actor_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_cancelled_by_user_id_user_id_fk" FOREIGN KEY ("cancelled_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_superseded_by_id_billing_address_versions_id_fk" FOREIGN KEY ("superseded_by_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk" FOREIGN KEY ("current_billing_address_version_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "usages" ADD CONSTRAINT "usages_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "usages" ADD CONSTRAINT "usages_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "album_grants_editorial_account_id_idx" ON "album_grants" USING btree ("editorial_account_id");--> statement-breakpoint
|
||||
CREATE INDEX "album_grants_immich_album_id_idx" ON "album_grants" USING btree ("immich_album_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "billing_report_items_report_usage_unique" ON "billing_report_items" USING btree ("billing_report_id","usage_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "billing_reports_report_number_unique" ON "billing_reports" USING btree ("report_number");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "billing_reports_invoice_number_unique" ON "billing_reports" USING btree ("invoice_number");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "download_events_editorial_idempotency_key_unique" ON "download_events" USING btree ("editorial_account_id","idempotency_key");
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1786299825190,
|
||||
"tag": "0000_initial",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -16,7 +16,9 @@
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"next": "^16.3.0",
|
||||
"pg": "^8.22.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"server-only": "^0.0.1",
|
||||
@@ -24,16 +26,20 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@testcontainers/postgresql": "^12.1.0",
|
||||
"@testing-library/jest-dom": "^7.0.0",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/pg": "^8.21.0",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^6.0.5",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-next": "^16.3.0",
|
||||
"jsdom": "^30.0.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"testcontainers": "^12.1.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
|
||||
Generated
+2279
-110
File diff suppressed because it is too large.
Load diff
@@ -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 });
|
||||
@@ -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),
|
||||
],
|
||||
);
|
||||
@@ -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"),
|
||||
});
|
||||
@@ -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(),
|
||||
});
|
||||
@@ -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,
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -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",
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./albums";
|
||||
export * from "./audit";
|
||||
export * from "./auth";
|
||||
export * from "./billing";
|
||||
export * from "./editorials";
|
||||
export * from "./usages";
|
||||
@@ -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,
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -0,0 +1,97 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { PostgreSqlContainer, type StartedPostgreSqlContainer } from "@testcontainers/postgresql";
|
||||
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
import { Pool } from "pg";
|
||||
|
||||
import * as schema from "@/db/schema";
|
||||
|
||||
type DownloadSeed = {
|
||||
editorialId: string;
|
||||
usageId: string;
|
||||
assetId: string;
|
||||
};
|
||||
|
||||
export type PostgresTestDatabase = {
|
||||
seedEditorialWithUsage(): Promise<DownloadSeed>;
|
||||
insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
};
|
||||
|
||||
export async function startPostgres(): Promise<PostgresTestDatabase> {
|
||||
const container = await new PostgreSqlContainer("postgres:17-alpine")
|
||||
.withDatabase("portal")
|
||||
.withUsername("portal")
|
||||
.withPassword("portal")
|
||||
.start();
|
||||
const pool = new Pool({ connectionString: container.getConnectionUri() });
|
||||
|
||||
await applyMigration(pool);
|
||||
|
||||
const db = drizzle({ client: pool, schema });
|
||||
|
||||
return {
|
||||
async seedEditorialWithUsage() {
|
||||
return seedEditorialWithUsage(db);
|
||||
},
|
||||
async insertDownload(input) {
|
||||
await db.insert(schema.downloadEvents).values({
|
||||
editorialAccountId: input.editorialId,
|
||||
usageId: input.usageId,
|
||||
immichAssetId: input.assetId,
|
||||
requestId: randomUUID(),
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
});
|
||||
},
|
||||
async stop() {
|
||||
await pool.end();
|
||||
await stopContainer(container);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function applyMigration(pool: Pool) {
|
||||
const migration = await readFile(path.join(process.cwd(), "drizzle/0000_initial.sql"), "utf8");
|
||||
await pool.query(migration);
|
||||
}
|
||||
|
||||
async function seedEditorialWithUsage(db: NodePgDatabase<typeof schema>): Promise<DownloadSeed> {
|
||||
const userId = randomUUID();
|
||||
const editorialId = randomUUID();
|
||||
const usageId = randomUUID();
|
||||
const assetId = "immich-asset-1";
|
||||
|
||||
await db.insert(schema.users).values({
|
||||
id: userId,
|
||||
name: "Test Redaktion",
|
||||
email: `test-${userId}@example.com`,
|
||||
emailVerified: true,
|
||||
});
|
||||
await db.insert(schema.editorialAccounts).values({
|
||||
id: editorialId,
|
||||
userId,
|
||||
name: "Test Redaktion",
|
||||
contactName: "Testkontakt",
|
||||
loginEmail: `test-${userId}@example.com`,
|
||||
status: "active",
|
||||
currentPriceCents: 1500,
|
||||
});
|
||||
await db.insert(schema.usages).values({
|
||||
id: usageId,
|
||||
editorialAccountId: editorialId,
|
||||
immichAssetId: assetId,
|
||||
filenameSnapshot: "bild.jpg",
|
||||
immichAlbumIdSnapshot: "immich-album-1",
|
||||
albumNameSnapshot: "Presse",
|
||||
purpose: "Artikel",
|
||||
priceCents: 1500,
|
||||
});
|
||||
|
||||
return { editorialId, usageId, assetId };
|
||||
}
|
||||
|
||||
async function stopContainer(container: StartedPostgreSqlContainer) {
|
||||
await container.stop();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { afterAll, expect, test } from "vitest";
|
||||
import { startPostgres } from "./postgres";
|
||||
|
||||
const testDb = await startPostgres();
|
||||
|
||||
afterAll(() => testDb.stop());
|
||||
|
||||
test("rejects duplicate download idempotency keys for one editorial", async () => {
|
||||
const seed = await testDb.seedEditorialWithUsage();
|
||||
|
||||
await testDb.insertDownload({ ...seed, idempotencyKey: "same-request" });
|
||||
|
||||
await expect(
|
||||
testDb.insertDownload({ ...seed, idempotencyKey: "same-request" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
+2
-1
@@ -7,6 +7,7 @@ const rootDirectory = path.dirname(fileURLToPath(import.meta.url));
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.join(rootDirectory, "src"),
|
||||
"server-only": path.join(rootDirectory, "src/test/server-only.ts"),
|
||||
},
|
||||
},
|
||||
@@ -27,6 +28,6 @@ export default defineConfig({
|
||||
LEGAL_PRIVACY_URL: "https://example.com/datenschutz",
|
||||
LEGAL_TERMS_URL: "https://example.com/nutzungsbedingungen",
|
||||
},
|
||||
include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
|
||||
include: ["src/**/*.test.ts", "src/**/*.test.tsx", "tests/**/*.test.ts"],
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user