feat(import): an Import page, with the numbers of every import kept

The report of an import used to be shown once in Settings and lost. Each
import is now stored (migration 0030, spotify_imports) as the report in
JSON, and GET /me/import/spotify lists the past ones, newest first.
POST /me/import/spotify answers with the same shape plus id and created_at.

The web app gets an Import page (menu, More tab) with the form and one card
for each past import: plays read, added, already there, not in the library,
the playlists it made and the artists that are missing. Settings only links
to it. An import that finds nothing is not kept, and a report that cannot be
stored is still returned to the person who asked.
This commit is contained in:
tgiachi 2026-11-15 10:34:12 +01:00
commit aa4883b955
17 changed files with 868 additions and 154 deletions

View file

@ -1,4 +1,4 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/api/client'
import type { components } from '@/api/schema'
@ -20,3 +20,14 @@ export function useImportSpotify() {
onSuccess: () => client.invalidateQueries(),
})
}
/** How many past imports the page reads: they are rare, so the page shows them all. */
const PAST_LIMIT = 100
/** What each import did, newest first. */
export function useSpotifyImports() {
return useQuery({
queryKey: ['imports', 'spotify'],
queryFn: () => api.get<components['schemas']['SpotifyImportPage']>(`/me/import/spotify?limit=${PAST_LIMIT}`),
})
}

View file

