fixes to track_user, and StatsLog model

This commit is contained in:
Sam
2021-03-03 13:18:06 +00:00
parent b793aaef36
commit d5b6dec656
2 changed files with 18 additions and 14 deletions

View File

@@ -31,40 +31,43 @@ class StatsLogViewSet(viewsets.ModelViewSet):
def track_user(request):
"""Track user actions on the site
Three types of actions to track:
- Load product details: view=True
- Load shop URL: shop=True
- Load company profile: view=True, action_object['model'] = 'company'
Params:
{
action: 'VIEW_NAME',
action_object: {
model: 'product',
'action': 'view' | 'shop',
'action_object': {
'model': 'product' | 'company',
id: 1,
},
'ip': '2134.234.234.2134',
'geo': (latitude: 324.32., longitud: 32423.23)
}
"""
try:
data = json.loads(request.body)
# geoip stuff
client_ip, is_routable = get_client_ip(request)
g = GeoIP2()
geo = None
if client_ip != '127.0.0.1':
geo = g.geos(client_ip)
# gather instance data
instance_data = {
'action_object': data.get('action_object'),
'user': None if request.user.is_anonymous else request.user,
'anonymous': request.user.is_anonymous,
'ip_address': client_ip,
'geo': geo,
'ip_address': data.get('ip'),
'geo': data.get('geo'),
}
if data['action_object'].get('model') == 'product':
instance_data['action_object'] = Product.objects.get(id=data['action_object'].get('id'))
elif data['action_object'].get('model') == 'company':
instance_data['action_object'] = Company.objects.get(id=data['action_object'].get('id'))
if instance_data['action_object'].shop is True:
instance_data['shop'] = True
if data.get('action') == 'view':
instance_data['view'] = True
elif data.get('action') == 'shop':
instance_data['shop'] = True
# crate new instance
new_stat = StatsLog.objects.create(**instance_data)