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]>
192 lines
8.3 KiB
TypeScript
192 lines
8.3 KiB
TypeScript
import type { BasePayload, Endpoint, PayloadRequest, Where } from 'payload'
|
|
|
|
import type { ConsentCategory } from '../categories.js'
|
|
import type { CookieReviewValues } from './merge.js'
|
|
import type { CookieChange } from './scan.js'
|
|
import type { CookieScannerOptions } from './types.js'
|
|
|
|
import { userMeetsRole } from '../../access/predicates.js'
|
|
import { CONSENT_CATEGORIES } from '../categories.js'
|
|
import { COOKIE_REVIEW_SLUG } from './collection.js'
|
|
import { textFor } from './merge.js'
|
|
import { addToCookieList } from './sync.js'
|
|
|
|
/**
|
|
* One approval for everything a scan or crawl found: the "Approve cookies" view
|
|
* lists what is waiting, grouped by consent category, and one button adds the
|
|
* ticked cookies to Cookies → Cookies — which feeds the cookie banner's
|
|
* detailed window and the cookie policy table. Nothing is added before that.
|
|
*/
|
|
export const COOKIE_APPROVAL_PATH = '/ipal/cookie-approval'
|
|
/** Admin view path (under the admin route). */
|
|
export const COOKIE_APPROVAL_VIEW_PATH = '/cookie-approval'
|
|
/** Category for cookies nothing knows, until an editor describes them. It needs consent. */
|
|
export const DEFAULT_UNKNOWN_CATEGORY: ConsentCategory = 'marketing'
|
|
|
|
export type CookieApprovalItem = {
|
|
category: ConsentCategory | null
|
|
change: CookieChange | null
|
|
id: number | string
|
|
name: string
|
|
purpose: null | string
|
|
retention: null | string
|
|
/** Nothing knew it: no category or no purpose yet. */
|
|
unknown: boolean
|
|
vendor: null | string
|
|
}
|
|
|
|
export type CookieApprovalList = {
|
|
/** Accepted cookies the latest scan or crawl no longer found — for review only. */
|
|
gone: CookieApprovalItem[]
|
|
/** Waiting for approval: drafts, and accepted cookies a scan changed. */
|
|
pending: CookieApprovalItem[]
|
|
}
|
|
|
|
export type CookieApprovalResult = { added: number; filled: number; needsDescription: number; skipped: number; unchanged: number }
|
|
|
|
type Doc = {
|
|
category?: ConsentCategory | null
|
|
change?: CookieChange | null
|
|
id: number | string
|
|
name: string
|
|
purpose?: null | Record<string, null | string> | string
|
|
retention?: null | Record<string, null | string> | string
|
|
source?: null | string
|
|
status?: 'accepted' | 'draft' | 'rejected' | null
|
|
vendor?: null | string
|
|
}
|
|
|
|
/** Pending = a draft, or an accepted cookie whose values a scan changed. */
|
|
export const PENDING_WHERE: Where = {
|
|
or: [{ status: { equals: 'draft' } }, { and: [{ status: { equals: 'accepted' } }, { change: { equals: 'changed' } }] }],
|
|
}
|
|
|
|
const asText = (v: Doc['purpose'], locale: string) =>
|
|
(typeof v === 'string' ? v : v ? (textFor(Object.fromEntries(Object.entries(v).filter(([, t]) => Boolean(t))) as Record<string, string>, locale) ?? null) : null) || null
|
|
|
|
function item(doc: Doc, locale: string): CookieApprovalItem {
|
|
const purpose = asText(doc.purpose, locale)
|
|
return {
|
|
id: doc.id,
|
|
name: doc.name,
|
|
category: doc.category && (CONSENT_CATEGORIES as readonly string[]).includes(doc.category) ? doc.category : null,
|
|
change: doc.change ?? null,
|
|
purpose,
|
|
retention: asText(doc.retention, locale),
|
|
unknown: !doc.category || !purpose || doc.source === 'unknown',
|
|
vendor: doc.vendor ?? null,
|
|
}
|
|
}
|
|
|
|
/** The approval list in one content locale (texts fall back to English, then any language). */
|
|
export async function loadCookieApproval({ locale, payload, req }: { locale: string; payload: BasePayload; req?: PayloadRequest }): Promise<CookieApprovalList> {
|
|
const common = { collection: COOKIE_REVIEW_SLUG as never, depth: 0, limit: 0, locale: 'all' as never, overrideAccess: true, pagination: false, req, sort: 'name' }
|
|
const [pending, gone] = await Promise.all([
|
|
payload.find({ ...common, where: PENDING_WHERE }),
|
|
payload.find({ ...common, where: { and: [{ status: { equals: 'accepted' } }, { change: { equals: 'gone' } }] } }),
|
|
])
|
|
return {
|
|
gone: (gone.docs as unknown as Doc[]).map((d) => item(d, locale)),
|
|
pending: (pending.docs as unknown as Doc[]).map((d) => item(d, locale)),
|
|
}
|
|
}
|
|
|
|
/** How many cookies wait for approval (dashboard, e-mail). Never throws. */
|
|
export async function countPendingCookies(payload: BasePayload): Promise<number> {
|
|
try {
|
|
return (await payload.count({ collection: COOKIE_REVIEW_SLUG as never, overrideAccess: true, where: PENDING_WHERE })).totalDocs
|
|
} catch {
|
|
return 0
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Approves pending entries (all of them, or only `ids`): each becomes accepted
|
|
* and goes to Cookies → Cookies in every locale — a missing row is added,
|
|
* an existing one (same name or pattern) only gets its empty text filled, its
|
|
* category is kept. A cookie without a category gets `unknownCategory` (needs
|
|
* consent) and every cookie without a purpose is flagged "Needs description".
|
|
* Never deletes, never adds a second row for the same cookie.
|
|
*/
|
|
export async function approveCookies({
|
|
addToList = true,
|
|
ids,
|
|
payload,
|
|
req,
|
|
unknownCategory = DEFAULT_UNKNOWN_CATEGORY,
|
|
}: {
|
|
/** False (`syncAccepted: false`) = only mark the entries accepted. */
|
|
addToList?: boolean
|
|
ids?: (number | string)[]
|
|
payload: BasePayload
|
|
req?: PayloadRequest
|
|
unknownCategory?: ConsentCategory
|
|
}): Promise<CookieApprovalResult> {
|
|
const common = { collection: COOKIE_REVIEW_SLUG as never, context: { ipalCookieScan: true }, depth: 0, overrideAccess: true, req }
|
|
const where: Where = ids ? { and: [PENDING_WHERE, { id: { in: ids } }] } : PENDING_WHERE
|
|
const { docs } = await payload.find({ ...common, limit: 0, locale: 'all' as never, pagination: false, where })
|
|
const result: CookieApprovalResult = { added: 0, filled: 0, needsDescription: 0, skipped: (ids?.length ?? docs.length) - docs.length, unchanged: 0 }
|
|
const defaultLocale = payload.config.localization ? payload.config.localization.defaultLocale : 'en'
|
|
|
|
for (const doc of docs as unknown as ({ name: string } & CookieReviewValues & Doc)[]) {
|
|
const category = doc.category ?? unknownCategory
|
|
const needsDescription = !asText(doc.purpose, defaultLocale)
|
|
const outcome = addToList ? await addToCookieList({ entry: { ...doc, category } as never, payload, req }) : 'unchanged'
|
|
result[outcome]++
|
|
if (needsDescription) {result.needsDescription++}
|
|
await payload.update({
|
|
...common,
|
|
id: doc.id,
|
|
data: { category, change: null, listed: true, needsDescription, status: 'accepted' } as never,
|
|
})
|
|
}
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* GET /api/ipal/cookie-approval?locale=pl → `CookieApprovalList`
|
|
* POST /api/ipal/cookie-approval, body `{ ids?: (string|number)[] }` → `{ ok, result }`
|
|
* Editors and up (`cookieScanner.access`).
|
|
*/
|
|
export function buildCookieApprovalEndpoints(options: CookieScannerOptions): Endpoint[] {
|
|
const approval = typeof options.approval === 'object' ? options.approval : {}
|
|
const allowed = async (req: PayloadRequest) =>
|
|
options.access ? Boolean(await options.access({ req })) : userMeetsRole(req, 'editor')
|
|
return [
|
|
{
|
|
handler: async (req) => {
|
|
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
|
|
const l = req.payload.config.localization
|
|
const asked = typeof req.query?.locale === 'string' ? req.query.locale : undefined
|
|
const locale = l ? (asked && l.localeCodes.includes(asked) ? asked : l.defaultLocale) : 'en'
|
|
return Response.json({ ok: true, ...(await loadCookieApproval({ locale, payload: req.payload, req })) })
|
|
},
|
|
method: 'get',
|
|
path: COOKIE_APPROVAL_PATH,
|
|
},
|
|
{
|
|
handler: async (req) => {
|
|
if (!(await allowed(req))) {return Response.json({ ok: false }, { status: 403 })}
|
|
let body: { ids?: unknown } = {}
|
|
try {
|
|
body = ((await (req as unknown as Request).json()) ?? {}) as { ids?: unknown }
|
|
} catch {
|
|
// no body = approve everything pending
|
|
}
|
|
const ids = Array.isArray(body.ids)
|
|
? body.ids.filter((id): id is number | string => (typeof id === 'string' && id.length <= 64) || Number.isInteger(id)).slice(0, 1000)
|
|
: undefined
|
|
try {
|
|
const result = await approveCookies({ addToList: options.syncAccepted !== false, ids, payload: req.payload, req, unknownCategory: approval.unknownCategory })
|
|
return Response.json({ ok: true, result })
|
|
} catch (err) {
|
|
req.payload.logger.error(`[ipal] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
return Response.json({ ok: false }, { status: 500 })
|
|
}
|
|
},
|
|
method: 'post',
|
|
path: COOKIE_APPROVAL_PATH,
|
|
},
|
|
]
|
|
}
|