Notification Service Internals (notification_service.py)
Relevant source files
The following files were used as context for generating this wiki page:The Notification Service is a standalone Python application that runs in the background to monitor the Point of Sale (POS) system's database. Its primary purpose is to provide automated, real-time alerts and daily summaries via Telegram. The service is designed to be decoupled from the main pos_app.py GUI application, allowing for continuous monitoring as long as the service is running.
The service performs two main functions:
- Zero-Stock Alerts: It periodically polls the inventory database and sends a Telegram message when a product's quantity reaches zero.
- Daily Sales Reports: It sends a scheduled daily summary of the previous day's sales, including top-selling products and total revenue.
The entire service is configurable through a config.json file and maintains its own state to prevent duplicate notifications.
Sources: notification_service.py:7-13, README_Notifications.txt:4-15, config.example.json
Architecture
The service is built with a multi-threaded architecture, orchestrated by the main NotificationService class. It comprises four key classes that handle distinct responsibilities: configuration, database access, state management, and communication.
Sources: notification_service.py:532-536
The following diagram illustrates the high-level class structure and their relationships.
Service Startup Flow
The service is initiated by running python notification_service.py or an equivalent batch script. The startup process involves loading configuration, setting up logging, initializing components, and launching the background monitoring threads.
Core Components
NotificationService (Orchestrator)
This is the main class that coordinates all activities. It is responsible for:
- Loading settings from
config.json. - Configuring a robust logging system with rotating file handlers for general and error logs.
- Initializing the
POSDatabaseReader,StateTracker, andTelegramNotifiercomponents. - Spawning and managing three background threads for the core monitoring tasks.
- Handling graceful shutdown on
SIGINT(Ctrl+C) orSIGTERMsignals.
Sources: notification_service.py:501-611
POSDatabaseReader (Data Access)
This class provides read-only access to the main POS database (pos_inventory.db). It is designed to prevent locking issues with the main GUI application by using a connection timeout.
Key methods include:
get_zero_stock_products(): Fetches all products wherequantity = 0.get_all_products(): Retrieves all product IDs and quantities, used to detect restocked items.get_top_selling_products(): Calculates the top N selling products for a given date based on quantity or revenue.get_total_sales(): Aggregates total sales, transaction count, and unique products sold for a given date.
Sources: notification_service.py:214-338, pos_app.py:28-48
StateTracker (State Management)
To avoid sending redundant notifications, this class manages the service's state in a separate SQLite database, notification_state.db.
Its responsibilities include:
- Tracking which products have already had a zero-stock alert sent.
- Logging which days a daily report has been sent for.
- Cleaning up the notification list when a product is restocked.
The state database schema is defined as follows:
Sources: notification_service.py:21-192
TelegramNotifier (Communication)
This class encapsulates all communication with the Telegram Bot API. It uses a bot_token and chat_id from the configuration.
Key features:
- Retry Logic: The
send_messagemethod includes a retry mechanism with exponential backoff to handle transient network errors. - Message Templating: It uses format strings defined in
config.jsonto construct messages for out-of-stock alerts and daily reports, ensuring consistent formatting.
Sources: notification_service.py:341-499, config.example.json:30-38, test_telegram.py:46-70
Key Workflows
Zero-Stock Monitoring
This workflow runs in a continuous loop, polling the database at an interval defined by zero_stock_interval_seconds.
The sequence of operations is as follows:
Sources: notification_service.py:560-583
Daily Report Generation
This workflow runs on a scheduler, checking every 30 seconds if the current time matches the configured send_time.
The sequence for sending the report is:
Sources: notification_service.py:585-609
Configuration
The service is configured via config.json. An example with default values is provided in config.example.json.
| Section | Key | Description | Default Value |
|---|---|---|---|
telegram | bot_token | The API token for the Telegram bot from @BotFather. | "123...-EXAMPLE" |
chat_id | The numeric ID of the user or group to send notifications to. | "123456789" | |
polling | zero_stock_interval_seconds | How often (in seconds) to check for zero-stock products. | 300 |
health_check_interval_seconds | How often to log a health check message. | 60 | |
daily_report | send_time | The time of day (HH:MM) to send the daily report. | "08:00" |
timezone | The timezone for the report scheduler (e.g., "America/Mexico_City"). | "America/Mexico_City" | |
top_products_count | The number of top-selling products to include in the report. | 10 | |
metric | The metric for ranking top products ('quantity' or 'revenue'). | "quantity" | |
database | pos_db_path | Path to the main POS inventory database. | "pos_inventory.db" |
state_db_path | Path to the service's state database. | "notification_state.db" | |
logging | log_level | The minimum level for console logs (e.g., INFO, DEBUG). | "INFO" |
log_file | Path for the main rotating log file. | "logs/notification_service.log" | |
error_log_file | Path for the error-only rotating log file. | "logs/notification_errors.log" | |
notifications | out_of_stock | Contains settings for zero-stock alerts, including enabled and message_template. | (see file) |
daily_report | Contains settings for daily reports, including enabled and message_template. | (see file) |
Sources: config.example.json, notification_service.py:509-518
Database Schemas
The service interacts with two separate SQLite databases.
POS Database (pos_inventory.db)
This is the primary database for the POS application, containing product inventory and sales history. The notification service accesses it in a read-only manner.
Sources: pos_app.py:28-86
State Database (notification_state.db)
This database is exclusive to the notification service and is used to track sent notifications to prevent duplicates.
Sources: notification_service.py:33-61
Deployment and Execution
The service can be run directly from the source using Python or as a pre-compiled executable.
- From Source: The
run_service.batscript executespython notification_service.py. This requires Python and the dependencies listed inrequirements.txt(requests,pytz) to be installed. - Executable: The
build_notification_exe.batscript uses PyInstaller to package the service and its dependencies into a singleTelegramNotifications.exefile.
For deployment, the following files must be in the same directory:
TelegramNotifications.exe(ornotification_service.py)config.json(configured with correct credentials)pos_inventory.db(the POS database to monitor)
Upon first run, the service will automatically create the logs/ directory and the notification_state.db file.
Sources: run_service.bat, build_notification_exe.bat, README_Notifications.txt:7-15, requirements.txt:5-6