Справочник моделей данных
NOTE
Статус: Target design. Документ описывает целевую доменную модель. Соответствующий код реализован частично (см.
backend/internal/core/) или пока не начат. Правила маркировки — в50-processes/documentation-standard.md.
Сводный реестр всех доменных моделей по Bounded Contexts. Здесь — что существует и в каком BC живёт, без бизнес-правил и инвариантов (они в файлах контекстов).
Назначение файла:
- Точка одного взгляда: «какие сущности у нас вообще есть».
- Источник имён для код-генерации, схем БД, событий Kafka.
- Сверка с
ubiquitous-language.mdи../GLOSSARY.md.
Подробные определения, инварианты, события, команды — в contexts/.
Большая картина и context map — в domain-model.md.
Условные обозначения
- Aggregate (🟨) — граница консистентности. Изменяется командами как единое целое.
- Entity (E) — имеет identity, изменяется во времени, но не управляет согласованностью внешних объектов.
- Value Object (VO) — без identity, immutable.
- Read Model (🟩) — проекция, не источник истины.
- Plugin / Port (⚙️) — интерфейс, реализация — за пределами BC.
Каталог
| Имя | Тип | Описание |
|---|---|---|
CanonicalProduct | 🟨 Aggregate | Единая единица товара. Идентифицируется identity_signature. Содержит media: [MediaAsset], certificates: [MediaAsset], external_identities: [ExternalIdentity] — набор ID из разных стандартов (ETIM class, GTIN, MPN, OKPD2). ADR-0028. |
IdentityProfile | E | Шаблон критических характеристик для группы товаров. |
Manufacturer | E | Производитель (бренд). С aliases[]. |
ManufacturerAlias | VO | Алиас написания. |
Characteristic | E | Определение атрибута: key, value_type, default_unit. |
Unit | E | Единица измерения с to_canonical. |
EquivalenceClass | E | Группа взаимозаменяемых canonical products. |
EquivalenceMember | VO | Связка member + source + confidence. |
ClassificationTag | VO | Свободный тег классификации. |
IdentitySignature | VO | Хэш-фингерпринт идентичности. |
LifecycleStatus | VO | new / active / deprecated / discontinued. |
SupplierCharacteristicMapping | 🟨 Aggregate | ACL маппинг (supplier_ref, supplier_char_code) → {Direct(tracium_key) | ViaTaxonomy(standard, external_code)}. Event-sourced. ADR-0028. |
SupplierClassificationMapping | 🟨 Aggregate | ACL маппинг (supplier_ref, supplier_class_code) → {Direct([tags]) | ViaTaxonomy(standard, external_code)}. Event-sourced. |
SupplierManufacturerMapping | 🟨 Aggregate | ACL маппинг (supplier_ref, supplier_manufacturer_code) → Manufacturer.id. Event-sourced. |
IdentityStandard | 🟨 Aggregate | Запись о federated taxonomy (ETIM v7, eCl@ss, UNSPSC, GS1 GTIN, MPN, OKPD2, …). {code, version?, domain, kind: classification|characteristic_schema|identifier|hybrid, status}. ADR-0028. |
TaxonomyCharacteristicMapping | 🟨 Aggregate | (standard_ref, external_feature_code) → Characteristic.key + unit_override?. Event-sourced. Один раз на стандарт — переиспользуется всеми поставщиками. |
TaxonomyClassMapping | 🟨 Aggregate | (standard_ref, external_class_code) → [ClassificationTag]. Multi-tag. Event-sourced. |
TaxonomyValueMapping | VO | (standard_ref, external_value_code) → tracium_value — для enum-характеристик (ETIM EV-codes). |
ExternalIdentity | VO | (standard_ref, external_code) — marker на CanonicalProduct.external_identities[]. |
MappingTarget | VO | Discriminated union: Direct(tracium_key) или ViaTaxonomy(standard_ref, external_code). |
MappingSource | VO enum | declared / imported / inferred / operator / moderation_accepted. |
MappingConfidence | VO | (score: float, method: string). |
Контекст: contexts/catalog.md. Deep-dive: product-identity.md, characteristics.md. Сценарий: scenarios/supplier-dictionary-sync.md.
Предложения
| Имя | Тип | Описание |
|---|---|---|
SupplierOffer | 🟨 Aggregate | Товарная канва у конкретного поставщика. Без цен/остатков. |
SupplierOfferObservation | 🟨 Aggregate (append-only) | Наблюдение цены/остатков/срока по (offer, credential, seller_ref?). Содержит MultiCurrencyPrices + StockCurrent + StockForecast + DeliveryTerm. seller_ref опционален для marketplace observations (ADR-0026). Поддерживает мультивалютные PriceSets (ADR-0025 extended). |
SkuIdentityPack | VO | (supplier_sku, manufacturer_article?, manufacturer_code?, client_sku?) — полный набор ID, которые вернул поставщик. |
OfferCharacteristicSnapshot | VO | Срез характеристик от поставщика, в исходной таксономии поставщика. |
Packaging | VO | Упаковка / единица отгрузки. |
PriceSet | VO | (net?, gross?, list_tarif?, retail_rec?, vat_rate?, currency, on_request, validity_window?, tags?) — мульти-цена в одной валюте. Валюта обязательна. validity_window: DateRange? — для discount / promo периодов (Systeme Electric pattern). ADR-0025. |
MultiCurrencyPrices | VO | map<ISO4217, PriceSet> — observation хранит несколько валют параллельно (DKC: RUB + KZT). Pricing выбирает PriceSet по PricingContext.requested_currency. |
PriceKind | VO enum | net / gross / list_tarif / retail_rec — какое поле PriceSet считается базовой ценой в данном PricingContext. |
DateRange | VO | (from: timestamp?, to: timestamp?) — open-ended допустим с любой стороны. |
StockCurrent | VO | Текущий остаток на набор складов. |
WarehouseStock | VO | (warehouse_ref, qty, available_at). |
StockForecast | VO | (incoming[], in_way[], backorders[]) — прогноз поступлений, транзит, заявки. См. ADR-0025. |
DeliveryTerm | VO | (lead_time_when_in_stock_days?, lead_time_when_out_of_stock_days?, production_term_days?, requires_specification, source_warehouse_ref?, notes?). Расширено ADR-0025. |
PricingMode | VO enum | fixed / on_request. Наследуется от PriceSet.on_request. |
MatchConfidence | VO enum | exact / strong / probable / weak / unmatched. |
RawPayloadRef | VO | Указатель в S3 на исходный body. |
MediaAsset | VO | (kind, url_small?, url_large?, mime, format?, watermarked, rights_source_credential_ref?). Kind: image / video / certificate / datasheet. |
Контекст: contexts/offers.md.
Загрузка данных
| Имя | Тип | Описание |
|---|---|---|
EnrichmentJob | 🟨 Aggregate | Async-задача на опрос поставщика. |
JobKind | VO enum | discovery / refresh_observation / refresh_characteristics / rebuild_supply_chain / full_catalog / stock_batch / incremental_sync / manufacturer_dictionary_refresh / characteristic_dictionary_refresh / classification_dictionary_refresh / taxonomy_dictionary_refresh / distributor_office_refresh. incremental_sync — revision/date-based delta (ADR-0029). taxonomy_dictionary_refresh — ETIM/eCl@ss/… dump (ADR-0028). |
JobStatus | VO enum | queued / running / awaiting_report / fetching / completed / failed / skipped. awaiting_report + fetching — для async-report паттерна (ADR-0024). |
JobPriority | VO enum | high / normal / low. |
RemoteJobRef | VO | (uuid, provider, submitted_at, deadline) — для polling async-report. |
PollStrategy | VO | (initial_delay, interval, max_wait, backoff). |
IncrementalSyncCursor | 🟨 Aggregate | (supplier_ref, data_scope) → {cursor_kind, cursor_value, last_applied_at, health}. data_scope: materials / stock / price / characteristics / certificates / packings / nodes / distributor_offices / taxonomy_<standard>. cursor_kind: revision / date / opaque_token. ADR-0029. |
CursorHealth | VO enum | healthy / stale / broken. |
DataScope | VO enum | materials / stock / price / characteristics / certificates / packings / nodes / distributor_offices / taxonomy_etim_v7 / taxonomy_eclass_10 / ... |
RawPayload | VO | Сырая полезная нагрузка от коннектора. |
ConnectorError | VO enum | AuthRejected / SessionExpired / RateLimited / NotFound / OnRequest / Transient / Permanent / PartialSuccess. Единая taxonomy (ADR-0024). |
Connector | ⚙️ Port | Интерфейс реализации поставщика. |
CredentialRouter | ⚙️ Port | Выбор credential для запроса. |
RateLimiter | ⚙️ Port | Двухуровневый бюджет: AuthBucket + DataBucket[endpoint_class] (ADR-0008). |
SessionManager | ⚙️ Port | Acquire/release session handle с проактивным refresh. |
Контекст: contexts/ingestion.md.
Матчинг
| Имя | Тип | Описание |
|---|---|---|
MatchDecision | 🟨 Aggregate | Решение о связке SupplierOffer ↔ CanonicalProduct. |
MatchSignal | VO | Один из сигналов: identity, embedding, classification, packaging, consensus, manual. |
OrphanItem | E | Offer без identity_profile, ждущий резолюции. |
OrphanCategory | VO enum | hot / warm / cold. |
RematchRequest | VO | Команда «пересчитать матчинг по этим offers». |
MatchExplanation | VO | Структурированное объяснение решения. |
Контекст: contexts/matching.md.
Обогащение
| Имя | Тип | Описание |
|---|---|---|
EnrichmentTask | 🟨 Aggregate | Задача обогащения для конкретного canonical / offer. |
EnrichmentResult | VO | Извлечённые поля + confidence + источник модели. |
EnrichmentSource | VO enum | llm / rule_calculated / manual. |
LlmModelRef | VO | model_name + version + prompt_hash. |
Контекст: contexts/enrichment.md.
Ценообразование
| Имя | Тип | Описание |
|---|---|---|
PriceRule | 🟨 Aggregate | Правило ценообразования. |
RuleScope | VO | На что распространяется (supplier / canonical / tag / customer_pricing_group). |
RuleAppliesTo | VO | Условия применимости. |
Transformation | VO | percentage / tiers / fixed / formula / logistics / vat. |
Priority | VO | Целое число; больше = выше. |
PricingContext | VO | (customer, quantity, region, delivery_point, contract, date). |
PricingResult | VO | Финальная цена + breakdown + observation_source. |
PriceBreakdownItem | VO | Одна строка breakdown: rule_id, label, amount. |
ObservationSource | VO | (type, credential_label, observed_at, fallback_reason). |
CustomPricingHandler | ⚙️ Plugin | Плагин клиента: применяет ценовые правила, когда API поставщика их не отдаёт. |
PricingAdjustment | VO | Возврат от handler: список доп. правил для применения. |
Контекст: contexts/pricing.md.
Видимость
| Имя | Тип | Описание |
|---|---|---|
DataVisibilityPolicy | 🟨 Aggregate | Правило видимости. |
Subject | VO | default / customer / customer_group / customer_pricing_group / role. |
TargetKind | VO enum | catalog / offer / observation / price / characteristic / analytics / media. |
Effect | VO enum | allow / deny / transform. |
Predicate | VO | JSONB-дерево предикатов. |
TransformSpec | VO | Описание трансформации (redact / round / hide / price_to_range). |
CompiledPolicy | 🟩 Read model | Кэшированное исполнимое представление per-subject. |
Контекст: contexts/visibility.md.
Поиск
| Имя | Тип | Описание |
|---|---|---|
SearchQuery | VO | Запрос пользователя (текст / артикул / фасеты / «не хуже чем»). |
SearchResult | 🟩 Read model | Ранжированный список кандидатов. |
SearchHit | VO | Один результат + score + explain. |
BetterDirection | VO enum | higher / lower / neutral. |
EmbeddingVector | VO | Dense vector для семантического поиска. |
Контекст: contexts/search.md.
Смета
| Имя | Тип | Описание |
|---|---|---|
Estimate | 🟨 Aggregate | Смета, версионируется. |
EstimateLine | E | Одна позиция сметы (после парсинга). |
EstimateLineDraft | VO | Сырая распарсенная строка с полями + confidence. |
EstimateOptimization | VO | Параметры оптимизатора (mode + constraints). |
OptimizationMode | VO enum | min_price / min_suppliers / min_lead_time / single_manufacturer. |
EstimateAlternative | VO | Альтернативный offer для строки. |
EstimateExplanation | VO | «Выбрано потому что …» — структурированно. |
Контекст: contexts/estimate.md.
Клиент
| Имя | Тип | Описание |
|---|---|---|
Customer | 🟨 Aggregate | Клиент, B2B или B2C. |
CustomerType | VO enum | individual / legal_entity. |
LegalInfo | VO | Для legal_entity: ИНН, КПП, company_name, country. |
ContactInfo | VO | Email, phone. |
CustomerPricingGroup | E | Группа тарификации (b2c_retail, b2b_standard, …). |
Contract | E | B2B-договор: набор Price Rules + payment_profile. |
PaymentProfile | VO | Способ оплаты. |
DeliveryAddress | VO | Адрес доставки. |
AuthIdentity | E | Способ входа (email+pass / OAuth / SSO). |
Session | E | Активная сессия. |
SessionContext | VO | (customer_id, customer_type, pricing_group, roles, session_id) — Shared Kernel, передаётся вниз во все BC. |
Контекст: contexts/customer.md.
Учётные данные
| Имя | Тип | Описание |
|---|---|---|
SupplierCredential | 🟨 Aggregate | Учётка доступа к API поставщика. |
CredentialScope | VO enum | system / customer. |
AuthSchema | VO enum | login_password / api_key / oauth2 / bearer_token / master_key_token_exchange / public_no_auth / custom. master_key_token_exchange — DKC pattern (MasterKey → short-lived access_token). public_no_auth — публичный file feed (КЭАЗ). |
AuthPayload | VO | JSONB; поля с secret: true зашифрованы. |
AuthMetadata | VO | Открытые поля. |
Fingerprint | VO | Стабильный hash для дедупликации. |
SupplierCredentialGroup | E | Группа credentials с одинаковым fingerprint. |
CredentialFeatures | VO enum-set | catalog / prices / stock / place_orders / media_unwatermarked / dictionary_exports / async_reports. |
CredentialConstraints | VO | (warehouse_scope?, classification_tag_scope?, egress_policy?) — per-credential ограничения, выдаваемые поставщиком. |
CredentialStatus | VO enum | draft / validating / active / failing / expired / revoked. |
CredentialContext | VO | Shared Kernel — передаётся в Connector при опросе. Включает rate-bucket refs, warehouse scope, features. |
ClientSkuMap | 🟨 Aggregate | Cross-reference клиентских SKU на коды поставщика. Per-(customer_ref, supplier_ref, credential_ref). |
ClientSkuMapping | VO | (client_sku, supplier_sku, manufacturer_article?, verified_at, source). |
ClientSkuMappingSource | VO enum | manual_csv / dictionary_export / observed_in_payload / operator. |
MasterKeyProvider | ⚙️ Port | Vault Transit / KMS / sealed-file. |
Контекст: contexts/credentials.md.
Сеть поставщиков
| Имя | Тип | Описание |
|---|---|---|
Supplier | 🟨 Aggregate | Узел графа поставщиков. |
SupplierKind | VO enum | manufacturer / distributor / aggregator / marketplace / marketplace_seller / agent / warehouse_operator / logistics / mixed. marketplace_seller — legitimate only внутри listed_on связи с aggregator (ADR-0026). |
SupplierRole | E | Одна из ролей supplier’а. Расширяемый словарь. |
RoleKindCode | VO | Машинный код из словаря supplier_role_kind. |
RoleScope | VO | full / classification_tag:{tag} / manufacturer_group:{id} / warehouse:{code}. |
SupplierRelationship | E | Направленное ребро графа. |
RelationshipKindCode | VO | aggregates / resells / is_agent_of / uses_api_of / uses_warehouse_of / subsidiary_of / exclusive_for / listed_on / GENERIC. listed_on — marketplace_seller → aggregator (ADR-0026). |
TrustLevel | VO enum | origin / tier_1 / tier_2 / unverified. |
SupplyChainTrace | VO | Shared Kernel — снэпшот цепочки для offer/observation. Включает warehouse_chain[]. |
Warehouse | E | Склад, привязан к warehouse_operator. Обязательное поле kind: WarehouseKind. |
WarehouseKind | VO enum | regional_center / logistics_center / pickup_office / manufacturer_warehouse / distributor_office / third_party / transit. Фиксированный enum, расширяется только через ADR. См. ADR-0025. distributor_office — офис официального дистрибьютора производителя (DKC /revisions/distributorOffices pattern). |
Seller | E | Дочерний узел агрегатора (marketplace). Lightweight: не требует credential / контракта. Идентифицируется (supplier_ref, external_seller_id). ADR-0026. |
SellerStatus | VO enum | active / inactive / banned. |
SellerRating | VO | (score 0..5, sample_size?, observed_at, source). source: marketplace / external_review / moderator. |
PreferredSellerPolicy | 🟨 Aggregate (Pricing BC) | Per-customer / per-pricing-group preferences: (preferred_sellers[], blocked_sellers[]). Применяется в tie-break. |
Контекст: contexts/supplier-network.md.
Модерация (AI)
| Имя | Тип | Описание |
|---|---|---|
ModerationCase | 🟨 Aggregate | Кейс модерации. Lifecycle queued → analyzing → decided → applied / escalated. |
CaseKind | VO enum | match_review / orphan_resolution / inferred_relationship_review / enrichment_critical_attr_review / priority_overlap_review / credential_group_candidate / legal_info_verification_edge / manufacturer_alias_proposal / identity_profile_proposal. |
CaseSource | VO | (bc, aggregate_ref, event_id) — откуда. |
CaseEvidence | VO | Структурированный input агенту. |
AgentRunner | E | Конфигурация агента per CaseKind: model, prompt, threshold, SLA. |
AgentDecision | VO | (verdict, confidence, reasoning, citations[], proposed_action). |
Verdict | VO enum | accept / reject / escalate / defer. |
ProposedAction | VO | Команда для source BC. |
EscalationPolicy | E | Когда / куда escalate. |
AgentRun | E (append-only) | Аудит одного выполнения LLM. |
HumanEscalation | E | Запись escalation, только для security-critical / low-confidence. |
LlmModelRef | VO | Shared Kernel с Enrichment. |
Контекст: contexts/moderation.md. Сценарий: scenarios/ai-moderation-flow.md.
Сквозные компоненты / Shared Kernel
Минимальный общий kernel — VO, разделяемый между BC. Изменение требует RFC и согласия всех владельцев.
| Имя | Тип | Где разделено |
|---|---|---|
Money | VO | (amount: Decimal, currency: ISO4217). Pricing, Estimate, Offers. |
SupplyChainTrace | VO | Supplier Network → Offers, Pricing, Visibility. |
CredentialContext | VO | Credentials → Ingestion, Pricing. |
SessionContext | VO | Customer → Search, Pricing, Estimate, Visibility. |
Subject | VO | Customer / Visibility. |
CorrelationId | VO | Все BC — для трассировки. |
EventMetadata | VO | Все BC — actor, correlation_id, trace_id, source, reason. |
Соответствие BC ↔ модули и сервисы
См. ../20-architecture/module-layout.md — отображение BC на internal/core/<module>/ и cmd/<process>/.
Соответствие BC ↔ event store / схемы
См. ../20-architecture/event-sourcing.md для списка event-sourced агрегатов.
См. ../20-architecture/schemas/events/ для машинных JSON Schema интеграционных событий.