From 3584b4a7a7921250b1ff021df2ccf2e74e3a5193 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Sun, 9 Aug 2026 21:15:30 +0200 Subject: [PATCH] feat: add editorial approval and account guards --- src/app/admin/layout.tsx | 25 ++ src/app/admin/redaktionen/[id]/page.tsx | 74 +++++ src/app/admin/redaktionen/page.tsx | 47 +++ src/app/redaktion/profil/page.tsx | 61 ++++ src/modules/auth/principal.test.ts | 46 +++ src/modules/auth/principal.ts | 131 +++++++++ src/modules/editorials/service.test.ts | 113 +++++++ src/modules/editorials/service.ts | 376 ++++++++++++++++++++++++ src/modules/mail/mailer.ts | 6 +- 9 files changed, 878 insertions(+), 1 deletion(-) create mode 100644 src/app/admin/layout.tsx create mode 100644 src/app/admin/redaktionen/[id]/page.tsx create mode 100644 src/app/admin/redaktionen/page.tsx create mode 100644 src/app/redaktion/profil/page.tsx create mode 100644 src/modules/auth/principal.test.ts create mode 100644 src/modules/auth/principal.ts create mode 100644 src/modules/editorials/service.test.ts create mode 100644 src/modules/editorials/service.ts diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx new file mode 100644 index 0000000..9b5f245 --- /dev/null +++ b/src/app/admin/layout.tsx @@ -0,0 +1,25 @@ +import type { ReactNode } from "react"; + +import { headers } from "next/headers"; +import Link from "next/link"; + +import { requireAdmin } from "@/modules/auth/principal"; + +export default async function AdminLayout({ children }: Readonly<{ children: ReactNode }>) { + await requireAdmin(new Headers(await headers())); + + return ( +
+
+ + Leon Tonhäuser + + Administration +
+ + {children} +
+ ); +} diff --git a/src/app/admin/redaktionen/[id]/page.tsx b/src/app/admin/redaktionen/[id]/page.tsx new file mode 100644 index 0000000..dd2e7e0 --- /dev/null +++ b/src/app/admin/redaktionen/[id]/page.tsx @@ -0,0 +1,74 @@ +import { and, eq, isNull } from "drizzle-orm"; +import { notFound } from "next/navigation"; + +import { db } from "@/db/client"; +import { albumGrants, editorialAccounts } from "@/db/schema"; + +export default async function EditorialDetailPage({ + params, +}: Readonly<{ params: Promise<{ id: string }> }>) { + const { id } = await params; + const [editorial] = await db + .select({ + id: editorialAccounts.id, + name: editorialAccounts.name, + contactName: editorialAccounts.contactName, + loginEmail: editorialAccounts.loginEmail, + status: editorialAccounts.status, + emailVerifiedAt: editorialAccounts.emailVerifiedAt, + currentPriceCents: editorialAccounts.currentPriceCents, + }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, id)) + .limit(1); + if (!editorial) { + notFound(); + } + + const [grant] = await db + .select({ id: albumGrants.id }) + .from(albumGrants) + .where( + and(eq(albumGrants.editorialAccountId, editorial.id), isNull(albumGrants.revokedAt)), + ) + .limit(1); + + return ( +
+

Redaktion

+

{editorial.name}

+
+
Ansprechperson
+
{editorial.contactName}
+
Anmelde-E-Mail
+
{editorial.loginEmail}
+
Status
+
{editorial.status}
+
E-Mail bestätigt
+
{editorial.emailVerifiedAt ? "Ja" : "Nein"}
+
Individueller Nettopreis
+
+ {editorial.currentPriceCents === null + ? "Noch nicht festgelegt" + : formatCents(editorial.currentPriceCents)} +
+
+ +
+

Freigabe

+ +

+ {grant + ? "Die Freigabe bleibt bis zur Verwaltungsoberfläche für Albumrechte deaktiviert." + : "Eine Freigabe ist erst möglich, wenn mindestens ein aktives Albumrecht zugewiesen wurde. Die Verwaltung der Albumrechte folgt im nächsten Schritt."} +

+
+
+ ); +} + +function formatCents(cents: number): string { + return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100); +} diff --git a/src/app/admin/redaktionen/page.tsx b/src/app/admin/redaktionen/page.tsx new file mode 100644 index 0000000..c498233 --- /dev/null +++ b/src/app/admin/redaktionen/page.tsx @@ -0,0 +1,47 @@ +import { desc } from "drizzle-orm"; + +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; + +export default async function EditorialsPage() { + const editorials = await db + .select({ + id: editorialAccounts.id, + name: editorialAccounts.name, + contactName: editorialAccounts.contactName, + loginEmail: editorialAccounts.loginEmail, + status: editorialAccounts.status, + currentPriceCents: editorialAccounts.currentPriceCents, + createdAt: editorialAccounts.createdAt, + }) + .from(editorialAccounts) + .orderBy(desc(editorialAccounts.createdAt)); + + return ( +
+

Kontoverwaltung

+

Redaktionen

+ {editorials.length === 0 ? ( +

Noch keine Redaktionen registriert.

+ ) : ( + + )} +
+ ); +} + +function formatCents(cents: number): string { + return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100); +} diff --git a/src/app/redaktion/profil/page.tsx b/src/app/redaktion/profil/page.tsx new file mode 100644 index 0000000..1510157 --- /dev/null +++ b/src/app/redaktion/profil/page.tsx @@ -0,0 +1,61 @@ +import { eq } from "drizzle-orm"; +import { headers } from "next/headers"; + +import { db } from "@/db/client"; +import { billingAddressVersions, editorialAccounts } from "@/db/schema"; +import { requireActiveEditorial } from "@/modules/auth/principal"; + +export default async function EditorialProfilePage() { + const principal = await requireActiveEditorial(new Headers(await headers())); + const [editorial] = await db + .select({ + name: editorialAccounts.name, + contactName: editorialAccounts.contactName, + loginEmail: editorialAccounts.loginEmail, + addressLine1: billingAddressVersions.addressLine1, + addressLine2: billingAddressVersions.addressLine2, + postalCode: billingAddressVersions.postalCode, + city: billingAddressVersions.city, + countryCode: billingAddressVersions.countryCode, + }) + .from(editorialAccounts) + .leftJoin( + billingAddressVersions, + eq(editorialAccounts.currentBillingAddressVersionId, billingAddressVersions.id), + ) + .where(eq(editorialAccounts.id, principal.editorialId)) + .limit(1); + + return ( +
+
+

Redaktionskonto

+

Profil

+
+
Redaktion
+
{editorial?.name}
+
Ansprechperson
+
{editorial?.contactName}
+
Anmelde-E-Mail
+
{editorial?.loginEmail}
+
Rechnungsadresse
+
+ {editorial?.addressLine1 ? ( +
+ {editorial.addressLine1} + {editorial.addressLine2 ?
: null} + {editorial.addressLine2} +
+ {editorial.postalCode} {editorial.city} +
+ {editorial.countryCode} +
+ ) : ( + "Keine Rechnungsadresse hinterlegt." + )} +
+
+
+
+ ); +} diff --git a/src/modules/auth/principal.test.ts b/src/modules/auth/principal.test.ts new file mode 100644 index 0000000..02e1a33 --- /dev/null +++ b/src/modules/auth/principal.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from "vitest"; + +import { createPrincipalGuard } from "./principal"; + +const editorialSession = { + user: { id: "editorial-user", role: "EDITORIAL" as const }, +}; + +test("rejects a suspended editorial after session authentication", async () => { + const guard = createPrincipalGuard({ + getSession: async () => editorialSession, + getAccount: async () => ({ id: "editorial-1", status: "suspended" as const }), + }); + + await expect(guard.requireActiveEditorial(new Headers())).rejects.toMatchObject({ + code: "ACCOUNT_SUSPENDED", + }); +}); + +test("uses the authenticated session user to resolve an editorial principal", async () => { + let accountUserId: string | undefined; + const guard = createPrincipalGuard({ + getSession: async () => editorialSession, + getAccount: async (userId) => { + accountUserId = userId; + return { id: "editorial-1", status: "active" }; + }, + }); + + await expect(guard.requireActiveEditorial(new Headers({ "x-editorial-id": "forged" }))).resolves.toEqual({ + userId: "editorial-user", + role: "EDITORIAL", + editorialId: "editorial-1", + status: "active", + }); + expect(accountUserId).toBe("editorial-user"); +}); + +test("rejects non-admin users from the admin guard", async () => { + const guard = createPrincipalGuard({ + getSession: async () => editorialSession, + getAccount: async () => ({ id: "editorial-1", status: "active" as const }), + }); + + await expect(guard.requireAdmin(new Headers())).rejects.toMatchObject({ code: "ADMIN_REQUIRED" }); +}); diff --git a/src/modules/auth/principal.ts b/src/modules/auth/principal.ts new file mode 100644 index 0000000..b344578 --- /dev/null +++ b/src/modules/auth/principal.ts @@ -0,0 +1,131 @@ +import "server-only"; + +import { eq } from "drizzle-orm"; + +import { auth } from "@/modules/auth/auth"; +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; +import { accountStatuses } from "@/db/schema/editorials"; + +export type AccountStatus = (typeof accountStatuses)[number]; + +export type PortalPrincipal = { + userId: string; + role: "ADMIN" | "EDITORIAL"; + editorialId: string | null; + status: AccountStatus; +}; + +type Session = { user: { id: string; role: "ADMIN" | "EDITORIAL" } } | null; +type EditorialAccount = { id: string; status: AccountStatus } | null; + +export type PrincipalGuardDependencies = { + getSession(requestHeaders: Headers): Promise; + getAccount(userId: string): Promise; +}; + +export class PrincipalAuthorizationError extends Error { + readonly name = "PrincipalAuthorizationError"; + + constructor( + readonly code: + | "AUTHENTICATION_REQUIRED" + | "ADMIN_REQUIRED" + | "EDITORIAL_ACCOUNT_NOT_FOUND" + | "ACCOUNT_PENDING_EMAIL" + | "ACCOUNT_PENDING_APPROVAL" + | "ACCOUNT_SUSPENDED" + | "ACCOUNT_REJECTED", + ) { + super(code); + } +} + +export function createPrincipalGuard({ getSession, getAccount }: PrincipalGuardDependencies) { + async function getAuthenticatedSession(requestHeaders: Headers): Promise> { + const session = await getSession(requestHeaders); + if (!session) { + throw new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"); + } + return session; + } + + return { + async requireAdmin(requestHeaders: Headers): Promise { + const session = await getAuthenticatedSession(requestHeaders); + if (session.user.role !== "ADMIN") { + throw new PrincipalAuthorizationError("ADMIN_REQUIRED"); + } + + return { + userId: session.user.id, + role: "ADMIN", + editorialId: null, + status: "active", + }; + }, + + async requireActiveEditorial( + requestHeaders: Headers, + ): Promise { + const session = await getAuthenticatedSession(requestHeaders); + if (session.user.role !== "EDITORIAL") { + throw new PrincipalAuthorizationError("ADMIN_REQUIRED"); + } + + const account = await getAccount(session.user.id); + if (!account) { + throw new PrincipalAuthorizationError("EDITORIAL_ACCOUNT_NOT_FOUND"); + } + if (account.status !== "active") { + throw new PrincipalAuthorizationError(accountStatusErrorCode(account.status)); + } + + return { + userId: session.user.id, + role: "EDITORIAL", + editorialId: account.id, + status: account.status, + }; + }, + }; +} + +function accountStatusErrorCode( + status: Exclude, +): PrincipalAuthorizationError["code"] { + const codes = { + pending_email: "ACCOUNT_PENDING_EMAIL", + pending_approval: "ACCOUNT_PENDING_APPROVAL", + suspended: "ACCOUNT_SUSPENDED", + rejected: "ACCOUNT_REJECTED", + } as const; + return codes[status]; +} + +export const principalGuard = createPrincipalGuard({ + async getSession(requestHeaders) { + const session = await auth.api.getSession({ headers: requestHeaders }); + if (!session) { + return null; + } + + const role = (session.user as { role?: unknown }).role; + if (role !== "ADMIN" && role !== "EDITORIAL") { + return null; + } + return { user: { id: session.user.id, role } }; + }, + + async getAccount(userId) { + const [account] = await db + .select({ id: editorialAccounts.id, status: editorialAccounts.status }) + .from(editorialAccounts) + .where(eq(editorialAccounts.userId, userId)) + .limit(1); + return account ?? null; + }, +}); + +export const requireAdmin = principalGuard.requireAdmin; +export const requireActiveEditorial = principalGuard.requireActiveEditorial; diff --git a/src/modules/editorials/service.test.ts b/src/modules/editorials/service.test.ts new file mode 100644 index 0000000..3f61cc5 --- /dev/null +++ b/src/modules/editorials/service.test.ts @@ -0,0 +1,113 @@ +import { expect, test, vi } from "vitest"; + +import { + createEditorialService, + type EditorialServiceRepository, +} from "./service"; + +function createRepository(): EditorialServiceRepository & { + prepareApproval: ReturnType; + recordApprovalNoticeSent: ReturnType; + recordApprovalNoticeFailure: ReturnType; + replaceBillingAddress: ReturnType; + transitionStatus: ReturnType; +} { + return { + prepareApproval: vi.fn().mockResolvedValue({ + editorialId: "e1", + to: "editorial@example.com", + editorialName: "Neue Redaktion", + }), + recordApprovalNoticeSent: vi.fn().mockResolvedValue(undefined), + recordApprovalNoticeFailure: vi.fn().mockResolvedValue(undefined), + replaceBillingAddress: vi.fn().mockResolvedValue("address-2"), + transitionStatus: vi.fn().mockResolvedValue(undefined), + }; +} + +test("approval requires a positive price in cents", async () => { + const repository = createRepository(); + const service = createEditorialService({ + repository, + mailer: { sendApprovalNotice: vi.fn() }, + }); + + await expect( + service.approveEditorial({ editorialId: "e1", priceCents: 0, adminUserId: "a1" }), + ).rejects.toMatchObject({ code: "INVALID_PRICE" }); + expect(repository.prepareApproval).not.toHaveBeenCalled(); +}); + +test("approval activates the account and sends the approval notice", async () => { + const repository = createRepository(); + const mailer = { sendApprovalNotice: vi.fn().mockResolvedValue(undefined) }; + const service = createEditorialService({ repository, mailer }); + + await service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }); + + expect(repository.prepareApproval).toHaveBeenCalledWith({ + editorialId: "e1", + priceCents: 1500, + adminUserId: "a1", + }); + expect(mailer.sendApprovalNotice).toHaveBeenCalledWith( + expect.objectContaining({ editorialId: "e1" }), + ); + expect(repository.recordApprovalNoticeSent).toHaveBeenCalledWith({ + editorialId: "e1", + adminUserId: "a1", + }); +}); + +test("records a failed approval notice without undoing approval", async () => { + const repository = createRepository(); + const mailer = { sendApprovalNotice: vi.fn().mockRejectedValue(new Error("SMTP unavailable")) }; + const service = createEditorialService({ repository, mailer }); + + await expect( + service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }), + ).rejects.toThrow("SMTP unavailable"); + expect(repository.recordApprovalNoticeFailure).toHaveBeenCalledWith({ + editorialId: "e1", + adminUserId: "a1", + }); +}); + +test("rejects approval until an active album grant exists", async () => { + const repository = createRepository(); + repository.prepareApproval.mockRejectedValueOnce( + Object.assign(new Error("Album grant required"), { code: "ALBUM_GRANT_REQUIRED" }), + ); + const service = createEditorialService({ repository, mailer: { sendApprovalNotice: vi.fn() } }); + + await expect( + service.approveEditorial({ editorialId: "e1", priceCents: 1500, adminUserId: "a1" }), + ).rejects.toMatchObject({ code: "ALBUM_GRANT_REQUIRED" }); +}); + +test("creates a new billing-address version instead of changing an existing address", async () => { + const repository = createRepository(); + const service = createEditorialService({ repository, mailer: { sendApprovalNotice: vi.fn() } }); + + await expect( + service.replaceBillingAddress("e1", { + companyName: "Neue Redaktion GmbH", + contactName: "Neue Ansprechperson", + addressLine1: "Presseweg 2", + postalCode: "10115", + city: "Berlin", + countryCode: "de", + }), + ).resolves.toBe("address-2"); + expect(repository.replaceBillingAddress).toHaveBeenCalledWith({ + editorialId: "e1", + input: { + companyName: "Neue Redaktion GmbH", + contactName: "Neue Ansprechperson", + addressLine1: "Presseweg 2", + postalCode: "10115", + city: "Berlin", + countryCode: "DE", + }, + }); +}); diff --git a/src/modules/editorials/service.ts b/src/modules/editorials/service.ts new file mode 100644 index 0000000..a687c65 --- /dev/null +++ b/src/modules/editorials/service.ts @@ -0,0 +1,376 @@ +import "server-only"; + +import { and, desc, eq, inArray, isNull } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { + albumGrants, + auditEvents, + billingAddressVersions, + editorialAccounts, +} from "@/db/schema"; +import type * as schema from "@/db/schema"; +import type { AccountStatus } from "@/modules/auth/principal"; +import { mailer, type Mailer } from "@/modules/mail/mailer"; + +export type BillingAddressInput = { + companyName: string; + contactName: string; + addressLine1: string; + addressLine2?: string; + postalCode: string; + city: string; + countryCode: string; +}; + +type ApprovalNotice = { + editorialId: string; + to: string; + editorialName: string; +}; + +export type EditorialServiceRepository = { + prepareApproval(input: { + editorialId: string; + priceCents: number; + adminUserId: string; + }): Promise; + recordApprovalNoticeSent(input: { editorialId: string; adminUserId: string }): Promise; + recordApprovalNoticeFailure(input: { editorialId: string; adminUserId: string }): Promise; + replaceBillingAddress(input: { + editorialId: string; + input: BillingAddressInput; + }): Promise; + transitionStatus(input: { + editorialId: string; + from: AccountStatus; + to: AccountStatus; + adminUserId: string; + }): Promise; +}; + +export class EditorialServiceError extends Error { + readonly name = "EditorialServiceError"; + + constructor( + readonly code: + | "INVALID_PRICE" + | "INVALID_ADDRESS" + | "EDITORIAL_NOT_FOUND" + | "EMAIL_NOT_VERIFIED" + | "ALBUM_GRANT_REQUIRED" + | "APPROVAL_NOTICE_DELIVERY_UNKNOWN" + | "INVALID_ACCOUNT_TRANSITION", + ) { + super(code); + } +} + +export function createEditorialService({ + repository, + mailer: mailerService, +}: { + repository: EditorialServiceRepository; + mailer: Pick; +}) { + return { + async approveEditorial(input: { + editorialId: string; + priceCents: number; + adminUserId: string; + }): Promise { + if (!Number.isSafeInteger(input.priceCents) || input.priceCents <= 0) { + throw new EditorialServiceError("INVALID_PRICE"); + } + + const notice = await repository.prepareApproval(input); + if (!notice) { + return; + } + + try { + await mailerService.sendApprovalNotice(notice); + } catch (error) { + try { + await repository.recordApprovalNoticeFailure({ + editorialId: input.editorialId, + adminUserId: input.adminUserId, + }); + } catch { + // Preserve the SMTP failure for the caller; approval is already committed. + } + throw error; + } + + await repository.recordApprovalNoticeSent({ + editorialId: input.editorialId, + adminUserId: input.adminUserId, + }); + }, + + async replaceBillingAddress(editorialId: string, input: BillingAddressInput): Promise { + return repository.replaceBillingAddress({ editorialId, input: validateBillingAddress(input) }); + }, + + async transitionEditorialStatus(input: { + editorialId: string; + from: AccountStatus; + to: AccountStatus; + adminUserId: string; + }): Promise { + if (!isAllowedTransition(input.from, input.to)) { + throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); + } + await repository.transitionStatus(input); + }, + }; +} + +export function createEditorialServiceRepository( + database: NodePgDatabase, +): EditorialServiceRepository { + return { + async prepareApproval({ editorialId, priceCents, adminUserId }) { + return database.transaction(async (transaction) => { + const [editorial] = await transaction + .select({ + id: editorialAccounts.id, + status: editorialAccounts.status, + emailVerifiedAt: editorialAccounts.emailVerifiedAt, + loginEmail: editorialAccounts.loginEmail, + name: editorialAccounts.name, + }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)) + .limit(1); + + if (!editorial) { + throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); + } + + const notice = { + editorialId: editorial.id, + to: editorial.loginEmail, + editorialName: editorial.name, + }; + + if (editorial.status === "active") { + const [delivery] = await transaction + .select({ eventType: auditEvents.eventType }) + .from(auditEvents) + .where( + and( + eq(auditEvents.entityType, "editorial_account"), + eq(auditEvents.entityId, editorial.id), + inArray(auditEvents.eventType, [ + "editorial_approval_notice_dispatch_started", + "editorial_approval_notice_sent", + "editorial_approval_notice_failed", + ]), + ), + ) + .orderBy(desc(auditEvents.occurredAt)) + .limit(1); + if (delivery?.eventType === "editorial_approval_notice_sent") { + return null; + } + if (delivery?.eventType === "editorial_approval_notice_dispatch_started") { + throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN"); + } + await transaction.insert(auditEvents).values({ + eventType: "editorial_approval_notice_dispatch_started", + actorUserId: adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorial.id, + newValues: { delivery: "dispatching" }, + }); + return notice; + } + + if (editorial.status !== "pending_approval") { + throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); + } + if (!editorial.emailVerifiedAt) { + throw new EditorialServiceError("EMAIL_NOT_VERIFIED"); + } + + const [grant] = await transaction + .select({ id: albumGrants.id }) + .from(albumGrants) + .where( + and( + eq(albumGrants.editorialAccountId, editorial.id), + isNull(albumGrants.revokedAt), + ), + ) + .limit(1); + if (!grant) { + throw new EditorialServiceError("ALBUM_GRANT_REQUIRED"); + } + + const approvedAt = new Date(); + const [approved] = await transaction + .update(editorialAccounts) + .set({ status: "active", currentPriceCents: priceCents, updatedAt: approvedAt }) + .where( + and( + eq(editorialAccounts.id, editorial.id), + eq(editorialAccounts.status, "pending_approval"), + ), + ) + .returning({ id: editorialAccounts.id }); + if (!approved) { + throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); + } + + await transaction.insert(auditEvents).values({ + eventType: "editorial_approved", + actorUserId: adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorial.id, + previousValues: { status: "pending_approval" }, + newValues: { status: "active", priceCents }, + occurredAt: approvedAt, + }); + await transaction.insert(auditEvents).values({ + eventType: "editorial_approval_notice_dispatch_started", + actorUserId: adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorial.id, + newValues: { delivery: "dispatching" }, + occurredAt: approvedAt, + }); + return notice; + }); + }, + + async recordApprovalNoticeSent({ editorialId, adminUserId }) { + await database.insert(auditEvents).values({ + eventType: "editorial_approval_notice_sent", + actorUserId: adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorialId, + newValues: { delivery: "sent" }, + }); + }, + + async recordApprovalNoticeFailure({ editorialId, adminUserId }) { + await database.insert(auditEvents).values({ + eventType: "editorial_approval_notice_failed", + actorUserId: adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorialId, + newValues: { delivery: "failed" }, + }); + }, + + async replaceBillingAddress({ editorialId, input }) { + return database.transaction(async (transaction) => { + const [editorial] = await transaction + .select({ id: editorialAccounts.id }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)) + .limit(1); + if (!editorial) { + throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); + } + + const changedAt = new Date(); + const [address] = await transaction + .insert(billingAddressVersions) + .values({ + editorialAccountId: editorial.id, + ...input, + validFrom: changedAt, + }) + .returning({ id: billingAddressVersions.id }); + + await transaction + .update(editorialAccounts) + .set({ currentBillingAddressVersionId: address.id, updatedAt: changedAt }) + .where(eq(editorialAccounts.id, editorial.id)); + return address.id; + }); + }, + + async transitionStatus({ editorialId, from, to, adminUserId }) { + await database.transaction(async (transaction) => { + const changedAt = new Date(); + const [changed] = await transaction + .update(editorialAccounts) + .set({ status: to, updatedAt: changedAt }) + .where( + and(eq(editorialAccounts.id, editorialId), eq(editorialAccounts.status, from)), + ) + .returning({ id: editorialAccounts.id }); + if (!changed) { + throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); + } + + await transaction.insert(auditEvents).values({ + eventType: "editorial_status_changed", + actorUserId: adminUserId, + actorType: "admin", + entityType: "editorial_account", + entityId: editorialId, + previousValues: { status: from }, + newValues: { status: to }, + occurredAt: changedAt, + }); + }); + }, + }; +} + +function validateBillingAddress(input: BillingAddressInput): BillingAddressInput { + const companyName = trim(input.companyName); + const contactName = trim(input.contactName); + const addressLine1 = trim(input.addressLine1); + const addressLine2 = trim(input.addressLine2) || undefined; + const postalCode = trim(input.postalCode); + const city = trim(input.city); + const countryCode = trim(input.countryCode).toUpperCase(); + if ( + !companyName || + !contactName || + !addressLine1 || + !postalCode || + !city || + !/^[A-Z]{2}$/.test(countryCode) + ) { + throw new EditorialServiceError("INVALID_ADDRESS"); + } + return { + companyName, + contactName, + addressLine1, + ...(addressLine2 ? { addressLine2 } : {}), + postalCode, + city, + countryCode, + }; +} + +function trim(value: unknown): string { + return typeof value === "string" ? value.trim() : ""; +} + +function isAllowedTransition(from: AccountStatus, to: AccountStatus): boolean { + return ( + (from === "pending_approval" && (to === "active" || to === "rejected")) || + (from === "active" && to === "suspended") || + (from === "suspended" && to === "active") || + (from === "pending_email" && to === "rejected") + ); +} + +export const editorialService = createEditorialService({ + repository: createEditorialServiceRepository(db), + mailer, +}); diff --git a/src/modules/mail/mailer.ts b/src/modules/mail/mailer.ts index 0c79d78..8d34b9f 100644 --- a/src/modules/mail/mailer.ts +++ b/src/modules/mail/mailer.ts @@ -18,7 +18,11 @@ export type MailTransport = { export type Mailer = { sendVerification(input: { to: string; verificationUrl: string }): Promise; sendPasswordReset(input: { to: string; resetUrl: string }): Promise; - sendApprovalNotice(input: { to: string; editorialName: string }): Promise; + sendApprovalNotice(input: { + to: string; + editorialName: string; + editorialId?: string; + }): Promise; }; export function createMailer({ from, transport }: { from: string; transport: MailTransport }): Mailer {