Claude AI Integration
Relevant source files
The following files were used as context for generating this wiki page:Introduction
The Telegram Notification Service is a standalone, background service designed to monitor the Point of Sale (POS) system's inventory database (pos_inventory.db). It operates independently of the main pos_app.py GUI application and provides automated alerts and reports via a configured Telegram bot. The service's primary functions are to send real-time notifications for products that have run out of stock and to deliver a daily sales summary report.
This service is designed to be run continuously on a machine with access to the POS database and an internet connection. It uses its own state-tracking database (notification_state.db) to prevent sending duplicate alerts and to manage the daily report schedule. The entire service is contained within notification_service.py and is configured via a config.json file.
Sources: notification_service.py, README_Notifications.txt
Architecture
The service is a multi-threaded Python application that runs as a console process. It is composed of several key classes that handle specific responsibilities: database reading, state tracking, and sending Telegram messages. The service runs independently of the main POS application, interacting with the shared pos_inventory.db in a read-only capacity.
The following diagram illustrates the high-level architecture and data flow between the service, the POS application, and external systems.
This diagram shows that the Notification Service reads data from the main POS database, manages its own state in a separate database, and sends notifications through the Telegram API.
Sources: notification_service.py, pos_app.py, README_Notifications.txt
Core Components
The service is built around four main classes, each with a distinct role.
Sources: notification_service.py
NotificationService Class
This is the main orchestrator class that initializes and manages the entire service.
- Responsibilities:
- Loads configuration from
config.json. - Sets up a robust logging system with file rotation.
- Initializes and starts the worker threads for monitoring and reporting.
- Handles graceful shutdown signals (SIGINT, SIGTERM) to ensure clean termination.
- Loads configuration from
- Key Threads:
zero_stock_monitor: Polls the database for out-of-stock products.daily_report_scheduler: Triggers the daily sales report at a configured time.health_monitor: Performs periodic health checks.
Sources: notification_service.py:440-578
POSDatabaseReader Class
This class provides read-only access to the main pos_inventory.db database. It is designed to avoid locking issues with the primary GUI application by using a connection timeout.
- Key Methods:
get_zero_stock_products(): Retrieves all products wherequantity = 0.get_all_products(): Fetches all products, used for cleaning up the notification state.get_top_selling_products(date, limit, metric): Gathers top-selling products for a given date, ordered by quantity or revenue.get_total_sales(date): Calculates summary sales statistics for a given date.
Sources: notification_service.py:202-337
StateTracker Class
This component is crucial for preventing alert spam. It manages a separate SQLite database (notification_state.db) to keep track of which notifications have already been sent.
- Responsibilities:
- Initializes the
notification_state.dbwith the required schema. is_notified(product_id): Checks if an out-of-stock alert has already been sent for a product.mark_notified(product): Records that an alert has been sent.cleanup_restocked_products(all_products): Removes products from the notified list if they are back in stock.report_sent_today(): Checks if the daily report has already been sent for the current day.log_daily_report(...): Records the successful sending of a daily report.
- Initializes the
Sources: notification_service.py:25-156
TelegramNotifier Class
This class acts as a wrapper for the Telegram Bot API, handling all outgoing communications.
- Responsibilities:
- Constructs and sends HTTP POST requests to the Telegram API.
- Implements a retry mechanism with exponential backoff for network resilience.
- Formats messages using templates defined in
config.json.
- Key Methods:
send_message(text): The core method for sending any text message.send_out_of_stock_alert(product): Formats and sends the zero-stock alert.send_daily_report(date, top_products, total_sales): Formats and sends the daily sales report.
Sources: notification_service.py:340-437, test_telegram.py:30-79
Service Logic and Flows
Zero-Stock Monitoring
The service continuously monitors for products that have run out of stock. The polling interval is defined by zero_stock_interval_seconds in the configuration.
The following sequence diagram illustrates the zero-stock alert process.
Daily Report Generation
The service generates a sales report for the previous day and sends it at a specific time, defined by send_time and timezone in the configuration.
The following sequence diagram shows the daily report generation flow.
State Management Database
The service relies on notification_state.db to maintain its operational state. This database is created and managed automatically.
The schema for notification_state.db is shown below.
notified_products: Stores products that have triggered a zero-stock alert. This prevents sending repeated notifications for the same item. Products are removed from this table if they are restocked.daily_report_log: Logs each time a daily report is successfully sent, ensuring it only runs once per day.service_state: A key-value table for storing miscellaneous service metadata.
Sources: notification_service.py:31-72
Configuration
The service is configured via config.json, which must be in the same directory as the executable. An example is provided in config.example.json.
| Section | Key | Type | Description | Example Value |
|---|---|---|---|---|
telegram | bot_token | String | The API token for the Telegram bot, obtained from @BotFather. | "123...xyz-EXAMPLE" |
telegram | chat_id | String | The unique identifier for the target chat where notifications will be sent. | "123456789" |
polling | zero_stock_interval_seconds | Integer | How often (in seconds) the service checks for out-of-stock products. | 300 (5 minutes) |
polling | health_check_interval_seconds | Integer | How often (in seconds) the service logs a health check message. | 60 (1 minute) |
daily_report | send_time | String | The time of day (24-hour format) to send the daily report. | "08:00" |
daily_report | timezone | String | The IANA timezone for scheduling the daily report. | "America/Mexico_City" |
daily_report | top_products_count | Integer | The number of top-selling products to include in the daily report. | 10 |
daily_report | metric | String | The metric to determine top products ("quantity" or "revenue"). | "quantity" |
database | pos_db_path | String | The file path to the main POS inventory database. | "pos_inventory.db" |
database | state_db_path | String | The file path for the service's state-tracking database. | "notification_state.db" |
notifications | out_of_stock | Object | Contains settings for the zero-stock alert, including the message template. | { "enabled": true, ... } |
notifications | daily_report | Object | Contains settings for the daily report, including the message template. | { "enabled": true, ... } |
Sources: config.example.json, notification_service.py:448-458
Message Templates
The config.json file allows for customizable notification messages using placeholders.
Out-of-Stock Alert Template:
"message_template": "⚠️ ALERTA: Producto agotado\n\n📦 Producto: {name}\n🔑 Clave: {barcode}\n🏷️ Categoría: {category}\n🏢 Marca: {brand}\n\n⏰ {timestamp}"
Daily Report Template:
"message_template": "📊 REPORTE DIARIO - {date}\n\n🏆 Top {count} Productos Más Vendidos:\n\n{products}\n\n💰 Ventas totales: ${total:.2f}\n📦 Productos únicos vendidos: {unique_count}"
Sources: config.example.json:28-35
Setup and Deployment
The service can be run directly from the Python source or as a compiled executable.
Dependencies
The service requires the following Python packages:
requests: For making HTTP calls to the Telegram API.pytz: For handling timezones for the daily report scheduler.
These can be installed using the provided requirements.txt file.
Sources: requirements.txt:5-6, install_dependencies.bat:20-21
Build Process
A build_notification_exe.bat script is provided to package the service into a single .exe file using PyInstaller. This allows the service to be deployed on a Windows machine without a Python installation.
- Command:
pyinstaller --onefile --console --name="TelegramNotifications" ... notification_service.py - The
--consoleflag is used because this is a background service that runs in a terminal window. - The output executable is
dist\TelegramNotifications.exe.
Sources: build_notification_exe.bat
Deployment
To deploy the service, the following files must be placed in the same directory:
TelegramNotifications.exe(the compiled service)config.json(with valid Telegram credentials)pos_inventory.db(the POS database to monitor)
When the executable is run, it will automatically create the logs/ directory and the notification_state.db file. A test_telegram.py script is also available to verify the bot token and chat ID in config.json before running the service.
Sources: README_Notifications.txt:10-15, 70-75, build_notification_exe.bat:38-46, test_telegram.py