From d37affc80f3a727cc8a548cca4315136c2231a9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Mon, 10 Aug 2026 17:31:42 +0200 Subject: [PATCH] feat: add billing period selection Co-Authored-By: Claude --- package.json | 1 + pnpm-lock.yaml | 16 + .../[editorialId]/BillingSelection.test.tsx | 204 ++++++++++++ .../[editorialId]/BillingSelection.tsx | 264 ++++++++++++++++ .../[editorialId]/page-content.ts | 121 +++++++ .../admin/abrechnungen/[editorialId]/page.tsx | 39 +++ src/app/admin/abrechnungen/page.tsx | 47 +++ src/app/admin/layout.tsx | 1 + src/app/globals.css | 298 ++++++++++++++++++ src/modules/billing/format.test.ts | 25 ++ src/modules/billing/format.ts | 15 + src/modules/billing/period.test.ts | 71 +++++ src/modules/billing/period.ts | 74 +++++ src/modules/billing/queries.test.ts | 243 ++++++++++++++ src/modules/billing/queries.ts | 206 ++++++++++++ 15 files changed, 1625 insertions(+) create mode 100644 src/app/admin/abrechnungen/[editorialId]/BillingSelection.test.tsx create mode 100644 src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx create mode 100644 src/app/admin/abrechnungen/[editorialId]/page-content.ts create mode 100644 src/app/admin/abrechnungen/[editorialId]/page.tsx create mode 100644 src/app/admin/abrechnungen/page.tsx create mode 100644 src/modules/billing/format.test.ts create mode 100644 src/modules/billing/format.ts create mode 100644 src/modules/billing/period.test.ts create mode 100644 src/modules/billing/period.ts create mode 100644 src/modules/billing/queries.test.ts create mode 100644 src/modules/billing/queries.ts diff --git a/package.json b/package.json index ae790a3..36cda36 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ }, "dependencies": { "@better-auth/drizzle-adapter": "^1.6.26", + "@js-temporal/polyfill": "^0.5.1", "better-auth": "^1.6.26", "drizzle-orm": "^0.45.2", "next": "^16.3.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5603f6b..80b00bd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@better-auth/drizzle-adapter': specifier: ^1.6.26 version: 1.6.26(@better-auth/core@1.6.26(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.8)(kysely@0.29.4)(nanostores@1.4.2))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0)) + '@js-temporal/polyfill': + specifier: ^0.5.1 + version: 0.5.1 better-auth: specifier: ^1.6.26 version: 1.6.26(drizzle-kit@0.31.10)(drizzle-orm@0.45.2(@types/pg@8.21.0)(kysely@0.29.4)(pg@8.22.0))(next@16.3.0(@babel/core@7.29.7(supports-color@7.2.0))(@types/node@24.13.3)(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(pg@8.22.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@4.1.10(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.3.0))(msw@2.15.0(@types/node@24.13.3)(typescript@5.9.3))(vite@8.2.1(@types/node@24.13.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.23.11)(yaml@2.9.0))) @@ -1084,6 +1087,10 @@ packages: '@js-sdsl/ordered-map@4.4.2': resolution: {integrity: sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==} + '@js-temporal/polyfill@0.5.1': + resolution: {integrity: sha512-hloP58zRVCRSpgDxmqCWJNlizAlUgJFqG2ypq79DCvyv9tHjRYMDOcPFjzfl/A1/YxDvRCZz8wvZvmapQnKwFQ==} + engines: {node: '>=12'} + '@kwsites/file-exists@1.1.1': resolution: {integrity: sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==} @@ -2901,6 +2908,9 @@ packages: resolution: {integrity: sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==} hasBin: true + jsbi@4.3.2: + resolution: {integrity: sha512-9fqMSQbhJykSeii05nxKl4m6Eqn2P6rOlYiS+C5Dr/HPIU/7yZxu5qzbs40tgaFORiw2Amd0mirjxatXYMkIew==} + jsdom@30.0.1: resolution: {integrity: sha512-52v7mUVUfNQVYYqE1lcdaymWL0njO7lTLUog6ZvW2U5KsbiLk/GnZlVJ+qx0xfNJZ6Gn+KSpPNE52vurbxZwrA==} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} @@ -4850,6 +4860,10 @@ snapshots: '@js-sdsl/ordered-map@4.4.2': {} + '@js-temporal/polyfill@0.5.1': + dependencies: + jsbi: 4.3.2 + '@kwsites/file-exists@1.1.1(supports-color@7.2.0)': dependencies: debug: 4.4.3(supports-color@7.2.0) @@ -6704,6 +6718,8 @@ snapshots: dependencies: argparse: 2.0.1 + jsbi@4.3.2: {} + jsdom@30.0.1(@noble/hashes@2.3.0): dependencies: '@asamuzakjp/css-color': 6.0.5 diff --git a/src/app/admin/abrechnungen/[editorialId]/BillingSelection.test.tsx b/src/app/admin/abrechnungen/[editorialId]/BillingSelection.test.tsx new file mode 100644 index 0000000..46ef1ed --- /dev/null +++ b/src/app/admin/abrechnungen/[editorialId]/BillingSelection.test.tsx @@ -0,0 +1,204 @@ +// @vitest-environment jsdom + +import { render, screen, fireEvent, cleanup } from "@testing-library/react"; +import { afterEach, expect, test } from "vitest"; + +import { BillingSelection } from "./BillingSelection"; +import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries"; + +afterEach(cleanup); + +const openPosition: BillingPosition = { + id: "u1", + assetId: "asset-1", + filename: "jubel.jpg", + albumName: "Presse 2026", + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + priceCents: 6_000, + status: "open", + selectable: true, + createdAt: new Date("2026-08-05T10:00:00.000Z"), + reportNumber: null, + invoiceNumber: null, +}; + +const billedPosition: BillingPosition = { + id: "u2", + assetId: "asset-2", + filename: "sport.jpg", + albumName: "Presse 2026", + purpose: "Sportbericht", + reference: null, + priceCents: 1_500, + status: "billed", + selectable: false, + createdAt: new Date("2026-08-06T10:00:00.000Z"), + reportNumber: 42, + invoiceNumber: "RE-2026-042", +}; + +const reopenedPosition: BillingPosition = { + id: "u3", + assetId: "asset-3", + filename: "redaktion.jpg", + albumName: "Presse 2026", + purpose: "Reopened", + reference: null, + priceCents: 1_500, + status: "reopened", + selectable: true, + createdAt: new Date("2026-08-07T10:00:00.000Z"), + reportNumber: null, + invoiceNumber: null, +}; + +const repeatDownload: RepeatDownloadPosition = { + id: "d1", + assetId: "asset-1", + usageId: "u1", + authorizedAt: new Date("2026-08-10T12:00:00.000Z"), + status: "completed", + repeatDownloadNote: "Zweite Nutzung", +}; + +const defaultProps = { + editorialId: "e1", + repeatDownloads: [] as RepeatDownloadPosition[], + year: 2026, + month: 8 as number | null, + quarter: null as number | null, + isQuarter: false, + periodLabel: "August 2026", +}; + +function getCheckbox(filename: string): HTMLInputElement { + return screen.getByRole("checkbox", { + name: `${filename} auswählen`, + }) as HTMLInputElement; +} + +test("renders billable positions with individual checkboxes", () => { + render( + , + ); + + expect(screen.getByText("jubel.jpg")).toBeTruthy(); + expect(screen.getByText("sport.jpg")).toBeTruthy(); + expect(getCheckbox("jubel.jpg").checked).toBe(false); +}); + +test("disables the checkbox for billed positions and shows report reference", () => { + render( + , + ); + + const checkbox = getCheckbox("sport.jpg"); + expect(checkbox.disabled).toBe(true); + expect(screen.getByText(/Bericht Nr\. 42/)).toBeTruthy(); + expect(screen.getByText(/RE-2026-042/)).toBeTruthy(); +}); + +test("selects all open positions via Alle offenen im Monat", () => { + render( + , + ); + + fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i })); + + expect(getCheckbox("jubel.jpg").checked).toBe(true); + expect(getCheckbox("redaktion.jpg").checked).toBe(true); + expect(getCheckbox("sport.jpg").checked).toBe(false); +}); + +test("clears the selection via Auswahl aufheben", () => { + render( + , + ); + + const checkbox = getCheckbox("jubel.jpg"); + fireEvent.click(checkbox); + expect(checkbox.checked).toBe(true); + + fireEvent.click(screen.getByRole("button", { name: /Auswahl aufheben/i })); + expect(checkbox.checked).toBe(false); +}); + +test("displays selected count and cents-derived EUR total", () => { + const { container } = render( + , + ); + + fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i })); + + const summary = container.querySelector(".billing-summary"); + expect(summary?.textContent ?? "").toMatch(/2 Nutzungen ausgewählt/); + expect(summary?.textContent ?? "").toMatch(/75,00 EUR/); +}); + +test("renders repeat downloads in a separate section", () => { + render( + , + ); + + expect(screen.getByText(/Kostenlose Wiederabrufe/)).toBeTruthy(); + expect(screen.getByText("Zweite Nutzung")).toBeTruthy(); +}); + +test("shows empty state when no billable positions exist", () => { + render( + , + ); + + expect(screen.getByText(/Keine abrechenbaren Nutzungen/)).toBeTruthy(); +}); + +test("links to quarter view from month view", () => { + render( + , + ); + + const quarterLink = screen.getByRole("link", { name: /Ganzes Quartal/i }); + expect(quarterLink.getAttribute("href") ?? "").toContain("quarter=3"); +}); + +test("links to month view from quarter view", () => { + render( + , + ); + + const monthLink = screen.getByRole("link", { name: /Monatsansicht/i }); + expect(monthLink.getAttribute("href") ?? "").toContain("month="); +}); \ No newline at end of file diff --git a/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx b/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx new file mode 100644 index 0000000..d540857 --- /dev/null +++ b/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx @@ -0,0 +1,264 @@ +"use client"; + +import { useMemo, useState } from "react"; +import Link from "next/link"; + +import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries"; +import { formatCents } from "@/modules/billing/format"; + +type BillingSelectionProps = { + editorialId: string; + positions: BillingPosition[]; + repeatDownloads: RepeatDownloadPosition[]; + year: number; + month: number | null; + quarter: number | null; + isQuarter: boolean; + periodLabel: string; +}; + +const MONTHS = [ + "Januar", + "Februar", + "März", + "April", + "Mai", + "Juni", + "Juli", + "August", + "September", + "Oktober", + "November", + "Dezember", +]; + +const STATUS_LABELS: Record = { + open: "Offen", + billed: "Abgerechnet", + reopened: "Wiedereröffnet", +}; + +export function BillingSelection({ + editorialId, + positions, + repeatDownloads, + year, + month, + quarter, + isQuarter, + periodLabel, +}: BillingSelectionProps) { + const [selectedIds, setSelectedIds] = useState>(new Set()); + + const selectablePositions = useMemo( + () => positions.filter((p) => p.selectable), + [positions], + ); + + const selectedCount = selectedIds.size; + const selectedTotalCents = useMemo( + () => + positions.reduce( + (sum, p) => (selectedIds.has(p.id) ? sum + p.priceCents : sum), + 0, + ), + [positions, selectedIds], + ); + + function togglePosition(id: string) { + setSelectedIds((prev) => { + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + } + + function selectAllOpen() { + setSelectedIds(new Set(selectablePositions.map((p) => p.id))); + } + + function clearSelection() { + setSelectedIds(new Set()); + } + + const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3); + const quarterHref = quarter + ? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}` + : `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarterParam}`; + const monthHref = `/admin/abrechnungen/${editorialId}?year=${year}&month=${month ?? (quarter ? (quarter - 1) * 3 + 1 : new Date().getUTCMonth() + 1)}`; + + return ( + <> + + +
+ + {isQuarter ? ( + + Monatsansicht + + ) : ( + + Ganzes Quartal + + )} + +
+ +

