Files
ipal-kit/test/fillEmptyLocales.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 b10c2dc0e3 Cookies: fill empty languages, and one Cookies entry in the admin
Every language filled (fillEmptyLocales, default on): text saved in one
language goes to every language where the same field is still empty, never
over a language's own text. Applies to the cookie list (purpose, duration)
and the cookie review (purpose, duration). Scanner and approval writes give
a language without its own text the default language's text. Building
blocks: buildFillEmptyLocalesGlobalHook / CollectionHook, fillEmptyLocales,
withFillLocales.

One Cookies entry (cookieScanner.adminLayout, default combined): the
Cookie banner global is now labelled Cookies and gets Review and approve
(scan box and approval list inline) and Site check tabs, built from ui
fields. Cookie review and Cookie check leave the navigation
(admin.group false) but keep their pages, data and API. This is
presentation only: no schema change and no migration, only
generate:importmap. adminLayout separate keeps the old layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:55:11 +01:00

143 lines
7.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Text written in one language fills the empty languages (cookie list, cookie
* review), never one that has its own text — through a REAL Payload (SQLite,
* pl + en + de). Plus the combined "Cookies" admin layout (config only).
*/
import type { Config, Field, GlobalConfig, Payload, Tab } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { suggestionFor } from '../src/modules/consent/scanner/merge.js'
import { addToCookieList } from '../src/modules/consent/scanner/sync.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
const i18n: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
{ code: 'de', label: 'Deutsch' },
],
}
type Row = { category?: string; duration?: null | string; id?: string; name: string; purpose?: null | string }
let payload: Payload
const list = async (locale: string) =>
((await payload.findGlobal({ slug: 'cookie-settings' as never, fallbackLocale: false as never, locale: locale as never })) as { cookies?: Row[] }).cookies ?? []
const row = async (locale: string, name: string) => (await list(locale)).find((r) => r.name === name)
const save = async (locale: string, rows: Row[]) =>
payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: rows } as never, locale: locale as never })
beforeAll(async () => {
payload = await getPayload({
config: buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })],
secret: 'fill-locales-test-secret',
telemetry: false,
}),
})
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('fill empty locales — cookie list', () => {
test('a row added in Polish gets the same text in English and German', async () => {
await save('pl', [{ name: 'chat_id', category: 'functional', duration: '1 rok', purpose: 'Okno czatu' }])
expect(await row('en', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
expect(await row('de', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
})
test('a language with its own text is never overwritten; each can still be changed alone', async () => {
const en = await list('en')
await save('en', en.map((r) => (r.name === 'chat_id' ? { ...r, duration: '1 year', purpose: 'Chat window' } : r)))
expect(await row('en', 'chat_id')).toMatchObject({ duration: '1 year', purpose: 'Chat window' })
expect(await row('pl', 'chat_id')).toMatchObject({ duration: '1 rok', purpose: 'Okno czatu' })
expect(await row('de', 'chat_id')).toMatchObject({ purpose: 'Okno czatu' }) // already had text: kept
})
test('the source is the language just edited, not the default one', async () => {
const en = await list('en')
await save('en', [...en, { name: 'map_id', category: 'marketing', purpose: 'Embedded map' }])
expect((await row('pl', 'map_id'))?.purpose).toBe('Embedded map')
expect((await row('de', 'map_id'))?.purpose).toBe('Embedded map')
})
test('scanner writes: a language without its own text gets the default language’s text', async () => {
const s = suggestionFor({ name: 'x', purpose: { en: 'EN', pl: 'PL' }, retention: '1 day', source: 'project', storage: 'cookie' }, ['pl', 'en', 'de'])
expect(s.purpose).toEqual({ de: 'PL', en: 'EN', pl: 'PL' })
expect(s.retention).toEqual({ de: '1 day', en: '1 day', pl: '1 day' })
await addToCookieList({ entry: { name: 'only_pl', category: 'analytics', purpose: { pl: 'Tylko po polsku' } }, payload })
expect((await row('en', 'only_pl'))?.purpose).toBe('Tylko po polsku')
expect((await row('de', 'only_pl'))?.purpose).toBe('Tylko po polsku')
})
})
describe('fill empty locales — cookie review', () => {
test('an entry described in English gets the text in the empty languages', async () => {
const created = (await payload.create({ collection: 'cookie-review' as never, data: { name: 'widget', storage: 'cookie' } as never, locale: 'pl' as never })) as { id: number }
await payload.update({ id: created.id, collection: 'cookie-review' as never, data: { purpose: 'Support widget', retention: '30 days' } as never, locale: 'en' as never })
const pl = (await payload.findByID({ id: created.id, collection: 'cookie-review' as never, fallbackLocale: false as never, locale: 'pl' as never })) as { purpose?: string; retention?: string }
expect(pl).toMatchObject({ purpose: 'Support widget', retention: '30 days' })
})
})
describe('options', () => {
const build = (extra: Record<string, unknown>) =>
ipalKit({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config)
const global = (c: Config, slug: string) => c.globals!.find((g) => g.slug === slug)!
const tabs = (g: GlobalConfig) => (g.fields.find((f) => f.type === 'tabs') as { tabs: Tab[] } & Field).tabs
test('fillEmptyLocales: false removes the hook; an object picks the fields', async () => {
expect(global(await build({}), 'cookie-settings').hooks?.afterChange).toHaveLength(1)
expect(global(await build({ fillEmptyLocales: false }), 'cookie-settings').hooks?.afterChange ?? []).toHaveLength(0)
expect(global(await build({ fillEmptyLocales: { 'cookie-settings': [] } }), 'cookie-settings').hooks?.afterChange ?? []).toHaveLength(0)
})
test('combined layout (default): one Cookies entry with Review and approve + Site check tabs', async () => {
const c = await build({ cookieScanner: { crawl: true } })
const cookies = global(c, 'cookie-settings')
expect(cookies.label).toEqual({ en: 'Cookies', pl: 'Cookies' })
const labels = tabs(cookies).map((t) => (t.label as Record<string, string>).en)
expect(labels.slice(-2)).toEqual(['Review and approve', 'Site check'])
expect(c.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toBe(false)
expect(global(c, 'cookie-crawl').admin?.group).toBe(false)
// Pages and API stay: the approval view and the endpoints are still there.
expect(c.admin?.components?.views?.ipalCookieApproval).toBeTruthy()
expect(c.endpoints?.some((e) => e.path === '/ipal/cookie-crawl')).toBe(true)
})
test('no crawl → no Site check tab; approval: false → the tab shows the scan and the list link only', async () => {
const c = await build({ cookieScanner: { approval: false } })
const review = tabs(global(c, 'cookie-settings')).at(-1)!
expect((review.label as Record<string, string>).en).toBe('Review and approve')
expect(JSON.stringify(review.fields)).toContain('"approval":false')
})
test("'separate' keeps every entry in the navigation and no extra tabs; the project's group wins", async () => {
const c = await build({ cookieScanner: { adminLayout: 'separate', crawl: true } })
expect(tabs(global(c, 'cookie-settings')).map((t) => (t.label as Record<string, string>).en)).not.toContain('Review and approve')
expect(c.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toEqual({ en: 'Privacy', pl: 'Prywatność' })
const own = await build({ cookieScanner: { collectionOverrides: { admin: { group: 'Legal' } } } })
expect(own.collections!.find((x) => x.slug === 'cookie-review')!.admin?.group).toBe('Legal')
})
})