Версия: 4.0.0
Дата: 2025-12-23
Статус: active
Централизованная библиотека переиспользуемого кода с иерархией уровней:
L2 Primitives → L3 Functions → L4 Components → L5 Services → L6 Integrations
(типы) (атомы) (молекулы) (организмы) (экосистемы)
library/
├── paths.py ← Централизованные пути
├── requirements.txt ← Зависимости
├── CLAUDE.md ← Эта документация
│
├── artifacts/ ← АРТЕФАКТЫ (готовые сборки)
│ └── cms/ ← CMS системы
│ └── drupal/ ← Drupal сборки
│ └── 11/ ← Drupal 11.3.3
│
├── primitives/ ← L2: ТИПЫ (атомы данных)
│ ├── types.py ← Pydantic модели
│ ├── enums.py ← Перечисления
│ ├── constants.py ← Константы
│ └── exceptions.py ← Иерархия исключений
│
├── functions/ ← L3: ФУНКЦИИ (атомы логики)
│ ├── format/ ← Форматирование
│ │ ├── money.py ← Деньги (babel)
│ │ ├── phone.py ← Телефоны (phonenumbers)
│ │ └── date.py ← Даты (dateutil)
│ ├── validate/ ← Валидация
│ │ ├── inn.py ← ИНН, ОГРН, КПП
│ │ ├── email.py ← Email (email-validator)
│ │ └── phone.py ← Телефоны
│ ├── normalize/ ← Нормализация
│ │ ├── text.py ← Текст (slugify, unidecode)
│ │ └── phone.py ← Телефоны
│ ├── transform/ ← Преобразования
│ ├── calc/ ← Вычисления
│ └── generate/ ← Генерация (shortuuid)
│
├── connectors/ ← L4: КОННЕКТОРЫ (транспорт)
│ ├── base.py ← BaseConnector, BaseApiConnector
│ ├── api/ ← Внешние API
│ │ ├── ozon/
│ │ ├── telegram/
│ │ └── pochta/
│ └── data/ ← Хранилища
│ ├── postgres/
│ └── redis/
│
├── parsers/ ← L4: ПАРСЕРЫ (форматы)
│ ├── base.py ← BaseParser, BaseTabularParser
│ ├── xlsx/
│ ├── csv/
│ └── pdf/
│
├── adapters/ ← L4: АДАПТЕРЫ (маппинг)
│ ├── base.py ← BaseAdapter, ConfigurableAdapter
│ ├── ozon/ ← OZON → Unified
│ └── suppliers/ ← Поставщики → Product
│
├── storages/ ← L4: ХРАНИЛИЩА (персистенция)
│ ├── base.py ← BaseRepository, BaseCache
│ ├── postgres/
│ └── nocodb/
│
├── services/ ← L5: СЕРВИСЫ (оркестрация)
│ ├── base.py ← BaseService, BaseSyncService
│ ├── sync/ ← Синхронизация
│ ├── worker/ ← Фоновые процессы
│ └── api/ ← REST API
│
└── integrations/ ← L6: ИНТЕГРАЦИИ (экосистемы)
├── base.py ← BaseIntegration, BaseSyncIntegration
├── ozon-1c/ ← OZON ↔ 1C
└── ozon-pochta/ ← OZON → Почта РФ
| Уровень | Папка | Что это | Зависит от |
|---|---|---|---|
| L2 | primitives/ | Типы данных | Только pydantic |
| L3 | functions/ | Чистые функции | L2 + внешние библиотеки |
| L4 | connectors/, parsers/, adapters/, storages/ | Компоненты | L2 + L3 |
| L5 | services/ | Бизнес-логика | L4 |
| L6 | integrations/ | Связь систем | L5 |
Правило: Уровень N может импортировать только N-1 и ниже.
from library.primitives.types import Money, Phone, Address
from library.primitives.enums import OrderStatus, PaymentType
from library.primitives.exceptions import ValidationError
order = Money(amount=150000, currency="RUB") # 1500.00 руб
from library.functions.format.money import format_money, parse_money
from library.functions.validate.inn import validate_inn
from library.functions.normalize.text import slugify
print(format_money(150000)) # "1 500,00 ₽"
print(validate_inn("7707083893")) # True
print(slugify("Привет мир")) # "privet-mir"
from library.connectors.base import BaseApiConnector
from library.adapters.base import BaseAdapter
from library.storages.base import BaseRepository
class OzonConnector(BaseApiConnector):
BASE_URL = "https://api-seller.ozon.ru"
async def get_orders(self) -> List[Dict]:
return await self._request("POST", "/v3/posting/fbs/list")
from library.services.base import BaseSyncService, ServiceResult
class OrderSyncService(BaseSyncService):
async def extract(self) -> List[Dict]:
return await self.ozon.get_orders()
async def transform(self, data: List[Dict]) -> List[Order]:
return self.adapter.adapt_many(data)
async def load(self, data: List[Order]) -> int:
for order in data:
await self.db.save(order)
return len(data)
result = await service.sync() # ServiceResult
from library.integrations.base import BaseSyncIntegration
class OzonTo1CIntegration(BaseSyncIntegration):
async def fetch_source(self) -> List[Dict]:
return await self.ozon_service.get_new_orders()
async def sync_to_target(self, items: List[Dict]) -> int:
for item in items:
await self.onec_service.create_order(item)
return len(items)
result = await integration.run_sync()
Все пути централизованы в library/paths.py:
from library.paths import PATHS, project_path
print(PATHS.WORKSPACE) # /opt/claude-workspace
print(PATHS.LIBRARY) # /opt/claude-workspace/library
print(project_path("pirotehnika")) # /opt/claude-workspace/projects/pirotehnika
ENV переменные:
- $WORKSPACE — корень рабочего пространства
- $DATASPACE — хранилище данных
pip install -r library/requirements.txt
Обязательные:
- pydantic — типы и валидация
L3 Functions:
- babel — форматирование денег/дат
- phonenumbers — телефоны
- python-dateutil — парсинг дат
- email-validator — валидация email
- python-slugify — slug
- shortuuid — генерация ID
L4 Components:
- aiohttp, httpx — HTTP
- openpyxl — Excel
- asyncpg — PostgreSQL
- redis — Redis
Готовые сборки для быстрого развертывания.
artifacts/
└── cms/ ← CMS системы
└── drupal/
└── 11/ ← Drupal 11.3.3
├── CLAUDE.md
├── drupal-11-clean-*.tar.gz (22 MB)
└── drupal-11-vanilla-*.tar.gz (29 MB)
Использование:
# Скопировать сборку
cp library/artifacts/cms/drupal/11/drupal-11-vanilla-*.tar.gz ~/
# Развернуть (см. artifacts/cms/drupal/11/CLAUDE.md)
tar -xzf drupal-11-vanilla-*.tar.gz -C ~/new-project/
См.: artifacts/cms/drupal/11/CLAUDE.md
projects/my/experiment/ → library/{level}/{name}/
(разработка) (stable)
Правила:
1. Новый код — сначала в projects/
2. После стабилизации — в library/
3. В library/ только tested код
Artifacts:
- Создаются в projects/ при достижении production-ready состояния
- Копируются в library/artifacts/ для переиспользования
- Версионируются по дате (YYYYMMDD)
Версия: 4.1.0