# Архитектура MVP: ERP для мастеров ## 🏗️ Общая архитектура ```mermaid graph TB subgraph "Frontend" A[Angular PWA] B[QR Scanner] end subgraph "Backend" C[Go Core Service (REST)] end subgraph "Infrastructure" E[PostgreSQL] end A <--> C B --> A C <--> E style A fill:#ff9999 style C fill:#99ccff style E fill:#ffcc99 ``` --- ## 🛠️ Технологический стек ### Backend (Go) - Framework: Gin (легкий и быстрый) - Database: PostgreSQL - Authentication: JWT - Validation: validator - API: REST + OpenAPI (Swagger) ### Frontend (Angular PWA) - Framework: Angular 17+ - PWA: @angular/service-worker (только кэш статики) - QR Scanner: @zxing/ngx-scanner - UI: Angular Material + Tailwind CSS - State Management: локальные сервисы (без NgRx на MVP) ### Infrastructure - Containerization: Docker - Orchestration: Docker Compose - Web server (опционально): Nginx для фронтенда - Security: HTTPS, CORS, JWT - Monitoring: структурированное логирование (метрики Post‑MVP) --- ## 📊 Структура базы данных ### ER-диаграмма ```mermaid erDiagram organizations { uuid id PK varchar name varchar type jsonb settings timestamp created_at } users { uuid id PK uuid organization_id FK varchar email varchar role timestamp created_at } storage_locations { uuid id PK uuid organization_id FK uuid parent_id FK varchar name varchar address varchar type jsonb coordinates varchar qr_code timestamp created_at } items { uuid id PK uuid organization_id FK varchar name text description varchar category timestamp created_at } item_placements { uuid id PK uuid organization_id FK uuid item_id FK uuid location_id FK integer quantity timestamp created_at } organizations ||--o{ users : "has" organizations ||--o{ storage_locations : "has" organizations ||--o{ items : "has" organizations ||--o{ item_placements : "has" storage_locations ||--o{ storage_locations : "parent-child" storage_locations ||--o{ item_placements : "contains" items ||--o{ item_placements : "placed_in" ``` ### Основные таблицы ```sql -- Организации CREATE TABLE organizations ( id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, type VARCHAR(100), settings JSONB, created_at TIMESTAMP DEFAULT NOW() ); -- Пользователи CREATE TABLE users ( id UUID PRIMARY KEY, organization_id UUID REFERENCES organizations(id), email VARCHAR(255) UNIQUE NOT NULL, role VARCHAR(50) DEFAULT 'user', created_at TIMESTAMP DEFAULT NOW() ); -- Места хранения CREATE TABLE storage_locations ( id UUID PRIMARY KEY, organization_id UUID REFERENCES organizations(id), parent_id UUID REFERENCES storage_locations(id), name VARCHAR(255) NOT NULL, address VARCHAR(100) NOT NULL, type VARCHAR(50) NOT NULL, coordinates JSONB, qr_code VARCHAR(255), created_at TIMESTAMP DEFAULT NOW() ); -- Товары CREATE TABLE items ( id UUID PRIMARY KEY, organization_id UUID REFERENCES organizations(id), name VARCHAR(255) NOT NULL, description TEXT, category VARCHAR(100), created_at TIMESTAMP DEFAULT NOW() ); -- Размещение товаров CREATE TABLE item_placements ( id UUID PRIMARY KEY, organization_id UUID REFERENCES organizations(id), item_id UUID REFERENCES items(id), location_id UUID REFERENCES storage_locations(id), quantity INTEGER DEFAULT 1, created_at TIMESTAMP DEFAULT NOW() ); ``` --- ## 🔌 API Endpoints ### Core Service (Go) - REST API ``` # Аутентификация POST /api/auth/login POST /api/auth/register # Организации GET /api/organizations/:id PUT /api/organizations/:id # Места хранения GET /api/locations POST /api/locations GET /api/locations/:id PUT /api/locations/:id DELETE /api/locations/:id # Товары GET /api/items POST /api/items GET /api/items/:id PUT /api/items/:id DELETE /api/items/:id # Операции POST /api/operations/place-item POST /api/operations/move-item GET /api/operations/search # Шаблоны GET /api/templates POST /api/templates/:id/apply ``` ## 🚀 Развертывание ### Docker Compose (MVP) ```yaml version: '3.8' services: core-service: build: ./core-service ports: - "8080:8080" environment: - DB_HOST=postgres - JWT_SECRET=your-secret depends_on: - postgres frontend: build: ./frontend ports: - "3000:80" depends_on: - core-service postgres: image: postgres:15 environment: - POSTGRES_DB=erp_mvp - POSTGRES_USER=erp_user - POSTGRES_PASSWORD=erp_pass volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: ``` ### Структура проекта ```mermaid graph TD A[erp-mvp/] --> B[core-service/] A --> C[doc-service/] A --> D[frontend/] A --> E[proto/] A --> F[docker-compose.yml] B --> B1[cmd/] B --> B2[internal/] B --> B3[pkg/] B --> B4[proto/] B --> B5[Dockerfile] C --> C1[app/] C --> C2[templates/] C --> C3[proto/] C --> C4[Dockerfile] D --> D1[src/] D --> D2[angular.json] D --> D3[Dockerfile] E --> E1[core.proto] E --> E2[document.proto] E --> E3[events.proto] style A fill:#e1f5fe style B fill:#f3e5f5 style C fill:#e8f5e8 style D fill:#fff3e0 style E fill:#fce4ec ``` --- ## 📚 Конкретные библиотеки и фреймворки ### Core Service (Go) ```go // Основные зависимости go.mod: - github.com/gin-gonic/gin v1.9.1 // HTTP framework - github.com/golang-jwt/jwt/v5 v5.0.0 // JWT authentication - github.com/lib/pq v1.10.9 // PostgreSQL driver - github.com/go-playground/validator/v10 // Validation - google.golang.org/grpc v1.58.0 // gRPC client/server - github.com/swaggo/gin-swagger v1.6.0 // API documentation - github.com/redis/go-redis/v9 v9.2.1 // Redis client ``` ### Document Service (Python) ```python # requirements.txt fastapi==0.104.1 # Web framework uvicorn==0.24.0 # ASGI server reportlab==4.0.4 # PDF generation weasyprint==60.1 # HTML to PDF python-docx==1.1.0 # Word documents openpyxl==3.1.2 # Excel files jinja2==3.1.2 # Templates redis==5.0.1 # Redis client grpcio==1.59.0 # gRPC protobuf==4.24.4 # Protocol Buffers pydantic==2.4.2 # Data validation ``` ### Frontend (Angular) ```json // package.json { "dependencies": { "@angular/core": "^17.0.0", "@angular/material": "^17.0.0", "@angular/service-worker": "^17.0.0", "@zxing/ngx-scanner": "^3.0.0", "@ngrx/store": "^17.0.0", "@ngrx/effects": "^17.0.0", "tailwindcss": "^3.3.0", "rxjs": "^7.8.0" } } ``` ## 📊 Мониторинг ### Логирование - **Go:** logrus или zerolog для structured logging - **Python:** structlog для structured logging - **Frontend:** Angular logging service - Correlation ID для отслеживания запросов через все сервисы ### Метрики - **Prometheus** для сбора метрик - **Grafana** для визуализации - Время отклика API по сервисам - Количество ошибок и их типы - Активные пользователи и операции ### Алерты - Высокое время отклика (>500ms) - Высокий процент ошибок (>5%) - Недоступность сервисов - Проблемы с генерацией документов