projects/org/pirotehnika/app/pim/README.md

PIM — Product Information Management

Версия: 3.0.0
Дата: 2025-12-27
Статус: Production


ЧТО ЭТО

Централизованная система управления товарными данными. Собирает информацию из 1С и прайсов поставщиков, обогащает и раздаёт на маркетплейсы и сайты.

ВХОДЫ:          ЯДРО:              ВЫХОДЫ:
1С (OData)                      OZON API
Прайсы xlsx  pim_products    OpenCart
              (PostgreSQL)       Отчёты

БЫСТРЫЙ СТАРТ

cd /opt/claude-workspace/projects/org/pirotehnika/app/pim

# Запуск API
uvicorn pim.main:app --reload --port 8000

# Синхронизация с 1С
python -m pim.sync_1c

# Импорт прайса
python -m pim.import_price /path/to/price.xlsx --supplier maxsem

API Docs: http://localhost:8000/api/v1/docs

Подробнее: QUICKSTART.md


ДОКУМЕНТАЦИЯ

Основные документы

Документ Описание
README.md Этот файл — точка входа
CLAUDE.md Контекст для AI-агента
QUICKSTART.md Быстрый старт
API_DOCUMENTATION.md API endpoints
DEPLOYMENT.md Развертывание

Стандарты PIM

Стандарт Назначение
standards/DATABASE.md Структура БД (таблицы, поля, индексы)
standards/MAPPING_1C.md Маппинг полей из 1С
standards/NAMING.md Шаблоны названий товаров
standards/VALIDATION.md Правила валидации данных

Навигатор: standards/README.md

Рабочие документы

Документ Описание
IMPORT_1C_GUIDE.md Импорт из 1С
1C_PIM_MASTER_MAPPING.md Маппинг реквизитов 1С
BRAND_IMPORT_README.md Импорт брендов
SECURITY_APPROVAL_SYSTEM.md Система одобрения AI
DATA_FLOW_STRATEGY.md Стратегия потоков данных

Архив

Папка Содержимое
archive/2025-12-23/ Отчёты, анализы, старые версии стандартов

Project Structure

pirotehnika/pim/
├── api/                          # API endpoints
   ├── __init__.py              # Router aggregation
   ├── products.py              # Product endpoints
   └── pricing.py               # Pricing endpoints

├── core/                         # Business logic
   ├── __init__.py
   ├── products.py              # Product service
   └── pricing.py               # Pricing service

├── models/                       # SQLAlchemy ORM models
   ├── __init__.py
   ├── product.py               # Product models (Product, PimProduct)
   ├── pricing.py               # Pricing models (PriceCostRule)
   └── supplier.py              # Supplier models (SupplierCost, SupplierStock)

├── schemas/                      # Pydantic validation schemas
   ├── __init__.py
   ├── product.py               # Product response/request schemas
   └── pricing.py               # Pricing response/request schemas

├── tests/                        # Test cases
   ├── __init__.py
   └── test_api.py              # API tests

├── database.py                   # Database connection & session management
├── config.py                     # Application settings
├── main.py                       # FastAPI application entry point
├── requirements.txt              # Python dependencies

├── README.md                     # This file
├── API_DOCUMENTATION.md          # API endpoints documentation
├── USAGE_EXAMPLES.md             # Usage examples and integration guides
└── DEPLOYMENT.md                 # Deployment instructions

Quick Start

1. Installation

cd /opt/claude-workspace/L1-SERVICE/pirotehnika/pim
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt

2. Configuration

Create .env file with database credentials:

DATABASE_HOST=91.218.142.168
DATABASE_PORT=5432
DATABASE_USER=noco
DATABASE_PASSWORD=your_password
DATABASE_NAME=nocodb_data
DATABASE_SCHEMA=pt7k98pv0fwi1el

3. Run Development Server

python -m uvicorn main:app --reload --host 0.0.0.0 --port 8000

4. Access API

API Endpoints

Products

Method Endpoint Description
GET /api/v1/products/{article} Get product by article
GET /api/v1/products/ List products with filters
POST /api/v1/products/search Search products
GET /api/v1/products/brand/{brand} Get products by brand
GET /api/v1/products/category/{category} Get products by category

Pricing

Method Endpoint Description
POST /api/v1/pricing/calculate Calculate price for product
POST /api/v1/pricing/calculate-bulk Calculate prices for multiple products
GET /api/v1/pricing/rules Get all cost rules
GET /api/v1/pricing/rules/{brand} Get rule for brand
POST /api/v1/pricing/rules Create cost rule
PUT /api/v1/pricing/rules/{brand} Update cost rule
DELETE /api/v1/pricing/rules/{brand} Delete cost rule

