HH/sync_complaint_types.py
2026-01-24 15:27:27 +03:00

80 lines
2.2 KiB
Python

#!/usr/bin/env python
"""Quick script to sync complaint types from AI metadata"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PX360.settings')
django.setup()
from apps.complaints.models import Complaint
from django.db.models import Q
print("=" * 60)
print("Starting complaint_type sync...")
print("=" * 60)
# Build query for complaints that need syncing
queryset = Complaint.objects.filter(
Q(metadata__ai_analysis__complaint_type__isnull=False) &
(
Q(complaint_type='complaint') | # Default value
Q(complaint_type__isnull=False)
)
)
# Count total
total = queryset.count()
print(f"Found {total} complaints to check\n")
if total == 0:
print("No complaints need syncing")
exit(0)
# Process complaints
updated = 0
skipped = 0
errors = 0
for complaint in queryset:
try:
ai_type = complaint.metadata.get('ai_analysis', {}).get('complaint_type', 'complaint')
# Check if model field differs from metadata
if complaint.complaint_type != ai_type:
# Update the complaint_type field
complaint.complaint_type = ai_type
complaint.save(update_fields=['complaint_type'])
print(f"Updated complaint {complaint.id}: '{complaint.complaint_type}' -> '{ai_type}'")
updated += 1
else:
skipped += 1
except Exception as e:
print(f"Error processing complaint {complaint.id}: {str(e)}")
errors += 1
# Summary
print("\n" + "=" * 60)
print("Sync Complete")
print("=" * 60)
print(f"Total complaints checked: {total}")
print(f"Updated: {updated}")
print(f"Skipped (already in sync): {skipped}")
print(f"Errors: {errors}")
print("\n" + f"Successfully updated {updated} complaint(s)")
# Show breakdown by type
if updated > 0:
print("\n" + "=" * 60)
print("Updated Complaints by Type:")
print("=" * 60)
type_counts = {}
for complaint in queryset:
ai_type = complaint.metadata.get('ai_analysis', {}).get('complaint_type', 'complaint')
if complaint.complaint_type == ai_type:
type_counts[ai_type] = type_counts.get(ai_type, 0) + 1
for complaint_type, count in sorted(type_counts.items()):
print(f" {complaint_type}: {count}")