Mathchast CMS / Build Series / 02

Payload Schema

Точное ТЗ на конфигурацию Payload CMS поверх PostgreSQL: Collections, Globals, Blocks, access control, hooks, drafts/versions, service role D30, indexing hooks, jobs и структура файлов проекта.

Payload CMS TypeScript PostgreSQL Drafts Versions Access Control Hooks D30 Service

1. Цель этапа

Перевести логическую модель из Build 01 в конкретную Payload-конфигурацию. После выполнения этого документа CMS должна уметь создавать, редактировать, ревьюить и публиковать статьи, обслуживать taxonomy, хранить structured blocks и безопасно принимать draft-обновления от D30.

Не переходить к frontend mapping Fyrre, пока эта схема не собирается, не мигрируется и не проходит access-control тесты.

2. Рекомендуемая структура проекта

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

3. payload.config.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,
    ],
  },
})
Точный API Payload зависит от установленной версии. ИИ-кодер обязан использовать API и синтаксис именно фактически установленной версии Payload, а не копировать устаревшие примеры.

4. Collection: Articles

ПолеPayload fieldRequiredОсобые правила
titletextYESmaxLength 500
slugtextYESunique, indexed
externalIdtextNOunique when present, D30 idempotency
excerpttextareaNO—
categoryrelationship → categoriesYESsingle
topicsrelationship → topicsNOhasMany
termsrelationship → termsNOhasMany
relatedArticlesrelationship → articlesNOhasMany, no self-reference
sourcerelationship → sourcesNOsingle
heroImageupload → mediaNOsingle
contentBlocksblocksYESтолько утверждённые blocks
d30ScorenumberNO0..100
evidenceStatusselectNOunknown/partial/verified/rejected
qualityGateselectYESpending/pass/fail/manual_review
refreshAfterdateNOadmin UI date+time
searchIndexedAtdateNOreadOnly admin UI
recommendationReadycheckboxYESdefault false
seogroup/plugin fieldsNOmetaTitle, description, canonical, ogImage

Articles config skeleton

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 },
  ],
}

5. Drafts / Versions

D30 создаёт и обновляет только draft-состояние. Публикация должна быть отдельным разрешённым действием пользователя/редактора.

6. Taxonomy Collections

Categories

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 },
]

Topics

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 },
]

Terms

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,
  ]},
]

7. Sources

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' },
]

8. Media

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 },
  ],
}
Физическое хранилище должно быть абстрагировано. Для production допустим S3-compatible storage, но schema не должна зависеть от конкретного провайдера.

9. Users и роли

roles:
- admin
- editor
- reviewer
- service_d30
РольAdmin UIDraft create/updatePublishDelete
adminYESYESYESYES
editorYESYESпо политикеограниченно
reviewerYESlimitedYES если разрешеноNO
service_d30NOYESNONO

10. Access control — обязательные функции

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)
  )
Критическое правило: service_d30 не может:
  • publish;
  • unpublish production content;
  • delete article;
  • изменять роли пользователей;
  • менять глобальные настройки сайта.

11. Hook: normalizeSlug

beforeValidate:
- если slug пустой → сформировать из title
- привести к lowercase
- нормализовать пробелы/тире
- удалить недопустимые символы
- не менять существующий slug автоматически после публикации
После первой публикации изменение slug должно быть сознательным действием и сопровождаться созданием redirect.

12. Hook: enforcePublishRules

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

13. Hook: relatedArticles validation

14. Hook: search indexing

Article published/updated
        ↓
afterChange hook
        ↓
enqueue job: searchIndexArticle
        ↓
Meilisearch adapter
        ↓
update searchIndexedAt
Не делать синхронный сетевой вызов Meilisearch внутри критического publish transaction, если он может блокировать сохранение статьи.

15. Hook: recommendation sync

Article becomes published
      ↓
enqueue syncRecommendation
      ↓
Gorse adapter
      ↓
success
      ↓
recommendationReady = true

16. ImportRuns / ImportItems

ImportRuns

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' },
]

ImportItems

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' },
]

17. D30 idempotency algorithm

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
Повторная отправка одного и того же материала должна быть безопасной.

18. ArticleEvents

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' },
]

19. Blocks — точный набор MVP

BlockslugПоля
RichTextBlockrichTextcontent: richText
ImageBlockimagemedia, altOverride?, caption?
GalleryBlockgalleryitems[] → media + caption
TableBlocktablecaption?, columns[], rows[]
WarningBlockwarninglevel, title?, content
QuoteBlockquotequote, source?
ProductBlockproducttitle, image?, url?, metadata?
AdBlockadslotCode
RelatedArticlesBlockrelatedArticlesmode, articles[]?, topic?
TermReferenceBlocktermReferenceterm, displayMode

