""" admin_stats.py --------------- Turns raw `extractions` rows and `po_approval_history` rows into per-day, per-user counts and daily activity history for the admin dashboard. Kept separate from app.py / Flask so it can be tested on its own. build_admin_stats(rows, po_history_rows=None) 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, "po_approved": 2, "item_code_approved": 1}, ... ], "po_history": [ {"id": 4, "time": "09:39:56", "invoice_number": "...", ...} ], "po_history_count": 1, "day_po_approved": 2, "day_item_approved": 1 }, ... ] sorted newest date first, users sorted alphabetically within a date. """ import json import re 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, 'po_approved': 0, 'item_code_approved': 0, } def _clean_audit_notes(notes, condition_type=None): """Sanitize technical condition names so internal rules like Condition 4/5 never show in UI.""" if not notes: return 'Approval action recorded in audit log' text = str(notes) text = re.sub(r'Condition\s*1\s*:\s*', 'Direct Verified: ', text, flags=re.IGNORECASE) text = re.sub(r'Condition\s*2\s*:\s*', 'Auto-Matched via DMH API: ', text, flags=re.IGNORECASE) text = re.sub(r'Condition\s*3\s*:\s*', 'Manual Item Code Review: ', text, flags=re.IGNORECASE) text = re.sub(r'Condition\s*4\s*:\s*', 'Manual PO Approved: ', text, flags=re.IGNORECASE) text = re.sub(r'Condition\s*5\s*:\s*', 'Manual PO & Item Verification: ', text, flags=re.IGNORECASE) text = re.sub(r'condition_[1-5]', '', text, flags=re.IGNORECASE) text = re.sub(r'\s{2,}', ' ', text) return text.strip() def build_admin_stats(rows, po_history_rows=None): daily = defaultdict(lambda: defaultdict(_empty_bucket)) po_by_date = defaultdict(list) # 1. Process extraction rows for row in (rows or []): 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 # 2. Process PO Approval History rows if po_history_rows: for po_row in po_history_rows: ts = po_row['approval_timestamp'] or '' date_str = ts[:10] if len(ts) >= 10 else 'unknown' username = po_row['approved_by_username'] or 'System Automated' app_type = po_row['approval_type'] or 'po_approval' status = po_row['approval_status'] or 'completed' bucket = daily[date_str][username] if app_type == 'item_code_approval': bucket['item_code_approved'] += 1 else: if status in ('approved', 'completed') and po_row['po_number_approved']: bucket['po_approved'] += 1 cond_type = po_row['condition_type'] if (hasattr(po_row, 'keys') and 'condition_type' in po_row.keys()) else None clean_notes = _clean_audit_notes(po_row['notes'], cond_type) po_by_date[date_str].append({ 'id': po_row['id'], 'time': ts[11:19] if len(ts) >= 19 else '--:--', 'timestamp': ts, 'invoice_number': po_row['invoice_number'] or '--', 'vendor_name': po_row['vendor_name'] or '--', 'po_number_previous': po_row['po_number_previous'] or '', 'po_number_approved': po_row['po_number_approved'] or '--', 'approval_status': status, 'approval_type': app_type, 'approved_by': username, 'notes': clean_notes, 'webhook_status': po_row['webhook_status'] or 'not_triggered', 'item_code_status': po_row['item_code_status'] or '' }) result = [] # Combine dates from extractions and PO approvals all_dates = sorted(set(daily.keys()) | set(po_by_date.keys()), reverse=True) for date_str in all_dates: users = daily[date_str] user_rows = [ {'username': username, **stats} for username, stats in sorted(users.items()) ] day_po = po_by_date.get(date_str, []) result.append({ 'date': date_str, 'users': user_rows, 'po_history': day_po, 'po_history_count': len(day_po), 'day_po_approved': sum(u['po_approved'] for u in user_rows), 'day_item_approved': sum(u['item_code_approved'] for u in 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']) total_po_approved = sum(u['po_approved'] for day in stats for u in day['users']) total_item_code_approved = sum(u['item_code_approved'] 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']} today_po_approved = sum(u['po_approved'] for day in stats if day['date'] == today_str for u in day['users']) today_item_code_approved = sum(u['item_code_approved'] 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, 'total_po_approved': total_po_approved, 'total_item_code_approved': total_item_code_approved, 'today_pdfs': today_pdfs, 'today_active_users': len(today_users), 'today_po_approved': today_po_approved, 'today_item_code_approved': today_item_code_approved, }