+ Zeitraum: {periodLabel} +

+ + {positions.length === 0 ? ( +

Keine abrechenbaren Nutzungen in diesem Zeitraum.

+ ) : ( + + + + + + + + + + + + + + + {positions.map((position) => ( + + + + + + + + + + ))} + +
+ Abrechenbare Nutzungen +
AuswahlDateiAlbumZweckReferenzPreisStatus
+ togglePosition(position.id)} + disabled={!position.selectable} + aria-label={`${position.filename} auswählen`} + /> + {position.filename}{position.albumName}{position.purpose}{position.reference ?? "—"}{formatCents(position.priceCents)} + + {STATUS_LABELS[position.status]} + {position.status === "billed" && position.reportNumber !== null && ( + + {" "}· Bericht Nr. {position.reportNumber} + {position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""} + + )} + +
+ )} + + {repeatDownloads.length > 0 && ( +
+

Kostenlose Wiederabrufe

+

+ Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht + abrechenbar. +

+ + + + + + + + + + + + {repeatDownloads.map((download) => ( + + + + + + + ))} + +
Wiederabrufe im Zeitraum
DateiDatumStatusNotiz
{download.assetId} + + {download.status}{download.repeatDownloadNote ?? "—"}
+
+ )} + +
+

+ {selectedCount} {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt +

+

+ Summe: {formatCents(selectedTotalCents)} +

+
+ + ); +} + +type PeriodSelectorProps = { + year: number; + month: number | null; + quarter: number | null; + isQuarter: boolean; +}; + +function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps) { + const years = [2025, 2026, 2027]; + + return ( +
+ + {isQuarter ? ( + + ) : ( + + )} + +
+ ); +} \ No newline at end of file diff --git a/src/app/admin/abrechnungen/[editorialId]/page-content.ts b/src/app/admin/abrechnungen/[editorialId]/page-content.ts new file mode 100644 index 0000000..16c15ac --- /dev/null +++ b/src/app/admin/abrechnungen/[editorialId]/page-content.ts @@ -0,0 +1,121 @@ +import "server-only"; + +import { eq } from "drizzle-orm"; + +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; +import { queries } from "@/modules/billing/queries"; +import { monthPeriod, quarterPeriod, type BillingPeriod } from "@/modules/billing/period"; +import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries"; + +export type BillingSelectionData = { + editorial: { id: string; name: string }; + period: BillingPeriod; + periodLabel: string; + isQuarter: boolean; + year: number; + month: number | null; + quarter: number | null; + positions: BillingPosition[]; + repeatDownloads: RepeatDownloadPosition[]; +}; + +export async function loadBillingSelection( + editorialId: string, + searchParams: Record, +): Promise { + const [editorial] = await db + .select({ id: editorialAccounts.id, name: editorialAccounts.name }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)) + .limit(1); + if (!editorial) return null; + + const { period, isQuarter, year, month, quarter, periodLabel } = resolvePeriod(searchParams); + + const [positions, repeatDownloads] = await Promise.all([ + queries.listBillablePositions(editorialId, period), + queries.listNonBillableDownloads(editorialId, period), + ]); + + return { + editorial, + period, + periodLabel, + isQuarter, + year, + month, + quarter, + positions, + repeatDownloads, + }; +} + +export function resolvePeriod(searchParams: Record): { + period: BillingPeriod; + isQuarter: boolean; + year: number; + month: number | null; + quarter: number | null; + periodLabel: string; +} { + const now = new Date(); + const defaultYear = now.getUTCFullYear(); + const defaultMonth = now.getUTCMonth() + 1; + + const year = parseNumberParam(searchParams.year, defaultYear); + const quarterParam = firstParam(searchParams.quarter); + + if (quarterParam !== undefined) { + const quarter = parseNumberParam(searchParams.quarter, Math.floor((defaultMonth - 1) / 3) + 1); + return { + period: quarterPeriod(year, quarter), + isQuarter: true, + year, + month: null, + quarter, + periodLabel: `Q${quarter} ${year}`, + }; + } + + const month = parseNumberParam(searchParams.month, defaultMonth); + return { + period: monthPeriod(year, month), + isQuarter: false, + year, + month, + quarter: null, + periodLabel: monthLabel(year, month), + }; +} + +function monthLabel(year: number, month: number): string { + const names = [ + "Januar", + "Februar", + "März", + "April", + "Mai", + "Juni", + "Juli", + "August", + "September", + "Oktober", + "November", + "Dezember", + ]; + return `${names[month - 1]} ${year}`; +} + +function parseNumberParam( + value: string | string[] | undefined, + fallback: number, +): number { + const parsed = Number.parseInt(firstParam(value) ?? "", 10); + return Number.isFinite(parsed) ? parsed : fallback; +} + +function firstParam(value: string | string[] | undefined): string | undefined { + if (Array.isArray(value)) return value[0]; + return value; +} \ No newline at end of file diff --git a/src/app/admin/abrechnungen/[editorialId]/page.tsx b/src/app/admin/abrechnungen/[editorialId]/page.tsx new file mode 100644 index 0000000..5587ae5 --- /dev/null +++ b/src/app/admin/abrechnungen/[editorialId]/page.tsx @@ -0,0 +1,39 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; + +import { loadBillingSelection } from "./page-content"; +import { BillingSelection } from "./BillingSelection"; + +export default async function BillingSelectionPage({ + params, + searchParams, +}: Readonly<{ + params: Promise<{ editorialId: string }>; + searchParams: Promise>; +}>) { + const { editorialId } = await params; + const sp = await searchParams; + const data = await loadBillingSelection(editorialId, sp); + if (!data) notFound(); + + return ( +
+

