feat: add editorial approval and account guards
This commit is contained in:
1 parent
a8d4e54ffb
commit
3584b4a7a7
9 files changed
+878
-1
No files matched your search
@@ -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" });
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
@@ -18,7 +18,11 @@ export type MailTransport = {
|
||||
export type Mailer = {
|
||||
sendVerification(input: { to: string; verificationUrl: 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 {
|
||||
|
||||
Reference in new issue
Block a user