import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import bcrypt from "bcryptjs"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { IngestService } from "../src/ingest/service.js"; import { type LegacyEvent, LegacyImporter, type LegacySource, type LegacyUser, splitTeams } from "../src/legacy/importer.js"; import { MemoryBroadcaster } from "../src/realtime.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { createTestApp, resetDb, seedUser, type TestContext } from "./helpers.js"; const quiet = { info: () => {}, warn: () => {} }; const OLD_PASSWORD = "old-app-password-123"; describe("legacy import (app.photoreport.pt)", () => { let ctx: TestContext; let dir: string; let oldPhotos: string; let storage: LocalStorage; let ingest: IngestService; const broadcaster = new MemoryBroadcaster(); beforeAll(async () => { dir = await mkdtemp(path.join(tmpdir(), "pr-legacy-")); oldPhotos = path.join(dir, "old-sftpgo"); ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: path.join(dir, "ingest") }, broadcaster); storage = new LocalStorage(ctx.config.STORAGE_ROOT); ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner(ctx.config.JWT_SECRET, 3600), broadcaster, ingestRoot: ctx.config.INGEST_ROOT, log: quiet }); }); afterAll(async () => { await ctx.app.close(); await ctx.db.$disconnect(); await rm(dir, { recursive: true, force: true }); }); beforeEach(async () => { await resetDb(ctx.db); }); async function oldSystem(): Promise { const users: LegacyUser[] = [ { id: "1", email: "Rui@Example.pt", username: "rui", passwordHash: await bcrypt.hash(OLD_PASSWORD, 4), admin: false, disabled: false }, { id: "2", email: "chefe@example.pt", username: "chefe", passwordHash: await bcrypt.hash("whatever-else-9", 4), admin: true, disabled: false }, ]; const events: LegacyEvent[] = [ { id: "10", ownerUserId: "1", folderName: "2026-09-23 VSC x AAAS", name: "VSC x AAAS", eventDate: new Date("2026-09-23"), createdAt: new Date(), location: "Pavilhão", iptc: { city: "Guimarães", keywords: ["andebol"] } }, { id: "11", ownerUserId: "1", folderName: "missing-folder", name: "Gala", eventDate: null, createdAt: new Date("2026-05-01"), location: null, iptc: {} }, ]; const folder = path.join(oldPhotos, "rui", "2026-09-23 VSC x AAAS", "sub"); await mkdir(folder, { recursive: true }); for (const [i, colour] of ["#123456", "#654321"].entries()) { await writeFile(path.join(folder, `IMG_${i}.JPG`), await sharp({ create: { width: 400, height: 300, channels: 3, background: colour } }).jpeg().toBuffer()); } return { users: async () => users, teams: async () => [ { id: "t1", name: "Vitória SC", abbreviation: "VSC" }, { id: "t2", name: "AA Avanca", abbreviation: "AAA" }, ], players: async () => [ { id: "p1", teamId: "t1", name: "Miguel Silva", fullName: null, shirtNumber: "07" }, { id: "p2", teamId: "t2", name: "Miguel Silva", fullName: null, shirtNumber: "10" }, { id: "p3", teamId: "t2", name: "João Costa", fullName: null, shirtNumber: "" }, ], events: async () => events, shares: async () => [ { id: "s1", userId: "1", folderName: "2026-09-23 VSC x AAAS", slug: "vsc-aaas", expiresAt: null, active: true, allowDownload: false, showInPortal: true, title: "Vitória x Avanca", forSale: true, passwordHash: null, createdAt: new Date("2026-09-24") }, { id: "s2", userId: "1", folderName: "2026-09-23 VSC x AAAS", slug: "familia", expiresAt: new Date("2026-01-01"), active: true, allowDownload: true, showInPortal: false, title: null, forSale: false, passwordHash: await bcrypt.hash("1234", 4), createdAt: new Date("2026-09-24") }, ], folderFiles: async (owner, folderName) => { const root = path.join(oldPhotos, owner?.username ?? "", folderName); const files = (await readdir(path.join(root, "sub")).catch(() => [])).map((f) => path.join(root, "sub", f)); return files.length ? { root, files } : null; }, affiliates: async () => [{ id: "a1", name: "Clube", email: "clube@example.pt", code: "clube", ratePct: 12.5, active: true }], orders: async () => [ { id: "7f6c1a2e-1111-2222-3333-444455556666", email: "pai@example.pt", country: "PT", vatNumber: null, reverseCharge: false, vatRate: 23, netCents: 1626, vatCents: 374, totalCents: 2000, paidAt: new Date("2026-09-25T10:00:00Z"), stripeSession: "cs_live_old", affiliateCode: "CLUBE", items: [ { shareSlug: "vsc-aaas", filePath: "sub/IMG_1.JPG", productType: "photo", label: null, unitCents: 800, quantity: 1 }, { shareSlug: "vsc-aaas", filePath: "IMG_0.JPG", productType: "ac_print", label: "20x30 glossy", unitCents: 600, quantity: 2 }, { shareSlug: "gone", filePath: "x.jpg", productType: "photo", label: null, unitCents: 0, quantity: 1 }, ], }, ], connectAccounts: async () => new Map([["1", "acct_old_rui"]]), eventFiles: async (e, owner) => { const d = path.join(oldPhotos, owner?.username ?? "", e.folderName); const walk = async (x: string): Promise => (await readdir(x, { withFileTypes: true }).catch(() => null))?.flatMap((f) => [path.join(x, f.name)]) ?? []; if (!(await walk(d)).length) return null; const sub = await walk(path.join(d, "sub")); return sub; }, }; } it("splits match names into teams", () => { expect(splitTeams("ABC Braga x CDE Gil Eanes")).toEqual({ home: "ABC Braga", away: "CDE Gil Eanes" }); expect(splitTeams("Benfica vs. Porto")).toEqual({ home: "Benfica", away: "Porto" }); expect(splitTeams("Gala do Andebol")).toEqual({ home: "Gala do Andebol", away: "" }); }); it("brings accounts, squads, events and photos over, and running again adds nothing", async () => { const { org, user: owner } = await seedUser(ctx.db, "owner@photoreport.pt", { org: "photoreport", role: "OWNER" }); const importer = new LegacyImporter({ db: ctx.db, storage, ingest, source: await oldSystem(), log: quiet }); const dry = await importer.run(org!.id, { dryRun: true, fallbackUserId: owner.id }); expect(dry).toMatchObject({ users: { created: 2 }, people: { created: 3 }, events: { created: 2 }, photos: { ingested: 2 } }); // would be ingested expect(await ctx.db.user.count()).toBe(1); const report = await importer.run(org!.id, { fallbackUserId: owner.id }); expect(report).toMatchObject({ users: { created: 2, existing: 0 }, people: { created: 3 }, events: { created: 2 }, photos: { ingested: 2, missingFolders: ["11 missing-folder"] } }); // The same password as before works, and is then stored the new way. const login = await ctx.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email: "rui@example.pt", password: OLD_PASSWORD, client: "web" } }); expect(login.statusCode).toBe(200); expect((await ctx.db.user.findUniqueOrThrow({ where: { email: "rui@example.pt" } })).passwordHash).toMatch(/^\$argon2/); const roles = await ctx.db.membership.findMany({ where: { organizationId: org!.id }, include: { user: true } }); expect(Object.fromEntries(roles.map((m) => [m.user.email, m.role]))).toMatchObject({ "rui@example.pt": "PHOTOGRAPHER", "chefe@example.pt": "ADMIN" }); const people = await ctx.db.person.findMany({ orderBy: { name: "asc" } }); expect(people.map((p) => [p.name, p.club, p.number])).toEqual([ ["João Costa", "AA Avanca", null], ["Miguel Silva", "Vitória SC", "7"], ["Miguel Silva (AAA)", "AA Avanca", "10"], ]); const event = await ctx.db.event.findFirstOrThrow({ where: { home: "VSC" }, include: { photos: true } }); expect(event).toMatchObject({ away: "AAAS", venue: "Pavilhão", city: "Guimarães", iptcTemplate: { city: "Guimarães", keywords: ["andebol"] } }); expect(event.photos).toHaveLength(2); // The old folder is untouched. expect(await readdir(path.join(oldPhotos, "rui", "2026-09-23 VSC x AAAS", "sub"))).toHaveLength(2); const again = await importer.run(org!.id, { fallbackUserId: owner.id }); expect(again).toMatchObject({ users: { created: 0, existing: 2 }, people: { created: 0, updated: 3 }, events: { created: 0, existing: 2 }, photos: { ingested: 0, duplicate: 2 } }); expect(await ctx.db.event.count()).toBe(2); expect(await ctx.db.photo.count()).toBe(2); expect(again.shop).toMatchObject({ galleries: { created: 0, existing: 2 }, orders: { created: 0, existing: 1 }, affiliates: { existing: 1 } }); expect(await ctx.db.order.count()).toBe(1); }); it("brings the storefront over: gallery links, paid orders, affiliates and Stripe accounts", async () => { const { org, user: owner } = await seedUser(ctx.db, "owner@photoreport.pt", { org: "photoreport", role: "OWNER" }); const importer = new LegacyImporter({ db: ctx.db, storage, ingest, source: await oldSystem(), log: quiet }); const report = await importer.run(org!.id, { fallbackUserId: owner.id }); expect(report.shop).toEqual({ galleries: { created: 2, existing: 0 }, photos: { ingested: 0, duplicate: 4, failed: 0 }, orders: { created: 1, existing: 0, unmatchedItems: 1 }, affiliates: { created: 1, existing: 0 }, stripeAccounts: 1 }); const galleries = await ctx.db.gallery.findMany({ orderBy: { slug: "asc" }, include: { photos: true, event: true } }); expect(galleries.map((g) => [g.slug, g.title, g.visibility, g.forSale, g.freeDownloads, !!g.publishedAt, g.photos.length, g.event?.home])).toEqual([ ["familia", "2026-09-23 VSC x AAAS", "PRIVATE", false, true, false, 2, "VSC"], // expired: imported unpublished ["vsc-aaas", "Vitória x Avanca", "PUBLIC", true, false, true, 2, "VSC"], ]); // The old PIN still opens the private gallery. const site = await ctx.db.site.create({ data: { organizationId: org!.id, domain: "old.test", name: "Old" } }); await ctx.db.gallery.update({ where: { id: galleries[0]!.id }, data: { publishedAt: new Date() } }); const unlock = await ctx.app.inject({ method: "POST", url: "/v1/public/galleries/familia/unlock", headers: { "x-site-domain": site.domain }, payload: { password: "1234" } }); expect(unlock.statusCode).toBe(200); const order = await ctx.db.order.findFirstOrThrow({ include: { items: { orderBy: { unitCents: "desc" } }, affiliate: true } }); expect(order).toMatchObject({ number: "OLD-7F6C1A2E11", status: "FULFILLED", provider: "legacy", totalCents: 2000, vatCents: 374, email: "pai@example.pt", affiliate: { code: "CLUBE", ratePct: 12.5 } }); expect(order.items.map((i) => [i.productName, i.kind, i.quantity, !!i.photoId, i.status])).toEqual([ ["Foto digital", "DIGITAL", 1, true, "READY"], ["20x30 glossy", "PRINT", 2, true, "SHIPPED"], ["Foto digital", "DIGITAL", 1, false, "READY"], ]); // History only: no earnings and no new downloads to render. expect(await ctx.db.earning.count()).toBe(0); const rui = await ctx.db.user.findUniqueOrThrow({ where: { email: "rui@example.pt" } }); expect((await ctx.db.membership.findFirstOrThrow({ where: { userId: rui.id } })).stripeAccountId).toBe("acct_old_rui"); }); });