import "server-only"; import { and, eq, inArray, isNull, sql } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; import { albumGrants, auditEvents, billingAddressVersions, editorialAccounts, downloadEvents, usages, lightboxItems, billingReports, billingReportItems, albumAutoRules, } from "@/db/schema"; import type * as schema from "@/db/schema"; import type { AccountStatus } from "@/modules/auth/principal"; import { writeAudit } from "@/modules/audit/write"; 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; claimApprovalNotice(input: { editorialId: string; 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; archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise; unarchiveEditorial(input: { editorialId: string; adminUserId: string; }): Promise<{ restoredGrants: number }>; hardDeleteEditorial(editorialId: string): Promise; resetUsageData(input: { editorialId: string; adminUserId: string; }): Promise<{ deletedUsages: number; deletedReports: number }>; }; /** * All editorial/grant mutations must take these locks in this exact order. * Task 6 grant and revocation transactions must use the same order. */ export const EDITORIAL_MUTATION_LOCK_ORDER = [ "pg_advisory_xact_lock(editorial account)", "editorial_accounts FOR UPDATE", "album_grants FOR UPDATE", ] as const; 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" | "EDITORIAL_NOT_ARCHIVED", ) { 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 || !(await repository.claimApprovalNotice(input))) { 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 { const addressId = await repository.replaceBillingAddress({ editorialId, input: validateBillingAddress(input), }); try { await writeAudit({ type: "billing_address_replaced", actorType: "admin", entityType: "editorial_account", entityId: editorialId, metadata: { addressId, countryCode: input.countryCode }, }); } catch { // Audit is observability, not a transaction participant. } return addressId; }, 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); }, async archiveEditorial(input: { editorialId: string; adminUserId: string }): Promise { await repository.archiveEditorial(input); }, async unarchiveEditorial(input: { editorialId: string; adminUserId: string }) { return repository.unarchiveEditorial(input); }, async hardDeleteEditorial(editorialId: string): Promise { await repository.hardDeleteEditorial(editorialId); }, async resetUsageData(input: { editorialId: string; adminUserId: string }) { return repository.resetUsageData(input); }, }; } export function createEditorialServiceRepository( database: NodePgDatabase, ): EditorialServiceRepository { return { async prepareApproval({ editorialId, priceCents, adminUserId }) { return database.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); 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)) .for("update") .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") { 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), ), ) .for("update") .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, approvalNoticeStatus: "not_requested", 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, }); return notice; }); }, async claimApprovalNotice({ editorialId, adminUserId }) { return database.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status, approvalNoticeStatus: editorialAccounts.approvalNoticeStatus, }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .for("update") .limit(1); if (!editorial) { throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); } if (editorial.status !== "active") { throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); } if (editorial.approvalNoticeStatus === "sent") { return false; } if (editorial.approvalNoticeStatus === "dispatching") { throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN"); } const [claimed] = await transaction .update(editorialAccounts) .set({ approvalNoticeStatus: "dispatching", updatedAt: new Date() }) .where( and( eq(editorialAccounts.id, editorial.id), eq(editorialAccounts.status, "active"), inArray(editorialAccounts.approvalNoticeStatus, ["not_requested", "failed"]), ), ) .returning({ id: editorialAccounts.id }); if (!claimed) { 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 true; }); }, async recordApprovalNoticeSent({ editorialId, adminUserId }) { await database.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); const [updated] = await transaction .update(editorialAccounts) .set({ approvalNoticeStatus: "sent", updatedAt: new Date() }) .where( and( eq(editorialAccounts.id, editorialId), eq(editorialAccounts.approvalNoticeStatus, "dispatching"), ), ) .returning({ id: editorialAccounts.id }); if (!updated) { throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN"); } await transaction.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.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); const [updated] = await transaction .update(editorialAccounts) .set({ approvalNoticeStatus: "failed", updatedAt: new Date() }) .where( and( eq(editorialAccounts.id, editorialId), eq(editorialAccounts.approvalNoticeStatus, "dispatching"), ), ) .returning({ id: editorialAccounts.id }); if (!updated) { throw new EditorialServiceError("APPROVAL_NOTICE_DELIVERY_UNKNOWN"); } await transaction.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) => { await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction .select({ id: editorialAccounts.id }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .for("update") .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) => { await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .for("update") .limit(1); if (!editorial || editorial.status !== from) { throw new EditorialServiceError("INVALID_ACCOUNT_TRANSITION"); } const changedAt = new Date(); const [changed] = await transaction .update(editorialAccounts) .set({ status: to, updatedAt: changedAt }) .where(eq(editorialAccounts.id, editorialId)) .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, }); }); }, async archiveEditorial({ editorialId, adminUserId }) { await database.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status, archivedAt: editorialAccounts.archivedAt, }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .for("update") .limit(1); if (!editorial) { throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); } if (editorial.archivedAt) { return; } const activeGrants = await transaction .select({ id: albumGrants.id, immichAlbumId: albumGrants.immichAlbumId }) .from(albumGrants) .where( and( eq(albumGrants.editorialAccountId, editorialId), isNull(albumGrants.revokedAt), ), ) .for("update"); const changedAt = new Date(); const newStatus = editorial.status === "active" ? "suspended" : editorial.status; await transaction .update(editorialAccounts) .set({ archivedAt: changedAt, archivedByUserId: adminUserId, status: newStatus, updatedAt: changedAt, }) .where(eq(editorialAccounts.id, editorialId)); if (activeGrants.length > 0) { const grantIds = activeGrants.map((g) => g.id); await transaction .update(albumGrants) .set({ revokedAt: changedAt }) .where(inArray(albumGrants.id, grantIds)); for (const grant of activeGrants) { await transaction.insert(auditEvents).values({ eventType: "album_revoked", actorUserId: adminUserId, actorType: "admin", entityType: "album_grant", entityId: grant.immichAlbumId, previousValues: { editorialId: editorialId, immichAlbumId: grant.immichAlbumId, granted: true, }, newValues: { editorialId: editorialId, immichAlbumId: grant.immichAlbumId, granted: false, }, occurredAt: changedAt, }); } } await transaction.insert(auditEvents).values({ eventType: "editorial_archived", actorUserId: adminUserId, actorType: "admin", entityType: "editorial_account", entityId: editorialId, previousValues: { status: editorial.status, archived: false }, newValues: { status: newStatus, archived: true }, occurredAt: changedAt, }); }); }, /** * Lifts the archive state: restores login (suspended -> active), clears * the archive markers and re-activates exactly those album grants that * were revoked by the archive step (stamped with the archive timestamp). */ async unarchiveEditorial({ editorialId, adminUserId }) { return db.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status, archivedAt: editorialAccounts.archivedAt, }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .for("update") .limit(1); if (!editorial) { throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); } if (!editorial.archivedAt) { throw new EditorialServiceError("EDITORIAL_NOT_ARCHIVED"); } // archiveEditorial stamped every active grant with revokedAt = changedAt // (one active row per album is guaranteed by the partial unique index), // so matching that exact timestamp restores precisely what was lost. // Albums granted manually in the meantime keep their newer active row. const restored = await transaction .update(albumGrants) .set({ revokedAt: null }) .where( and( eq(albumGrants.editorialAccountId, editorialId), eq(albumGrants.revokedAt, editorial.archivedAt), sql`not exists ( select 1 from ${albumGrants} other where other.editorial_account_id = ${albumGrants.editorialAccountId} and lower(other.immich_album_id) = lower(${albumGrants.immichAlbumId}) and other.revoked_at is null )`, ), ) .returning({ id: albumGrants.id }); const changedAt = new Date(); const newStatus = editorial.status === "suspended" ? "active" : editorial.status; await transaction .update(editorialAccounts) .set({ archivedAt: null, archivedByUserId: null, status: newStatus, updatedAt: changedAt, }) .where(eq(editorialAccounts.id, editorialId)); await transaction.insert(auditEvents).values({ eventType: "editorial_unarchived", actorUserId: adminUserId, actorType: "admin", entityType: "editorial_account", entityId: editorialId, previousValues: { status: editorial.status, archived: true }, newValues: { status: newStatus, archived: false, restoredGrants: restored.length }, occurredAt: changedAt, }); return { restoredGrants: restored.length }; }); }, async hardDeleteEditorial(editorialId: string) { await db.transaction(async (transaction) => { await lockEditorialForMutation(transaction, editorialId); const [editorial] = await transaction .select({ userId: editorialAccounts.userId, loginEmail: editorialAccounts.loginEmail }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)); if (!editorial) return; // Capture IDs for audit-trail cleanup before the referenced rows go // away. const usageIds = ( await transaction .select({ id: usages.id }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)) ).map((row) => row.id); const reportIds = ( await transaction .select({ id: billingReports.id }) .from(billingReports) .where(eq(billingReports.editorialAccountId, editorialId)) ).map((row) => row.id); // Cascade deletions manually due to restrict constraints. Order is // dictated by the FK graph: // billing_report_items -> usages (restrict) // download_events -> usages (restrict) // usages.billing_report_id -> billing_reports (child side) if (reportIds.length > 0) { await transaction .delete(billingReportItems) .where(inArray(billingReportItems.billingReportId, reportIds)); } await transaction.delete(downloadEvents).where(eq(downloadEvents.editorialAccountId, editorialId)); await transaction.delete(usages).where(eq(usages.editorialAccountId, editorialId)); await transaction.delete(lightboxItems).where(eq(lightboxItems.editorialAccountId, editorialId)); if (reportIds.length > 0) { await transaction.delete(billingReports).where(inArray(billingReports.id, reportIds)); } await transaction.delete(albumAutoRules).where(eq(albumAutoRules.editorialAccountId, editorialId)); await transaction.delete(albumGrants).where(eq(albumGrants.editorialAccountId, editorialId)); // billing_address_versions is referenced by // editorial_accounts.current_billing_address_version_id and // self-references via superseded_by_id — clear both before deleting. await transaction .update(editorialAccounts) .set({ currentBillingAddressVersionId: null }) .where(eq(editorialAccounts.id, editorialId)); await transaction .update(billingAddressVersions) .set({ supersededById: null }) .where(eq(billingAddressVersions.editorialAccountId, editorialId)); await transaction.delete(billingAddressVersions).where(eq(billingAddressVersions.editorialAccountId, editorialId)); // Purge the audit trail entries that point at this editorial's data; // leftover rows would dangle after the account is gone. const { verifications } = await import("@/db/schema/auth"); await transaction.delete(auditEvents).where(and(eq(auditEvents.entityType, "editorial_account"), eq(auditEvents.entityId, editorialId))); if (usageIds.length > 0) { await transaction.delete(auditEvents).where(and(eq(auditEvents.entityType, "usage"), inArray(auditEvents.entityId, usageIds))); } if (reportIds.length > 0) { await transaction.delete(auditEvents).where(and(eq(auditEvents.entityType, "billing_report"), inArray(auditEvents.entityId, reportIds))); } await transaction.delete(auditEvents).where( and( eq(auditEvents.entityType, "album_grant"), sql`lower(${auditEvents.newValues}->>'editorialId') = lower(${editorialId})`, ), ); await transaction.delete(editorialAccounts).where(eq(editorialAccounts.id, editorialId)); if (editorial.userId) { // Safety net: any remaining audit row attributed to the editorial // user would block user deletion via the restrict FK. await transaction.delete(auditEvents).where(eq(auditEvents.actorUserId, editorial.userId)); const { accounts, sessions, users } = await import("@/db/schema/auth"); await transaction.delete(accounts).where(eq(accounts.userId, editorial.userId)); await transaction.delete(sessions).where(eq(sessions.userId, editorial.userId)); await transaction.delete(users).where(eq(users.id, editorial.userId)); } // Better Auth verification tokens are keyed by e-mail, not FK-linked. await transaction.delete(verifications).where(eq(verifications.identifier, editorial.loginEmail)); }); }, /** * Removes every usage/billing artifact of ONE editorial (downloads, * usages, reports incl. items + related audit rows) so the account no * longer appears in statistics. Intended to clean up test accounts; * grants, price, status and login stay untouched. */ async resetUsageData(input: { editorialId: string; adminUserId: string }) { return db.transaction(async (transaction) => { await lockEditorialForMutation(transaction, input.editorialId); const [editorial] = await transaction .select({ id: editorialAccounts.id }) .from(editorialAccounts) .where(eq(editorialAccounts.id, input.editorialId)) .for("update") .limit(1); if (!editorial) { throw new EditorialServiceError("EDITORIAL_NOT_FOUND"); } const usageIds = ( await transaction .select({ id: usages.id }) .from(usages) .where(eq(usages.editorialAccountId, editorial.id)) ).map((row) => row.id); const reportIds = ( await transaction .select({ id: billingReports.id }) .from(billingReports) .where(eq(billingReports.editorialAccountId, editorial.id)) ).map((row) => row.id); // Same FK order as hardDelete: items -> downloads -> usages -> reports. if (reportIds.length > 0) { await transaction .delete(billingReportItems) .where(inArray(billingReportItems.billingReportId, reportIds)); } await transaction .delete(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorial.id)); await transaction.delete(usages).where(eq(usages.editorialAccountId, editorial.id)); if (reportIds.length > 0) { await transaction.delete(billingReports).where(inArray(billingReports.id, reportIds)); await transaction .delete(auditEvents) .where(and(eq(auditEvents.entityType, "billing_report"), inArray(auditEvents.entityId, reportIds))); } if (usageIds.length > 0) { await transaction .delete(auditEvents) .where(and(eq(auditEvents.entityType, "usage"), inArray(auditEvents.entityId, usageIds))); } const changedAt = new Date(); await transaction.insert(auditEvents).values({ eventType: "editorial_usage_reset", actorUserId: input.adminUserId, actorType: "admin", entityType: "editorial_account", entityId: editorial.id, previousValues: { usages: usageIds.length, reports: reportIds.length }, newValues: { usages: 0, reports: 0 }, occurredAt: changedAt, }); return { deletedUsages: usageIds.length, deletedReports: reportIds.length }; }); }, }; } 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 === "rejected") || (from === "active" && to === "suspended") || (from === "suspended" && to === "active") || (from === "pending_email" && to === "rejected") ); } async function lockEditorialForMutation( transaction: NodePgDatabase, editorialId: string, ): Promise { await transaction.execute( sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`, ); } export const editorialService = createEditorialService({ repository: createEditorialServiceRepository(db), mailer, });