71 lines
2.0 KiB
Python
71 lines
2.0 KiB
Python
import json
|
|
import logging
|
|
|
|
# Create your views here.
|
|
from rest_framework import viewsets
|
|
from rest_framework.decorators import api_view
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
|
|
from ipware import get_client_ip
|
|
from django.contrib.gis.geoip2 import GeoIP2
|
|
|
|
from back_latienda.permissions import IsStaff
|
|
|
|
from products.models import Product
|
|
from companies.models import Company
|
|
|
|
from stats.models import StatsLog
|
|
from stats.serializers import StatsLogSerializer
|
|
|
|
|
|
class StatsLogViewSet(viewsets.ModelViewSet):
|
|
queryset = StatsLog.objects.all()
|
|
serializer_class = StatsLogSerializer
|
|
permission_classes = [IsStaff,]
|
|
|
|
|
|
@api_view(['POST'])
|
|
def track_user(request):
|
|
"""Track user actions on the site
|
|
|
|
Params:
|
|
{
|
|
action: view,
|
|
object: {
|
|
model: name,
|
|
id: 1,
|
|
},
|
|
}
|
|
"""
|
|
try:
|
|
data = json.loads(request.body)
|
|
|
|
# geoip stuff
|
|
client_ip, is_routable = get_client_ip(request)
|
|
g = GeoIP2()
|
|
|
|
# gather instance data
|
|
instance_data = {
|
|
'action': data.get('action'),
|
|
'user': request.user,
|
|
'anonymous': request.user.is_anonymous,
|
|
'ip_address': client_ip,
|
|
'geo': g.geos(client_ip),
|
|
# 'contact' ???
|
|
}
|
|
|
|
if data['object'].get('name') == 'product':
|
|
instance_data['action_object'] = Product.objects.get(id=data['object'].get('id'))
|
|
elif data['object'].get('name') == 'company':
|
|
instance_data['action_object'] = Company.objects.get(id=data['object'].get('id'))
|
|
if instance_data['action_object'].shop is True:
|
|
instance_data['shop'] = True
|
|
|
|
# crate new instance
|
|
new_stat = StatsLog.objects.create(**instance_data)
|
|
return Response(status=status.HTTP_201_CREATED)
|
|
except Exception as e:
|
|
logging.error(f"Stats could not be created: {str(e)}")
|
|
return Response(f"Process could not be registered: {str(type(e))}")
|