20. Пример WarningBlock

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,
    },
  ],
}

21. Пример TermReferenceBlock

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'],
    },
  ],
}

22. Globals

SiteSettings

fields:
- siteName
- siteDescription
- logo
- favicon
- defaultOgImage
- defaultSeoTitle
- defaultSeoDescription
- contacts
- socialLinks

Navigation

fields:
- headerItems[]
- footerColumns[]
- highlightedCategories[]

EditorialSettings

fields:
- defaultRelatedCount
- defaultRefreshDays
- requireQualityGateBeforePublish = true
- enableRecommendations
- enableAds
- enableTerms

23. Ads MVP

AdSlots

fields:
- code UNIQUE
- name
- placementType
- isActive

Campaigns

fields:
- name
- advertiser
- startsAt
- endsAt
- status
- priority

Ads

fields:
- campaign
- slots[]
- title
- media
- targetUrl
- active
- weight
- targeting JSON

24. Redirects

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 },
]

25. Hooks при смене slug

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

26. Jobs

TaskTriggerЧто делает
searchIndexArticlepublish/updateиндексирует опубликованную статью в Meilisearch
syncRecommendationpublish/updateпередаёт item metadata в Gorse
refreshArticlerefreshAfterставит статью в очередь D30 refresh workflow
cleanupOrphanMediamaintenanceтолько находит кандидатов; удаление отдельным безопасным действием

27. Admin UI — обязательные удобства

Articles list
title, category, status, qualityGate, updatedAt.
Фильтры
status, category, evidenceStatus, qualityGate.
Read-only поля
searchIndexedAt, технические import metadata.
D30-origin
видно externalId и последний runId.
Preview
preview draft на Next.js frontend.
Version diff
использовать штатную историю версий Payload.

28. Public API правила

29. API контракт D30 → Payload

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"
}
Если входной запрос от D30 содержит _status: "published", сервер должен отвергнуть публикацию или принудительно оставить draft. Нельзя доверять клиентскому полю.

30. Schema migrations

  1. Никаких ручных изменений production schema без migration file.
  2. Каждая новая collection/field/index → миграция.
  3. Миграции хранятся в git.
  4. Тест: пустая PostgreSQL → все migrations → рабочая CMS.
  5. Rollback-план обязателен для destructive changes.

31. Seed

MINIMUM SEED:
3 Categories
6 Topics
10 Terms
5 Sources
20 Articles
10 Media objects
3 AdSlots
1 Campaign
3 Ads

Seed должен включать статьи со всеми типами blocks, чтобы frontend позднее можно было строить не на фиктивных данных.

32. Тесты access control

#СценарийОжидание
A01anonymous reads draftDENY
A02anonymous reads publishedALLOW
A03service_d30 creates draftALLOW
A04service_d30 updates own/imported draftALLOW
A05service_d30 publishesDENY
A06service_d30 deletesDENY
A07editor edits draftALLOW
A08reviewer publishes qualityGate=failDENY
A09reviewer publishes qualityGate=passALLOW

33. Тесты hooks

#ПроверкаPASS
H01slug normalizationстабильный валидный slug
H02self related articleотклоняется/удаляется
H03publish enqueue searchjob создан
H04publish enqueue Gorse syncjob создан
H05slug change published article301 redirect создан
H06duplicate externalId importupdate draft, no duplicate

34. Что ИИ-кодеру нельзя делать

  • Не добавлять RawHtmlBlock в MVP.
  • Не разрешать service_d30 publish/delete.
  • Не использовать frontend API key с admin/service правами.
  • Не писать network sync с Meili/Gorse прямо в критический DB transaction.
  • Не заменять structured blocks одним richText/HTML полем.
  • Не добавлять новые CMS сущности без нужды.
  • Не менять taxonomy-модель без фиксации причины.
  • Не использовать локальные Fyrre JSON-файлы как source of truth.

35. Что должен выполнить ИИ-кодер

  1. Реализовать структуру файлов из раздела 2.
  2. Создать все Collections и Globals.
  3. Создать 10 Blocks.
  4. Включить drafts/versions там, где требуется.
  5. Реализовать roles/access-control.
  6. Реализовать hooks публикации, slug, indexing queue, recommendation queue.
  7. Реализовать D30 idempotency.
  8. Создать migrations.
  9. Создать seed.
  10. Запустить тесты access/hook.
  11. Выдать schema report.

36. Deliverables от ИИ-кодера

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

37. Gate Build 02

PASS только если:
FAIL → не переходить к Build 03.

38. Следующий документ

После PASS: создать build_03_fyrre_mapping.html — точное сопоставление страниц, компонентов и визуальной структуры Fyrre Magazine с Payload Collections/Blocks и данными Mathchast.