""" admin_stats.py --------------- Turns raw `extractions` rows into per-day, per-user counts for the admin dashboard. Kept separate from app.py / Flask so it can be tested on its own. build_admin_stats(rows) expects an iterable of objects that support row['user_id'], row['username'], row['created_at'], row['extraction_data'] (a sqlite3.Row or a plain dict both work) and returns: [ { "date": "2026-09-22", "users": [ {"username": "shivani", "pdfs_processed": 3, "total_items": 40, "items_with_code": 35, "items_auto_matched": 20, "items_manual": 10, "items_missing": 5}, ... ] }, ... ] sorted newest date first, users sorted alphabetically within a date. """ import json from collections import defaultdict def _empty_bucket(): return { 'pdfs_processed': 0, 'total_items': 0, 'items_with_code': 0, 'items_auto_matched': 0, 'items_manual': 0, 'items_missing': 0, } def build_admin_stats(rows): daily = defaultdict(lambda: defaultdict(_empty_bucket)) for row in rows: created_at = row['created_at'] or '' date_str = created_at[:10] if len(created_at) >= 10 else 'unknown' username = row['username'] or 'unknown' bucket = daily[date_str][username] bucket['pdfs_processed'] += 1 raw = row['extraction_data'] try: data = json.loads(raw) if raw else {} except (TypeError, ValueError): data = {} items = data.get('items') if isinstance(data, dict) else None if not isinstance(items, list): continue for item in items: if not isinstance(item, dict): continue bucket['total_items'] += 1 code = str(item.get('item_code') or '').strip() source = item.get('item_code_source') if code: bucket['items_with_code'] += 1 if source == 'drug_list_match': bucket['items_auto_matched'] += 1 elif source == 'manual': bucket['items_manual'] += 1 if not code: bucket['items_missing'] += 1 result = [] for date_str in sorted(daily.keys(), reverse=True): users = daily[date_str] user_rows = [ {'username': username, **stats} for username, stats in sorted(users.items()) ] result.append({'date': date_str, 'users': user_rows}) return result def build_summary(stats, today_str): total_pdfs = sum(u['pdfs_processed'] for day in stats for u in day['users']) total_items = sum(u['total_items'] for day in stats for u in day['users']) total_manual = sum(u['items_manual'] for day in stats for u in day['users']) total_missing = sum(u['items_missing'] for day in stats for u in day['users']) today_pdfs = sum(u['pdfs_processed'] for day in stats if day['date'] == today_str for u in day['users']) today_users = {u['username'] for day in stats if day['date'] == today_str for u in day['users']} return { 'total_pdfs': total_pdfs, 'total_items': total_items, 'total_manual': total_manual, 'total_missing': total_missing, 'today_pdfs': today_pdfs, 'today_active_users': len(today_users), }