Skip to content

Commit

Permalink
admin with grappelli, html modification
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzobracciale committed Oct 29, 2013
1 parent 739a8ff commit a4a1676
Show file tree
Hide file tree
Showing 63 changed files with 2,214 additions and 508 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@ This is a fusolab registration project.

It needs: django, python image library, unidecode, django-form-utils, sorl-thumbnail, django-qsstats-magic, python-dateutil.

Sorl thumbnail have these requirements: http://sorl-thumbnail.readthedocs.org/en/latest/requirements.html

For print the receipts, need to configure the browser to remove url in prints and to remove any print confirmation window.



4 changes: 2 additions & 2 deletions fusolab2_0/apps/bar/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
class BarBalanceAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'cashier':
kwargs['queryset'] = User.objects.filter(groups__name='turnisti')
kwargs['queryset'] = UserProfile.objects.filter(user__groups__name='turnisti')
return super(BarBalanceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

class SmallBalanceAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'cashier':
kwargs['queryset'] = User.objects.filter(groups__name='turnisti')
kwargs['queryset'] = UserProfile.objects.filter(user__groups__name='turnisti')
return super(SmallBalanceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

# Re-register UserAdmin
Expand Down
13 changes: 9 additions & 4 deletions fusolab2_0/apps/bar/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ class BarBalanceModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(BarBalanceModelForm, self).__init__(*args, **kwargs)
self.fields['cashier'].queryset = UserProfile.objects.filter(user__groups__name="turnisti")

self.fields['amount'].localize = True

class Meta:
model = BarBalance
exclude = ('parent', 'date')
Expand All @@ -33,14 +34,16 @@ def __init__(self, *args, **kwargs):
self.fields['promoter'] = forms.CharField(required=False)
self.fields['name'] = forms.CharField(required=False)
self.fields['subtype'] = forms.CharField(widget=forms.HiddenInput(), required=False)

self.fields['amount'].label = 'Contanti iniziali'

class BarClosingModelForm(BarBalanceModelForm):
def __init__(self, *args, **kwargs):
super(BarClosingModelForm, self).__init__(*args, **kwargs)
self.fields['operation'] = forms.CharField(widget=forms.HiddenInput(),initial=CLOSING)
self.fields['subtype'] = forms.CharField(widget=forms.HiddenInput(), required=False)
self.fields['promoter'] = forms.CharField(widget=forms.HiddenInput(), required=False)
self.fields['name'] = forms.CharField(widget=forms.HiddenInput(), required=False)
self.fields['amount'].label = 'Contanti finali'

class BarPaymentModelForm(BarBalanceModelForm):
def __init__(self, *args, **kwargs):
Expand All @@ -49,7 +52,7 @@ def __init__(self, *args, **kwargs):
self.fields['subtype'] = forms.CharField(widget=forms.Select(choices=PAYMENT_SUBTYPES))
self.fields['promoter'] = forms.CharField(widget=forms.HiddenInput(), required=False)
self.fields['name'] = forms.CharField(widget=forms.HiddenInput(), required=False)

self.fields['amount'].label = 'Contanti finali'

class BarDepositModelForm(BarBalanceModelForm):
def __init__(self, *args, **kwargs):
Expand All @@ -75,6 +78,7 @@ class SmallBalanceModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(SmallBalanceModelForm, self).__init__(*args, **kwargs)
self.fields['cashier'].queryset = UserProfile.objects.filter(user__groups__name="turnisti")
self.fields['amount'].localize = True

class Meta:
model = SmallBalance
Expand All @@ -87,7 +91,8 @@ class Meta:
class SmallCashpointModelForm(SmallBalanceModelForm):
def __init__(self, *args, **kwargs):
super(SmallCashpointModelForm, self).__init__(*args, **kwargs)
self.fields['operation'] = forms.CharField(widget=forms.HiddenInput(),initial=CASHPOINT)
self.fields['operation'] = forms.CharField(widget=forms.HiddenInput(),initial=CASHPOINT)
self.fields['amount'].label = 'In cassa'

class SmallPaymentModelForm(SmallBalanceModelForm):
def __init__(self, *args, **kwargs):
Expand Down
77 changes: 62 additions & 15 deletions fusolab2_0/apps/bar/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ class Balance(models.Model):
date = models.DateTimeField("Data", default=datetime.now)
cashier = models.ForeignKey('base.UserProfile', verbose_name="Cassiere")
note = models.TextField(blank=True)

objects = BalanceManager()

class Meta:
Expand All @@ -84,7 +83,7 @@ def __unicode__(self):
return "%d - %d %s %.2f %s" % (self.id, self.parent.id, self.get_operation_display(), self.amount, self.date.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT)))

class Meta:
ordering = ['-date']
ordering = ['date']
verbose_name = "Voce di bilancio del Bar"
verbose_name_plural = "Voci di bilancio del Bar"

Expand All @@ -106,7 +105,7 @@ def __unicode__(self):
return "%d - %s %.2f %s" % (self.id, self.get_operation_display(), self.amount, self.date.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT)))

