from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework import status from api.models import Bhagat, Region, Notification from channels.layers import get_channel_layer from asgiref.sync import async_to_sync import json @api_view(['GET']) @permission_classes([IsAuthenticated]) def get_users_by_filter(request): """ Get users based on filter type: all, region, usertype, or search query Query params: - type: all|region|usertype|search - value: region_id or usertype value or search query """ filter_type = request.GET.get('type', 'all') filter_value = request.GET.get('value', '') try: if filter_type == 'all': users = Bhagat.objects.all().values('id', 'first_name', 'last_name', 'email', 'user_type', 'region__name') elif filter_type == 'region': users = Bhagat.objects.filter(region_id=filter_value).values('id', 'first_name', 'last_name', 'email', 'user_type', 'region__name') elif filter_type == 'usertype': users = Bhagat.objects.filter(user_type=filter_value).values('id', 'first_name', 'last_name', 'email', 'user_type', 'region__name') elif filter_type == 'search': users = Bhagat.objects.filter( first_name__icontains=filter_value ) | Bhagat.objects.filter( last_name__icontains=filter_value ) | Bhagat.objects.filter( email__icontains=filter_value ) users = users.values('id', 'first_name', 'last_name', 'email', 'user_type', 'region__name') else: return Response({'error': 'Invalid filter type'}, status=status.HTTP_400_BAD_REQUEST) # Format user data user_list = [ { 'id': user['id'], 'name': f"{user['first_name']} {user['last_name']}", 'email': user['email'], 'user_type': user['user_type'], 'region': user['region__name'] } for user in users ] return Response({'users': user_list}, status=status.HTTP_200_OK) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['GET']) @permission_classes([IsAuthenticated]) def get_regions(request): """Get all regions""" try: regions = Region.objects.all().values('id', 'name') return Response({'regions': list(regions)}, status=status.HTTP_200_OK) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['POST']) @permission_classes([IsAuthenticated]) def create_notification(request): """ Create and send a notification Expected data: { "title": "Notification Title", "content": "Notification content", "notification_type": "orange", "delivery_type": "all|region|usertype|individualuser", "recipients": [user_ids] or region_id or usertype } """ try: data = request.data title = data.get('title', '') content = data.get('content', '') notification_type = data.get('notification_type', 'orange') delivery_type = data.get('delivery_type', 'all') recipients_data = data.get('recipients', []) # Validation if not content: return Response({'error': 'Content is required'}, status=status.HTTP_400_BAD_REQUEST) # Create notification notification = Notification.objects.create( sender=request.user, title=title, content=content, notification_type=notification_type ) # Determine recipients recipients = [] if delivery_type == 'all': recipients = Bhagat.objects.all() elif delivery_type == 'region': region_id = recipients_data[0] if isinstance(recipients_data, list) else recipients_data recipients = Bhagat.objects.filter(region_id=region_id) elif delivery_type == 'usertype': user_type = recipients_data[0] if isinstance(recipients_data, list) else recipients_data recipients = Bhagat.objects.filter(user_type=user_type) elif delivery_type == 'individualuser': recipient_ids = [r if isinstance(r, int) else r.get('id') for r in recipients_data] recipients = Bhagat.objects.filter(id__in=recipient_ids) # Add recipients to notification notification.recipients.set(recipients) notification.save() # Send via WebSocket channel_layer = get_channel_layer() message_data = { 'title': title, 'content': content, 'type': notification_type, 'sender': f"{request.user.first_name} {request.user.last_name}", 'timestamp': notification.timestamp.strftime('%Y-%m-%d %H:%M:%S') } async_to_sync(channel_layer.group_send)( 'Yuvak', { 'type': 'send_notification', 'message': message_data } ) return Response({ 'success': True, 'message': 'Notification sent successfully', 'notification': { 'id': notification.id, 'title': notification.title, 'content': notification.content, 'notification_type': notification.notification_type, 'timestamp': notification.timestamp.strftime('%Y-%m-%d %H:%M:%S'), 'recipients_count': notification.recipients.count() } }, status=status.HTTP_201_CREATED) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)