@ -1553,7 +1553,14 @@ export interface paths {
path?: never;
cookie?: never;
};
get?: never;
/**
* Your past imports of Spotify data
* @description What each import of yours did, newest first: how many plays were recorded, how many were already there,
* how many are not in your library, the playlists it made and the artists you are missing. The files
* themselves are never kept, only these numbers. Only yours. An import is listed once it is done; one that
* found nothing is not.
*/
get: operations["listMySpotifyImports"];
put?: never;
/**
* Import your Spotify history and playlists
@ -3801,7 +3808,21 @@ export interface components {
*/
discover_from_listening: boolean;
};
SpotifyImportPage: {
items: components["schemas"]["SpotifyImportReport"][];
/** @description Size of the whole result, not of this page. */
total: number;
limit: number;
offset: number;
};
SpotifyImportReport: {
/** @description The import. 0 when its report could not be kept. */
id: number;
/**
* Format: date-time
* @description When the import was done.
*/
created_at: string;
history: {
/** @description Plays of songs that were read. */
entries: number;
@ -6646,6 +6667,32 @@ export interface operations {
401: components["responses"]["Unauthorized"];
};
};
listMySpotifyImports: {
parameters: {
query?: {
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of imports. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["SpotifyImportPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
};
};
importMySpotify: {
parameters: {
query?: never;
@ -6662,7 +6709,10 @@ export interface operations {
};
};
responses: {
/** @description What the import did. */
/**
* @description What the import did. It is also kept (`GET /me/import/spotify`); if keeping it failed the report is still
* sent, with `id` 0.
*/
200: {
headers: {
[name: string]: unknown;

View file

@ -0,0 +1,59 @@
import { render, screen, within } from '@testing-library/react'
import { beforeEach, expect, test, vi } from 'vitest'
import type { SpotifyImportReport } from '@/api/importSpotify'
import { initI18n } from '@/i18n'
import ImportReportCard from './ImportReportCard'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
})
const report: SpotifyImportReport = {
id: 3,
created_at: '2026-11-15T10:00:00Z',
history: { entries: 120, matched: 100, imported: 80, already_there: 20, not_found: 20, ignored: 3 },
playlists: [
{ name: 'Road', tracks: 20, matched: 15, status: 'created' },
{ name: 'Mine', tracks: 5, matched: 5, status: 'exists' },
{ name: 'Nothing', tracks: 4, matched: 0, status: 'empty' },
],
missing: { total: 3, artists: [{ name: 'Blur', count: 9 }, { name: 'Oasis', count: 4 }] },
}
test('a card says when the import was done and what it did', () => {
render(<ImportReportCard report={report} />)
const card = screen.getByRole('article', { name: /^Import of November 15, 2026/ })
expect(within(card).getByText('120 plays read from the files.')).toBeInTheDocument()
expect(within(card).getByText('80 listens added to your history.')).toBeInTheDocument()
expect(within(card).getByText('20 were already there.')).toBeInTheDocument()
expect(within(card).getByText('20 plays are of songs that are not in your library.')).toBeInTheDocument()
expect(within(card).getByText(/3 plays skipped/)).toBeInTheDocument()
})
test('the playlists say what became of each', () => {
render(<ImportReportCard report={report} />)
expect(screen.getByText('Road: 15 of 20 songs found')).toBeInTheDocument()
expect(screen.getByText('Made')).toBeInTheDocument()
expect(screen.getByText('You already have one with this name')).toBeInTheDocument()
expect(screen.getByText('None of its songs is in your library')).toBeInTheDocument()
})
test('the missing artists are behind a summary that counts them, most played first', () => {
render(<ImportReportCard report={report} />)
expect(screen.getByText('3 artists you are missing')).toBeInTheDocument()
expect(screen.getByText('Blur')).toBeInTheDocument()
expect(screen.getByText('9')).toBeInTheDocument()
expect(screen.getByText('and 1 more')).toBeInTheDocument() // 3 artists miss songs, 2 are listed
})
test('an import with nothing to show says so, and has no empty lists', () => {
render(
<ImportReportCard
report={{ ...report, history: { entries: 0, matched: 0, imported: 0, already_there: 0, not_found: 0, ignored: 0 }, playlists: [], missing: { total: 0, artists: [] } }}
/>,
)
expect(screen.getByText('No plays in these files.')).toBeInTheDocument()
expect(screen.queryByText('Playlists')).not.toBeInTheDocument()
expect(screen.queryByText(/you are missing/)).not.toBeInTheDocument()
})

View file

@ -0,0 +1,64 @@
import { useTranslation } from 'react-i18next'
import type { SpotifyImportReport } from '@/api/importSpotify'
/**
* What one import of Spotify data did, with the day it was done: the plays added, the ones that were already there,
* the ones of songs that are not in the library, the playlists it made and the artists that are missing.
*/
export default function ImportReportCard({ report }: { report: SpotifyImportReport }) {
const { t, i18n } = useTranslation()
const h = report.history
const more = report.missing.total - report.missing.artists.length
const when = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'long', timeStyle: 'short' }).format(new Date(report.created_at))
const title = t('spotify.importOf', { when })
return (
<article aria-label={title} className="flex flex-col gap-4 border-t border-border pt-6 first:border-t-0 first:pt-0">
<h3 className="text-lg font-bold">{title}</h3>
{h.entries === 0 && report.playlists.length === 0 ? (
<p>{t('spotify.noPlays')}</p>
) : (
h.entries > 0 && (
<ul className="flex flex-col gap-1 tabular-nums">
<li>{t('spotify.read', { count: h.entries })}</li>
<li className="font-semibold">{t('spotify.imported', { count: h.imported })}</li>
{h.already_there > 0 && <li>{t('spotify.already', { count: h.already_there })}</li>}
{h.not_found > 0 && <li>{t('spotify.notFound', { count: h.not_found })}</li>}
{h.ignored > 0 && <li>{t('spotify.ignored', { count: h.ignored })}</li>}
</ul>
)
)}
{report.playlists.length > 0 && (
<div className="flex flex-col gap-2">
<h4 className="font-semibold">{t('spotify.playlists')}</h4>
<ul className="flex flex-col gap-2">
{report.playlists.map((p, i) => (
<li key={`${i}-${p.name}`} className="flex flex-col">
<span>{t('spotify.playlistLine', { name: p.name, matched: p.matched, tracks: p.tracks })}</span>
<span className="text-sm text-muted-foreground">{t(`spotify.status.${p.status}`)}</span>
</li>
))}
</ul>
</div>
)}
{report.missing.artists.length > 0 && (
<details className="flex flex-col gap-2">
<summary className="min-h-11 cursor-pointer font-semibold">{t('spotify.missingCount', { count: report.missing.total })}</summary>
<p className="text-sm text-muted-foreground">{t('spotify.missing')}</p>
<ul className="flex max-h-72 flex-col gap-1 overflow-y-auto text-sm">
{report.missing.artists.map((a) => (
<li key={a.name} className="flex justify-between gap-4">
<span>{a.name}</span>
<span className="tabular-nums text-muted-foreground">{a.count}</span>
</li>
))}
</ul>
{more > 0 && <p className="text-sm text-muted-foreground">{t('spotify.missingMore', { count: more })}</p>}
</details>
)}
</article>
)
}

View file

@ -1,5 +1,5 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
@ -12,6 +12,8 @@ beforeEach(async () => {
})
const report = {
id: 3,
created_at: '2026-11-15T10:00:00Z',
history: { entries: 120, matched: 100, imported: 80, already_there: 20, not_found: 20, ignored: 3 },
playlists: [
{ name: 'Road', tracks: 20, matched: 15, status: 'created' },
@ -43,31 +45,20 @@ test('it says what is imported and that nothing leaves the server', () => {
expect(screen.getByRole('button', { name: 'Import' })).toBeDisabled()
})
test('the files are sent together as a form, and the report says what was done', async () => {
test('the files are sent together as a form, and the import says it is done', async () => {
const { calls } = setup()
await userEvent.upload(screen.getByLabelText('Files from Spotify'), [zip, json])
expect(screen.getByText('2 files chosen')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Import' }))
const done = await screen.findByRole('region', { name: 'Import done' })
expect(await screen.findByRole('status')).toHaveTextContent(/Import done/)
const sent = calls.filter((c) => c.key === 'POST /api/v1/me/import/spotify')
expect(sent).toHaveLength(1)
const form = sent[0].init.body as FormData
expect(form.getAll('files').map((f) => (f as File).name)).toEqual(['my_spotify_data.zip', 'Streaming_History_Audio_2020_0.json'])
expect(within(done).getByText('80 listens added to your history.')).toBeInTheDocument()
expect(within(done).getByText('20 were already there.')).toBeInTheDocument()
expect(within(done).getByText('20 plays are of songs that are not in your library.')).toBeInTheDocument()
expect(within(done).getByText(/3 plays skipped/)).toBeInTheDocument()
expect(within(done).getByText('Road: 15 of 20 songs found')).toBeInTheDocument()
expect(within(done).getByText('Made')).toBeInTheDocument()
expect(within(done).getByText('You already have one with this name')).toBeInTheDocument()
expect(within(done).getByText('None of its songs is in your library')).toBeInTheDocument()
expect(within(done).getByText('Blur')).toBeInTheDocument()
expect(within(done).getByText('9')).toBeInTheDocument()
expect(within(done).getByText('and 1 more')).toBeInTheDocument() // 3 artists have songs not found, 2 are shown
})
test('while it works the button is off and says so', async () => {
let finish: (r: Response) => void = () => {}
setup({ 'POST /api/v1/me/import/spotify': () => new Promise<Response>((resolve) => (finish = resolve)) })
@ -76,7 +67,7 @@ test('while it works the button is off and says so', async () => {
expect(await screen.findByRole('status')).toHaveTextContent(/Importing/)
expect(screen.getByRole('button', { name: 'Import' })).toBeDisabled()
finish(new Response(JSON.stringify(report), { status: 200, headers: { 'Content-Type': 'application/json' } }))
expect(await screen.findByRole('region', { name: 'Import done' })).toBeInTheDocument()
expect(await screen.findByText(/Import done/)).toBeInTheDocument()
})
test('files that are not Spotify’s are explained', async () => {
@ -84,7 +75,7 @@ test('files that are not Spotify’s are explained', async () => {
await userEvent.upload(screen.getByLabelText('Files from Spotify'), json)
await userEvent.click(screen.getByRole('button', { name: 'Import' }))
expect(await screen.findByRole('alert')).toHaveTextContent(/do not hold a Spotify streaming history or playlists/)
expect(screen.queryByRole('region', { name: 'Import done' })).not.toBeInTheDocument()
expect(screen.queryByText(/Import done/)).not.toBeInTheDocument()
})
test('an import that is too large, damaged or already running has its own message', async () => {
@ -100,10 +91,3 @@ test('an import that is too large, damaged or already running has its own messag
expect(await screen.findByRole('alert')).toHaveTextContent(text)
}
})
test('an import with no plays in it says so', async () => {
setup({ 'POST /api/v1/me/import/spotify': () => ({ ...report, history: { entries: 0, matched: 0, imported: 0, already_there: 0, not_found: 0, ignored: 0 }, playlists: [], missing: { total: 0, artists: [] } }) })
await userEvent.upload(screen.getByLabelText('Files from Spotify'), json)
await userEvent.click(screen.getByRole('button', { name: 'Import' }))
expect(await screen.findByText('No plays in these files.')).toBeInTheDocument()
})

View file

@ -1,14 +1,14 @@
import { useState, type ChangeEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { ApiError } from '@/api/client'
import { useImportSpotify, type SpotifyImportReport } from '@/api/importSpotify'
import { useImportSpotify } from '@/api/importSpotify'
import { Button } from '@/components/ui/button'
import { errorMessageKey } from '@/i18n'
/**
* Bringing the history and the playlists of a Spotify export in. The files are sent to this server, which reads them
* and keeps nothing of them but the listens and playlists that match the library; the report says what was done and
* which artists are missing from the library.
* and keeps nothing of them but the listens and playlists that match the library. What was done is kept as a report,
* which the list of past imports shows (ImportReportCard).
*/
export default function SpotifyImportBlock() {
const { t } = useTranslation()
@ -53,60 +53,11 @@ export default function SpotifyImportBlock() {
{t(errorMessageKey(run.error instanceof ApiError ? run.error.code : 'unknown'))}
</p>
)}
{run.data && !run.isPending && <Report report={run.data} />}
{run.isSuccess && (
<p role="status" className="text-sm font-semibold">
{t('spotify.finished')}
</p>
)}
</div>
)
}
function Report({ report }: { report: SpotifyImportReport }) {
const { t } = useTranslation()
const h = report.history
const more = report.missing.total - report.missing.artists.length
return (
<section aria-label={t('spotify.done')} className="flex flex-col gap-4 border-t border-border pt-4">
<h3 className="text-lg font-bold">{t('spotify.done')}</h3>
{h.entries === 0 && report.playlists.length === 0 ? (
<p>{t('spotify.noPlays')}</p>
) : (
h.entries > 0 && (
<ul className="flex flex-col gap-1 tabular-nums">
<li className="font-semibold">{t('spotify.imported', { count: h.imported })}</li>
{h.already_there > 0 && <li>{t('spotify.already', { count: h.already_there })}</li>}
{h.not_found > 0 && <li>{t('spotify.notFound', { count: h.not_found })}</li>}
{h.ignored > 0 && <li>{t('spotify.ignored', { count: h.ignored })}</li>}
</ul>
)
)}
{report.playlists.length > 0 && (
<div className="flex flex-col gap-2">
<h4 className="font-semibold">{t('spotify.playlists')}</h4>
<ul className="flex flex-col gap-2">
{report.playlists.map((p, i) => (
<li key={`${i}-${p.name}`} className="flex flex-col">
<span>{t('spotify.playlistLine', { name: p.name, matched: p.matched, tracks: p.tracks })}</span>
<span className="text-sm text-muted-foreground">{t(`spotify.status.${p.status}`)}</span>
</li>
))}
</ul>
</div>
)}
{report.missing.artists.length > 0 && (
<div className="flex flex-col gap-2">
<h4 className="font-semibold">{t('spotify.missing')}</h4>
<ul className="flex max-h-72 flex-col gap-1 overflow-y-auto text-sm">
{report.missing.artists.map((a) => (
<li key={a.name} className="flex justify-between gap-4">
<span>{a.name}</span>
<span className="tabular-nums text-muted-foreground">{a.count}</span>
</li>
))}
</ul>
{more > 0 && <p className="text-sm text-muted-foreground">{t('spotify.missingMore', { count: more })}</p>}
</div>
)}
</section>
)
}

View file

@ -27,7 +27,7 @@ function renderSidebar(friends: { id: number; name: string }[] = [], path = '/al
test('the menu is words, one for each page, and the page that is open is the current one', () => {
const nav = renderSidebar()
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'Admin', 'Settings']) {
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'Import', 'Admin', 'Settings']) {
expect(within(nav).getByRole('link', { name })).toBeInTheDocument()
}
expect(within(nav).getByRole('link', { name: 'Albums' })).toHaveAttribute('aria-current', 'page')

View file

@ -15,6 +15,7 @@ const LINKS: { to: string; key: string; end: boolean; adminOnly: boolean; friend
{ to: '/mixes', key: 'nav.mixes', end: false, adminOnly: false },
{ to: '/playlists', key: 'nav.playlists', end: false, adminOnly: false },
{ to: '/smart-playlists', key: 'nav.smartPlaylists', end: false, adminOnly: false },
{ to: '/import', key: 'nav.import', end: false, adminOnly: false },
{ to: '/friends', key: 'nav.friends', end: false, adminOnly: false, friends: true },
{ to: '/admin', key: 'nav.admin', end: false, adminOnly: true },
{ to: '/settings', key: 'nav.settings', end: false, adminOnly: false },

View file

@ -19,6 +19,7 @@
"friends": "Friends",
"admin": "Admin",
"settings": "Settings",
"import": "Import",
"more": "More",
"tabs": "Tabs"
},
@ -99,7 +100,9 @@
"replayGainTrack": "Song by song",
"replayGainAlbum": "Album by album",
"replayGainOff": "Off",
"spotify": "Import from Spotify",
"spotify": "Import",
"importHint": "Bring in your Spotify history and playlists, and see what each import did, on the Import page.",
"importLink": "Open the Import page",
"password": "Password",
"currentPassword": "Current password",
"newPassword": "New password",
@ -792,7 +795,12 @@
"chosen_other": "{{count}} files chosen",
"start": "Import",
"running": "Importing. With a long history this can take a minute…",
"done": "Import done",
"finished": "Import done. What it did is the first one in the list below.",
"importOf": "Import of {{when}}",
"read_one": "{{count}} play read from the files.",
"read_other": "{{count}} plays read from the files.",
"missingCount_one": "{{count}} artist you are missing",
"missingCount_other": "{{count}} artists you are missing",
"noPlays": "No plays in these files.",
"imported_one": "{{count}} listen added to your history.",
"imported_other": "{{count}} listens added to your history.",
@ -813,6 +821,11 @@
"missing": "Artists you play on Spotify and have no music of here",
"missingMore": "and {{count}} more"
},
"import": {
"spotify": "Spotify",
"past": "Past imports",
"none": "No import yet. When you bring in a Spotify export, what it did is kept here."
},
"playlists": {
"empty": "You have no playlists yet. Make one below, or put a song in a new one with the playlist button next to it.",
"newLabel": "Name of the new playlist",

View file

@ -19,6 +19,7 @@
"friends": "Amici",
"admin": "Admin",
"settings": "Impostazioni",
"import": "Importa",
"more": "Altro",
"tabs": "Schede"
},
@ -99,7 +100,9 @@
"replayGainTrack": "Brano per brano",
"replayGainAlbum": "Album per album",
"replayGainOff": "Disattivato",
"spotify": "Importa da Spotify",
"spotify": "Importa",
"importHint": "Porta qui la cronologia e le playlist di Spotify, e guarda cosa ha fatto ogni importazione, nella pagina Importa.",
"importLink": "Apri la pagina Importa",
"password": "Password",
"currentPassword": "Password attuale",
"newPassword": "Nuova password",
@ -792,7 +795,12 @@
"chosen_other": "{{count}} file scelti",
"start": "Importa",
"running": "Importazione in corso. Con una cronologia lunga può volerci un minuto…",
"done": "Importazione finita",
"finished": "Importazione finita. Cosa ha fatto è la prima della lista qui sotto.",
"importOf": "Importazione del {{when}}",
"read_one": "{{count}} ascolto letto dai file.",
"read_other": "{{count}} ascolti letti dai file.",
"missingCount_one": "{{count}} artista che ti manca",
"missingCount_other": "{{count}} artisti che ti mancano",
"noPlays": "Nessun ascolto in questi file.",
"imported_one": "{{count}} ascolto aggiunto alla cronologia.",
"imported_other": "{{count}} ascolti aggiunti alla cronologia.",
@ -813,6 +821,11 @@
"missing": "Artisti che ascolti su Spotify e di cui qui non hai musica",
"missingMore": "e altri {{count}}"
},
"import": {
"spotify": "Spotify",
"past": "Importazioni passate",
"none": "Nessuna importazione, per ora. Quando porti qui un export di Spotify, cosa ha fatto resta salvato qui."
},
"playlists": {
"empty": "Non hai ancora nessuna playlist. Creane una qui sotto, oppure metti un brano in una nuova con il pulsante accanto al brano.",
"newLabel": "Nome della nuova playlist",

View file

@ -0,0 +1,81 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
import ImportPage from './ImportPage'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
})
const run = (id: number, imported: number, at: string) => ({
id,
created_at: at,
history: { entries: imported + 5, matched: imported, imported, already_there: 0, not_found: 5, ignored: 0 },
playlists: [],
missing: { total: 1, artists: [{ name: 'Blur', count: 5 }] },
})
function setup(routes: MockRoutes) {
const mocked = mockFetch(routes)
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
render(
<QueryClientProvider client={client}>
<MemoryRouter>
<ImportPage />
</MemoryRouter>
</QueryClientProvider>,
)
return mocked
}
test('the page has the form to import and the imports of the past, newest first', async () => {
setup({
'GET /api/v1/me/import/spotify': () => ({ items: [run(2, 40, '2026-11-15T10:00:00Z'), run(1, 7, '2026-11-01T09:00:00Z')], total: 2, limit: 100, offset: 0 }),
})
expect(screen.getByRole('heading', { level: 1, name: 'Import' })).toBeInTheDocument()
expect(screen.getByLabelText('Files from Spotify')).toBeInTheDocument()
const past = await screen.findByRole('region', { name: 'Past imports' })
const cards = await within(past).findAllByRole('article')
expect(cards).toHaveLength(2)
expect(within(cards[0]).getByText('40 listens added to your history.')).toBeInTheDocument()
expect(within(cards[1]).getByText('7 listens added to your history.')).toBeInTheDocument()
})
test('with no import yet it says where they will be kept', async () => {
setup({ 'GET /api/v1/me/import/spotify': () => ({ items: [], total: 0, limit: 100, offset: 0 }) })
expect(await screen.findByText(/No import yet/)).toBeInTheDocument()
})
test('a list that cannot be read has a way to try again', async () => {
let fail = true
const { calls } = setup({
'GET /api/v1/me/import/spotify': () => (fail ? apiError(500, 'internal', 'x') : { items: [run(1, 3, '2026-11-01T09:00:00Z')], total: 1, limit: 100, offset: 0 }),
})
const retry = await screen.findByRole('button', { name: 'Try again' })
fail = false
await userEvent.click(retry)
expect(await screen.findByText('3 listens added to your history.')).toBeInTheDocument()
expect(calls.filter((c) => c.key === 'GET /api/v1/me/import/spotify').length).toBeGreaterThan(1)
})
test('an import that is done shows up in the list', async () => {
let done = false
setup({
'GET /api/v1/me/import/spotify': () => ({ items: done ? [run(1, 12, '2026-11-15T10:00:00Z')] : [], total: done ? 1 : 0, limit: 100, offset: 0 }),
'POST /api/v1/me/import/spotify': () => {
done = true
return run(1, 12, '2026-11-15T10:00:00Z')
},
})
await screen.findByText(/No import yet/)
await userEvent.upload(screen.getByLabelText('Files from Spotify'), new File(['PK'], 'my_spotify_data.zip'))
await userEvent.click(screen.getByRole('button', { name: 'Import' }))
expect(await screen.findByText('12 listens added to your history.')).toBeInTheDocument()
expect(screen.queryByText(/No import yet/)).not.toBeInTheDocument()
})

View file

@ -0,0 +1,38 @@
import { useTranslation } from 'react-i18next'
import { useSpotifyImports } from '@/api/importSpotify'
import ImportReportCard from '@/components/ImportReportCard'
import PageTitle from '@/components/PageTitle'
import Section from '@/components/Section'
import SpotifyImportBlock from '@/components/SpotifyImportBlock'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
/** Bringing music data in from elsewhere (for now Spotify), and what each import did, kept so it can be read again. */
export default function ImportPage() {
const { t } = useTranslation()
const past = useSpotifyImports()
return (
<div className="flex flex-col gap-10">
<PageTitle>{t('nav.import')}</PageTitle>
<Section title={t('import.spotify')}>
<SpotifyImportBlock />
</Section>
<Section title={t('import.past')}>
{past.isError ? (
<ErrorMessage error={past.error} onRetry={() => void past.refetch()} />
) : past.isPending ? (
<Loading />
) : past.data.items.length === 0 ? (
<EmptyMessage>{t('import.none')}</EmptyMessage>
) : (
<div className="flex max-w-xl flex-col gap-6">
{past.data.items.map((report) => (
<ImportReportCard key={report.id} report={report} />
))}
</div>
)}
</Section>
</div>
)
}

View file

@ -31,7 +31,7 @@ test('Library is a list of the places of the music, each a row that leads there'
])
})
test('More has Settings, and Admin only for an admin', () => {
test('More has Import and Settings, and Admin only for an admin', () => {
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'ann@example.org', is_admin: false } })
const { unmount } = render(
<MemoryRouter>
@ -39,6 +39,7 @@ test('More has Settings, and Admin only for an admin', () => {
</MemoryRouter>,
)
expect(screen.getByRole('heading', { level: 1, name: 'More' })).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Import' })).toHaveAttribute('href', '/import')
expect(screen.getByRole('link', { name: 'Settings' })).toHaveAttribute('href', '/settings')
expect(screen.queryByRole('link', { name: 'Admin' })).not.toBeInTheDocument()
unmount()

View file

@ -7,7 +7,10 @@ import PageTitle from '@/components/PageTitle'
export default function MorePage() {
const { t } = useTranslation()
const { user } = useSession()
const links = [{ to: '/settings', label: t('nav.settings') }]
const links = [
{ to: '/import', label: t('nav.import') },
{ to: '/settings', label: t('nav.settings') },
]
if (user?.is_admin) links.push({ to: '/admin', label: t('nav.admin') })
return (
<div className="flex flex-col gap-6">

View file

@ -104,6 +104,13 @@ test('choosing Italian changes the words on the page', async () => {
expect(localStorage.getItem('sonda.lang')).toBe('it')
})
test('Settings points to the Import page instead of holding the form', () => {
renderSettings()
const group = screen.getByRole('region', { name: 'Import' })
expect(within(group).getByRole('link', { name: 'Open the Import page' })).toHaveAttribute('href', '/import')
expect(screen.queryByLabelText('Files from Spotify')).not.toBeInTheDocument()
})
test('Discover has its own group with the switch for using your listening, off until you turn it on', async () => {
renderSettings()
expect(screen.getByRole('region', { name: 'Discover' })).toBeInTheDocument()

View file

@ -1,11 +1,11 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import { api, ApiError } from '@/api/client'
import { logout, useSession } from '@/auth/session'
import ChoiceGroup from '@/components/ChoiceGroup'
import ListeningSwitch from '@/components/ListeningSwitch'
import MastodonBlock from '@/components/MastodonBlock'
import SpotifyImportBlock from '@/components/SpotifyImportBlock'
import Section from '@/components/Section'
import { useInstall } from '@/pwa/useInstall'
import { Button } from '@/components/ui/button'
@ -185,7 +185,10 @@ export default function SettingsPage() {
</Section>
<Section title={t('settings.spotify')}>
<SpotifyImportBlock />
<p className="max-w-xl">{t('settings.importHint')}</p>
<Link to="/import" className="self-start font-semibold underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">
{t('settings.importLink')}
</Link>
</Section>
<Section title={t('settings.password')}>

View file

@ -34,6 +34,7 @@ export const routes: RouteObject[] = [
{ path: '/smart-playlists/suggested/:key', lazy: page(() => import('@/pages/SuggestedSmartPage')) },
{ path: '/smart-playlists/:id', lazy: page(() => import('@/pages/SmartPlaylistPage')) },
{ path: '/smart-playlists/:id/edit', lazy: page(() => import('@/pages/SmartEditorPage')) },
{ path: '/import', lazy: page(() => import('@/pages/ImportPage')) },
{ path: '/settings', lazy: page(() => import('@/pages/SettingsPage')) },
{
path: '/admin',