class Meta:
ordering = ['-date']
ordering = ['date']
verbose_name = "Voce di bilancio dell'Interregno"
verbose_name_plural = "Voci di bilancio dell'Interregno"

Expand All @@ -119,11 +118,20 @@ def save(self, *args, **kwargs):
def get_bar_summary(closing):
notes = []
d = {}

notes.append("apertura "+ str(closing.parent.amount))
if closing.parent.promoter:
notes.append(" "+closing.parent.promoter)
if closing.parent.name:
notes.append(" "+closing.parent.name)
if closing.parent.note:
notes.append(closing.parent.note.replace("\r\n"," "+"\n"))
else:
notes.append("\n")

d['date'] = closing.parent.date.strftime("%d/%m/%Y")
d['cashier'] = closing.cashier
d['opening_amount'] = closing.parent.amount
if closing.parent.note:
notes.append("apertura "+str(closing.parent.amount)+" "+closing.parent.note)
d['last_closing_amount'] = BarBalance.objects.get_last_closing(closing.parent)
d['closing_amount'] = closing.amount

Expand Down Expand Up @@ -152,13 +160,33 @@ def get_bar_summary(closing):

for transaction in opening_transactions:
d[transaction.operation]+=transaction.amount
notes.append(transaction.get_operation_display() + " " + str(transaction.amount))
if transaction.operation in [DEPOSIT]:
d['expected_balance']+=transaction.amount
elif transaction.operation in [PAYMENT,WITHDRAW]:
if transaction.subtype:
notes.append(" "+get_deposit_display(transaction.subtype))
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," "+"\n"))
else:
notes.append("\n")
elif transaction.operation in [PAYMENT]:
d['expected_balance']-=transaction.amount
if transaction.subtype:
notes.append(" "+get_payment_display(transaction.subtype))
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," ")+"\n")
else:
notes.append("\n")
elif transaction.operation in [WITHDRAW]:
d['expected_balance']-=transaction.amount

if transaction.note:
notes.append(transaction.get_operation_display()+" "+str(transaction.amount)+" "+transaction.note+"\n")
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," "+"\n"))
else:
notes.append("\n")
else:
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," "+"\n"))


d['notes'] = notes
d['opening_check'] = d['opening_amount'] - d['last_closing_amount']
Expand Down Expand Up @@ -211,13 +239,32 @@ def get_small_summary(checkpoint):
if checkpoint_transactions:
for transaction in checkpoint_transactions:
d[transaction.operation]+=transaction.amount
notes.append(transaction.get_operation_display() + " " + str(transaction.amount))
if transaction.operation in [DEPOSIT]:
d['expected_checkpoint']+=transaction.amount
elif transaction.operation in [PAYMENT,WITHDRAW]:
d['expected_checkpoint']-=transaction.amount

if transaction.note:
notes.append(transaction.get_operation_display()+" "+str(transaction.amount)+": "+transaction.note)
d['expected_balance']+=transaction.amount
if transaction.subtype:
notes.append(" "+get_deposit_display(transaction.subtype))
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," "+"\n"))
else:
notes.append("\n")
elif transaction.operation in [PAYMENT]:
d['expected_balance']-=transaction.amount
if transaction.subtype:
notes.append(" "+get_payment_display(transaction.subtype))
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," ")+"\n")
else:
notes.append("\n")
elif transaction.operation in [WITHDRAW]:
d['expected_balance']-=transaction.amount
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," "+"\n"))
else:
notes.append("\n")
else:
if transaction.note:
notes.append(" "+transaction.note.replace("\r\n"," "+"\n"))

d['notes'] = notes
d['check'] = d['checkpoint'] - d['expected_checkpoint']
Expand Down
45 changes: 17 additions & 28 deletions fusolab2_0/apps/bar/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,45 +12,34 @@
DATE_FORMAT = "%d-%m-%Y"
TIME_FORMAT = "%H:%M:%S"


@receiver(post_save, sender=BarBalance)
def bar_handler(sender, **kwargs):
saved_balance = kwargs['instance']

if saved_balance.operation == CLOSING:
subject = ''
template = get_template('closing_mail.html')

print "saved_balance parent:" , saved_balance.parent
d = get_bar_summary(saved_balance)
context = Context(d)
content = template.render(context)

if ('warning' in d):
subject += 'WARNING '
subject += 'riepilogo bar '+saved_balance.parent.date.strftime("%d/%m/%Y")

msg = EmailMessage(subject, content, '[email protected]', to=settings.EMAIL_NOTIFICATION_LIST)
msg.content_subtype = "html"
msg.send()
template = get_template('closing_mail.html')
context = Context(d)
content = template.render(context)
subject = 'WARNING riepilogo bar '+saved_balance.parent.date.strftime("%d/%m/%Y")
msg = EmailMessage(subject, content, '[email protected]', to=settings.EMAIL_NOTIFICATION_LIST)
msg.content_subtype = "html"
msg.send()

@receiver(post_save, sender=SmallBalance)
def bar_handler(sender, **kwargs):
def small_handler(sender, **kwargs):
saved_balance = kwargs['instance']

if saved_balance.operation == CASHPOINT:
subject = ''
template = get_template('base/smallbalance_mail.html')

