Commit 63d9df77 authored by Hamza Dely's avatar Hamza Dely

[consos/models] Les transactions sont jouées lors de leur enregistrement

parent d9a70dce
......@@ -135,6 +135,9 @@ class Transaction(models.Model):
null=True, blank=True, related_name="transactions_recues",
)
# Variables internes
_was_valid = False
class Meta:
default_permissions = []
permissions = [
......@@ -157,18 +160,40 @@ class Transaction(models.Model):
"L'émetteur et le destinataire d'une transaction doivent être distincts"
)
@classmethod
def from_db(cls, db, field_names, values):
instance = super(Transaction, cls).from_db(db, field_names, values)
instance._was_valid = instance.valide
return instance
@transaction.atomic
def _do_transaction(self):
if self.emetteur is not None:
self.emetteur.solde = models.F('solde') - self.quantite*self.montant
self.emetteur.save(update_fields=['solde'])
if self.destinataire is not None:
self.destinataire.solde = models.F('solde') + self.quantite*self.montant
self.destinataire.save(update_fields=['solde'])
@transaction.atomic
def _undo_transaction(self):
if self.destinataire is not None:
self.destinataire.solde = models.F('solde') - self.quantite*self.montant
self.destinataire.save(update_fields=['solde'])
if self.emetteur is not None:
self.emetteur.solde = models.F('solde') + self.quantite*self.montant
self.emetteur.save(update_fields=['solde'])
def save(self, *args, **kwargs):
"""
Enregistre la transaction et l'effectue si celle-ci est nouvelle
"""
if self.id is None:
if self.emetteur is not None:
self.emetteur.solde = models.F('solde') - self.quantite*self.montant
self.emetteur.save(update_fields=['solde'])
if self.destinataire is not None:
self.destinataire.solde = models.F('solde') + self.quantite*self.montant
self.destinataire.save(update_fields=['solde'])
if self.valide and not self._was_valid:
self._do_transaction()
elif not self.valide and self._was_valid:
self._undo_transaction()
self._was_valid = self.valide
super().save(*args, **kwargs)
class Bouton(models.Model):
......
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