A production-ready Telegram bot for selling physical goods with comprehensive inventory management, Bitcoin/cash payments, referral system, and advanced order tracking capabilities.
π¦ This version is for PHYSICAL GOODS (inventory, shipping, delivery addresses, etc.)
πΎ Need to sell DIGITAL GOODS instead? (accounts, keys, licenses, etc.) π Use this version: Telegram Digital Goods Shop
The digital goods version features instant delivery, ItemValues storage, and automatic content distribution without inventory management.
- Overview
- Key Features
- Architecture
- Requirements
- Environment Variables
- Installation
- Bot CLI Commands
- Order Lifecycle
- Background Tasks
- Database Schema
- Security Features
- Monitoring & Logging
- Testing
- License
- Contributing
- Acknowledgments
- Support
- Additional Documentation
This bot is specifically designed for physical goods (not digital products) with:
- Inventory management with stock tracking and reservation system
- Dual payment methods: Bitcoin (address pool) and Cash on Delivery
- Shopping cart with checkout flow
- Reference codes for controlled user registration
- Referral bonuses for customer acquisition
- Order tracking with delivery time management
- CLI tool for comprehensive shop administration
This is NOT a typical digital goods Telegram shop. Key differences:
- β Physical inventory with stock levels
- β Reservation system with timeouts
- β Delivery address & phone collection
- β Dual payment methods (Bitcoin + Cash on Delivery)
- β Reference code requirement for registration
- β Multi-stage order lifecycle (pending β reserved β confirmed β delivered)
- β Admin CLI for order & inventory management
- Categories & Products: Organize items by categories
- Stock Tracking: Real-time inventory with
stock_quantityandreserved_quantity - Reservation System: Items reserved for 24 hours (configurable) during checkout
- Shopping Cart: Add multiple items before checkout
- Lazy Loading: Efficient pagination for large catalogs
Two Payment Methods:
- Address Pool: Load Bitcoin addresses from
btc_addresses.txt - One-Time Use: Each address used only once per order
- Auto-Reload: File watcher automatically loads new addresses when file changes
- Usage Tracking: Complete address usage audit trail in database
- Critical: Must add addresses to
btc_addresses.txtbefore accepting Bitcoin orders
- Manual Confirmation: Admin confirms cash receipt via CLI
- No Prepayment: Customer pays upon delivery
- Flexible: No cryptocurrency wallet required
- Reference Code Required: Users must enter valid code on first
/start - User Types: Regular users and admins (with different code creation privileges)
- User Banning: Ban/unban users via admin panel or CLI with optional reason tracking
- Referral System: Track who referred whom with configurable bonus percentage
- Bonus Balance: Accumulated referral bonuses can be applied to orders
- Customer Profiles: Saved delivery address, phone, order history
- Order Codes: 6-character unique codes (e.g., ECBDJI) for easy reference
- Order Status:
pendingβreservedβconfirmedβdeliveredβcancelled/expired - Delivery Information: Address, phone number, optional delivery note
- Delivery Time: Admin-set planned delivery time
- Reservation Timeout: Configurable timeout (default 24h) with automatic cleanup
- Order Modifications: Add/remove items, update delivery time via CLI
- Role-Based Access: USER, ADMIN, OWNER roles with granular permissions
- CLI Tool (
bot_cli.py): Comprehensive command-line interface for shop management - Statistics: Real-time shop statistics and analytics
- Broadcast: Send messages to all users or specific groups
- Export: CSV export for customers, orders, reference codes
- Web Dashboard: Real-time metrics at
http://localhost:9090/dashboard - Health Checks: System status monitoring
- Structured Logging: Separate logs for orders, reference codes, customer changes
- Timezone Support: Configurable timezone for all logs
- Inventory Audit: Complete audit trail of all inventory changes
- Rate Limiting: Configurable limits per action
- Security Middleware: SQL injection, XSS, CSRF protection
- Cryptographic Codes: Secure reference code generation
- Bot Detection: Automatic blocking of bot accounts
- Transaction Safety: Row-level locking prevents overselling
Project Structure Schema (click to expand)
telegram_shop/
βββ run.py # Entry point
βββ bot_cli.py # CLI admin tool
βββ btc_addresses.txt # Bitcoin address pool
βββ requirements.txt # Python dependencies
βββ Dockerfile # Docker image definition
βββ docker-compose.yml # Multi-container setup
βββ .env.example # Environment template
β
βββ bot/
β βββ __init__.py
β βββ main.py # Bot initialization & startup
β βββ logger_mesh.py # Logging configuration
β β
β βββ config/ # Configuration management
β β βββ env.py # Environment variables
β β βββ storage.py # Redis/Memory storage
β β βββ timezone.py # Timezone handling
β β
β βββ database/ # Database layer
β β βββ main.py # Database engine & session
β β βββ dsn.py # Connection string builder
β β βββ models/ # SQLAlchemy models
β β β βββ main.py # All model definitions
β β βββ methods/ # Database operations
β β βββ create.py # INSERT operations
β β βββ read.py # SELECT operations
β β βββ update.py # UPDATE operations
β β βββ delete.py # DELETE operations
β β βββ inventory.py # Inventory management
β β βββ cache_utils.py # Cache invalidation
β β βββ lazy_queries.py # Pagination queries
β β
β βββ handlers/ # Request handlers
β β βββ main.py # Handler registration
β β βββ other.py # Misc handlers
β β βββ user/ # User-facing handlers
β β β βββ main.py # /start, /help
β β β βββ shop_and_goods.py # Browse catalog
β β β βββ cart_handler.py # Shopping cart
β β β βββ order_handler.py # Checkout & orders
β β β βββ orders_view_handler.py # Order history
β β β βββ reference_code_handler.py # Code entry
β β β βββ referral_system.py # Referral bonuses
β β βββ admin/ # Admin-only handlers
β β βββ main.py # Admin menu
β β βββ broadcast.py # Mass messaging
β β βββ shop_management_states.py # Shop stats
β β βββ goods_management_states.py # Product CRUD
β β βββ categories_management_states.py # Category CRUD
β β βββ adding_position_states.py # Add products
β β βββ update_position_states.py # Edit products
β β βββ user_management_states.py # User admin
β β βββ reference_code_management.py # Code admin
β β βββ settings_management.py # Bot settings
β β
β βββ states/ # FSM states
β β βββ user_state.py # User flow states
β β βββ shop_state.py # Shopping states
β β βββ payment_state.py # Payment flow
β β βββ goods_state.py # Product management
β β βββ category_state.py # Category management
β β βββ broadcast_state.py # Broadcast states
β β
β βββ keyboards/ # Inline keyboards
β β βββ inline.py # Keyboard builders
β β
β βββ middleware/ # Request middleware
β β βββ security.py # CSRF, injection detection
β β βββ rate_limit.py # Rate limiting
β β
β βββ filters/ # Custom filters
β β βββ main.py # Role filters, etc.
β β
β βββ i18n/ # Internationalization
β β βββ main.py # Locale manager
β β βββ strings.py # Translations
β β
β βββ payments/ # Payment processing
β β βββ bitcoin.py # BTC address management
β β βββ notifications.py # Payment notifications
β β
β βββ referrals/ # Referral system
β β βββ codes.py # Code generation & validation
β β
β βββ tasks/ # Background tasks
β β βββ reservation_cleaner.py # Expire old reservations
β β βββ file_watcher.py # Watch btc_addresses.txt
β β
β βββ caching/ # Caching layer
β β βββ cache.py # CacheManager & decorators
β β βββ scheduler.py # Cache maintenance scheduler
β β βββ stats_cache.py # Statistics caching
β β
β βββ monitoring/ # Observability
β β βββ metrics.py # MetricsCollector
β β βββ dashboard.py # Web dashboard
β β βββ recovery.py # Error recovery
β β
β βββ communication/ # User communication
β β βββ broadcast_system.py # Mass messaging
β β
β βββ export/ # Data export
β βββ customer_csv.py # Customer data export
β βββ custom_logging.py # Structured logging
β
βββ logs/ # Log files
β βββ bot.log # Main log
β βββ audit.log # Security events
β βββ orders.log # Order lifecycle
β βββ reference_code.log # Code operations
β βββ changes.log # Customer changes
β
βββ data/ # Runtime data
βββ final_metrics.json # Shutdown metrics
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Telegram Bot API β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Aiogram Bot (main.py) β
β ββββββββββββββββββ¬βββββββββββββββ¬βββββββββββββββββββββββββ β
β β Handlers β Middleware β Background Tasks β β
β β (user/admin) β (security/ β (reservation cleanup, β β
β β β rate limit) β file watcher) β β
β ββββββββββββββββββ΄βββββββββββββββ΄βββββββββββββββββββββββββ β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββΌβββββββββββββββ¬βββββββββββββββ
βΌ βΌ βΌ βΌ
ββββββββββββββββ ββββββββββββ βββββββββββββ ββββββββββββββββ
β PostgreSQL β β Redis β β Bot CLI β β Monitoring β
β Database β β Cache β β (bot_cli. β β Server β
β (inventory, β β & FSM β β py) β β (port 9090) β
β orders, β β Storage β βββββββββββββ ββββββββββββββββ
β users, etc.)β ββββββββββββ
ββββββββββββββββ
Core Models:
User: Telegram users with role and referral trackingRole: Permission-based access control (USER/ADMIN/OWNER)Goods: Products withstock_quantity,reserved_quantity,priceCategories: Product categoriesShoppingCart: User cart items
Order System:
Order: Orders with status, delivery info, payment method, reservation timeoutOrderItem: Individual items in orders with quantityCustomerInfo: Customer delivery preferences, spending history, bonus balance
Inventory System:
InventoryLog: Complete audit trail of all inventory changes
Reference Code System:
ReferenceCode: Reference codes with expiry, usage limits, notesReferenceCodeUsage: Tracking who used which code
Payment System:
BitcoinAddress: Pool of Bitcoin addresses with usage tracking
Referral System:
ReferralEarnings: Referral bonus transactions
Configuration:
BotSettings: Dynamic bot settings (timezone, bonus percentage, etc.)
- Python 3.11+
- PostgreSQL 16+
- Redis 7+
- Docker & Docker Compose (recommended)
The application requires the following environment variables:
π€ Telegram
| Variable | Description | Required |
|---|---|---|
TOKEN |
Bot Token from @BotFather | β |
OWNER_ID |
Your Telegram ID | β |
π³ Payments
| Variable | Description | Default |
|---|---|---|
PAY_CURRENCY |
Display currency (RUB, USD, EUR, etc.) | RUB |
MIN_AMOUNT |
Minimum payment amount | 20 |
MAX_AMOUNT |
Maximum payment amount | 10000 |
π Links / UI
| Variable | Description | Default |
|---|---|---|
CHANNEL_URL |
News channel link (public channels only) | - |
HELPER_ID |
Support user Telegram ID | - |
RULES |
Bot usage rules text | - |
π Locale & Logs
| Variable | Description | Default |
|---|---|---|
BOT_LOCALE |
Localization language (ru/en) | ru |
LOG_TO_STDOUT |
Console logging (1/0) | 1 |
LOG_TO_FILE |
File logging (1/0) | 1 |
DEBUG |
Debug mode (1/0) | 0 |
π Monitoring
| Variable | Description | Default |
|---|---|---|
MONITORING_HOST |
Monitoring server bind address | localhost |
MONITORING_PORT |
Monitoring server port | 9090 |
Note: When running in Docker, set MONITORING_HOST=0.0.0.0 to allow external access.
π¦ Redis Storage
| Variable | Description | Default |
|---|---|---|
REDIS_HOST |
Redis server address | redis |
REDIS_PORT |
Redis server port | 6379 |
REDIS_DB |
Redis database number | 0 |
REDIS_PASSWORD |
Redis password (if enabled) | - |
ποΈ Database (Docker)
| Variable | Description | Default |
|---|---|---|
POSTGRES_DB |
PostgreSQL database name | Required |
POSTGRES_USER |
PostgreSQL username | postgres |
POSTGRES_PASSWORD |
PostgreSQL password | Required |
DB_PORT |
PostgreSQL port | 5432 |
DB_DRIVER |
Database driver | postgresql+psycopg2 |
ποΈ Database (Manual Deploy)
For manual deployment, configure DATABASE_URL in bot/config/env.py:
DATABASE_URL = "postgresql+psycopg2://user:password@localhost:5432/db_name"-
Clone the repository
git clone https://github.com/yourusername/telegram_shop.git cd telegram_shop -
Configure environment
cp .env.example .env nano .env # Edit with your values -
Add Bitcoin addresses (Required ONLY if accepting Bitcoin payments)
nano btc_addresses.txt # Add your Bitcoin addresses, one per line: # bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh # bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4 # Note: Skip this step if using cash on delivery only
-
Start services
docker compose up -d --build bot
-
View logs
docker compose logs -f bot
-
Clone repository
git clone https://github.com/yourusername/telegram_shop.git cd telegram_shop -
Create virtual environment
python3.11 -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install --upgrade pip pip install -r requirements.txt
-
Set up PostgreSQL
createdb telegram_shop createuser shop_user -P
-
Configure environment
- Set environment variables in PyCharm
- Or export them in terminal:
export TOKEN="your_bot_token" export OWNER_ID="your_telegram_id" # Set other required variables from .env.example
-
Add Bitcoin addresses (optional - only if accepting Bitcoin)
nano btc_addresses.txt # Add addresses as shown above # Skip if using cash on delivery only
-
Run the bot
python run.py
These can be changed at runtime via CLI:
# Enable/disable reference codes
python bot_cli.py settings set reference_codes_enabled true
# Set referral bonus percentage (0-100)
python bot_cli.py settings set reference_bonus_percent 5
# Set timezone for logs
python bot_cli.py settings set timezone "America/New_York"
# Set order timeout (hours)
python bot_cli.py settings set cash_order_timeout_hours 24
# Set help auto-response
python bot_cli.py settings set help_auto_message "We'll respond within 24 hours"The bot_cli.py script provides comprehensive shop management while the bot is running.
# 1. User places order β order is 'pending', inventory reserved
# 2. Confirm order with delivery time
python bot_cli.py order --order-code ABCDEF --status-confirmed --delivery-time "2025-11-20 14:30"
# 3. Mark as delivered (deducts inventory from stock)
python bot_cli.py order --order-code ABCDEF --status-delivered# Cancel order (releases reserved inventory, refunds bonus if applied)
python bot_cli.py order --order-code ABCDEF --cancel# Add item to order
python bot_cli.py order --order-code ABCDEF --add-item "Product Name" --quantity 2 --notify
# Remove item from order
python bot_cli.py order --order-code ABCDEF --remove-item "Product Name" --quantity 1 --notify
# Update delivery time
python bot_cli.py order --order-code ABCDEF --update-delivery-time --delivery-time "2025-11-21 16:00" --notify# Set inventory to specific value
python bot_cli.py inventory "Product Name" --set 100
# Add to current inventory
python bot_cli.py inventory "Product Name" --add 50
# Remove from inventory
python bot_cli.py inventory "Product Name" --remove 25# Create admin reference code
python bot_cli.py refcode create --expires-hours 48 --max-uses 10 --note "VIP customers"
# Create unlimited code (no expiry, unlimited uses)
python bot_cli.py refcode create --expires-hours 0 --max-uses 0 --note "Permanent invite"
# Disable code
python bot_cli.py refcode disable CODE123 --reason "No longer valid"
# List all codes
python bot_cli.py refcode list
# List only active codes
python bot_cli.py refcode list --active-only# Add single address
python bot_cli.py btc add --address bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh
# Add addresses from file
python bot_cli.py btc add --file new_addresses.txt
# Check address pool status
python bot_cli.py btc list
# Show all addresses with details
python bot_cli.py btc list --show-all
# Sync addresses (cleanup)
python bot_cli.py btc sync# Export all data
python bot_cli.py export --all --output-dir backups/
# Export only customers
python bot_cli.py export --customers --output-dir backups/
# Export only reference codes
python bot_cli.py export --refcodes --output-dir backups/
# Export only orders
python bot_cli.py export --orders --output-dir backups/# Set a setting
python bot_cli.py settings set reference_codes_enabled true
python bot_cli.py settings set reference_bonus_percent 5
python bot_cli.py settings set timezone "UTC"
# Get a setting value
python bot_cli.py settings get reference_codes_enabled
# List all settings
python bot_cli.py settings list# Ban a user
python bot_cli.py ban 123456789 --reason "Violating terms of service" --notify
# Ban a user without notification
python bot_cli.py ban 123456789 --reason "Spam"
# Unban a user
python bot_cli.py unban 123456789 --notify
# Unban a user without notification
python bot_cli.py unban 1234567891. User browses shop
β
2. User adds items to cart
β
3. User clicks "Proceed to Checkout"
β
4. System asks for delivery info:
- Delivery address
- Phone number
- Delivery note (optional)
β
5. System asks about applying referral bonus (if available)
β
6. User selects payment method:
- Bitcoin: System assigns address from pool, user receives payment instructions
- Cash on Delivery: Order proceeds directly to confirmation
β
7. Order created with status: pending β reserved
- Inventory RESERVED for 24 hours (configurable)
- reserved_until timestamp set
β
8. Admin receives order notification
β
9. Customer pays (Bitcoin) or prepares cash (COD)
β
10. Admin confirms order via CLI:
python bot_cli.py order --order-code XXXXX --status-confirmed --delivery-time "YYYY-MM-DD HH:MM"
- Order status: reserved β confirmed
- Delivery time set
- Customer notified
- For Bitcoin: After payment is verified
- For COD: After reviewing order details
β
11. Admin delivers order and marks as delivered via CLI:
python bot_cli.py order --order-code XXXXX --status-delivered
- Order status: confirmed β delivered
- Inventory DEDUCTED from stock (actual reduction)
- reserved_quantity reduced
- stock_quantity reduced
- Customer spending updated
- Referral bonus credited (if applicable)
- Customer notified
- For COD: Cash collected at this point
pending: Order just created, waiting for reservationreserved: Inventory reserved, waiting for payment/confirmationconfirmed: Payment confirmed, delivery time set, awaiting deliverydelivered: Order completed, inventory deducted, customer updatedcancelled: Manually cancelled by admin, inventory releasedexpired: Reservation timeout exceeded, inventory automatically released
stock_quantity: 100
reserved_quantity: 0 β 5
available_quantity: 100 β 95
stock_quantity: 100 β 95
reserved_quantity: 5 β 0
available_quantity: 95 (unchanged)
stock_quantity: 100 (unchanged)
reserved_quantity: 5 β 0
available_quantity: 95 β 100
File: bot/tasks/reservation_cleaner.py
Runs every 60 seconds to:
- Find orders with
order_status='reserved'andreserved_until < now() - Release reserved inventory back to available stock
- Mark orders as
expired - Refund referral bonus if applied
- Notify customers about expired orders
- Log all actions to
inventory_log
File: bot/tasks/file_watcher.py
Monitors btc_addresses.txt for changes:
- Watches file for modifications
- Debounces rapid changes (2-second default)
- Automatically loads new addresses into database
- Logs all operations
- Thread-safe with locking
The bot implements a layered middleware architecture for security, performance, and observability:
Request Flow:
User β Telegram API β aiogram Dispatcher
β
AnalyticsMiddleware (tracks all events)
β
AuthenticationMiddleware (verifies user identity, caches roles)
β
SecurityMiddleware (CSRF protection, suspicious pattern detection)
β
RateLimitMiddleware (prevents spam, configurable limits)
β
Handler (business logic)
Middleware Details:
-
AnalyticsMiddleware (
bot/monitoring/metrics.py)- Tracks every event (messages, callbacks)
- Measures handler execution time
- Records errors and conversion funnels
- Sends metrics to Prometheus
-
AuthenticationMiddleware (
bot/middleware/security.py)- Verifies user identity
- Caches user roles (5-minute TTL)
- Blocks bot accounts automatically
- Prevents unauthorized admin access
-
SecurityMiddleware (
bot/middleware/security.py)- Generates CSRF tokens for critical actions
- Detects SQL injection, XSS, command injection patterns
- Validates callback data age (1-hour max)
- Logs all security events to audit log
-
RateLimitMiddleware (
bot/middleware/rate_limit.py)- Global limit: 30 requests/60 seconds (configurable)
- Action-specific limits:
- Broadcast: 1/hour
- Shop views: 60/minute
- Purchases: 5/minute
- Temporary bans: 5 minutes after limit exceeded
- Admin bypass support
Access at http://localhost:9090/dashboard (or your configured host/port):
- Real-time metrics
- Event tracking
- Performance analysis
- Error tracking
- System health
MetricsCollector (bot/monitoring/metrics.py) tracks:
1. Events:
- Order lifecycle: created, reserved, confirmed, delivered, cancelled, expired
- Cart operations: add, remove, view, clear, checkout
- Payment events: initiated, bonus applied, completed
- Referral actions: code created/used, bonus paid
- Inventory changes: reserved, released, deducted
- Security alerts: suspicious patterns, rate limits, unauthorized access
2. Timings:
- Handler execution duration
- Database query latency
- Cache operation speed
- External API calls
3. Errors:
- Error type categorization
- Error frequency tracking
- Stack trace logging
4. Conversions:
# Customer journey funnel
shop β category β item β cart β checkout β payment β order
# Referral funnel
code_created β code_used β bonus_paidLog Levels:
DEBUG: Development debugging (disabled in production)INFO: Normal operations, startup/shutdownWARNING: Recoverable issues, rate limitsERROR: Errors that need attentionCRITICAL: System failures
Specialized Logs:
-
bot.log - Main application log
- Bot startup/shutdown
- Handler execution
- Database operations
- Background tasks
-
audit.log - Security events
- Critical action attempts
- Failed authorization
- Suspicious patterns
- Rate limit violations
-
orders.log - Order operations
- Order creation
- Status changes
- Delivery updates
- Completions/cancellations
-
reference_code.log - Code lifecycle
- Code generation
- Code usage
- Code deactivation
-
changes.log - Customer data modifications
- Profile updates
- Spending changes
- Bonus adjustments
Log Format:
[2025-11-19 14:30:45] [INFO] [bot.main:239] Starting bot: @shopbot (ID: 123456789)
[2025-11-19 14:30:46] [INFO] [bot.tasks.reservation_cleaner:14] Reservation cleaner started
Automatic CSV generation in logs/:
customer_list.csv: Customer database with all details- Updated in real-time as customer data changes
Metrics available at http://localhost:9090/metrics/prometheus for Grafana integration.
System health at http://localhost:9090/health for uptime monitoring.
Comprehensive test suite for the Telegram Physical Goods Shop Bot.
This test suite provides comprehensive coverage for all major components of the bot:
- Database models and relationships
- CRUD operations
- Inventory management system
- Order lifecycle
- Shopping cart
- Referral system
- Reference code system
- Bitcoin payment system
- Validators and utilities
tests/
βββ conftest.py # Shared fixtures and pytest configuration
βββ unit/ # Unit tests
β βββ database/ # Database-related tests
β β βββ test_models.py # Model tests
β β βββ test_crud.py # CRUD operation tests
β β βββ test_inventory.py # Inventory management tests
β β βββ test_cart.py # Shopping cart tests
β βββ utils/ # Utility tests
β β βββ test_validators.py # Validator tests
β β βββ test_order_codes.py # Order code generation tests
β βββ payments/ # Payment system tests
β β βββ test_bitcoin.py # Bitcoin address tests
β βββ referrals/ # Referral system tests
β βββ test_reference_codes.py # Reference code tests
βββ integration/ # Integration tests
βββ test_order_lifecycle.py # Complete order flow tests
pytestpytest --cov=bot --cov-report=html --cov-report=term-missingCoverage report will be generated in htmlcov/ directory.
Run only unit tests:
pytest -m unitRun only integration tests:
pytest -m integrationRun only database tests:
pytest -m databaseRun only model tests:
pytest -m models# Run model tests
pytest tests/unit/database/test_models.py
# Run CRUD tests
pytest tests/unit/database/test_crud.py
# Run inventory tests
pytest tests/unit/database/test_inventory.py
# Run order lifecycle tests
pytest tests/integration/test_order_lifecycle.py# Run specific test class
pytest tests/unit/database/test_models.py::TestRoleModel
# Run specific test function
pytest tests/unit/database/test_models.py::TestRoleModel::test_create_rolepytest -vpytest -spytest -xpytest --lfTests are organized with markers for easy filtering:
unit- Unit testsintegration- Integration testsdatabase- Tests requiring databaseslow- Slow running testsmodels- Database model testscrud- CRUD operation testsinventory- Inventory management testsorders- Order management testscart- Shopping cart testsreferrals- Referral system testsbitcoin- Bitcoin payment testsvalidators- Validator tests
db_engine- Test database engine (in-memory SQLite)db_session- Test database sessiondb_with_roles- Database session with roles initialized
test_user- Sample usertest_admin- Sample admin usertest_category- Sample categorytest_goods- Sample goods with stocktest_goods_low_stock- Sample goods with low stocktest_order- Sample order with itemstest_customer_info- Sample customer informationtest_bitcoin_address- Sample Bitcoin addresstest_reference_code- Sample reference codetest_shopping_cart- Sample cart itemtest_bot_settings- Sample bot settings
populated_database- Database with all test datamultiple_products- List of multiple productsmultiple_categories- List of multiple categories
-
Database Models (100%)
- All model creation and validation
- Relationships between models
- Property calculations (e.g., available_quantity)
- Permission system
-
CRUD Operations (95%)
- Create operations for all models
- Read operations with caching
- Update operations with validation
- Proper error handling
-
Inventory Management (100%)
- Reservation system
- Release mechanism
- Deduction on order completion
- Stock tracking and logging
- Concurrent access handling
-
Order System (100%)
- Order creation
- Status transitions
- Order cancellation
- Multi-item orders
- Order code generation
-
Shopping Cart (100%)
- Adding items
- Quantity updates
- Stock validation
- Total calculation
-
Referral System (100%)
- Reference code generation
- Code validation
- Usage tracking
- Expiration handling
- Usage limits
-
Bitcoin System (95%)
- Address loading
- Address assignment
- Usage tracking
- File synchronization
-
Validators (100%)
- Input validation
- Data sanitization
- Error handling
This project is licensed under the MIT License - see the LICENSE file for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Aiogram - Telegram Bot framework
- SQLAlchemy - Database ORM
- Redis - Cache and FSM storage
- PostgreSQL - Database
- Watchdog - File system monitoring
- Issues: Report bugs via GitHub Issues
- Logs: Check
logs/directory for detailed error information
.env.example- Environment variable referencebot_cli.py --help- CLI usage help