print "saved_balance parent:" , saved_balance.parent
d = get_small_summary(saved_balance)
context = Context(d)
content = template.render(context)

if ('warning' in d):
subject += 'WARNING '
subject += 'riepilogo interregno '+saved_balance.date.strftime("%d/%m/%Y")

msg = EmailMessage(subject, content, '[email protected]', to=settings.EMAIL_NOTIFICATION_LIST)
msg.content_subtype = "html"
msg.send()
template = get_template('base/smallbalance_mail.html')
context = Context(d)
content = template.render(context)
subject = 'WARNING riepilogo interregno '+saved_balance.date.strftime("%d/%m/%Y")
msg = EmailMessage(subject, content, '[email protected]', to=settings.EMAIL_NOTIFICATION_LIST)
msg.content_subtype = "html"
msg.send()


24 changes: 21 additions & 3 deletions fusolab2_0/apps/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
from django.core.validators import MinValueValidator
from django.db.models.signals import post_save
from django.utils.safestring import mark_safe
from django.core.cache import cache
from decimal import Decimal
from datetime import datetime
from datetime import *
from django.conf import settings
#from sorl.thumbnail import ImageField

DOCUMENT_TYPES = ( ('ci', 'Carta d\'identita\''), ('pp', 'Passaporto'), ('pa', 'Patente') )
DATE_FORMAT = "%d-%m-%Y"
Expand All @@ -14,19 +17,34 @@
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)

doc_type = models.CharField(max_length=2, choices=DOCUMENT_TYPES, blank=True)
doc_id = models.CharField(max_length=20, blank=True)
born_date = models.DateField(blank=True, null=True)
born_place = models.CharField(max_length=50, blank=True)

photo = models.ImageField(upload_to='photo/', blank=True) #TODO fare check nel form per size ed eventualmente resizing
how_hear = models.CharField(max_length=500, blank=True)
salutatore = models.CharField(max_length=500, blank=True)

def __unicode__(self):
return u'%s %s' % (self.user.first_name, self.user.last_name)

def get_photo(self):
return self.photo if self.photo else '/static/images/fusolab_unnamed.jpg'

def last_seen(self):
return cache.get('seen_%s' % self.user.username)

def online(self):
if self.last_seen():
now = datetime.now()
if now > self.last_seen() + timedelta(
seconds=settings.USER_ONLINE_TIMEOUT):
return False
else:
return True
else:
return False

class Meta:
verbose_name = "Utente"
verbose_name_plural = "Utenti"
Expand Down
57 changes: 57 additions & 0 deletions fusolab2_0/apps/base/templatetags/usertags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from django import template
from django.contrib.auth.models import User
import datetime

register = template.Library()

"""
namefile: usertags.py
You would need a template nest for every method, for example to online_users.
/templates/tag/online_users.html
{% if users %}
<ul>
{% for user in users %}
<li>{{user.username}}</li>
{% endfor %}
</ul>
{% endif %}
to load
{% load usertags %}
{% online_users 5 %}
{% last_registers 5 %}
{% last_logins 5 %}
"""

#@register.inclusion_tag('tags/online_users.html')
@register.assignment_tag
def online_users(num):
"""
Show user that has been login an hour ago.
"""
two_hour_ago = datetime.datetime.now() - datetime.timedelta(hours=2)
sql_datetime = datetime.datetime.strftime(two_hour_ago, '%Y-%m-%d %H:%M:%S')
users = User.objects.filter(last_login__gt=sql_datetime,
is_active__exact=1).order_by('-last_login')[:num]
return users

#@register.inclusion_tag('tags/last_registers.html')
@register.assignment_tag
def last_registers(num):
"""
Show last registered users.
"""
users = User.objects.filter(is_active__exact=1).order_by('-date_joined')[:num]
return users

#@register.inclusion_tag('tags/last_logins.html')
@register.assignment_tag
def last_logins(num):
"""
Show last logins ...
"""
users = User.objects.filter(is_active__exact=1).order_by('-last_login')[:num]
return users
5 changes: 4 additions & 1 deletion fusolab2_0/apps/base/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@

urlpatterns = patterns('',
url(r'^accounts/edit/$', 'base.views.edit', name='base_account_edit'),
url(r'activate/(?P<activation_key>\w+)/$', 'base.views.edit', name='edit'),
url(r'activate/(?P<activation_key>\w+)/$', 'base.views.edit', name='base_activate_edit'),
url(r'^$', 'base.views.home', name='home' ),
url(r'^index.html$', 'base.views.home'),
url(r'^tuttoapposto/(?P<next_page>\S+)$', 'base.views.tuttoapposto', name='tuttoapposto'),
url(r'^regolamento/$', TemplateView.as_view(template_name='regolamento.html'), name='base_regolamento'),

url(r'^disponibilita/$', TemplateView.as_view(template_name='base/disponibilita.html'), name='base_disponibilita'),
url(r'^turni/$', TemplateView.as_view(template_name='base/turni.html'), name='base_turni'),
)
Loading

0 comments on commit a4a1676

Please sign in to comment.