feat: add editorial approval and account guards

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 21:15:30 +02:00
1 parent a8d4e54ffb
commit 3584b4a7a7
9 files changed
+878 -1

No files matched your search

+25
View File
@@ -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 (
<main className="portal-shell">
<header className="masthead">
<Link className="wordmark" href="/admin">
Leon Tonhäuser
</Link>
<span className="section-label">Administration</span>
</header>
<nav aria-label="Administration">
<Link href="/admin/redaktionen">Redaktionen</Link>
</nav>
{children}
</main>
);
}
+74
View File
@@ -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 (
<section className="content-section" aria-labelledby="editorial-title">
<p className="eyebrow">Redaktion</p>
<h1 id="editorial-title">{editorial.name}</h1>
<dl>
<dt>Ansprechperson</dt>
<dd>{editorial.contactName}</dd>
<dt>Anmelde-E-Mail</dt>
<dd>{editorial.loginEmail}</dd>
<dt>Status</dt>
<dd>{editorial.status}</dd>
<dt>E-Mail bestätigt</dt>
<dd>{editorial.emailVerifiedAt ? "Ja" : "Nein"}</dd>
<dt>Individueller Nettopreis</dt>
<dd>
{editorial.currentPriceCents === null
? "Noch nicht festgelegt"
: formatCents(editorial.currentPriceCents)}
</dd>
</dl>
<section aria-labelledby="approval-title">
<h2 id="approval-title">Freigabe</h2>
<button type="button" disabled aria-describedby="approval-help">
Redaktion freigeben
</button>
<p id="approval-help">
{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."}
</p>
</section>
</section>
);
}
function formatCents(cents: number): string {
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
}
+47
View File
@@ -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 (
<section className="content-section" aria-labelledby="editorials-title">
<p className="eyebrow">Kontoverwaltung</p>
<h1 id="editorials-title">Redaktionen</h1>
{editorials.length === 0 ? (
<p>Noch keine Redaktionen registriert.</p>
) : (
<ul>
{editorials.map((editorial) => (
<li key={editorial.id}>
<a href={`/admin/redaktionen/${editorial.id}`}>{editorial.name}</a>
<p>
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
{editorial.currentPriceCents === null
? " · Preis noch nicht festgelegt"
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
</p>
</li>
))}
</ul>
)}
</section>
);
}
function formatCents(cents: number): string {
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
}
+61
View File
@@ -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 (
<main className="portal-shell">
<section className="content-section" aria-labelledby="profile-title">
<p className="eyebrow">Redaktionskonto</p>
<h1 id="profile-title">Profil</h1>
<dl>
<dt>Redaktion</dt>
<dd>{editorial?.name}</dd>
<dt>Ansprechperson</dt>
<dd>{editorial?.contactName}</dd>
<dt>Anmelde-E-Mail</dt>
<dd>{editorial?.loginEmail}</dd>
<dt>Rechnungsadresse</dt>
<dd>
{editorial?.addressLine1 ? (
<address>
{editorial.addressLine1}
{editorial.addressLine2 ? <br /> : null}
{editorial.addressLine2}
<br />
{editorial.postalCode} {editorial.city}
<br />
{editorial.countryCode}
</address>
) : (
"Keine Rechnungsadresse hinterlegt."
)}
</dd>
</dl>
</section>
</main>
);
}
+46
View File
@@ -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" });
});
+131
View File
@@ -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<Session>;
getAccount(userId: string): Promise<EditorialAccount>;
};
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<NonNullable<Session>> {
const session = await getSession(requestHeaders);
if (!session) {
throw new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED");
}
return session;
}
return {
async requireAdmin(requestHeaders: Headers): Promise<PortalPrincipal> {
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<PortalPrincipal & { editorialId: string }> {
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<AccountStatus, "active">,
): 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;
+113
View File
@@ -0,0 +1,113 @@
import { expect, test, vi } from "vitest";
import {
createEditorialService,
type EditorialServiceRepository,
} from "./service";
function createRepository(): EditorialServiceRepository & {
prepareApproval: ReturnType<typeof vi.fn>;
recordApprovalNoticeSent: ReturnType<typeof vi.fn>;
recordApprovalNoticeFailure: ReturnType<typeof vi.fn>;
replaceBillingAddress: ReturnType<typeof vi.fn>;
transitionStatus: ReturnType<typeof vi.fn>;
} {
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",
},
});
});
+376
View File
@@ -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<ApprovalNotice | null>;
recordApprovalNoticeSent(input: { editorialId: string; adminUserId: string }): Promise<void>;
recordApprovalNoticeFailure(input: { editorialId: string; adminUserId: string }): Promise<void>;
replaceBillingAddress(input: {
editorialId: string;
input: BillingAddressInput;
}): Promise<string>;
transitionStatus(input: {
editorialId: string;
from: AccountStatus;
to: AccountStatus;
adminUserId: string;
}): Promise<void>;
};
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<Mailer, "sendApprovalNotice">;
}) {
return {
async approveEditorial(input: {
editorialId: string;
priceCents: number;
adminUserId: string;
}): Promise<void> {
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<string> {
return repository.replaceBillingAddress({ editorialId, input: validateBillingAddress(input) });
},
async transitionEditorialStatus(input: {
editorialId: string;
from: AccountStatus;
to: AccountStatus;
adminUserId: string;
}): Promise<void> {
if (!isAllowedTransition(input.from, input.to)) {
throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION");
}
await repository.transitionStatus(input);
},
};
}
export function createEditorialServiceRepository(
database: NodePgDatabase<typeof schema>,
): 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,
});
+5 -1
View File
@@ -18,7 +18,11 @@ export type MailTransport = {
export type Mailer = { export type Mailer = {
sendVerification(input: { to: string; verificationUrl: string }): Promise<void>; sendVerification(input: { to: string; verificationUrl: string }): Promise<void>;
sendPasswordReset(input: { to: string; resetUrl: string }): Promise<void>; sendPasswordReset(input: { to: string; resetUrl: string }): Promise<void>;
sendApprovalNotice(input: { to: string; editorialName: string }): Promise<void>; sendApprovalNotice(input: {
to: string;
editorialName: string;
editorialId?: string;
}): Promise<void>;
}; };
export function createMailer({ from, transport }: { from: string; transport: MailTransport }): Mailer { export function createMailer({ from, transport }: { from: string; transport: MailTransport }): Mailer {