fix: preserve legacy accounting migration data
This commit is contained in:
1 parent
3de1530074
commit
3cdca5c82c
10 files changed
+559
-177
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { index, pgTable, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||
|
||||
import { users } from "./auth";
|
||||
import { editorialAccounts } from "./editorials";
|
||||
@@ -10,7 +11,7 @@ export const albumGrants = pgTable(
|
||||
editorialAccountId: uuid("editorial_account_id")
|
||||
.notNull()
|
||||
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
|
||||
immichAlbumId: uuid("immich_album_id").notNull(),
|
||||
immichAlbumId: text("immich_album_id").notNull(),
|
||||
grantedAt: timestamp("granted_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
revokedAt: timestamp("revoked_at", { withTimezone: true }),
|
||||
grantedByUserId: uuid("granted_by_user_id").references(() => users.id, {
|
||||
@@ -20,5 +21,9 @@ export const albumGrants = pgTable(
|
||||
(table) => [
|
||||
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
|
||||
index("album_grants_immich_album_id_idx").on(table.immichAlbumId),
|
||||
check(
|
||||
"album_grants_canonical_immich_album_id_check",
|
||||
sql`${table.immichAlbumId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
|
||||
),
|
||||
],
|
||||
);
|
||||
+37
-20
@@ -28,24 +28,37 @@ export const downloadStatuses = [
|
||||
] as const;
|
||||
export const downloadStatus = pgEnum("download_status", downloadStatuses);
|
||||
|
||||
export const usages = pgTable("usages", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
editorialAccountId: uuid("editorial_account_id")
|
||||
.notNull()
|
||||
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
|
||||
immichAssetId: uuid("immich_asset_id").notNull(),
|
||||
filenameSnapshot: text("filename_snapshot").notNull(),
|
||||
immichAlbumIdSnapshot: uuid("immich_album_id_snapshot").notNull(),
|
||||
albumNameSnapshot: text("album_name_snapshot").notNull(),
|
||||
purpose: text("purpose").notNull(),
|
||||
internalReference: text("internal_reference"),
|
||||
priceCents: integer("price_cents").notNull(),
|
||||
billingStatus: usageBillingStatus("billing_status").notNull().default("open"),
|
||||
billingReportId: uuid("billing_report_id").references(() => billingReports.id, {
|
||||
onDelete: "restrict",
|
||||
}),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
export const usages = pgTable(
|
||||
"usages",
|
||||
{
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
editorialAccountId: uuid("editorial_account_id")
|
||||
.notNull()
|
||||
.references(() => editorialAccounts.id, { onDelete: "restrict" }),
|
||||
immichAssetId: text("immich_asset_id").notNull(),
|
||||
filenameSnapshot: text("filename_snapshot").notNull(),
|
||||
immichAlbumIdSnapshot: text("immich_album_id_snapshot").notNull(),
|
||||
albumNameSnapshot: text("album_name_snapshot").notNull(),
|
||||
purpose: text("purpose").notNull(),
|
||||
internalReference: text("internal_reference"),
|
||||
priceCents: integer("price_cents").notNull(),
|
||||
billingStatus: usageBillingStatus("billing_status").notNull().default("open"),
|
||||
billingReportId: uuid("billing_report_id").references(() => billingReports.id, {
|
||||
onDelete: "restrict",
|
||||
}),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
check(
|
||||
"usages_canonical_immich_asset_id_check",
|
||||
sql`${table.immichAssetId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
|
||||
),
|
||||
check(
|
||||
"usages_canonical_immich_album_id_check",
|
||||
sql`${table.immichAlbumIdSnapshot} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const downloadEvents = pgTable(
|
||||
"download_events",
|
||||
@@ -57,7 +70,7 @@ export const downloadEvents = pgTable(
|
||||
usageId: uuid("usage_id")
|
||||
.notNull()
|
||||
.references(() => usages.id, { onDelete: "restrict" }),
|
||||
immichAssetId: uuid("immich_asset_id").notNull(),
|
||||
immichAssetId: text("immich_asset_id").notNull(),
|
||||
authorizedAt: timestamp("authorized_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
startedAt: timestamp("started_at", { withTimezone: true }),
|
||||
completedAt: timestamp("completed_at", { withTimezone: true }),
|
||||
@@ -77,7 +90,7 @@ export const downloadEvents = pgTable(
|
||||
),
|
||||
check(
|
||||
"download_events_intent_kind_check",
|
||||
sql`${table.intentKind} in ('new_usage', 'repeat_download')`,
|
||||
sql`${table.intentKind} in ('new_usage', 'repeat_download', 'legacy')`,
|
||||
),
|
||||
check(
|
||||
"download_events_request_fingerprint_hex_check",
|
||||
@@ -87,5 +100,9 @@ export const downloadEvents = pgTable(
|
||||
"download_events_canonical_idempotency_key_check",
|
||||
sql`${table.legacyIntent} OR ${table.idempotencyKey} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
|
||||
),
|
||||
check(
|
||||
"download_events_canonical_immich_asset_id_check",
|
||||
sql`${table.immichAssetId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -18,6 +18,11 @@ type Audit = {
|
||||
newValues: Record<string, unknown>;
|
||||
};
|
||||
|
||||
const editorialUuid = "1111111a-1111-4111-8111-11111111111a";
|
||||
const albumUuid = "2222222b-2222-4222-8222-22222222222b";
|
||||
const adminUuid = "3333333c-3333-4333-8333-33333333333c";
|
||||
const unavailableAlbumUuid = "4444444d-4444-4444-8444-44444444444d";
|
||||
|
||||
function createRepository(initial: Grant[] = []) {
|
||||
const grants = [...initial];
|
||||
const audit: Audit[] = [];
|
||||
@@ -31,7 +36,7 @@ function createRepository(initial: Grant[] = []) {
|
||||
const active = grants.find(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId === input.immichAlbumId &&
|
||||
grant.albumId.toLowerCase() === input.immichAlbumId &&
|
||||
grant.revokedAt === null,
|
||||
);
|
||||
if (active) return false;
|
||||
@@ -39,7 +44,7 @@ function createRepository(initial: Grant[] = []) {
|
||||
const revoked = grants.find(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId === input.immichAlbumId &&
|
||||
grant.albumId.toLowerCase() === input.immichAlbumId &&
|
||||
grant.revokedAt !== null,
|
||||
);
|
||||
if (revoked) {
|
||||
@@ -61,7 +66,7 @@ function createRepository(initial: Grant[] = []) {
|
||||
const active = grants.find(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId === input.immichAlbumId &&
|
||||
grant.albumId.toLowerCase() === input.immichAlbumId &&
|
||||
grant.revokedAt === null,
|
||||
);
|
||||
if (!active) return false;
|
||||
@@ -84,7 +89,7 @@ function createService(initial: Grant[] = []) {
|
||||
const { repository, grants, audit } = createRepository(initial);
|
||||
const immich = {
|
||||
getAlbum: vi.fn().mockResolvedValue({
|
||||
id: "album-1",
|
||||
id: albumUuid,
|
||||
albumName: "Pressefotos",
|
||||
description: null,
|
||||
albumThumbnailAssetId: "cover-1",
|
||||
@@ -93,7 +98,7 @@ function createService(initial: Grant[] = []) {
|
||||
}),
|
||||
listAlbums: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "album-1",
|
||||
id: albumUuid,
|
||||
albumName: "Pressefotos",
|
||||
description: null,
|
||||
albumThumbnailAssetId: "cover-1",
|
||||
@@ -114,23 +119,80 @@ test("refuses to grant an album that the service user cannot read", async () =>
|
||||
immich.getAlbum.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
|
||||
|
||||
await expect(
|
||||
service.grantAlbum({ editorialId: "e1", immichAlbumId: "hidden", adminUserId: "a1" }),
|
||||
service.grantAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: unavailableAlbumUuid,
|
||||
adminUserId: adminUuid,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" });
|
||||
});
|
||||
|
||||
test("canonicalizes UUID grant input before Immich and repository side effects", async () => {
|
||||
const { service, immich, grants } = createService();
|
||||
|
||||
await service.grantAlbum({
|
||||
editorialId: editorialUuid.toUpperCase(),
|
||||
immichAlbumId: albumUuid.toUpperCase(),
|
||||
adminUserId: adminUuid.toUpperCase(),
|
||||
});
|
||||
|
||||
expect(immich.getAlbum).toHaveBeenCalledWith(albumUuid);
|
||||
expect(grants).toEqual([
|
||||
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
|
||||
]);
|
||||
});
|
||||
|
||||
test("treats an uppercase historical album grant as the canonical active grant", async () => {
|
||||
const { service, grants, audit } = createService([
|
||||
{ editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null },
|
||||
]);
|
||||
|
||||
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
|
||||
await service.grantAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: adminUuid,
|
||||
});
|
||||
|
||||
expect(grants).toHaveLength(1);
|
||||
expect(audit).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("rejects a non-UUID grant before external side effects", async () => {
|
||||
const { service, immich, grants } = createService();
|
||||
|
||||
await expect(
|
||||
service.grantAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: "legacy-album",
|
||||
adminUserId: adminUuid,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "INVALID_ALBUM_GRANT_INPUT" });
|
||||
expect(immich.getAlbum).not.toHaveBeenCalled();
|
||||
expect(grants).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("granting an album is idempotent and records one state-change audit event", async () => {
|
||||
const { service, audit } = createService();
|
||||
|
||||
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
await service.grantAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: adminUuid,
|
||||
});
|
||||
await service.grantAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: adminUuid,
|
||||
});
|
||||
|
||||
await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]);
|
||||
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
|
||||
expect(audit).toEqual([
|
||||
expect.objectContaining({
|
||||
eventType: "album_granted",
|
||||
actorUserId: "a1",
|
||||
editorialId: "e1",
|
||||
albumId: "album-1",
|
||||
actorUserId: adminUuid,
|
||||
editorialId: editorialUuid,
|
||||
albumId: albumUuid,
|
||||
previousValues: { granted: false },
|
||||
newValues: { granted: true },
|
||||
}),
|
||||
@@ -139,29 +201,41 @@ test("granting an album is idempotent and records one state-change audit event",
|
||||
|
||||
test("a revoked album can be re-granted without creating another current grant", async () => {
|
||||
const { service, grants } = createService([
|
||||
{ editorialId: "e1", albumId: "album-1", revokedAt: new Date("2026-08-08T00:00:00Z") },
|
||||
{
|
||||
editorialId: editorialUuid,
|
||||
albumId: albumUuid,
|
||||
revokedAt: new Date("2026-08-08T00:00:00Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
await service.grantAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: adminUuid,
|
||||
});
|
||||
|
||||
expect(grants).toHaveLength(1);
|
||||
await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]);
|
||||
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
|
||||
});
|
||||
|
||||
test("revocation immediately removes the album from visible IDs and records the actor", async () => {
|
||||
const { service, audit } = createService([
|
||||
{ editorialId: "e1", albumId: "album-1", revokedAt: null },
|
||||
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
|
||||
]);
|
||||
|
||||
await service.revokeAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
await service.revokeAlbum({
|
||||
editorialId: editorialUuid,
|
||||
immichAlbumId: albumUuid,
|
||||
adminUserId: adminUuid,
|
||||
});
|
||||
|
||||
await expect(service.getGrantedAlbumIds("e1")).resolves.not.toContain("album-1");
|
||||
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.not.toContain(albumUuid);
|
||||
expect(audit).toContainEqual(
|
||||
expect.objectContaining({
|
||||
eventType: "album_revoked",
|
||||
actorUserId: "a1",
|
||||
editorialId: "e1",
|
||||
albumId: "album-1",
|
||||
actorUserId: adminUuid,
|
||||
editorialId: editorialUuid,
|
||||
albumId: albumUuid,
|
||||
previousValues: { granted: true },
|
||||
newValues: { granted: false },
|
||||
}),
|
||||
@@ -176,7 +250,7 @@ test("reports a stable unavailable error when the Immich album list cannot be lo
|
||||
const { service, immich } = createService();
|
||||
immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" });
|
||||
|
||||
await expect(service.listAssignableAlbums("e1")).rejects.toEqual(
|
||||
await expect(service.listAssignableAlbums(editorialUuid)).rejects.toEqual(
|
||||
new AlbumGrantError("IMMICH_UNAVAILABLE"),
|
||||
);
|
||||
});
|
||||
@@ -49,36 +49,38 @@ export function createAlbumGrantService({
|
||||
}) {
|
||||
return {
|
||||
async listAssignableAlbums(editorialId: string): Promise<AssignableAlbum[]> {
|
||||
assertIdentifier(editorialId);
|
||||
const normalizedEditorialId = normalizeIdentifier(editorialId);
|
||||
const [albums, grantedAlbumIds] = await Promise.all([
|
||||
loadAlbums(immich),
|
||||
repository.listActiveAlbumIds(editorialId),
|
||||
repository.listActiveAlbumIds(normalizedEditorialId),
|
||||
]);
|
||||
const granted = new Set(grantedAlbumIds);
|
||||
return albums.map((album) => ({ ...album, isGranted: granted.has(album.id) }));
|
||||
const granted = new Set(grantedAlbumIds.map(canonicalizeStoredIdentifier));
|
||||
return albums.map((album) => ({
|
||||
...album,
|
||||
isGranted: granted.has(canonicalizeStoredIdentifier(album.id)),
|
||||
}));
|
||||
},
|
||||
|
||||
async grantAlbum(input: AlbumGrantInput): Promise<void> {
|
||||
assertInput(input);
|
||||
const normalizedInput = normalizeInput(input);
|
||||
try {
|
||||
await immich.getAlbum(input.immichAlbumId);
|
||||
await immich.getAlbum(normalizedInput.immichAlbumId);
|
||||
} catch (error) {
|
||||
if (hasCode(error, "IMMICH_NOT_FOUND")) {
|
||||
throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE");
|
||||
}
|
||||
throw new AlbumGrantError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
await repository.grant(input);
|
||||
await repository.grant(normalizedInput);
|
||||
},
|
||||
|
||||
async revokeAlbum(input: AlbumGrantInput): Promise<void> {
|
||||
assertInput(input);
|
||||
await repository.revoke(input);
|
||||
await repository.revoke(normalizeInput(input));
|
||||
},
|
||||
|
||||
async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
|
||||
assertIdentifier(editorialId);
|
||||
return repository.listActiveAlbumIds(editorialId);
|
||||
const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId));
|
||||
return albumIds.map(canonicalizeStoredIdentifier);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -194,16 +196,30 @@ async function loadAlbums(immich: Pick<ImmichClient, "listAlbums">): Promise<Imm
|
||||
}
|
||||
}
|
||||
|
||||
function assertInput(input: AlbumGrantInput): void {
|
||||
assertIdentifier(input.editorialId);
|
||||
assertIdentifier(input.immichAlbumId);
|
||||
assertIdentifier(input.adminUserId);
|
||||
function normalizeInput(input: AlbumGrantInput): AlbumGrantInput {
|
||||
return {
|
||||
editorialId: normalizeIdentifier(input.editorialId),
|
||||
immichAlbumId: normalizeIdentifier(input.immichAlbumId),
|
||||
adminUserId: normalizeIdentifier(input.adminUserId),
|
||||
};
|
||||
}
|
||||
|
||||
function assertIdentifier(value: string): void {
|
||||
if (!value.trim()) {
|
||||
function normalizeIdentifier(value: string): string {
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
||||
) {
|
||||
throw new AlbumGrantError("INVALID_ALBUM_GRANT_INPUT");
|
||||
}
|
||||
return value.toLowerCase();
|
||||
}
|
||||
|
||||
function canonicalizeStoredIdentifier(value: string): string {
|
||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||
value,
|
||||
)
|
||||
? value.toLowerCase()
|
||||
: value;
|
||||
}
|
||||
|
||||
function hasCode(error: unknown, code: string): boolean {
|
||||
@@ -246,7 +262,7 @@ async function lockAlbumGrants(
|
||||
.where(
|
||||
and(
|
||||
eq(albumGrants.editorialAccountId, editorialId),
|
||||
eq(albumGrants.immichAlbumId, immichAlbumId),
|
||||
sql`lower(${albumGrants.immichAlbumId}) = ${immichAlbumId}`,
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
|
||||
@@ -154,7 +154,7 @@ export function createUsageServiceRepository(
|
||||
.where(
|
||||
and(
|
||||
eq(albumGrants.editorialAccountId, input.editorialId),
|
||||
eq(albumGrants.immichAlbumId, input.albumId),
|
||||
sql`lower(${albumGrants.immichAlbumId}) = ${input.albumId}`,
|
||||
isNull(albumGrants.revokedAt),
|
||||
),
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user