-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
731 lines (583 loc) · 24.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# This Python file uses the following encoding: utf-8
import logging
import datetime
from decimal import *
from types import *
from django.db import models
from django.contrib.auth.models import User, Group
from django import forms
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.template.loader import render_to_string
from django.core.mail import send_mail, EmailMultiAlternatives
from biereapp import settings
from biereapp.middleware import GlobalUser
# Setup debugging
LOG_FILENAME = 'debug.log'
#logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
def logit(what):
d = datetime.datetime.now()
if settings.DEBUG:
print "logit: " + what
#logging.debug(d.ctime() + ": " + what)
TYPE_TRANS = (
('CMD', 'Commande'),
('CRE', 'Crédit'),
('INV_IN', 'Inventaire In'),
('INV_OUT', 'Vente'),
('PAIE', 'Paiement'),
('RBS', 'Rabais'),
('RT', 'Retour'),
('RTV', 'Retour vide'),
)
TRANS_FACTURABLE = (
'CMD',
'INV_OUT'
)
TRANS_NON_FACTURABLE = (
'CRE',
'INV_IN',
'PAIE',
'RBS',
'RT'
)
TYPE_PRIX = (
('COST', 'Prix cost'),
('AFF', 'Prix affiché'),
('SPE', 'Spécial'),
)
class Client(models.Model):
Nom = models.CharField(max_length=60)
def __unicode__(self):
return self.Nom
def get_factures(self):
# ToDo
factures = Facture.objects.filter(Client=self).order_by('-Date')
return factures
def get_factures_html(self, template="client_factures.html"):
factures = self.get_factures()
return render_to_string('snippets/'+ template, {'factures': factures})
def is_client_interne(self):
try:
client_interne = Option.get("Client interne")
if self.Nom == client_interne:
return True
else:
return False
except Exception as e:
return False
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
if self.id:
if not GlobalUser.user.has_perm('biereapp.change_client'):
raise Exception("Vous ne pouvez pas changer de Client")
return False
else:
if not GlobalUser.user.has_perm('biereapp.add_client'):
raise Exception("Vous ne pouvez pas ajouter de client")
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Client, self).save()
class Brasseur(models.Model):
Nom = models.CharField(max_length=60)
def __unicode__(self):
return self.Nom
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
if self.id:
if not GlobalUser.user.has_perm('biereapp.change_rasseur'):
raise Exception("Vous ne pouvez pas changer de Brasseur")
return False
else:
if not GlobalUser.user.has_perm('biereapp.add_brasseur'):
raise Exception("Vous ne pouvez pas ajouter de Brasseur")
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Brasseur, self).save()
class Produit(models.Model):
Nom = models.CharField(max_length = 60)
Consigne = models.DecimalField(max_digits=5, decimal_places=2)
Brasseur = models.ForeignKey('Brasseur')
def prix(self):
"""
Obtenir le liste de prix pour le produit
"""
prix = Prix.objects.filter(Produit=self)
return prix
def __unicode__(self):
return self.Brasseur.__unicode__() + ' ' + self.Nom
def get_in(self):
inventaire_in = Transaction.objects.filter(Type='INV_IN').filter(Prix__Produit=self)
retour = Transaction.objects.filter(Type='RETOUR').filter(Prix__Produit=self)
tot = 0
for i in inventaire_in:
tot += i.Qte
for r in retour:
tot += r.Qte
return tot
def get_out(self):
inventaire_out = Transaction.objects.filter(Type='INV_OUT').filter(Prix__Produit=self)
tot = 0
for o in inventaire_out:
tot += o.Qte
return tot
def get_stock(self):
return self.get_in() - self.get_out()
def get_commande_etudiant(self):
client_interne = Option.get('Client interne')
try:
client_interne = Client.objects.filter(Nom=client_interne)[0:1].get()
except DoesNotExist:
client_interne = Client()
# No Client interne, only opened Facture
etudiant = Transaction.objects.filter(Facture__EstFermee=False).filter(Type='CMD').filter(Prix__Produit=self).exclude(Facture__Client=client_interne.id)
return etudiant.count()
def get_commande_fournisseur(self):
client_interne = Option.get('Client interne')
try:
client_interne = Client.objects.filter(Nom=client_interne)[0:1].get()
except DoesNotExist:
client_interne = Client()
# Only client interne and opened Facture
fournisseur = Transaction.objects.filter(Facture__EstFermee=False).filter(Prix__Produit=self).filter(Type='CMD').filter(Facture__Client=client_interne.id)
return fournisseur.count()
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
if self.id:
if not GlobalUser.user.has_perm('biereapp.change_produit'):
raise Exception("Vous ne pouvez pas changer de Produit")
return False
else:
if not GlobalUser.user.has_perm('biereapp.add_produit'):
raise Exception("Vous ne pouvez pas ajouter de Produit")
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Produit, self).save()
class Prix(models.Model):
Note = models.CharField(max_length=140, blank=True)
Prix = models.DecimalField(max_digits=5,decimal_places=2)
Produit = models.ForeignKey('Produit')
Type = models.CharField(max_length=5, choices=TYPE_PRIX)
# Prix privée sont les trucs comme le cost ou les prix que
# les usagés régulier ne peuvent pas voir
Prive = models.BooleanField()
def __unicode__(self):
return self.Produit.__unicode__() + ': ' + self.Type + ': ' + str(self.Prix)
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
if self.id:
if not GlobalUser.user.has_perm('biereapp.change_prix'):
raise Exception("Vous ne pouvez pas changer de Prix")
return False
else:
if not GlobalUser.user.has_perm('biereapp.add_prix'):
raise Exception("Vous ne pouvez pas ajouter de Prix")
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Prix, self).save()
class Transaction(models.Model):
Prix = models.ForeignKey('Prix', blank=True, null=True)
Type = models.CharField(max_length=10, choices=TYPE_TRANS)
Date = models.DateTimeField(auto_now_add=True)
# Support for decimal in quantities in order to make
# Consigne esayer to support
Qte = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True)
Facture = models.ForeignKey('Facture', blank=True, null=True)
User = models.ForeignKey(User)
# Dans le cas ou la transation est arbitraire (crédit ou autre)
# On peut utiliser ce champs, il faut aussi remplir la raison
# Le champs arbitraire est pour indiquer un prix et le Champs raison Expliquer pourquoi
Arbitraire = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True, default=-1)
Raison = models.CharField(max_length=140, blank=True)
class Meta:
# Chaque type de transation à besoin d'une permission pour
# être effectué
permissions = TYPE_TRANS
# Ajoute le transaction comme une commande
def add_to_commande(self):
self.Type = 'CMD'
self.save( )
def get_total(self):
# Returns the total for the current transaction
# ToDo
# ('INV_IN', 'Inventaire In'),
# ('INV_OUT', 'Inventaire Out'),
# ('RT', 'Retour'),
# ('CMD', 'Commande'),
# ('RTV', 'Retour vide'),
# ('CRE', 'Crédit'),
# ('RBS', 'Rabais'),
# ('PAIE', 'Paiement'),
# Support Arbitraire priority
if self.Type == 'RBS':
return -self.Arbitraire
if self.Arbitraire > -1:
if self.Type == 'PAIE':
return -self.Arbitraire
return self.Arbitraire
# - Calculate based on the transaction type
# You do not oay when making a Commande
if self.Type == 'CMD' or self.Type == 'RTV':
return 0
# Those lines are just wrong
# Retour de Vide mean you give part of the Consigne back
#if self.Type == 'RTV':
# return self.Qte * self.Prix.Produit.Consigne
if type(self.Prix.Prix) is not Decimal:
self.Prix.Prix = 0
if type(self.Qte) is not Decimal:
self.Qte = 0
tot = self.Prix.Prix * self.Qte
if not tot:
tot = 0
return tot
# ToDo
def get_consigne(self):
# Only calculate the consigne for beers that
# have left inventory
# If the beer has come back, we make a negative
# consigne
if self.Type == 'INV_OUT':
return self.Qte * self.Prix.Produit.Consigne
# Briging bottles back, we get a credit
if self.Type == 'RTV':
return -self.Qte * self.Prix.Produit.Consigne
return 0
def get_taxes(self):
# ToDo: Get tha latest TAXES options by date this
# option should be formatted as such {TPS: {taux:0.05, aff: "5%"}, TVQ: {taux: 0.0895, aff: "8,5%"} }
# return a dict with all the listed taxes and their value
t = self.get_total()
getcontext().prec = 10
# Sub is the subtotal without the taxes
taxes = { 'TPS': 0, 'TVQ': 0, 'sub': 0 }
# We cannot apply taxes to negative numbers
if t <= 0:
return taxes
TPS = Decimal( str(0.05) )
TVQ = Decimal( str(0.085) )
ratio = ((1 + TPS)*(1 + TVQ))
ratio = Decimal( str( ratio ) )
amount_without_taxes = Decimal( str(t / ratio) )
amount_tps = amount_without_taxes * TPS
amount_tvq = (amount_without_taxes + amount_tps) * TVQ
taxes['TVQ'] = amount_tvq
taxes['TPS'] = amount_tps
taxes['sub'] = amount_without_taxes
return taxes
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
self.User = GlobalUser.user
# Get Facture based on the number needed
user = BiereUser.as_current_user()
client = user.is_restricted_user()
if client:
if self.Facture.Client != client:
raise Exception("Vous ne pouvez pas faire cette action, méchant garnement, hors d'ici!")
return False
if not GlobalUser.user.has_perm('biereapp.add_transaction'):
raise Exception("Vous ne pouvez pas ajouter de Transaction")
return False
if not GlobalUser.user.has_perm('biereapp.'+self.Type):
raise Exception(u"Vous ne pouvez pas sauvegarder ce genre de transaction, désoler: " + self.Type)
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Transaction, self).save()
def __unicode__(self):
return self.Prix.Produit.Nom + str(self.get_total())
class Facture(models.Model):
Client = models.ForeignKey(Client)
Date = models.DateTimeField(auto_now_add=True)
EstFermee = models.BooleanField(default=False)
Note = models.CharField("Événement ou raison", max_length=140)
def __unicode__(self):
return self.Date.__str__() + ' pour ' + self.Client.Nom
def transactions(self, filtre=False):
# We need a user in order to discriminate
# What transactions can be shown
if not filtre:
qs = Transaction.objects.filter(Facture=self);
else:
qs = Transaction.objects.filter(Type__in=filtre).filter(Facture=self);
if len(qs) < 1:
return {}
return qs
def total(self, balance=False):
if balance:
trans = self.transactions( )
else:
trans = self.transactions( TRANS_FACTURABLE )
tot = 0
for t in trans:
if type(t) is Transaction:
tot += t.get_total()
if type(tot) is not Decimal:
tot = 0
return tot
def consigne(self):
trans = self.transactions()
tot = 0
for t in trans:
if type(t) is Transaction:
tot += t.get_consigne()
return tot
def get_total_template(self, template_path):
# Output the total of a Facture, with all the details
# If there is a template_path we return a response
# Otherwise we return a dict with all the values in it
pass
# Build a form with a product and the type of transaction a
# user can do. Hide the transaction form if there is only
# one possible TRANS_TYPE
def transaction_form(self):
form = TransactionForm({'Facture': self.id})
return form.as_ul( )
def transaction_details(self, template = 'transaction_details.html'):
trans = Transaction.objects.filter(Facture=self).order_by( 'Prix__Produit__id', 'Date' )
return render_to_string('facture/' + template, { 'transactions': trans, 'facture': self })
def get_taxes(self):
trans = self.transactions()
tot = []
tps = 0
tvq = 0
sub = 0
for t in trans:
if type(t) is Transaction:
txs = t.get_taxes()
tps += txs['TPS']
tvq += txs['TVQ']
sub += txs['sub']
tot.append(['Sous-total', sub])
tot.append(['TPS', tps])
tot.append(['TVQ', tvq])
return tot
def is_client_interne(self):
return self.Client.is_client_interne()
def get_id(self):
# Makes the ID based on user defined options
num = Option.get("Numéro facture")
prefix = Option.get("Préfixe facture")
try:
num = int(num)
except:
num = 0
num += self.id
id = prefix + str(num)
return id
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
if self.id:
if not GlobalUser.user.has_perm('biereapp.change_facture'):
raise Exception("Vous ne pouvez pas changer de Facture")
return False
else:
if not GlobalUser.user.has_perm('biereapp.add_facture'):
raise Exception("Vous ne pouvez pas ajouter de Facture")
return False
# Get Facture based on the number needed
user = BiereUser.as_current_user()
client = user.is_restricted_user()
if client:
if self.Client != client:
raise Exception("Vous ne pouvez pas faire cette action, méchant garnement, hors d'ici!")
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Facture, self).save()
def fermer(self):
# Wasn't closed before, so we send the mail
if not self.EstFermee:
mail_subject = render_to_string('mail/title.txt', {'facture': self})
mail_message = render_to_string('mail/content.html', {'facture': self})
mail_to = Option.get('Courriels')
mail_to = mail_to.split(',')
#send_mail(mail_subject, mail_message, '[email protected]',mail_to, fail_silently=False)
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(mail_subject, '', '[email protected]', mail_to)
msg.attach_alternative(mail_message, "text/html")
msg.send()
self.EstFermee = True
self.save()
class Meta:
permissions = (
("creer", "Peut creer des factures"),
("fermer", "Peut designer une facture comme payee"),
("crer_pour_lui", "Creer une facture pour seulement pour l'usage en cours"),
)
class Option(models.Model):
Nom = models.CharField(max_length=40)
Valeur = models.CharField(max_length=255)
Date = models.DateTimeField(auto_now_add=True)
@staticmethod
def get(option):
try:
valeur = Option.objects.filter(Nom=option)[0:1].get()
except:
return ''
return valeur.Valeur
def __unicode__(self):
return self.Nom + ': ' + self.Valeur
def save(self):
# Can we have a global user that we could put here, without having it passed
# as a parameter
try:
if self.id:
if not GlobalUser.user.has_perm('biereapp.change_option'):
raise Exception("Vous ne pouvez pas changer d'Option")
return False
else:
if not GlobalUser.user.has_perm('biereapp.add_option'):
raise Exception("Vous ne pouvez pas ajouter d'Option")
return False
except NameError:
raise Exception(u"Erreur fatale, le Middleware GlobalUser n'est pas actif, impossible de faire des sauvegardes.")
# Call the parent method
super(Option, self).save()
class Meta:
ordering = ('-Date', 'Nom')
class FactureForm(forms.ModelForm):
class Meta:
model = Facture
fields = ('Note','Client')
# Proxy model for User
class BiereUser(User):
@staticmethod
def as_current_user():
try:
u = BiereUser.objects.get(id=GlobalUser.user.id)
return u
except:
# Empty user
return BiereUser()
class Meta:
proxy = True
# Returns all the facture,
# returns the number if count is true
def get_facture(self, count=False):
bills = Facture.objects.filter(User=self).order_by('-Date')
if count:
return len(bills)
return bills
# returns a list of ferme Facture, returns the number
# if count is set to True
def get_facture_fermee(self, count = False):
bills = Facture.objects.filter(User=self, EstFermee=True).order_by('-Date')
if count:
return len(bills)
return bills
# Returned the rendered template to show
# a standardized list of Facture for the current
# user. We ask for a copy of GET but it can be any old
#QueryDict with a page index int it.
def show_user_facture(self, GET):
factures = self.get_facture()
number = self.get_facture(True)
paginator = Paginator(factures, 5)
number_fermee = self.get_facture_fermee(True)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
bills = paginator.page(page)
except (EmptyPage, InvalidPage):
bills = paginator.page(paginator.num_pages)
return render_to_string('snippets/user_facture.html', {'paged_factures': bills, 'user': self, 'nb_fact_tot': number, 'nb_fact_fermee': number_fermee})
def is_restricted_user(self):
try:
# We return the client, more efficient, enventhough misleading
client = Client.objects.filter(Nom=self.username)[0:1].get()
return client
except:
return False
class ProduitForm(forms.ModelForm):
class Meta:
model = Produit
class TransactionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TransactionForm, self).__init__(*args, **kwargs)
#self.fields['Facture'] = forms.CharField(facture.id,widget=forms.HiddenInput, initial=facture.id)
self.fields['Prix'].queryset = self.DiscriminateProduits()
def DiscriminateProduits(self):
user = GlobalUser.user
# Get the users' permissions
perms = ('',)
#for p in TYPE_TRANS:
# Loop permissions to check what kind of Prix you can get
if not user.has_perm('biereapp.add_permission'):
queryset = Prix.objects.exclude(Type='COST').exclude(Prive=True)
else:
queryset = Prix.objects.all()
return queryset
class Meta:
model = Transaction
fields = ['Type', 'Prix', 'Qte', 'Raison', 'Arbitraire', 'Facture' ]
class CommandeProduitForm(forms.Form):
# ToDo: Faire marcher la discrimination de produit
Type = forms.ChoiceField(choices=TYPE_TRANS, label="Type de transaction")
Prix = forms.ModelChoiceField(queryset=None, empty_label="Aucun produit", label="Produits disponibles")
Qte = forms.IntegerField(min_value=1, max_value=100, label="Quantité (max 100)")
Facture = forms.CharField(widget=forms.HiddenInput)
Arbitraire = forms.DecimalField(decimal_places=2)
Raison = forms.CharField()
def __init__(self, facture, *args, **kwargs):
# facture doit être une instance de la classe Facture
self.facture = facture
qs = self.DiscriminateProduits()
super(CommandeProduitForm, self).__init__(*args, **kwargs)
self.fields['Prix'].queryset = qs
self.fields['Facture'] = forms.CharField(facture.id,widget=forms.HiddenInput, initial=facture.id)
def DiscriminateProduits(self):
# Get the users' permissions
perms = ('',)
#for p in TYPE_TRANS:
# Loop permissions to check what kind of Prix you can get
#if self.user.has_perm('Prix.'+p[0]):
# perms = perms + (p[0],)
#queryset = Prix.objects.all().filter(Type__in=perms)
queryset = Prix.objects.all()
return queryset
def DiscriminateTransaction(self):
"""Select the kind of transaction a user can make"""
perms = ('',)
#for p in TYPE_PRIX:
# Loop permissions to check what kind of Prix you can get
#if self.user.has_perm('Prix.'+p[0]):
# perms = perms + (p[0],)
#queryset = Prix.objects.all().filter(Type__in=perms)
def __unicode__(self):
return super(CommandeProduitForm, self).__unicode__()
class ClientForm(forms.ModelForm):
class Meta:
model = Client
class PrixForm(forms.ModelForm):
class Meta:
model = Prix
widgets = {
'Produit': forms.HiddenInput(),
}