Abrechnungen

+

{data.editorial.name}

+

+ Zurück zur Übersicht +

+ + +
+ ); +} \ No newline at end of file diff --git a/src/app/admin/abrechnungen/page.tsx b/src/app/admin/abrechnungen/page.tsx new file mode 100644 index 0000000..ee5e921 --- /dev/null +++ b/src/app/admin/abrechnungen/page.tsx @@ -0,0 +1,47 @@ +import { desc } from "drizzle-orm"; + +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; +import { formatCents } from "@/modules/billing/format"; + +export default async function BillingOverviewPage() { + const editorials = await db + .select({ + id: editorialAccounts.id, + name: editorialAccounts.name, + contactName: editorialAccounts.contactName, + loginEmail: editorialAccounts.loginEmail, + status: editorialAccounts.status, + currentPriceCents: editorialAccounts.currentPriceCents, + }) + .from(editorialAccounts) + .orderBy(desc(editorialAccounts.createdAt)); + + return ( +
+

Abrechnungen

+

Redaktionen

+

+ Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal + auszuwählen. +

+ {editorials.length === 0 ? ( +

Noch keine Redaktionen registriert.

+ ) : ( +
    + {editorials.map((editorial) => ( +
  • + {editorial.name} +

    + {editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status} + {editorial.currentPriceCents === null + ? " · Preis noch nicht festgelegt" + : ` · Netto ${formatCents(editorial.currentPriceCents)}`} +

    +
  • + ))} +
+ )} +
+ ); +} \ No newline at end of file diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx index 9b5f245..bc39af9 100644 --- a/src/app/admin/layout.tsx +++ b/src/app/admin/layout.tsx @@ -18,6 +18,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea {children} diff --git a/src/app/globals.css b/src/app/globals.css index f2f93f3..d765b64 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -961,3 +961,301 @@ a { flex-direction: column-reverse; } } + +/* Billing selection */ + +.content-section { + width: min(100%, 108rem); + margin: 0 auto; + padding: clamp(2rem, 5vw, 5.5rem) clamp(1.25rem, 4vw, 5rem) 5rem; +} + +.content-section h1 { + max-width: 15ch; + margin: 0 0 1.5rem; + font-size: clamp(2.5rem, 5vw, 5.5rem); + font-weight: 600; + letter-spacing: -0.065em; + line-height: 0.9; +} + +.content-section > p { + max-width: 44rem; + margin: 0 0 2rem; + color: var(--graphite); + font-size: 0.95rem; + line-height: 1.5; +} + +.billing-editorial-list { + display: grid; + gap: 1.25rem; + padding: 0; + list-style: none; +} + +.billing-editorial-list li { + padding-bottom: 1.25rem; + border-bottom: 1px solid var(--line); +} + +.billing-editorial-list a { + font-size: 1.15rem; + font-weight: 650; + text-decoration: none; +} + +.billing-editorial-list a:hover { + text-decoration: underline; + text-underline-offset: 0.2em; +} + +.billing-editorial-list p { + margin: 0.35rem 0 0; + color: var(--metadata); + font-size: 0.85rem; +} + +.billing-period-selector { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 1rem; + margin-bottom: 2rem; + padding-bottom: 1.25rem; + border-bottom: 1px solid var(--ink); +} + +.billing-period-selector label { + display: grid; + gap: 0.35rem; + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.billing-period-selector select { + min-width: 8rem; + min-height: 2.8rem; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); + font: inherit; + font-size: 0.875rem; + padding: 0.4rem 0.6rem; +} + +.billing-period-selector button { + min-height: 2.8rem; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--ink); + color: var(--paper); + cursor: pointer; + font: inherit; + font-size: 0.8rem; + font-weight: 700; + padding-inline: 1rem; +} + +.billing-period-selector button:hover { + background: var(--graphite); +} + +.billing-period-selector a { + align-self: center; + font-size: 0.8125rem; + font-weight: 650; + text-underline-offset: 0.2em; +} + +.billing-selection-controls { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + margin-bottom: 1.5rem; +} + +.billing-selection-controls button { + min-height: 2.6rem; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); + cursor: pointer; + font: inherit; + font-size: 0.8rem; + font-weight: 700; + padding-inline: 1rem; +} + +.billing-selection-controls button:hover:not(:disabled) { + background: var(--ink); + color: var(--paper); +} + +.billing-selection-controls button:disabled { + border-color: var(--line); + color: var(--metadata); + cursor: not-allowed; +} + +.billing-nav-link { + display: inline-flex; + align-items: center; + min-height: 2.6rem; + border: 1px solid var(--ink); + border-radius: 0; + background: var(--paper); + color: var(--ink); + font: inherit; + font-size: 0.8rem; + font-weight: 700; + padding-inline: 1rem; + text-decoration: none; +} + +.billing-nav-link:hover { + background: var(--ink); + color: var(--paper); +} + +.billing-period-label { + margin: 0 0 1.5rem; + color: var(--metadata); + font-size: 0.8125rem; + font-weight: 650; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.billing-empty { + max-width: 38rem; + color: var(--graphite); + font-size: 1rem; + line-height: 1.55; +} + +.billing-table { + width: 100%; + border-collapse: collapse; + font-size: 0.85rem; +} + +.billing-caption { + margin-bottom: 0.75rem; + color: var(--metadata); + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + text-align: left; + caption-side: top; +} + +.billing-table thead th { + padding: 0.6rem 0.5rem; + border-bottom: 1px solid var(--ink); + color: var(--metadata); + font-size: 0.65rem; + font-weight: 700; + letter-spacing: 0.08em; + text-align: left; + text-transform: uppercase; +} + +.billing-table tbody td { + padding: 0.65rem 0.5rem; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +.billing-table tbody tr.billing-row-billed { + background: var(--soft); + color: var(--metadata); +} + +.billing-row-billed td { + color: var(--metadata); +} + +.billing-row-billed .billing-status { + font-style: italic; +} + +.billing-report-ref { + display: block; + margin-top: 0.15rem; + font-size: 0.7rem; + font-style: normal; +} + +.billing-price { + text-align: right; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.billing-status { + font-size: 0.75rem; + font-weight: 650; +} + +.billing-repeat-section { + margin-top: 3rem; + padding-top: 1.5rem; + border-top: 1px solid var(--ink); +} + +.billing-repeat-section h2 { + margin: 0 0 0.5rem; + font-size: 1.15rem; + font-weight: 650; + letter-spacing: -0.02em; +} + +.billing-table-repeat { + margin-top: 1rem; +} + +.billing-summary { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 1rem; + margin-top: 2rem; + padding: 1rem 0; + border-top: 2px solid var(--ink); + font-size: 0.875rem; +} + +.billing-summary p { + margin: 0; +} + +.billing-summary-total { + font-size: 1.1rem; + font-variant-numeric: tabular-nums; +} + +.billing-summary strong { + font-weight: 700; +} + +@media (max-width: 48rem) { + .billing-table { + display: block; + overflow-x: auto; + } + + .billing-period-selector { + flex-direction: column; + align-items: stretch; + } + + .billing-period-selector a { + align-self: flex-start; + } +} diff --git a/src/modules/billing/format.test.ts b/src/modules/billing/format.test.ts new file mode 100644 index 0000000..676856e --- /dev/null +++ b/src/modules/billing/format.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from "vitest"; + +import { formatCents } from "./format"; + +test("formats whole euros without fractional cents", () => { + expect(formatCents(6_000)).toBe("60,00 EUR"); +}); + +test("formats fractional cents with zero padding", () => { + expect(formatCents(1_500)).toBe("15,00 EUR"); + expect(formatCents(1_599)).toBe("15,99 EUR"); + expect(formatCents(99)).toBe("0,99 EUR"); +}); + +test("formats zero as 0,00 EUR", () => { + expect(formatCents(0)).toBe("0,00 EUR"); +}); + +test("formats large amounts with German thousands separators", () => { + expect(formatCents(1_234_567)).toBe("12.345,67 EUR"); +}); + +test("formats negative amounts with a leading minus", () => { + expect(formatCents(-1_500)).toBe("-15,00 EUR"); +}); \ No newline at end of file diff --git a/src/modules/billing/format.ts b/src/modules/billing/format.ts new file mode 100644 index 0000000..02a0cd5 --- /dev/null +++ b/src/modules/billing/format.ts @@ -0,0 +1,15 @@ +/** + * Formats an integer-Euro-cents amount as a German EUR display string using + * only integer math (division and modulo). Never converts to floating point. + * + * Examples: 6000 -> "60,00 EUR", 1500 -> "15,00 EUR", 0 -> "0,00 EUR" + */ +export function formatCents(cents: number): string { + const sign = cents < 0 ? "-" : ""; + const absCents = Math.abs(Math.trunc(cents)); + const euros = Math.floor(absCents / 100); + const remainingCents = absCents % 100; + const euroString = new Intl.NumberFormat("de-DE").format(euros); + const centsString = remainingCents.toString().padStart(2, "0"); + return `${sign}${euroString},${centsString} EUR`; +} \ No newline at end of file diff --git a/src/modules/billing/period.test.ts b/src/modules/billing/period.test.ts new file mode 100644 index 0000000..88a49b2 --- /dev/null +++ b/src/modules/billing/period.test.ts @@ -0,0 +1,71 @@ +import { expect, test } from "vitest"; + +import { monthPeriod, quarterPeriod, type BillingPeriod } from "./period"; + +test("converts a Berlin month to an exclusive UTC range", () => { + expect(monthPeriod(2026, 3)).toEqual({ + fromUtc: new Date("2026-02-28T23:00:00.000Z"), + toUtcExclusive: new Date("2026-03-31T22:00:00.000Z"), + }); +}); + +test("converts a Berlin month in full summer (CEST) to an exclusive UTC range", () => { + expect(monthPeriod(2026, 8)).toEqual({ + fromUtc: new Date("2026-07-31T22:00:00.000Z"), + toUtcExclusive: new Date("2026-08-31T22:00:00.000Z"), + }); +}); + +test("converts a Berlin month in full winter (CET) to an exclusive UTC range", () => { + expect(monthPeriod(2026, 1)).toEqual({ + fromUtc: new Date("2025-12-31T23:00:00.000Z"), + toUtcExclusive: new Date("2026-01-31T23:00:00.000Z"), + }); +}); + +test("converts a Berlin quarter spanning a DST transition to an exclusive UTC range", () => { + // Q1 2026: Jan 1 to Apr 1. Start is CET (+1), end is CEST (+2) after Mar 29 switch. + expect(quarterPeriod(2026, 1)).toEqual({ + fromUtc: new Date("2025-12-31T23:00:00.000Z"), + toUtcExclusive: new Date("2026-03-31T22:00:00.000Z"), + }); +}); + +test("converts a Berlin quarter fully in summer (CEST) to an exclusive UTC range", () => { + // Q3 2026: Jul 1 to Oct 1. Both CEST (+2) until Oct 25 switch. Oct 1 is still CEST. + expect(quarterPeriod(2026, 3)).toEqual({ + fromUtc: new Date("2026-06-30T22:00:00.000Z"), + toUtcExclusive: new Date("2026-09-30T22:00:00.000Z"), + }); +}); + +test("converts a Berlin quarter spanning the autumn DST transition", () => { + // Q4 2026: Oct 1 to Jan 1 2027. Start is CEST (+2), end is CET (+1) after Oct 25 switch. + expect(quarterPeriod(2026, 4)).toEqual({ + fromUtc: new Date("2026-09-30T22:00:00.000Z"), + toUtcExclusive: new Date("2026-12-31T23:00:00.000Z"), + }); +}); + +test("BillingPeriod has fromUtc and toUtcExclusive Date fields", () => { + const period: BillingPeriod = monthPeriod(2026, 8); + expect(period.fromUtc).toBeInstanceOf(Date); + expect(period.toUtcExclusive).toBeInstanceOf(Date); + expect(period.toUtcExclusive.getTime()).toBeGreaterThan(period.fromUtc.getTime()); +}); + +test("rolls over the year boundary for December", () => { + expect(monthPeriod(2026, 12)).toEqual({ + fromUtc: new Date("2026-11-30T23:00:00.000Z"), + toUtcExclusive: new Date("2026-12-31T23:00:00.000Z"), + }); +}); + +test("supports an explicit timezone override", () => { + // America/New_York is UTC-5 in winter (EST), UTC-4 in summer (EDT). + // March 2026: Mar 1 00:00 EST = Mar 1 05:00 UTC; Apr 1 00:00 EDT = Apr 1 04:00 UTC. + expect(monthPeriod(2026, 3, "America/New_York")).toEqual({ + fromUtc: new Date("2026-03-01T05:00:00.000Z"), + toUtcExclusive: new Date("2026-04-01T04:00:00.000Z"), + }); +}); \ No newline at end of file diff --git a/src/modules/billing/period.ts b/src/modules/billing/period.ts new file mode 100644 index 0000000..60ddc31 --- /dev/null +++ b/src/modules/billing/period.ts @@ -0,0 +1,74 @@ +import { Temporal } from "@js-temporal/polyfill"; + +/** + * A half-open UTC date range covering a billing period (month or quarter) + * as observed in a specific IANA time zone. + * + * `fromUtc` is inclusive; `toUtcExclusive` is exclusive. A usage/download + * belongs to the period when its timestamp is in `[fromUtc, toUtcExclusive)`. + */ +export type BillingPeriod = { + fromUtc: Date; + toUtcExclusive: Date; +}; + +const MIDNIGHT = Temporal.PlainTime.from("00:00:00"); + +/** + * Returns the half-open UTC range for the given calendar month in the + * given IANA time zone (default `Europe/Berlin`). + * + * `month` is 1-indexed (1 = January, 12 = December). Boundaries are computed + * via Temporal so that DST transitions between the start and end of the + * month are handled correctly — the start and end may have different UTC + * offsets (e.g. March 2026 starts at CET +1 and ends at CEST +2). + */ +export function monthPeriod(year: number, month: number, zone = "Europe/Berlin"): BillingPeriod { + if (!Number.isInteger(month) || month < 1 || month > 12) { + throw new RangeError(`month must be 1–12, received ${month}`); + } + + const startPlain = Temporal.PlainDate.from({ year, month, day: 1 }); + const { year: endYear, month: endMonth } = addMonths(year, month, 1); + const endPlain = Temporal.PlainDate.from({ year: endYear, month: endMonth, day: 1 }); + + return toBillingPeriod(startPlain, endPlain, zone); +} + +/** + * Returns the half-open UTC range for the given calendar quarter in the + * given IANA time zone (default `Europe/Berlin`). + * + * `quarter` is 1-indexed (1 = Jan–Mar, 4 = Oct–Dec). As with `monthPeriod`, + * boundaries are computed via Temporal to handle DST transitions correctly. + */ +export function quarterPeriod(year: number, quarter: number, zone = "Europe/Berlin"): BillingPeriod { + if (!Number.isInteger(quarter) || quarter < 1 || quarter > 4) { + throw new RangeError(`quarter must be 1–4, received ${quarter}`); + } + + const startMonth = (quarter - 1) * 3 + 1; + const startPlain = Temporal.PlainDate.from({ year, month: startMonth, day: 1 }); + const { year: endYear, month: endMonth } = addMonths(year, startMonth, 3); + const endPlain = Temporal.PlainDate.from({ year: endYear, month: endMonth, day: 1 }); + + return toBillingPeriod(startPlain, endPlain, zone); +} + +function toBillingPeriod( + startPlain: Temporal.PlainDate, + endPlain: Temporal.PlainDate, + zone: string, +): BillingPeriod { + const fromInstant = startPlain.toZonedDateTime({ timeZone: zone, plainTime: MIDNIGHT }).toInstant(); + const toInstant = endPlain.toZonedDateTime({ timeZone: zone, plainTime: MIDNIGHT }).toInstant(); + return { + fromUtc: new Date(fromInstant.epochMilliseconds), + toUtcExclusive: new Date(toInstant.epochMilliseconds), + }; +} + +function addMonths(year: number, month: number, count: number): { year: number; month: number } { + const total = year * 12 + (month - 1) + count; + return { year: Math.floor(total / 12), month: (total % 12) + 1 }; +} \ No newline at end of file diff --git a/src/modules/billing/queries.test.ts b/src/modules/billing/queries.test.ts new file mode 100644 index 0000000..0ccc9c4 --- /dev/null +++ b/src/modules/billing/queries.test.ts @@ -0,0 +1,243 @@ +import { expect, test } from "vitest"; + +import { + createBillingQueries, + type BillingRepository, + type RawBillableUsage, + type RawRepeatDownload, +} from "./queries"; +import { monthPeriod, type BillingPeriod } from "./period"; + +const august2026: BillingPeriod = monthPeriod(2026, 8); +const fromUtc = august2026.fromUtc; +const toUtcExclusive = august2026.toUtcExclusive; + +function createRepository() { + const billable: RawBillableUsage[] = []; + const repeatDownloads: RawRepeatDownload[] = []; + + const repository: BillingRepository = { + async findBillableUsages(editorialId, from, to) { + expect(editorialId).toBe("e1"); + expect(from).toBe(fromUtc); + expect(to).toBe(toUtcExclusive); + return billable; + }, + async findRepeatDownloads(editorialId, from, to) { + expect(editorialId).toBe("e1"); + expect(from).toBe(fromUtc); + expect(to).toBe(toUtcExclusive); + return repeatDownloads; + }, + }; + + return { repository, billable, repeatDownloads }; +} + +function createQueries() { + const state = createRepository(); + return { ...state, queries: createBillingQueries({ repository: state.repository }) }; +} + +test("returns billed rows disabled and open rows selectable", async () => { + const { queries, billable } = createQueries(); + billable.push( + { + id: "u1", + immichAssetId: "asset-1", + filenameSnapshot: "jubel.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Titelgeschichte", + internalReference: "Ausgabe 8/26", + priceCents: 1_500, + billingStatus: "open", + createdAt: new Date("2026-08-05T10:00:00.000Z"), + billingReportId: null, + reportNumber: null, + invoiceNumber: null, + }, + { + id: "u2", + immichAssetId: "asset-2", + filenameSnapshot: "sport.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Sportbericht", + internalReference: null, + priceCents: 1_500, + billingStatus: "billed", + createdAt: new Date("2026-08-06T10:00:00.000Z"), + billingReportId: "r1", + reportNumber: 42, + invoiceNumber: "RE-2026-042", + }, + { + id: "u3", + immichAssetId: "asset-3", + filenameSnapshot: "redaktion.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Reopened story", + internalReference: null, + priceCents: 1_500, + billingStatus: "reopened", + createdAt: new Date("2026-08-07T10:00:00.000Z"), + billingReportId: null, + reportNumber: null, + invoiceNumber: null, + }, + ); + + const result = await queries.listBillablePositions("e1", august2026); + + expect(result.find((x) => x.status === "billed")?.selectable).toBe(false); + expect(result.find((x) => x.status === "open")?.selectable).toBe(true); + expect(result.find((x) => x.status === "reopened")?.selectable).toBe(true); +}); + +test("maps raw billable usages to billing positions with snapshot fields", async () => { + const { queries, billable } = createQueries(); + billable.push({ + id: "u1", + immichAssetId: "asset-1", + filenameSnapshot: "jubel.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Titelgeschichte", + internalReference: "Ausgabe 8/26", + priceCents: 6_000, + billingStatus: "open", + createdAt: new Date("2026-08-05T10:00:00.000Z"), + billingReportId: null, + reportNumber: null, + invoiceNumber: null, + }); + + const [position] = await queries.listBillablePositions("e1", august2026); + + expect(position).toEqual({ + id: "u1", + assetId: "asset-1", + filename: "jubel.jpg", + albumName: "Presse 2026", + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + priceCents: 6_000, + status: "open", + selectable: true, + createdAt: new Date("2026-08-05T10:00:00.000Z"), + reportNumber: null, + invoiceNumber: null, + }); +}); + +test("surfaces report and invoice references on billed positions", async () => { + const { queries, billable } = createQueries(); + billable.push({ + id: "u2", + immichAssetId: "asset-2", + filenameSnapshot: "sport.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Sportbericht", + internalReference: null, + priceCents: 1_500, + billingStatus: "billed", + createdAt: new Date("2026-08-06T10:00:00.000Z"), + billingReportId: "r1", + reportNumber: 42, + invoiceNumber: "RE-2026-042", + }); + + const [position] = await queries.listBillablePositions("e1", august2026); + + expect(position.status).toBe("billed"); + expect(position.selectable).toBe(false); + expect(position.reportNumber).toBe(42); + expect(position.invoiceNumber).toBe("RE-2026-042"); +}); + +test("excludes voided usages from billable positions", async () => { + const { queries, billable } = createQueries(); + billable.push( + { + id: "u-void", + immichAssetId: "asset-void", + filenameSnapshot: "void.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Voided", + internalReference: null, + priceCents: 1_500, + billingStatus: "voided", + createdAt: new Date("2026-08-03T10:00:00.000Z"), + billingReportId: null, + reportNumber: null, + invoiceNumber: null, + }, + { + id: "u-open", + immichAssetId: "asset-open", + filenameSnapshot: "open.jpg", + albumNameSnapshot: "Presse 2026", + purpose: "Open", + internalReference: null, + priceCents: 1_500, + billingStatus: "open", + createdAt: new Date("2026-08-04T10:00:00.000Z"), + billingReportId: null, + reportNumber: null, + invoiceNumber: null, + }, + ); + + const result = await queries.listBillablePositions("e1", august2026); + + expect(result).toHaveLength(1); + expect(result[0].id).toBe("u-open"); +}); + +test("returns repeat download events in the period as non-billable positions", async () => { + const { queries, repeatDownloads } = createQueries(); + repeatDownloads.push({ + id: "d1", + immichAssetId: "asset-1", + usageId: "u1", + authorizedAt: new Date("2026-08-10T12:00:00.000Z"), + status: "completed", + repeatDownloadNote: "Zweite Nutzung", + }); + + const result = await queries.listNonBillableDownloads("e1", august2026); + + expect(result).toEqual([ + { + id: "d1", + assetId: "asset-1", + usageId: "u1", + authorizedAt: new Date("2026-08-10T12:00:00.000Z"), + status: "completed", + repeatDownloadNote: "Zweite Nutzung", + }, + ]); +}); + +test("includes repeat downloads even if the original usage was already billed", async () => { + const { queries, repeatDownloads } = createQueries(); + repeatDownloads.push({ + id: "d1", + immichAssetId: "asset-1", + usageId: "u1", + authorizedAt: new Date("2026-08-10T12:00:00.000Z"), + status: "interrupted", + repeatDownloadNote: null, + }); + + const result = await queries.listNonBillableDownloads("e1", august2026); + + expect(result).toHaveLength(1); + expect(result[0].status).toBe("interrupted"); +}); + +test("returns an empty array when no repeat downloads exist", async () => { + const { queries } = createQueries(); + + const result = await queries.listNonBillableDownloads("e1", august2026); + + expect(result).toEqual([]); +}); \ No newline at end of file diff --git a/src/modules/billing/queries.ts b/src/modules/billing/queries.ts new file mode 100644 index 0000000..fa45840 --- /dev/null +++ b/src/modules/billing/queries.ts @@ -0,0 +1,206 @@ +import "server-only"; + +import { and, desc, eq, gte, inArray, lt } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { billingReports, downloadEvents, usages } from "@/db/schema"; +import type * as schema from "@/db/schema"; + +import type { BillingPeriod } from "./period"; + +// --------------------------------------------------------------------------- +// Domain types +// --------------------------------------------------------------------------- + +export type BillingPosition = { + id: string; + assetId: string; + filename: string; + albumName: string; + purpose: string; + reference: string | null; + priceCents: number; + status: "open" | "billed" | "reopened"; + selectable: boolean; + createdAt: Date; + reportNumber: number | null; + invoiceNumber: string | null; +}; + +export type RepeatDownloadPosition = { + id: string; + assetId: string; + usageId: string; + authorizedAt: Date; + status: string; + repeatDownloadNote: string | null; +}; + +// --------------------------------------------------------------------------- +// Repository interface (raw DB rows) +// --------------------------------------------------------------------------- + +export type RawBillableUsage = { + id: string; + immichAssetId: string; + filenameSnapshot: string; + albumNameSnapshot: string; + purpose: string; + internalReference: string | null; + priceCents: number; + billingStatus: "open" | "billed" | "reopened" | "voided"; + createdAt: Date; + billingReportId: string | null; + reportNumber: number | null; + invoiceNumber: string | null; +}; + +export type RawRepeatDownload = { + id: string; + immichAssetId: string; + usageId: string; + authorizedAt: Date; + status: string; + repeatDownloadNote: string | null; +}; + +export type BillingRepository = { + findBillableUsages( + editorialId: string, + fromUtc: Date, + toUtcExclusive: Date, + ): Promise; + findRepeatDownloads( + editorialId: string, + fromUtc: Date, + toUtcExclusive: Date, + ): Promise; +}; + +// --------------------------------------------------------------------------- +// Service factory +// --------------------------------------------------------------------------- + +export function createBillingQueries({ repository }: { repository: BillingRepository }) { + return { + async listBillablePositions( + editorialId: string, + period: BillingPeriod, + ): Promise { + const rows = await repository.findBillableUsages( + editorialId, + period.fromUtc, + period.toUtcExclusive, + ); + return rows + .filter((row) => row.billingStatus !== "voided") + .map((row) => toBillingPosition(row)); + }, + + async listNonBillableDownloads( + editorialId: string, + period: BillingPeriod, + ): Promise { + const rows = await repository.findRepeatDownloads( + editorialId, + period.fromUtc, + period.toUtcExclusive, + ); + return rows.map((row) => ({ + id: row.id, + assetId: row.immichAssetId, + usageId: row.usageId, + authorizedAt: row.authorizedAt, + status: row.status, + repeatDownloadNote: row.repeatDownloadNote, + })); + }, + }; +} + +function toBillingPosition(row: RawBillableUsage): BillingPosition { + const status = row.billingStatus as BillingPosition["status"]; + return { + id: row.id, + assetId: row.immichAssetId, + filename: row.filenameSnapshot, + albumName: row.albumNameSnapshot, + purpose: row.purpose, + reference: row.internalReference, + priceCents: row.priceCents, + status, + selectable: status === "open" || status === "reopened", + createdAt: row.createdAt, + reportNumber: row.reportNumber, + invoiceNumber: row.invoiceNumber, + }; +} + +// --------------------------------------------------------------------------- +// Drizzle repository implementation +// --------------------------------------------------------------------------- + +export function createBillingRepository( + database: NodePgDatabase, +): BillingRepository { + return { + async findBillableUsages(editorialId, fromUtc, toUtcExclusive) { + return database + .select({ + id: usages.id, + immichAssetId: usages.immichAssetId, + filenameSnapshot: usages.filenameSnapshot, + albumNameSnapshot: usages.albumNameSnapshot, + purpose: usages.purpose, + internalReference: usages.internalReference, + priceCents: usages.priceCents, + billingStatus: usages.billingStatus, + createdAt: usages.createdAt, + billingReportId: usages.billingReportId, + reportNumber: billingReports.reportNumber, + invoiceNumber: billingReports.invoiceNumber, + }) + .from(usages) + .leftJoin(billingReports, eq(usages.billingReportId, billingReports.id)) + .where( + and( + eq(usages.editorialAccountId, editorialId), + gte(usages.createdAt, fromUtc), + lt(usages.createdAt, toUtcExclusive), + inArray(usages.billingStatus, ["open", "billed", "reopened"]), + ), + ) + .orderBy(desc(usages.createdAt), desc(usages.id)); + }, + + async findRepeatDownloads(editorialId, fromUtc, toUtcExclusive) { + return database + .select({ + id: downloadEvents.id, + immichAssetId: downloadEvents.immichAssetId, + usageId: downloadEvents.usageId, + authorizedAt: downloadEvents.authorizedAt, + status: downloadEvents.status, + repeatDownloadNote: downloadEvents.repeatDownloadNote, + }) + .from(downloadEvents) + .where( + and( + eq(downloadEvents.editorialAccountId, editorialId), + gte(downloadEvents.authorizedAt, fromUtc), + lt(downloadEvents.authorizedAt, toUtcExclusive), + eq(downloadEvents.intentKind, "repeat_download"), + inArray(downloadEvents.status, ["completed", "interrupted"]), + ), + ) + .orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id)); + }, + }; +} + +// --------------------------------------------------------------------------- +// Default singleton wired to the real database +// --------------------------------------------------------------------------- + +export const queries = createBillingQueries({ repository: createBillingRepository(db) }); \ No newline at end of file