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

+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,
});