From 1905d4956507bc4161285a647274e746bf90a44a Mon Sep 17 00:00:00 2001 From: PyDevDeep Date: Sat, 20 Jun 2026 08:37:28 +0300 Subject: [PATCH] feat(statistics): parse and display WooCommerce UTM tags Added extraction of _wc_order_attribution_* keys from WooCommerce order metadata. The tags are now sorted by frequency in the daily statistics report to better identify popular traffic sources. --- app/services/statistics_service.py | 6 +++++- app/services/woo_service.py | 26 ++++++++++++++++++++++---- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/app/services/statistics_service.py b/app/services/statistics_service.py index 3fe6ed3..588b74d 100644 --- a/app/services/statistics_service.py +++ b/app/services/statistics_service.py @@ -119,7 +119,11 @@ async def gather_and_send_daily_report_job() -> None: msg_lines.append("") msg_lines.append("🏷 Джерела / Мітки (від усього):") total_orders = woo_stats.get("total", 1) or 1 - for tag, count in tags.items(): + + # Sort tags by count descending + sorted_tags = sorted(tags.items(), key=lambda item: item[1], reverse=True) + + for tag, count in sorted_tags: pct = (count / total_orders) * 100 msg_lines.append(f" - {tag}: {count} ({pct:.1f}%)") diff --git a/app/services/woo_service.py b/app/services/woo_service.py index e69dccb..2b32558 100644 --- a/app/services/woo_service.py +++ b/app/services/woo_service.py @@ -201,10 +201,28 @@ async def get_daily_orders_stats(self) -> dict[str, Any]: meta_data = cast(list[dict[str, Any]], meta_data_raw) for meta in meta_data: key = str(meta.get("key", "")) - if key in ("utm_source", "source", "bot_tag", "created_via"): - val = str(meta.get("value", "")).strip().lower() - if val: - tags[val] = tags.get(val, 0) + 1 + val = str(meta.get("value", "")).strip() + if not val: + continue + + tag_name = None + if key in ("utm_source", "source", "_wc_order_attribution_utm_source"): + tag_name = f"Джерело: {val.lower()}" + elif key in ("bot_tag", "created_via"): + tag_name = f"Створено: {val.lower()}" + elif key == "_wc_order_attribution_utm_campaign": + tag_name = f"Кампанія: {val}" + elif key == "_wc_order_attribution_utm_medium": + tag_name = f"Канал: {val.lower()}" + elif key == "_wc_order_attribution_referrer": + if val.startswith("http"): + from urllib.parse import urlparse + + val = urlparse(val).netloc + tag_name = f"Реферер: {val}" + + if tag_name: + tags[tag_name] = tags.get(tag_name, 0) + 1 except Exception as e: logger.error("WooCommerce API Orders Stats Error", error=str(e))