Add permanencies tracking to counters

This commit is contained in:
Skia 2016-07-18 13:22:50 +02:00
parent 593050d9e2
commit 2147f6a468
4 changed files with 80 additions and 11 deletions

View File

@ -112,7 +112,7 @@ class User(AbstractBaseUser):
return reverse('core:user_profile', kwargs={'user_id': self.pk}) return reverse('core:user_profile', kwargs={'user_id': self.pk})
def __str__(self): def __str__(self):
return "User: " + self.username return self.username
def to_dict(self): def to_dict(self):
return self.__dict__ return self.__dict__

View File

@ -0,0 +1,26 @@
# -*- 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)),
],
),
]

View File

@ -100,15 +100,50 @@ class Counter(models.Model):
def can_be_viewed_by(self, user): def can_be_viewed_by(self, user):
return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP) 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): def get_barmen_list(counter_id):
"""
Returns the barman list as list of Subscriber
Also handle the timeout of the barmen
"""
bl = [] bl = []
counter_id = str(counter_id) counter_id = int(counter_id)
if counter_id in list(Counter.barmen_session.keys()): if counter_id in list(Counter.barmen_session.keys()):
if (timezone.now() - Counter.barmen_session[counter_id]['time']) < timedelta(minutes=settings.SITH_BARMAN_TIMEOUT):
for b in Counter.barmen_session[counter_id]['users']: for b in Counter.barmen_session[counter_id]['users']:
bl.append(Subscriber.objects.filter(id=b).first()) # 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):
Counter.barmen_session[counter_id]['time'] = timezone.now() Counter.barmen_session[counter_id]['time'] = timezone.now()
else: else:
for b in bl:
Counter.del_barman(counter_id, b.id)
bl = []
Counter.barmen_session[counter_id]['users'] = set() Counter.barmen_session[counter_id]['users'] = set()
return bl return bl
@ -167,6 +202,19 @@ class Selling(models.Model):
# def get_absolute_url(self): # def get_absolute_url(self):
# return reverse('counter:details', kwargs={'counter_id': self.id}) # 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: # TODO:
# une classe Vente # une classe Vente

View File

@ -64,8 +64,6 @@ class CounterMain(DetailView, ProcessFormView, FormMixin):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
""" """
We handle here the login form for the barman We handle here the login form for the barman
Also handle the timeout
""" """
if self.request.method == 'POST': if self.request.method == 'POST':
self.object = self.get_object() self.object = self.get_object()
@ -285,10 +283,7 @@ class CounterLogin(RedirectView):
form = AuthenticationForm(request, data=request.POST) form = AuthenticationForm(request, data=request.POST)
if form.is_valid(): if form.is_valid():
user = Subscriber.objects.filter(username=form.cleaned_data['username']).first() user = Subscriber.objects.filter(username=form.cleaned_data['username']).first()
if self.counter_id not in Counter.barmen_session.keys(): Counter.add_barman(self.counter_id, user.id)
Counter.barmen_session[self.counter_id] = {'users': {user.id}, 'time': timezone.now()}
else:
Counter.barmen_session[self.counter_id]['users'].add(user.id)
else: else:
print("Error logging the barman") # TODO handle that nicely print("Error logging the barman") # TODO handle that nicely
return super(CounterLogin, self).post(request, *args, **kwargs) return super(CounterLogin, self).post(request, *args, **kwargs)
@ -303,7 +298,7 @@ class CounterLogout(RedirectView):
Unregister the user from the barman Unregister the user from the barman
""" """
self.counter_id = kwargs['counter_id'] 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) return super(CounterLogout, self).post(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs): def get_redirect_url(self, *args, **kwargs):