Usage Examples

Get Product

curl -X GET "http://localhost:8000/api/v1/products/НФ-00001234"

Calculate Price

curl -X POST "http://localhost:8000/api/v1/pricing/calculate" \
  -H "Content-Type: application/json" \
  -d '{
    "article": "НФ-00001234",
    "markup_percent": 30
  }'

Python Client

import httpx

async with httpx.AsyncClient() as client:
    # Get product
    response = await client.get("http://localhost:8000/api/v1/products/НФ-00001234")
    product = response.json()

    # Calculate price
    response = await client.post(
        "http://localhost:8000/api/v1/pricing/calculate",
        json={
            "article": "НФ-00001234",
            "markup_percent": 30
        }
    )
    prices = response.json()

See USAGE_EXAMPLES.md for more examples.

Data Models

PimProduct

article: str              # Product SKU (primary key)
name: str                 # Product name
brand: str                # Brand (e.g., "JF-Pyro", "Maxsem")
category: str             # Product category
base_price: Decimal       # Manufacturer base price (прайс бренда)
fixed_price: Decimal      # Supplier final price (цена поставщика)
tier: str                 # Price tier: эконом, стандарт, премиум
product_type: str         # "simple" or "bundle"
code_1c: str              # Code in 1C system
barcode: str              # Product barcode
created_at: datetime      # Creation timestamp
updated_at: datetime      # Last update timestamp

PriceCostRule

id: int                   # Primary key
brand: str                # Brand name (unique)
discount_percent: Decimal # Discount percentage (0-100)
description: str          # Rule description
is_active: bool           # Is rule active
created_at: datetime      # Creation timestamp
updated_at: datetime      # Last update timestamp

Note: В версии 3.0.0 (миграция 029 от 2025-12-28) система ценообразования упрощена. См. PRICING_FINAL_CONCEPT.md для подробностей.

Key Concepts

Pricing Calculation

Ценообразование базируется на функциях PostgreSQL:

  1. Cost Price (себестоимость):
    sql calculate_cost_price(article) → base_price × (1 - discount%) OR fixed_price

  2. Retail Price (розничная цена):
    sql calculate_retail_price(article) → base_value × (1 + markup%) -- Fallback: MAX(base_price × 1.2, cost_price × 2)

Подробнее: PRICING_FINAL_CONCEPT.md

Example

Base Price: 100 RUB
Brand Discount: 30%
Cost Price: 100 × (1 - 0.30) = 70 RUB
Markup: 30%
Retail Price: 70 × (1 + 0.30) = 91 RUB

Architecture

Layered Architecture

API Layer (Endpoints)
    ↓
Business Logic Layer (Services)
    ↓
Data Access Layer (Models)
    ↓
Database Layer (PostgreSQL)

Technologies

Development

Running Tests

pytest tests/ -v
pytest tests/test_api.py::test_get_product -v

Code Quality

# Formatting
black .

# Linting
flake8 .

# Type checking
mypy .

Production Deployment

See DEPLOYMENT.md for detailed instructions on:
- Gunicorn + Uvicorn setup
- Docker deployment
- systemd service configuration
- Nginx reverse proxy
- Database backup and recovery
- Security considerations
- Monitoring and logging

Configuration

Environment Variables

# Database
DATABASE_HOST=91.218.142.168
DATABASE_PORT=5432
DATABASE_USER=noco
DATABASE_PASSWORD=password
DATABASE_NAME=nocodb_data
DATABASE_SCHEMA=pt7k98pv0fwi1el

# API
API_V1_PREFIX=/api/v1
API_TITLE=PIM Service API
API_VERSION=1.0.0
API_DESCRIPTION=Product Information Management for pirotehnika

# CORS
CORS_ORIGINS=["*"]

# Logging
LOG_LEVEL=INFO

API Documentation

Error Handling

All errors follow standard HTTP status codes:

Performance

Optimization Tips

  1. Use pagination when listing products
  2. Leverage database indexes on frequently searched fields
  3. Cache cost rules (they change infrequently)
  4. Use bulk endpoints for multiple operations
  5. Monitor query performance with echo=True in dev

Database Indexes

The service automatically creates indexes on:
- products.brand
- products.category
- cost_rules.brand

Roadmap

License

Internal use only

Support

For issues or questions, contact the development team.

Authors

Version

API Version: 1.0.0
Service Version: 1.0.0