Files
j_kedzierski/scripts/migrate_services_anchors.ts

112 lines
3.7 KiB
TypeScript

import { getPayload } from 'payload'
import configPromise from '../src/payload.config'
import { toSlug } from '@intecion/ipal-kit'
async function run() {
console.log('Rozpoczynam migrację kotwic usług...')
const payload = await getPayload({ config: configPromise })
const locales = ['pl', 'de'] as const
const urls: Record<string, string> = {
pl: '/uslugi',
de: '/leistungen'
}
let updatedPagesCount = 0
for (const locale of locales) {
const pages = await payload.find({
collection: 'pages',
locale,
limit: 100
})
for (const page of pages.docs) {
if (!page.layout) continue
let changed = false
const titleToAnchor: Record<string, string> = {}
// Pass 1: Generate anchors for servicesDetailed
const newLayout = page.layout.map((block: any) => {
if (block.blockType === 'servicesDetailed') {
if (block.services && Array.isArray(block.services)) {
block.services = block.services.map((service: any) => {
if (!service.anchor) {
service.anchor = toSlug(service.title)
changed = true
}
titleToAnchor[service.title] = service.anchor
return service
})
}
}
return block
})
// We need to fetch the ServicesDetailed from the services page if we are on the homepage
// Actually, it's easier to just assume they have similar titles, or we can just fetch the anchors from the services page
// Let's first fetch the services page to build a global map for this locale
const servicesPage = pages.docs.find(p => p.slug === 'uslugi' || p.slug === 'leistungen')
let globalTitleToAnchor: Record<string, string> = {}
if (servicesPage && servicesPage.layout) {
servicesPage.layout.forEach((b: any) => {
if (b.blockType === 'servicesDetailed' && b.services) {
b.services.forEach((s: any) => {
const anchor = s.anchor || toSlug(s.title)
globalTitleToAnchor[s.title] = anchor
// Also map some generic prefixes if needed, but exact match is best
})
}
})
}
// Pass 2: Update servicesList on any page
const finalLayout = newLayout.map((block: any) => {
if (block.blockType === 'servicesList') {
if (block.services && Array.isArray(block.services)) {
block.services = block.services.map((service: any) => {
// Try to find matching anchor
let anchor = globalTitleToAnchor[service.title]
if (!anchor) {
// Fuzzy match
const foundKey = Object.keys(globalTitleToAnchor).find(k =>
k.toLowerCase().includes(service.title.toLowerCase()) ||
service.title.toLowerCase().includes(k.toLowerCase())
)
if (foundKey) anchor = globalTitleToAnchor[foundKey]
}
const newUrl = anchor ? `${urls[locale]}#${anchor}` : urls[locale]
if (service.linkUrl !== newUrl) {
service.linkUrl = newUrl
changed = true
}
return service
})
}
}
return block
})
if (changed) {
console.log(`Aktualizacja strony ${locale.toUpperCase()}: ${page.title} (ID: ${page.id})`)
await payload.update({
collection: 'pages',
id: page.id,
locale,
data: { layout: finalLayout }
})
updatedPagesCount++
}
}
}
console.log(`Zaktualizowano ${updatedPagesCount} stron.`)
process.exit(0)
}
run()