Files
immich-redaktions-plugin/tests/db/accounting-migration.test.ts
T

256 lines
7.9 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, expect, test, vi } from "vitest";
import { downloadEvents } from "@/db/schema";
import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service";
import { requestFingerprint } from "@/modules/usages/types";
import { startPostgres } from "./postgres";
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
afterAll(() => testDb.stop());
const validAssetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const validAlbumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const cleanKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const collidingKey = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
const authorizedAt = new Date("2026-08-09T08:00:00.000Z");
async function insertLegacyUsage({
editorialId,
assetId = validAssetId,
albumId = validAlbumId,
purpose = "Titelgeschichte",
reference = "Ausgabe 8/26",
}: {
editorialId: string;
assetId?: string;
albumId?: string;
purpose?: string;
reference?: string | null;
}) {
const usageId = randomUUID();
await testDb.pool.query(
`insert into usages (
id, editorial_account_id, immich_asset_id, filename_snapshot,
immich_album_id_snapshot, album_name_snapshot, purpose,
internal_reference, price_cents, billing_status, created_at
) values ($1, $2, $3, 'legacy.jpg', $4, 'Legacy Album', $5, $6, 2300, 'open', $7)`,
[usageId, editorialId, assetId, albumId, purpose, reference, authorizedAt],
);
return usageId;
}
async function insertLegacyEvent({
editorialId,
usageId,
assetId = validAssetId,
idempotencyKey = randomUUID(),
note = null,
at = authorizedAt,
}: {
editorialId: string;
usageId: string;
assetId?: string;
idempotencyKey?: string;
note?: string | null;
at?: Date;
}) {
const eventId = randomUUID();
await testDb.pool.query(
`insert into download_events (
id, editorial_account_id, usage_id, immich_asset_id, authorized_at,
status, repeat_download_note, request_id, idempotency_key
) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8)`,
[eventId, editorialId, usageId, assetId, at, note, randomUUID(), idempotencyKey],
);
return eventId;
}
test("0002 preserves dirty rows and reconstructs only provable legacy intents", async () => {
const userId = randomUUID();
const editorialId = randomUUID();
await testDb.pool.query(
`insert into users (id, name, email, email_verified)
values ($1, 'Legacy Redaktion', $2, true)`,
[userId, `${userId}@example.com`],
);
await testDb.pool.query(
`insert into editorial_accounts (
id, user_id, name, contact_name, login_email, status, current_price_cents
) values ($1, $2, 'Legacy Redaktion', 'Legacy Kontakt', $3, 'active', 2300)`,
[editorialId, userId, `${userId}@example.com`],
);
await testDb.pool.query(
`insert into album_grants (editorial_account_id, immich_album_id)
values ($1, $2), ($1, $3)`,
[editorialId, validAlbumId.toUpperCase(), "legacy album / 2019"],
);
const cleanUsageId = await insertLegacyUsage({
editorialId,
assetId: validAssetId.toUpperCase(),
albumId: validAlbumId.toUpperCase(),
});
const cleanEventId = await insertLegacyEvent({
editorialId,
usageId: cleanUsageId,
assetId: validAssetId.toUpperCase(),
idempotencyKey: cleanKey.toUpperCase(),
});
const dirtyAssetId = "legacy-asset/not-a-uuid";
const dirtyAlbumId = "legacy album / 2019";
const dirtyUsageId = await insertLegacyUsage({
editorialId,
assetId: dirtyAssetId,
albumId: dirtyAlbumId,
});
const dirtyEventId = await insertLegacyEvent({
editorialId,
usageId: dirtyUsageId,
assetId: dirtyAssetId,
idempotencyKey: "legacy-request",
});
const equalTimeUsageId = await insertLegacyUsage({ editorialId });
const equalTimeEventIds = await Promise.all([
insertLegacyEvent({ editorialId, usageId: equalTimeUsageId }),
insertLegacyEvent({
editorialId,
usageId: equalTimeUsageId,
note: "Wiederholung",
}),
]);
const contradictoryUsageId = await insertLegacyUsage({ editorialId });
const contradictoryEventId = await insertLegacyEvent({
editorialId,
usageId: contradictoryUsageId,
note: "Als Wiederholung markiert",
});
const collisionUsageIds = await Promise.all([
insertLegacyUsage({ editorialId }),
insertLegacyUsage({ editorialId }),
]);
const collisionEventIds = await Promise.all([
insertLegacyEvent({
editorialId,
usageId: collisionUsageIds[0],
idempotencyKey: collidingKey.toUpperCase(),
}),
insertLegacyEvent({
editorialId,
usageId: collisionUsageIds[1],
idempotencyKey: collidingKey,
}),
]);
await testDb.applyRemainingMigrations();
const immich = {
listAlbumsForAsset: vi.fn(),
getAsset: vi.fn(),
};
const usageService = createUsageService({
repository: createUsageServiceRepository(testDb.database),
immich,
});
await expect(
usageService.createNewUsage({
editorialId: editorialId.toUpperCase(),
assetId: validAssetId.toUpperCase(),
albumId: validAlbumId.toUpperCase(),
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
idempotencyKey: cleanKey.toUpperCase(),
}),
).resolves.toEqual({
id: cleanEventId,
usageId: cleanUsageId,
assetId: validAssetId.toUpperCase(),
priceCents: 2300,
billable: true,
status: "authorized",
authorizedAt,
});
expect(immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(immich.getAsset).not.toHaveBeenCalled();
const migratedEvents = await testDb.pool.query<{
id: string;
idempotency_key: string;
immich_asset_id: string;
intent_kind: string;
request_fingerprint: string;
}>(
`select id, idempotency_key, immich_asset_id, intent_kind, request_fingerprint
from download_events`,
);
expect(migratedEvents.rows).toHaveLength(7);
const byId = new Map(migratedEvents.rows.map((row) => [row.id, row]));
expect(byId.get(cleanEventId)).toMatchObject({
idempotency_key: cleanKey,
immich_asset_id: validAssetId.toUpperCase(),
intent_kind: "new_usage",
request_fingerprint: requestFingerprint({
kind: "new_usage",
editorialId,
assetId: validAssetId,
albumId: validAlbumId,
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
}),
});
expect(byId.get(dirtyEventId)).toMatchObject({
idempotency_key: "legacy-request",
immich_asset_id: dirtyAssetId,
intent_kind: "legacy",
});
for (const id of [
...equalTimeEventIds,
contradictoryEventId,
...collisionEventIds,
]) {
expect(byId.get(id)?.intent_kind).toBe("legacy");
expect(byId.get(id)?.request_fingerprint).toMatch(/^[0-9a-f]{64}$/);
}
expect(collisionEventIds.map((id) => byId.get(id)?.idempotency_key).sort()).toEqual(
[collidingKey.toUpperCase(), collidingKey].sort(),
);
const dirtySnapshots = await testDb.pool.query<{
immich_asset_id: string;
immich_album_id_snapshot: string;
}>("select immich_asset_id, immich_album_id_snapshot from usages where id = $1", [dirtyUsageId]);
expect(dirtySnapshots.rows[0]).toEqual({
immich_asset_id: dirtyAssetId,
immich_album_id_snapshot: dirtyAlbumId,
});
const dirtyGrant = await testDb.pool.query<{ immich_album_id: string }>(
"select immich_album_id from album_grants where immich_album_id = $1",
[dirtyAlbumId],
);
expect(dirtyGrant.rows).toEqual([{ immich_album_id: dirtyAlbumId }]);
await expect(
usageService.createNewUsage({
editorialId,
assetId: validAssetId,
albumId: validAlbumId,
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
idempotencyKey: collidingKey,
}),
).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
const [cleanEvent] = await testDb.database
.select()
.from(downloadEvents)
.where(eq(downloadEvents.id, cleanEventId));
expect(cleanEvent).toMatchObject({ legacyIntent: true, intentKind: "new_usage" });
});