Точное ТЗ на конфигурацию Payload CMS поверх PostgreSQL: Collections, Globals, Blocks, access control, hooks, drafts/versions, service role D30, indexing hooks, jobs и структура файлов проекта.
Перевести логическую модель из Build 01 в конкретную Payload-конфигурацию. После выполнения этого документа CMS должна уметь создавать, редактировать, ревьюить и публиковать статьи, обслуживать taxonomy, хранить structured blocks и безопасно принимать draft-обновления от D30.
src/
├── payload.config.ts
├── collections/
│ ├── Articles.ts
│ ├── Categories.ts
│ ├── Topics.ts
│ ├── Terms.ts
│ ├── Media.ts
│ ├── Sources.ts
│ ├── Users.ts
│ ├── ImportRuns.ts
│ ├── ImportItems.ts
│ ├── ArticleEvents.ts
│ ├── AdSlots.ts
│ ├── Campaigns.ts
│ ├── Ads.ts
│ └── Redirects.ts
├── globals/
│ ├── SiteSettings.ts
│ ├── Navigation.ts
│ └── EditorialSettings.ts
├── blocks/
│ ├── RichTextBlock.ts
│ ├── ImageBlock.ts
│ ├── GalleryBlock.ts
│ ├── TableBlock.ts
│ ├── WarningBlock.ts
│ ├── QuoteBlock.ts
│ ├── ProductBlock.ts
│ ├── AdBlock.ts
│ ├── RelatedArticlesBlock.ts
│ └── TermReferenceBlock.ts
├── access/
│ ├── isAdmin.ts
│ ├── canEditContent.ts
│ ├── canPublish.ts
│ └── isServiceD30.ts
├── hooks/
│ ├── articles/
│ │ ├── normalizeSlug.ts
│ │ ├── enforcePublishRules.ts
│ │ ├── enqueueSearchIndex.ts
│ │ ├── enqueueRecommendationSync.ts
│ │ └── writeArticleEvent.ts
│ └── imports/
│ └── enforceIdempotency.ts
├── jobs/
│ ├── searchIndexArticle.ts
│ ├── syncRecommendation.ts
│ ├── refreshArticle.ts
│ └── cleanupOrphanMedia.ts
└── lib/
├── slug.ts
├── permissions.ts
└── validation.ts
import { buildConfig } from 'payload'
import { postgresAdapter } from '@payloadcms/db-postgres'
export default buildConfig({
db: postgresAdapter({
pool: {
connectionString: process.env.DATABASE_URL,
},
}),
collections: [
Users,
Media,
Categories,
Topics,
Terms,
Sources,
Articles,
ImportRuns,
ImportItems,
ArticleEvents,
AdSlots,
Campaigns,
Ads,
Redirects,
],
globals: [
SiteSettings,
Navigation,
EditorialSettings,
],
jobs: {
tasks: [
searchIndexArticle,
syncRecommendation,
refreshArticle,
cleanupOrphanMedia,
],
},
})
| Поле | Payload field | Required | Особые правила |
|---|---|---|---|
| title | text | YES | maxLength 500 |
| slug | text | YES | unique, indexed |
| externalId | text | NO | unique when present, D30 idempotency |
| excerpt | textarea | NO | — |
| category | relationship → categories | YES | single |
| topics | relationship → topics | NO | hasMany |
| terms | relationship → terms | NO | hasMany |
| relatedArticles | relationship → articles | NO | hasMany, no self-reference |
| source | relationship → sources | NO | single |
| heroImage | upload → media | NO | single |
| contentBlocks | blocks | YES | только утверждённые blocks |
| d30Score | number | NO | 0..100 |
| evidenceStatus | select | NO | unknown/partial/verified/rejected |
| qualityGate | select | YES | pending/pass/fail/manual_review |
| refreshAfter | date | NO | admin UI date+time |
| searchIndexedAt | date | NO | readOnly admin UI |
| recommendationReady | checkbox | YES | default false |
| seo | group/plugin fields | NO | metaTitle, description, canonical, ogImage |
export const Articles: CollectionConfig = {
slug: 'articles',
admin: {
useAsTitle: 'title',
defaultColumns: ['title', 'category', '_status', 'updatedAt'],
},
versions: {
drafts: true,
maxPerDoc: 50,
},
access: {
read: readPublishedOrEditor,
create: canCreateArticle,
update: canUpdateArticle,
delete: canDeleteArticle,
},
fields: [
{ name: 'title', type: 'text', required: true, maxLength: 500 },
{ name: 'slug', type: 'text', required: true, unique: true, index: true },
{ name: 'externalId', type: 'text', unique: true, index: true },
{ name: 'excerpt', type: 'textarea' },
{
name: 'category',
type: 'relationship',
relationTo: 'categories',
required: true,
},
{
name: 'topics',
type: 'relationship',
relationTo: 'topics',
hasMany: true,
},
{
name: 'terms',
type: 'relationship',
relationTo: 'terms',
hasMany: true,
},
{
name: 'relatedArticles',
type: 'relationship',
relationTo: 'articles',
hasMany: true,
},
{ name: 'source', type: 'relationship', relationTo: 'sources' },
{ name: 'heroImage', type: 'upload', relationTo: 'media' },
{
name: 'contentBlocks',
type: 'blocks',
required: true,
blocks: [
RichTextBlock,
ImageBlock,
GalleryBlock,
TableBlock,
WarningBlock,
QuoteBlock,
ProductBlock,
AdBlock,
RelatedArticlesBlock,
TermReferenceBlock,
],
},
{
name: 'd30Score',
type: 'number',
min: 0,
max: 100,
},
{
name: 'evidenceStatus',
type: 'select',
options: ['unknown', 'partial', 'verified', 'rejected'],
},
{
name: 'qualityGate',
type: 'select',
required: true,
defaultValue: 'pending',
options: ['pending', 'pass', 'fail', 'manual_review'],
},
{ name: 'refreshAfter', type: 'date' },
{ name: 'searchIndexedAt', type: 'date', admin: { readOnly: true } },
{ name: 'recommendationReady', type: 'checkbox', defaultValue: false },
],
}
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'slug', type: 'text', required: true, unique: true, index: true },
{ name: 'description', type: 'textarea' },
{ name: 'parent', type: 'relationship', relationTo: 'categories' },
{ name: 'heroImage', type: 'upload', relationTo: 'media' },
{ name: 'sortOrder', type: 'number', defaultValue: 0 },
{ name: 'isActive', type: 'checkbox', defaultValue: true },
]
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'slug', type: 'text', required: true, unique: true, index: true },
{ name: 'description', type: 'textarea' },
{ name: 'category', type: 'relationship', relationTo: 'categories' },
{ name: 'isActive', type: 'checkbox', defaultValue: true },
]
versions: { drafts: true }
fields: [
{ name: 'term', type: 'text', required: true },
{ name: 'slug', type: 'text', required: true, unique: true, index: true },
{ name: 'shortDefinition', type: 'textarea', required: true },
{ name: 'aliases', type: 'array', fields: [
{ name: 'value', type: 'text', required: true }
]},
{ name: 'body', type: 'blocks', blocks: [
RichTextBlock,
ImageBlock,
TableBlock,
WarningBlock,
RelatedArticlesBlock,
]},
]
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'sourceType', type: 'select',
options: ['web', 'book', 'manual', 'internal', 'other'],
required: true
},
{ name: 'canonicalUrl', type: 'text' },
{ name: 'publisher', type: 'text' },
{ name: 'language', type: 'text', defaultValue: 'ru' },
{ name: 'licenseNotes', type: 'textarea' },
{ name: 'metadata', type: 'json' },
]
export const Media: CollectionConfig = {
slug: 'media',
upload: {
staticDir: 'media',
mimeTypes: ['image/*'],
},
fields: [
{ name: 'alt', type: 'text' },
{ name: 'caption', type: 'textarea' },
{ name: 'credit', type: 'text' },
{ name: 'checksum', type: 'text', index: true },
],
}
roles: - admin - editor - reviewer - service_d30
| Роль | Admin UI | Draft create/update | Publish | Delete |
|---|---|---|---|---|
| admin | YES | YES | YES | YES |
| editor | YES | YES | по политике | ограниченно |
| reviewer | YES | limited | YES если разрешено | NO |
| service_d30 | NO | YES | NO | NO |
export const isAdmin = ({ req }) =>
req.user?.roles?.includes('admin')
export const isServiceD30 = ({ req }) =>
req.user?.roles?.includes('service_d30')
export const canPublish = ({ req }) =>
req.user?.roles?.some(role =>
['admin', 'reviewer'].includes(role)
)
beforeValidate: - если slug пустой → сформировать из title - привести к lowercase - нормализовать пробелы/тире - удалить недопустимые символы - не менять существующий slug автоматически после публикации
beforeChange: IF incoming _status == "published": require canPublish(req.user) require qualityGate == "pass" require title require slug require category require contentBlocks.length > 0 IF req.user.role == "service_d30": reject _status == "published" reject delete operation
Article published/updated
↓
afterChange hook
↓
enqueue job: searchIndexArticle
↓
Meilisearch adapter
↓
update searchIndexedAt
Article becomes published
↓
enqueue syncRecommendation
↓
Gorse adapter
↓
success
↓
recommendationReady = true
fields: [
{ name: 'runId', type: 'text', required: true, unique: true, index: true },
{ name: 'sourceSystem', type: 'text', required: true },
{ name: 'status', type: 'select',
options: ['queued','running','partial','success','failed','cancelled']
},
{ name: 'startedAt', type: 'date' },
{ name: 'finishedAt', type: 'date' },
{ name: 'inputCount', type: 'number', defaultValue: 0 },
{ name: 'createdCount', type: 'number', defaultValue: 0 },
{ name: 'updatedCount', type: 'number', defaultValue: 0 },
{ name: 'failedCount', type: 'number', defaultValue: 0 },
{ name: 'metadata', type: 'json' },
]
fields: [
{ name: 'run', type: 'relationship', relationTo: 'import-runs', required: true },
{ name: 'externalId', type: 'text', required: true, index: true },
{ name: 'article', type: 'relationship', relationTo: 'articles' },
{ name: 'action', type: 'select', options: ['create','update','skip','fail'] },
{ name: 'status', type: 'select', options: ['pending','success','fail'] },
{ name: 'errorCode', type: 'text' },
{ name: 'errorMessage', type: 'textarea' },
{ name: 'inputHash', type: 'text' },
]
INPUT:
externalId
payload
runId
1. validate externalId
2. find article WHERE externalId == input.externalId
3. IF found:
update DRAFT only
action = "update"
ELSE:
create DRAFT
action = "create"
4. never publish
5. write ImportItem
6. write ArticleEvent
7. on retry with identical payload:
do not create duplicate
fields: [
{ name: 'article', type: 'relationship', relationTo: 'articles' },
{ name: 'eventType', type: 'select',
options: [
'created','imported','updated','reviewed',
'published','unpublished','reindexed','failed'
]
},
{ name: 'actorType', type: 'select',
options: ['user','service','system']
},
{ name: 'actorId', type: 'text' },
{ name: 'runId', type: 'text' },
{ name: 'payload', type: 'json' },
]
| Block | slug | Поля |
|---|---|---|
| RichTextBlock | richText | content: richText |
| ImageBlock | image | media, altOverride?, caption? |
| GalleryBlock | gallery | items[] → media + caption |
| TableBlock | table | caption?, columns[], rows[] |
| WarningBlock | warning | level, title?, content |
| QuoteBlock | quote | quote, source? |
| ProductBlock | product | title, image?, url?, metadata? |
| AdBlock | ad | slotCode |
| RelatedArticlesBlock | relatedArticles | mode, articles[]?, topic? |
| TermReferenceBlock | termReference | term, displayMode |
export const WarningBlock: Block = {
slug: 'warning',
fields: [
{
name: 'level',
type: 'select',
required: true,
defaultValue: 'info',
options: ['info', 'warning', 'danger', 'tip'],
},
{
name: 'title',
type: 'text',
},
{
name: 'content',
type: 'richText',
required: true,
},
],
}
export const TermReferenceBlock: Block = {
slug: 'termReference',
fields: [
{
name: 'term',
type: 'relationship',
relationTo: 'terms',
required: true,
},
{
name: 'displayMode',
type: 'select',
defaultValue: 'inline',
options: ['inline', 'card', 'definition'],
},
],
}
fields: - siteName - siteDescription - logo - favicon - defaultOgImage - defaultSeoTitle - defaultSeoDescription - contacts - socialLinks
fields: - headerItems[] - footerColumns[] - highlightedCategories[]
fields: - defaultRelatedCount - defaultRefreshDays - requireQualityGateBeforePublish = true - enableRecommendations - enableAds - enableTerms
fields: - code UNIQUE - name - placementType - isActive
fields: - name - advertiser - startsAt - endsAt - status - priority
fields: - campaign - slots[] - title - media - targetUrl - active - weight - targeting JSON
fields: [
{ name: 'fromPath', type: 'text', required: true, unique: true, index: true },
{ name: 'toPath', type: 'text', required: true },
{ name: 'statusCode', type: 'select',
defaultValue: '301',
options: ['301','302','307','308']
},
{ name: 'isActive', type: 'checkbox', defaultValue: true },
]
IF existing article is published
AND slug changed:
create Redirect:
fromPath = old article URL
toPath = new article URL
status = 301
do not create duplicate redirect
do not overwrite unrelated existing redirect silently
| Task | Trigger | Что делает |
|---|---|---|
| searchIndexArticle | publish/update | индексирует опубликованную статью в Meilisearch |
| syncRecommendation | publish/update | передаёт item metadata в Gorse |
| refreshArticle | refreshAfter | ставит статью в очередь D30 refresh workflow |
| cleanupOrphanMedia | maintenance | только находит кандидатов; удаление отдельным безопасным действием |
POST /api/articles
Authorization: service_d30 token
payload:
{
"externalId": "d30:wood:00001234",
"title": "...",
"slug": "...",
"excerpt": "...",
"category": "...",
"topics": [...],
"terms": [...],
"contentBlocks": [...],
"d30Score": 91.4,
"evidenceStatus": "verified",
"qualityGate": "pending",
"_status": "draft"
}
_status: "published", сервер должен отвергнуть публикацию или принудительно оставить draft. Нельзя доверять клиентскому полю.MINIMUM SEED: 3 Categories 6 Topics 10 Terms 5 Sources 20 Articles 10 Media objects 3 AdSlots 1 Campaign 3 Ads
Seed должен включать статьи со всеми типами blocks, чтобы frontend позднее можно было строить не на фиктивных данных.
| # | Сценарий | Ожидание |
|---|---|---|
| A01 | anonymous reads draft | DENY |
| A02 | anonymous reads published | ALLOW |
| A03 | service_d30 creates draft | ALLOW |
| A04 | service_d30 updates own/imported draft | ALLOW |
| A05 | service_d30 publishes | DENY |
| A06 | service_d30 deletes | DENY |
| A07 | editor edits draft | ALLOW |
| A08 | reviewer publishes qualityGate=fail | DENY |
| A09 | reviewer publishes qualityGate=pass | ALLOW |
| # | Проверка | PASS |
|---|---|---|
| H01 | slug normalization | стабильный валидный slug |
| H02 | self related article | отклоняется/удаляется |
| H03 | publish enqueue search | job создан |
| H04 | publish enqueue Gorse sync | job создан |
| H05 | slug change published article | 301 redirect создан |
| H06 | duplicate externalId import | update draft, no duplicate |
1. src/payload.config.ts 2. src/collections/* 3. src/globals/* 4. src/blocks/* 5. src/access/* 6. src/hooks/* 7. src/jobs/* 8. migrations/* 9. seed script 10. access-control test results 11. hook test results 12. generated Payload types 13. DB schema/index summary 14. deviations.md 15. commit hash
build_03_fyrre_mapping.html — точное сопоставление страниц, компонентов и визуальной структуры Fyrre Magazine с Payload Collections/Blocks и данными Mathchast.