Commit 2147f6a4 authored by Skia's avatar Skia

Add permanencies tracking to counters

parent 593050d9
......@@ -112,7 +112,7 @@ class User(AbstractBaseUser):
return reverse('core:user_profile', kwargs={'user_id': self.pk})
def __str__(self):
return "User: " + self.username
return self.username
def to_dict(self):
return self.__dict__
......
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('counter', '0006_auto_20160717_1033'),
]
operations = [
migrations.CreateModel(
name='Permanency',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('start', models.DateTimeField(verbose_name='start date')),
('end', models.DateTimeField(verbose_name='end date')),
('counter', models.ForeignKey(related_name='permanencies', to='counter.Counter')),
('user', models.ForeignKey(related_name='permanencies', to=settings.AUTH_USER_MODEL)),
],
),
]
......@@ -100,15 +100,50 @@ class Counter(models.Model):
def can_be_viewed_by(self, user):
return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP)
def add_barman(counter_id, user_id):
"""
Logs a barman in to the given counter
A user is stored as a tuple with its login time
"""
counter_id = int(counter_id)
user_id = int(user_id)
if counter_id not in Counter.barmen_session.keys():
Counter.barmen_session[counter_id] = {'users': {(user_id, timezone.now())}, 'time': timezone.now()}
else:
Counter.barmen_session[counter_id]['users'].add((user_id, timezone.now()))
def del_barman(counter_id, user_id):
"""
Logs a barman out and store its permanency
"""
counter_id = int(counter_id)
user_id = int(user_id)
user_tuple = None
for t in Counter.barmen_session[counter_id]['users']:
if t[0] == user_id: user_tuple = t
Counter.barmen_session[counter_id]['users'].remove(user_tuple)
u = User.objects.filter(id=user_id).first()
c = Counter.objects.filter(id=counter_id).first()
Permanency(user=u, counter=c, start=user_tuple[1], end=Counter.barmen_session[counter_id]['time']).save()
def get_barmen_list(counter_id):
"""
Returns the barman list as list of Subscriber
Also handle the timeout of the barmen
"""
bl = []
counter_id = str(counter_id)
counter_id = int(counter_id)
if counter_id in list(Counter.barmen_session.keys()):
for b in Counter.barmen_session[counter_id]['users']:
# Reminder: user is stored as a tuple with its login time
bl.append(Subscriber.objects.filter(id=b[0]).first())
if (timezone.now() - Counter.barmen_session[counter_id]['time']) < timedelta(minutes=settings.SITH_BARMAN_TIMEOUT):
for b in Counter.barmen_session[counter_id]['users']:
bl.append(Subscriber.objects.filter(id=b).first())
Counter.barmen_session[counter_id]['time'] = timezone.now()
else:
for b in bl:
Counter.del_barman(counter_id, b.id)
bl = []
Counter.barmen_session[counter_id]['users'] = set()
return bl
......@@ -167,6 +202,19 @@ class Selling(models.Model):
# def get_absolute_url(self):
# return reverse('counter:details', kwargs={'counter_id': self.id})
class Permanency(models.Model):
"""
This class aims at storing a traceability of who was barman where and when
"""
user = models.ForeignKey(User, related_name="permanencies")
counter = models.ForeignKey(Counter, related_name="permanencies")
start = models.DateTimeField(_('start date'))
end = models.DateTimeField(_('end date'))
def __str__(self):
return "%s in %s from %s to %s" % (self.user, self.counter,
self.start.strftime("%Y-%m-%d %H:%M:%S"), self.end.strftime("%Y-%m-%d %H:%M:%S"))
# TODO:
# une classe Vente
......
......@@ -64,8 +64,6 @@ class CounterMain(DetailView, ProcessFormView, FormMixin):
def get_context_data(self, **kwargs):
"""
We handle here the login form for the barman
Also handle the timeout
"""
if self.request.method == 'POST':
self.object = self.get_object()
......@@ -285,10 +283,7 @@ class CounterLogin(RedirectView):
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = Subscriber.objects.filter(username=form.cleaned_data['username']).first()
if self.counter_id not in Counter.barmen_session.keys():
Counter.barmen_session[self.counter_id] = {'users': {user.id}, 'time': timezone.now()}
else:
Counter.barmen_session[self.counter_id]['users'].add(user.id)
Counter.add_barman(self.counter_id, user.id)
else:
print("Error logging the barman") # TODO handle that nicely
return super(CounterLogin, self).post(request, *args, **kwargs)
......@@ -303,7 +298,7 @@ class CounterLogout(RedirectView):
Unregister the user from the barman
"""
self.counter_id = kwargs['counter_id']
Counter.barmen_session[str(self.counter_id)]['users'].remove(int(request.POST['user_id']))
Counter.del_barman(self.counter_id, request.POST['user_id'])
return super(CounterLogout, self).post(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment