Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

models.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. from decimal import Decimal
  2. from django.db import models
  3. from django.template.defaultfilters import slugify
  4. from django.utils.translation import ugettext as _
  5. from django.conf import settings
  6. class Transaction(models.Model):
  7. """
  8. A transaction for payment sources which need a secondary 'transaction' to actually take the money
  9. This applies mainly to credit card sources which can be a pre-auth for the money. A 'complete'
  10. needs to be run later to debit the money from the account.
  11. """
  12. source = models.ForeignKey('payment.Source', related_name='transactions', verbose_name=_("Source"))
  13. # We define some sample types
  14. AUTHORISE, DEBIT, REFUND = 'Authorise', 'Debit', 'Refund'
  15. txn_type = models.CharField(_("Type"), max_length=128, blank=True)
  16. amount = models.DecimalField(_("Amount"), decimal_places=2, max_digits=12)
  17. reference = models.CharField(_("Reference"), max_length=128, null=True)
  18. status = models.CharField(_("Status"), max_length=128, null=True)
  19. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  20. def __unicode__(self):
  21. return _("%(type)s of %(amount).2f") % {'type': self.txn_type, 'amount': self.amount}
  22. class Meta:
  23. verbose_name = _("Transaction")
  24. verbose_name_plural = _("Transactions")
  25. class Source(models.Model):
  26. """
  27. A source of payment for an order.
  28. This is normally a credit card which has been pre-authed for the order
  29. amount, but some applications will allow orders to be paid for using
  30. multiple sources such as cheque, credit accounts, gift cards. Each payment
  31. source will have its own entry.
  32. """
  33. order = models.ForeignKey('order.Order', related_name='sources', verbose_name=_("Order"))
  34. source_type = models.ForeignKey('payment.SourceType', verbose_name=_("Source Type"))
  35. currency = models.CharField(_("Currency"), max_length=12, default=settings.OSCAR_DEFAULT_CURRENCY)
  36. # Track the various amounts associated with this source
  37. amount_allocated = models.DecimalField(_("Amount Allocated"), decimal_places=2, max_digits=12, default=Decimal('0.00'))
  38. amount_debited = models.DecimalField(_("Amount Debited"), decimal_places=2, max_digits=12, default=Decimal('0.00'))
  39. amount_refunded = models.DecimalField(_("Amount Refunded"), decimal_places=2, max_digits=12, default=Decimal('0.00'))
  40. # Reference number for this payment source. This is often used to look up a
  41. # transaction model for a particular payment partner.
  42. reference = models.CharField(_("Reference"), max_length=128, blank=True, null=True)
  43. # A customer-friendly label for the source, eg XXXX-XXXX-XXXX-1234
  44. label = models.CharField(_("Label"), max_length=128, blank=True, null=True)
  45. # A dictionary of submission data that is stored as part of the
  46. # checkout process.
  47. submission_data = None
  48. # We keep a list of deferred transactions that are only actually saved when
  49. # the source is saved for the first time
  50. deferred_txns = None
  51. class Meta:
  52. verbose_name = _("Source")
  53. verbose_name_plural = _("Sources")
  54. def __unicode__(self):
  55. description = _("Allocation of %(amount).2f from type %(type)s") % {
  56. 'amount': self.amount_allocated, 'type': self.source_type}
  57. if self.reference:
  58. description += _(" (reference: %s)") % self.reference
  59. return description
  60. def save(self, *args, **kwargs):
  61. super(Source, self).save(*args, **kwargs)
  62. if self.deferred_txns:
  63. for txn in self.deferred_txns:
  64. self._create_transaction(*txn)
  65. def balance(self):
  66. return self.amount_allocated - self.amount_debited + self.amount_refunded
  67. def create_deferred_transaction(self, txn_type, amount, reference=None, status=None):
  68. """
  69. Register the data for a transaction that can't be created yet due to FK
  70. constraints. This happens at checkout where create an payment source and a
  71. transaction but can't save them until the order model exists.
  72. """
  73. if self.deferred_txns is None:
  74. self.deferred_txns = []
  75. self.deferred_txns.append((txn_type, amount, reference, status))
  76. def _create_transaction(self, txn_type, amount, reference=None, status=None):
  77. Transaction.objects.create(source=self,
  78. txn_type=txn_type,
  79. amount=amount,
  80. reference=reference,
  81. status=status)
  82. def allocate(self, amount, reference=None, status=None):
  83. """
  84. Convenience method for ring-fencing money against this source
  85. """
  86. self.amount_allocated += amount
  87. self.save()
  88. self._create_transaction(Transaction.AUTHORISE, amount, reference, status)
  89. def debit(self, amount=None, reference=None, status=None):
  90. """
  91. Convenience method for recording debits against this source
  92. """
  93. if amount is None:
  94. amount = self.balance()
  95. self.amount_debited += amount
  96. self.save()
  97. self._create_transaction(Transaction.DEBIT, amount, reference, status)
  98. def refund(self, amount, reference=None, status=None):
  99. """
  100. Convenience method for recording refunds against this source
  101. """
  102. self.amount_refunded += amount
  103. self.save()
  104. self._create_transaction(Transaction.REFUND, amount, reference, status)
  105. @property
  106. def amount_available_for_refund(self):
  107. """
  108. Return the amount available to be refunded
  109. """
  110. return self.amount_debited - self.amount_refunded
  111. class SourceType(models.Model):
  112. """
  113. A type of payment source.
  114. This could be an external partner like PayPal or DataCash,
  115. or an internal source such as a managed account.i
  116. """
  117. name = models.CharField(_("Name"), max_length=128)
  118. code = models.SlugField(_("Code"), max_length=128, help_text=_("""This is used within
  119. forms to identify this source type"""))
  120. class Meta:
  121. verbose_name = _("Source Type")
  122. verbose_name_plural = _("Source Types")
  123. def __unicode__(self):
  124. return self.name
  125. def save(self, *args, **kwargs):
  126. if not self.code:
  127. self.code = slugify(self.name)
  128. super(SourceType, self).save(*args, **kwargs)
  129. class Bankcard(models.Model):
  130. user = models.ForeignKey('auth.User', related_name='bankcards', verbose_name=_("User"))
  131. card_type = models.CharField(_("Card Type"), max_length=128)
  132. name = models.CharField(_("Name"), max_length=255)
  133. number = models.CharField(_("Number"), max_length=32)
  134. expiry_date = models.DateField(_("Expiry Date"))
  135. # For payment partners who are storing the full card details for us
  136. partner_reference = models.CharField(_("Partner Reference"), max_length=255, null=True, blank=True)
  137. class Meta:
  138. verbose_name = _("Bankcard")
  139. verbose_name_plural = _("Bankcards")
  140. def save(self, *args, **kwargs):
  141. self.number = self._get_obfuscated_number()
  142. super(Bankcard, self).save(*args, **kwargs)
  143. def _get_obfuscated_number(self):
  144. return u"XXXX-XXXX-XXXX-%s" % self.number[-4:]