πŸ” Overview

This document describes the Celery task responsible for generating and sending daily statistics reports to users via Telegram. The task aggregates data on blocked and unblocked links, as well as manually switched links, and sends a summary message to each user.


πŸ“ Task Definitions

@celery.task
def generate_statistics_task():
    logger.info("Generating statistics...")
    yesterday = (timezone.now() - timezone.timedelta(days=1)).date()
    for user in UserModel.objects.all():
        logger.info(f"Generating statistics for user {str(user)}...")
        domain_blocked = set()
        blocked_links = (
            Link.objects.filter(owner=user, blocked_at__date=yesterday)
            .exclude(status=LinkStatuses.ACTIVE.value)
            .all()
        )
        for link in blocked_links:
            domain_blocked.add(link.domain)
        domain_unblocked = set()
        unblocked_links = (
            Link.objects.filter(owner=user, unblocked_at__date=yesterday)
            .exclude(status=LinkStatuses.BLOCKED.value)
            .all()
        )
        for link in unblocked_links:
            domain_unblocked.add(link.domain)
        manually_switched_domains = set()
        manually_switched_links = (
            Link.objects.filter(owner=user, blocked_at__date=yesterday, reason=BlockReasons.BLOCKED_BY_USER.value)
            .exclude(status=LinkStatuses.ACTIVE.value)
            .all()
        )
        for link in manually_switched_links:
            manually_switched_domains.add(link.domain)
        TelegramSender.send_daily_statistics_message(
            report_date=yesterday.strftime("%Y-%m-%d"),
            blocked_domains=list(domain_blocked),
            unblocked_domains=list(domain_unblocked),
            manually_switched_domains=list(manually_switched_domains),
            user=user
        )
        logger.info(f"Statistics for user {str(user)} generated successfully.")
    logger.info("Statistics generation completed.")

βš™οΈ Task Behavior & Flow

  1. The task generate_statistics_task is scheduled to run daily (every 8:30 AM) via Celery Beat.
  2. It calculates the date for β€œyesterday” to gather statistics for the previous day.
  3. For each user in the system, it performs the following:
    • Retrieves all links that were blocked yesterday and collects their domains.
    • Retrieves all links that were unblocked yesterday and collects their domains.
    • Retrieves all links that were manually switched (blocked by user action) yesterday and collects their domains.
  4. Sends a summary message (see Telegram Messages) to the user via the Telegram bot, including lists of blocked, unblocked, and manually switched domains.
  5. Logs the completion of statistics generation for each user and the overall task.