Files
ipal-kit/src/modules/consent/scanner/CookieApprovalForm.tsx
T
Radosław SmolińskiandClaude Opus 5.5 86ff3f5ff7 Cookie scanner: one approval for everything a scan finds
After "Scan cookies" or a site check, the new Approve cookies view
(/admin/cookie-approval) lists what waits, grouped by consent category, with
provider, purpose and duration and New / Changed / Needs description markers.
One "Approve and add" puts every ticked cookie into Cookie banner -> Cookie
list in every locale. That list feeds the cookie policy table and the
detailed settings window.

- Never overwrites editor text or categories, never adds a second row (a
  pattern and a concrete name are the same cookie), never deletes.
- Unknown cookies are approved into a category that needs consent
  (approval.unknownCategory, default marketing) and flagged Needs
  description; writing a purpose clears the flag.
- Cookies a scan or crawl no longer finds are flagged No longer found, for
  review only.
- The dashboard and the crawl e-mail say how many cookies wait and link to
  the view; nothing is added without approval.
- Optional: cookieScanner.approval false keeps per-entry review.
- Migration: cookie-review gains change and needsDescription.

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

190 lines
7.4 KiB
TypeScript

'use client'
import { Button, toast, useConfig, useTranslation } from '@payloadcms/ui'
import { useRouter } from 'next/navigation.js'
import { useState } from 'react'
import type { ConsentCategory } from '../categories.js'
import type { CookieApprovalItem, CookieApprovalResult } from './approval.js'
import type { CookieScanLabels } from './labels.js'
import { COOKIE_SCAN_LABELS } from './labels.js'
const CATEGORY_ORDER: ConsentCategory[] = ['necessary', 'functional', 'analytics', 'marketing']
// COOKIE_REVIEW_SLUG — not imported: collection.ts is server config, this file ships to the browser.
const REVIEW_SLUG = 'cookie-review'
const hidden = { clip: 'rect(0 0 0 0)', height: 1, overflow: 'hidden', position: 'absolute', width: 1 } as const
const fill = (template: string, values: Record<string, number | string>) =>
template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? ''))
const CSS = `
.ipal-cookie-approval table { border-collapse: collapse; width: 100%; margin-bottom: 1.5rem; }
.ipal-cookie-approval th, .ipal-cookie-approval td { border-bottom: 1px solid var(--theme-elevation-150); padding: .5rem .5rem; text-align: left; vertical-align: top; }
.ipal-cookie-approval th { font-weight: 600; font-size: .85rem; color: var(--theme-elevation-600); }
.ipal-cookie-approval h2 { margin: 1.5rem 0 .5rem; font-size: 1.15rem; }
.ipal-cookie-approval .ipal-badge { display: inline-block; border-radius: 999px; padding: 0 .5rem; margin: 0 .25rem .25rem 0; font-size: .75rem; line-height: 1.5rem; white-space: nowrap; background: var(--theme-elevation-100); }
.ipal-cookie-approval .ipal-badge--new { background: var(--theme-success-100, #d9f2e3); color: var(--theme-success-800, #14532d); }
.ipal-cookie-approval .ipal-badge--changed { background: var(--theme-warning-100, #fff1c2); color: var(--theme-warning-800, #6b4e00); }
.ipal-cookie-approval .ipal-badge--unknown { background: var(--theme-error-100, #fde2e2); color: var(--theme-error-800, #7f1d1d); }
.ipal-cookie-approval .ipal-bar { position: sticky; bottom: 0; display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; padding: 1rem 0; background: var(--theme-bg); border-top: 1px solid var(--theme-elevation-150); }
`
/**
* The approval list (client): one table per consent category, every cookie
* ticked, a marker for new / changed / not yet described, an Edit link to the
* review entry, and one "Approve and add" button for the ticked ones.
*/
export function CookieApprovalForm({
adminRoute = '/admin',
gone,
labels = COOKIE_SCAN_LABELS,
pending,
unknownCategory,
}: {
adminRoute?: string
gone: CookieApprovalItem[]
labels?: Record<string, CookieScanLabels>
pending: CookieApprovalItem[]
unknownCategory: ConsentCategory
}) {
const { i18n } = useTranslation()
const { config } = useConfig()
const router = useRouter()
const t = labels[i18n.language] ?? labels.en ?? COOKIE_SCAN_LABELS.en
const endpoint = `${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/cookie-approval`
const admin = adminRoute.replace(/\/$/, '')
const [excluded, setExcluded] = useState<Set<number | string>>(() => new Set())
const [busy, setBusy] = useState(false)
const [done, setDone] = useState<CookieApprovalResult | null>(null)
const selected = pending.filter((p) => !excluded.has(p.id))
const toggle = (id: number | string) =>
setExcluded((prev) => {
const next = new Set(prev)
if (next.has(id)) {next.delete(id)}
else {next.add(id)}
return next
})
const approve = async () => {
setBusy(true)
try {
const res = await fetch(endpoint, {
body: JSON.stringify({ ids: selected.map((p) => p.id) }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
const data = (await res.json()) as { ok?: boolean; result?: CookieApprovalResult }
if (!res.ok || !data.ok || !data.result) {throw new Error('approval failed')}
setDone(data.result)
toast.success(fill(t.approvalDone, { ...data.result }))
setExcluded(new Set())
router.refresh()
} catch {
toast.error(t.approvalError)
} finally {
setBusy(false)
}
}
const groups = [
...CATEGORY_ORDER.map((c) => ({ items: pending.filter((p) => p.category === c), key: c, note: null as null | string, title: t[c] })),
{
items: pending.filter((p) => !p.category),
key: 'none',
note: fill(t.uncategorizedNote, { category: t[unknownCategory].toLowerCase() }),
title: t.uncategorized,
},
].filter((g) => g.items.length)
const row = (p: CookieApprovalItem, withBox: boolean) => (
<tr key={p.id}>
{withBox ? (
<td style={{ width: '2rem' }}>
<input
aria-label={`${t.include}: ${p.name}`}
checked={!excluded.has(p.id)}
onChange={() => toggle(p.id)}
type="checkbox"
/>
</td>
) : null}
<td>
<code>{p.name}</code>
<div>
{p.change === 'new' ? <span className="ipal-badge ipal-badge--new">{t.markerNew}</span> : null}
{p.change === 'changed' ? <span className="ipal-badge ipal-badge--changed">{t.markerChanged}</span> : null}
{p.unknown ? <span className="ipal-badge ipal-badge--unknown">{t.markerUnknown}</span> : null}
</div>
</td>
<td>{p.vendor ?? ''}</td>
<td>{p.purpose ?? ''}</td>
<td>{p.retention ?? ''}</td>
<td>
<a href={`${admin}/collections/${REVIEW_SLUG}/${p.id}`}>{t.edit}</a>
</td>
</tr>
)
const head = (withBox: boolean) => (
<thead>
<tr>
{withBox ? <th scope="col"><span style={hidden}>{t.include}</span></th> : null}
<th scope="col">{t.name}</th>
<th scope="col">{t.vendor}</th>
<th scope="col">{t.purpose}</th>
<th scope="col">{t.retention}</th>
<th scope="col"><span style={hidden}>{t.edit}</span></th>
</tr>
</thead>
)
return (
<div className="ipal-cookie-approval">
<style>{CSS}</style>
{pending.length ? (
<>
<p>{t.approvalIntro}</p>
{groups.map((g) => (
<section data-ipal={`approval-${g.key}`} key={g.key}>
<h2>{g.title} ({g.items.length})</h2>
{g.note ? <p style={{ marginTop: 0 }}>{g.note}</p> : null}
<table>
{head(true)}
<tbody>{g.items.map((p) => row(p, true))}</tbody>
</table>
</section>
))}
<div className="ipal-bar">
<Button buttonStyle="primary" disabled={busy || !selected.length} margin={false} onClick={() => void approve()} size="large">
{busy ? t.approving : `${t.approvalButton} (${selected.length})`}
</Button>
<span>{fill(t.approvalSelected, { count: selected.length })} / {pending.length}</span>
</div>
</>
) : (
<p>{t.approvalEmpty}</p>
)}
{done ? (
<p role="status">
✓ {fill(t.approvalDone, { ...done })} <a href={`${admin}/globals/cookie-settings`}>{t.openCookieBanner}</a>
</p>
) : null}
{gone.length ? (
<section data-ipal="approval-gone">
<h2>{t.goneTitle} ({gone.length})</h2>
<p style={{ marginTop: 0 }}>{t.goneNote}</p>
<table>
{head(false)}
<tbody>{gone.map((p) => row(p, false))}</tbody>
</table>
</section>
) : null}
</div>
)
}
export default CookieApprovalForm