QLFW-5: добавить страницы новостей и миграцию

This commit is contained in:
Peppa 2026-11-17 16:57:35 +05:00
parent fe16506468
commit 9f845209f5
13 changed files with 150 additions and 10 deletions

View File

@ -0,0 +1,39 @@
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { getDict, isLocale, locales } from '@/i18n'
import { loadNews } from '@/lib/content'
import { visibleNews } from '@/lib/news-model'
import { SectionPage } from '@/components/SectionPage'
export const dynamic = 'force-dynamic'
import { safeWebUrl } from '@/lib/news-model'
import Image from 'next/image'
import { cache } from 'react'
const findNews = cache(async (locale: 'ru' | 'kk' | 'en', id: string) => visibleNews(await loadNews(locale)).find(n => String(n.id) === id))
export async function generateMetadata({ params }: { params: Promise<{ locale: string; id: string }> }) {
const { locale, id } = await params
if (!isLocale(locale)) notFound()
const n = await findNews(locale, id)
if (!n) notFound()
return { title: `${n.title} — ${getDict(locale).siteName}`, description: n.summary || n.title, alternates: { languages: Object.fromEntries(locales.map(l => [l, `/${l}/news/${id}`])) } }
}
export default async function Page({ params }: { params: Promise<{ locale: string; id: string }> }) {
const { locale, id } = await params
if (!isLocale(locale)) notFound()
const t = getDict(locale)
const n = await findNews(locale, id)
if (!n) notFound()
const image = safeWebUrl(n.imageUrl)
const source = safeWebUrl(n.sourceUrl)
return <SectionPage t={t} locale={locale} path={`/news/${id}`} title={n.title} showNews>
<article className="max-w-3xl">
<time dateTime={n.date}>{new Intl.DateTimeFormat(locale, { dateStyle: 'long' }).format(new Date(n.date))}</time>
{n.place && <p className="mt-3">{n.place}</p>}
{image && <Image unoptimized width={1200} height={800} src={image} alt={n.title} loading="lazy" className="mt-8 h-auto max-w-full" />}
{(n.body || n.summary || t.tbc).split(/\n\s*\n/).map((text, index) => <p key={index} className="mt-6 whitespace-pre-line leading-relaxed">{text}</p>)}
{source && <p className="mt-8"><a href={source} rel="noopener noreferrer" className="underline underline-offset-4">{t.sections.source}</a></p>}
<Link href={`/${locale}/news`} className="mt-10 inline-flex min-h-11 items-center underline underline-offset-4">{t.news.title}</Link>
</article>
</SectionPage>
}

View File

