Skip to content

Repository files navigation

YCLIENTS-Bitrix24 Integration

Bidirectional integration between YCLIENTS (salon management) and Bitrix24 (CRM) — built for a real beauty salon chain with 5 branches.

Двусторонняя интеграция YCLIENTS и Bitrix24 — разработана для реальной сети салонов красоты (5 филиалов).

Python FastAPI PostgreSQL Docker Nginx


What it does / Что делает

1. Real-time Event Sync (automatic)

Синхронизация событий (автоматическая)

YCLIENTS Event Bitrix24 Action
New appointment Create deal + link contact by phone
Updated appointment Update deal fields (staff, service, time)
Deleted appointment Close deal (LOSE)
Bitrix24 Event YCLIENTS Action
Deal stage changed Update attendance status
  • Processes webhooks from both systems in real-time
  • Automatic client matching by phone number normalization
  • Retry logic with exponential backoff
  • Rate limiting to respect Bitrix24 API limits (2 req/s)

2. Booking Widget (manual, embedded in Bitrix24)

Виджет записи (встроен в Bitrix24)

Managers can book YCLIENTS appointments directly from a Bitrix24 deal card — without switching apps:

Менеджеры записывают клиентов в YCLIENTS прямо из карточки сделки Bitrix24:

Branch (5 salons) → Date (60-day calendar) → Staff → Time (15-min grid) → Service → Confirm
  • Custom JavaScript SPA embedded via Bitrix24 Placement API
  • OAuth 2.0 authentication with automatic token refresh
  • Service search with duration display per staff member
  • Visual timeline with 15-minute slot grid

Architecture / Архитектура

                                     ┌─────────────────────────────────────────┐
                                     │           Docker Compose                │
                                     │                                         │
┌──────────────┐  webhook   ┌────────┴────────┐        ┌─────────────────┐    │
│   YCLIENTS   │ ─────────→ │                 │        │                 │    │
│   (salon     │            │   FastAPI App   │ ─────→ │   PostgreSQL    │    │
│   system)    │            │   (async)       │        │   (events DB)   │    │
└──────────────┘            │                 │        └─────────────────┘    │
                            │  Webhook ingest │                               │
┌──────────────┐  webhook   │  Event processor│        ┌─────────────────┐    │
│   Bitrix24   │ ─────────→ │  Booking API    │        │    Monitor      │    │
│   (CRM)      │ ←───────── │  OAuth manager  │        │  Health + Alerts│    │
└──────────────┘  REST API  └─────────────────┘        │  (Telegram)     │    │
       ▲                           │                   └─────────────────┘    │
       │         ┌─────────────────┴──────────────┐                           │
       │         │       Booking Widget           │                           │
       └─────────┤   JavaScript SPA (vanilla)     │                           │
   Placement API │   Embedded in Bitrix24 iframe  │                           │
                 └────────────────────────────────┘                           │
                                     └─────────────────────────────────────────┘

Tech Stack

Layer Technology
Backend Python 3.12, FastAPI, asyncio, httpx
Database PostgreSQL 16 (Alpine)
Frontend Vanilla JavaScript SPA (BookingApp class)
Infrastructure Docker Compose, Nginx, Let's Encrypt SSL
Monitoring Custom health checks + Telegram alerts
Auth OAuth 2.0 (Bitrix24), Bearer tokens (YCLIENTS), HMAC webhook tokens

Key Features / Ключевые решения

  • Async event processing — background processor with batch fetching (10 events/cycle), 2s polling interval
  • Exponential backoff — retries with jitter on 503/rate-limit responses
  • Phone normalization — handles +79991234567, 89991234567, 8 (999) 123-45-67 → unified format
  • Rate limiter — 0.5s minimum between Bitrix24 API calls to stay within limits
  • Graceful degradation — fallback to JSONL file if DB insert fails
  • Auto-migration — DB schema created on startup, custom Bitrix24 fields provisioned automatically
  • CSP headersframe-ancestors for secure iframe embedding in Bitrix24

API Endpoints

Webhooks

Endpoint Description
GET /healthz Health check
POST /yclients?token=... YCLIENTS webhook receiver
POST /bitrix?token=... Bitrix24 webhook receiver

Booking Widget API (REST)

Endpoint Description
GET /bitrix-app/oauth/callback OAuth 2.0 callback
GET /bitrix-app/api/services Services list with duration per staff
GET /bitrix-app/api/working-staff Available staff by date
GET /bitrix-app/api/staff-schedule Staff schedule (15-min timeline)
GET /bitrix-app/api/deal-info Client data from Bitrix24 deal
POST /bitrix-app/api/book Create YCLIENTS appointment

Quick Start

# 1. Configure
cp .env.example .env
nano .env  # fill in YCLIENTS tokens, Bitrix24 credentials, webhook secret

# 2. Run
docker compose up -d --build

# 3. Verify
curl http://127.0.0.1:8011/healthz

See docs/DEPLOY_NOW.md for full server deployment guide.


Project Structure / Структура проекта

yclients-bitrix/
├── app/
│   ├── main.py              # FastAPI app, webhook endpoints, DB schema auto-creation
│   ├── integration.py       # Bidirectional sync engine (YCLIENTS ↔ Bitrix)
│   ├── bitrix_app.py        # OAuth 2.0 + REST API for booking widget
│   ├── yclients_api.py      # YCLIENTS REST API client
│   └── monitor.py           # Health checks, disk alerts, Telegram notifications
├── static/widget/
│   ├── booking-app.html     # Booking widget UI (v2.2)
│   ├── booking-app.css      # Styles (gradient cards, timeline grid)
│   └── booking-app.js       # BookingApp SPA class
├── nginx/                   # Nginx config with SSL + CSP headers
├── migrations/              # SQL migrations
├── scripts/                 # Data migration & branch config tools
├── docker-compose.yml       # 3 services: app, db, monitor
├── Dockerfile               # Python 3.12-slim, uvicorn
├── .env.example             # All configuration variables documented
└── requirements.txt

Production Results / Результаты в продакшене

This integration was deployed and running in production for a beauty salon chain:

Metric Value
Branches served 5 salons
Events processed ~1,400
Success rate 91% (129 failures due to a known UUID parsing edge case)
Records migrated 793 historical appointments linked
Uptime Monitored with automatic Telegram alerts

Documentation / Документация

Document Description
ARCHITECTURE.md System architecture, DB schema, component details
IMPLEMENTATION.md Development log — problems solved and decisions made
CHANGELOG.md Version history and known issues
docs/DEPLOY_NOW.md Server deployment guide
docs/QUICK_START.md Bitrix24 app setup walkthrough
docs/BITRIX_APP_INSTALL.md Detailed Bitrix24 REST app installation

License

MIT

About

Bidirectional YCLIENTS ↔ Bitrix24 integration: real-time event sync + booking widget. FastAPI, PostgreSQL, Docker. Built for a 5-branch beauty salon chain.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages