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