@ -0,0 +1,30 @@
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { getDict, isLocale, locales } from '@/i18n'
import { loadNews } from '@/lib/content'
import { visibleNews } from '@/lib/news-model'
import { SectionPage } from '@/components/SectionPage'
export const dynamic = 'force-dynamic'
export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
if (!isLocale(locale)) notFound()
const t = getDict(locale)
return { title: `${t.news.title} — ${t.siteName}`, description: t.metaDescription, alternates: { languages: Object.fromEntries(locales.map(l => [l, `/${l}/news`])) } }
}
export default async function Page({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
if (!isLocale(locale)) notFound()
const t = getDict(locale)
const news = visibleNews(await loadNews(locale))
if (!news.length) notFound()
const fmt = new Intl.DateTimeFormat(locale, { dateStyle: 'long' })
return <SectionPage t={t} locale={locale} path="/news" title={t.news.title} showNews>
<ul className="divide-y divide-line">{news.map(n => <li key={n.id} className="py-7">
<time dateTime={n.date}>{fmt.format(new Date(n.date))}</time>
<h2 className="mt-3 font-serif text-2xl"><Link href={`/${locale}/news/${n.id}`} className="underline underline-offset-4">{n.title}</Link></h2>
{n.summary && <p className="mt-4">{n.summary}</p>}
</li>)}</ul>
</SectionPage>
}

View File

@ -101,7 +101,7 @@ export default async function Home({ params }: { params: Promise<{ locale: strin
<div className="mt-1 text-burgundy">{n.kind === 'event' ? t.news.event : t.news.news}</div>
</div>
<div>
<h3 className="font-serif text-2xl">{n.title}</h3>
<h3 className="font-serif text-2xl"><Link href={`/${locale}/news/${n.id}`} className="underline underline-offset-4">{n.title}</Link></h3>
{n.summary && <p className="mt-2 text-muted">{n.summary}</p>}
{n.place && <p className="mt-2 text-sm text-muted">{n.place}</p>}
</div>

View File

@ -5,6 +5,7 @@ import { notFound } from 'next/navigation'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { getDict, isLocale } from '@/i18n'
import { loadContent } from '@/lib/content'
import { bookUrl } from '@/lib/home-model'
const path = '/projects/ermek-serkebayev'
@ -20,9 +21,10 @@ export default async function BookProject({ params }: { params: Promise<{ locale
const { locale } = await params
if (!isLocale(locale)) notFound()
const t = getDict(locale)
const { news } = await loadContent(locale)
return <>
<Header t={t} locale={locale} showProjects showNews={false} path={path} />
<main className="mx-auto max-w-6xl px-5 pb-20 pt-56 sm:px-8 md:pt-44">
<Header t={t} locale={locale} showProjects showNews={news.length > 0} path={path} />
<main className="mx-auto max-w-6xl px-5 pb-20 pt-64 sm:px-8 sm:pt-56 md:pt-44">
<Link href={`/${locale}#projects`} className="underline underline-offset-4">{t.projects.title}</Link>
<article className="mt-8 grid gap-8 md:grid-cols-[1fr_2fr] md:gap-12">
<Image src="/books/serkebayev/cover.jpg" alt={t.book.cover} width={677} height={1000} priority sizes="(min-width: 768px) 340px, 100vw" className="mx-auto h-auto w-full max-w-sm" />

View File

@ -7,6 +7,9 @@ export const News: CollectionConfig = {
access: { read: () => true },
fields: [
{ name: 'title', label: 'Заголовок', type: 'text', required: true, localized: true },
{ name: 'body', label: 'Полный текст', type: 'textarea', localized: true },
{ name: 'imageUrl', label: 'Адрес фотографии (https)', type: 'text' },
{ name: 'sourceUrl', label: 'Ссылка на публикацию', type: 'text', localized: true },
{ name: 'summary', label: 'Краткое описание', type: 'textarea', localized: true },
{
name: 'kind',

View File

@ -6,7 +6,7 @@ import { Footer } from '@/components/Footer'
import { Header } from '@/components/Header'
import { Tbc } from '@/components/Tbc'
import { getDict, isLocale, locales } from '@/i18n'
import { loadLegal } from '@/lib/content'
import { loadContent, loadLegal } from '@/lib/content'
import { buildLegalModel, type LegalKind } from '@/lib/legal-model'
type Props = { params: Promise<{ locale: string }> }
@ -29,13 +29,14 @@ export async function LegalPage({ params, kind }: Props & { kind: LegalKind }) {
const { locale } = await params
if (!isLocale(locale)) notFound()
const t = getDict(locale)
const { news } = await loadContent(locale)
const m = buildLegalModel(await loadLegal(locale), kind, t)
const fmt = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'long', year: 'numeric' })
return (
<>
<Header t={t} locale={locale} showProjects={false} showNews={false} path={`/${kind}`} />
<main className="mx-auto max-w-3xl px-5 pb-24 pt-40 sm:px-8">
<Header t={t} locale={locale} showProjects showNews={news.length > 0} path={`/${kind}`} />
<main className="mx-auto max-w-3xl px-5 pb-24 pt-64 sm:px-8 sm:pt-56 md:pt-44">
<Link href={`/${locale}`} className="text-sm text-muted hover:text-burgundy">← {t.legal.back}</Link>
<h1 className="mt-6 font-serif text-4xl leading-tight text-burgundy sm:text-5xl">{m.title}</h1>
{m.updated && (

View File

@ -1,5 +1,6 @@
import config from '@payload-config'
import { getPayload } from 'payload'
import { visibleNews } from './news-model'
import type { Locale } from '@/i18n'
import type { CmsHome, CmsNews } from './home-model'
import type { CmsLegal } from './legal-model'
@ -10,9 +11,9 @@ export async function loadContent(locale: Locale): Promise<{ home: CmsHome | nul
const payload = await getPayload({ config })
const [home, news] = await Promise.all([
payload.findGlobal({ slug: 'home', locale, fallbackLocale: false }),
payload.find({ collection: 'news', locale, sort: '-date', limit: 3 }),
loadNews(locale),
])
return { home: home as unknown as CmsHome, news: news.docs as unknown as CmsNews[] }
return { home: home as unknown as CmsHome, news: visibleNews(news).slice(0, 3) }
} catch (e) {
console.error('content load failed', e)
return { home: null, news: [] }
@ -29,3 +30,16 @@ export async function loadLegal(locale: Locale): Promise<CmsLegal | null> {
return null
}
}
/** Все новости текущего языка; не ограничиваем каталог тремя карточками главной. */
export async function loadNews(locale: Locale): Promise<CmsNews[]> {
const payload = await getPayload({ config })
const items: CmsNews[] = []
let page = 1
while (true) {
const result = await payload.find({ collection: 'news', locale, fallbackLocale: false, sort: '-date', limit: 100, page })
items.push(...result.docs as unknown as CmsNews[])
if (!result.hasNextPage) return items
page++
}
}

View File

@ -1,3 +1,4 @@
import { visibleNews } from './news-model'
import type { Dict } from '@/i18n'
export type CmsItem = { title?: string | null; text?: string | null }
@ -8,7 +9,7 @@ export type CmsHome = {
collaboration?: string | null
contactEmail?: string | null
}
export type CmsNews = { id: string | number; title: string; summary?: string | null; kind?: string | null; date: string; place?: string | null }
export type CmsNews = { id: string | number; title: string; summary?: string | null; kind?: string | null; date: string; place?: string | null; body?: string | null; imageUrl?: string | null; sourceUrl?: string | null }
export type Card = { title: string; text: string | null; tbc: boolean }
export type HomeModel = {
@ -38,7 +39,7 @@ export function buildHomeModel(cms: CmsHome | null, news: CmsNews[], t: Dict): H
mission: { text: mission ?? t.mission.text, tbc: false },
directions,
projects,
news,
news: visibleNews(news),
collaboration: { text: clean(cms?.collaboration) ?? t.collaboration.text, email: clean(cms?.contactEmail) ?? foundationEmail },
}
}

View File

@ -0,0 +1,16 @@
import { describe, it, expect } from 'vitest'
import { visibleNews, safeWebUrl } from './news-model'
describe('Материалы новостей', () => {
it('Материал опубликован: сохраняет дату и полный текст', () => {
const item = { id: 1, title: 'Презентация книги', date: '2026-11-17', body: 'Полный текст' }
expect(visibleNews([item])).toEqual([item])
})
it('Нет перевода: скрывает материал без заголовка текущего языка', () => {
expect(visibleNews([{ id: 1, title: '', date: '2026-11-17' }])).toEqual([])
})
it('Пустой раздел остаётся пустым', () => expect(visibleNews([])).toEqual([]))
it('Повреждённая дата не ломает страницу', () => expect(visibleNews([{ id: 1, title: 'Новость', date: 'bad' }])).toEqual([]))
it.each(['javascript:alert(1)', 'data:text/html,test', '/relative', 'https://user:password@example.org'])('Небезопасная ссылка %s скрыта', value => expect(safeWebUrl(value)).toBeNull())
it('Источник открывает обычную веб-страницу', () => expect(safeWebUrl('https://example.org/article')).toBe('https://example.org/article'))
})

12
src/lib/news-model.ts Normal file
View File

@ -0,0 +1,12 @@
import type { CmsNews } from './home-model'
export function safeWebUrl(value?: string | null): string | null {
if (!value?.trim()) return null
try {
const url = new URL(value)
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? url.href : null
} catch { return null }
}
export function visibleNews(items: CmsNews[]): CmsNews[] {
return items.filter(item => item.title?.trim() && Number.isFinite(Date.parse(item.date)))
}

View File

@ -0,0 +1,13 @@
import { type MigrateUpArgs, type MigrateDownArgs, sql } from '@payloadcms/db-sqlite'
export async function up({ db }: MigrateUpArgs): Promise<void> {
await db.run(sql`ALTER TABLE news ADD COLUMN image_url text`)
await db.run(sql`ALTER TABLE news_locales ADD COLUMN body text`)
await db.run(sql`ALTER TABLE news_locales ADD COLUMN source_url text`)
}
export async function down({ db }: MigrateDownArgs): Promise<void> {
await db.run(sql`ALTER TABLE news DROP COLUMN image_url`)
await db.run(sql`ALTER TABLE news_locales DROP COLUMN body`)
await db.run(sql`ALTER TABLE news_locales DROP COLUMN source_url`)
}

View File

@ -1,9 +1,11 @@
import * as migration_news_details from './20261117_170000_news_details';
import * as migration_20261117_120000_legal_texts from './20261117_120000_legal_texts';
import * as migration_20261116_103502_init from './20261116_103502_init';
import * as migration_20261117_045758_legal from './20261117_045758_legal';
export const migrations = [
{
up: migration_20261116_103502_init.up,
down: migration_20261116_103502_init.down,
@ -15,4 +17,5 @@ export const migrations = [
name: '20261117_045758_legal'
},
{ up: migration_20261117_120000_legal_texts.up, down: migration_20261117_120000_legal_texts.down, name: '20261117_120000_legal_texts' },
{ up: migration_news_details.up, down: migration_news_details.down, name: '20261117_170000_news_details' },
];

View File

@ -156,6 +156,9 @@ export interface User {
export interface News {
id: number;
title: string;
body?: string | null;
imageUrl?: string | null;
sourceUrl?: string | null;
summary?: string | null;
kind?: ('news' | 'event') | null;
date: string;
@ -266,6 +269,9 @@ export interface UsersSelect<T extends boolean = true> {
*/
export interface NewsSelect<T extends boolean = true> {
title?: T;
body?: T;
imageUrl?: T;
sourceUrl?: T;
summary?: T;
kind?: T;
date?: T;