Files
@ e9ebf5da03ea
Branch filter:
Location: symposion_app/registrasion/models/commerce.py
e9ebf5da03ea
8.8 KiB
text/x-python
Writes inventory and overview documentation, and updates docstrings on a LOT of modules.
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 | from . import conditions
from . import inventory
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import F, Q
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from model_utils.managers import InheritanceManager
# Commerce Models
@python_2_unicode_compatible
class Cart(models.Model):
''' Represents a set of product items that have been purchased, or are
pending purchase. '''
class Meta:
app_label = "registrasion"
index_together = [
("active", "time_last_updated"),
("active", "released"),
("active", "user"),
("released", "user"),
]
def __str__(self):
return "%d rev #%d" % (self.id, self.revision)
user = models.ForeignKey(User)
# ProductItems (foreign key)
vouchers = models.ManyToManyField(inventory.Voucher, blank=True)
time_last_updated = models.DateTimeField(
db_index=True,
)
reservation_duration = models.DurationField()
revision = models.PositiveIntegerField(default=1)
active = models.BooleanField(
default=True,
db_index=True,
)
released = models.BooleanField(
default=False,
db_index=True
) # Refunds etc
@classmethod
def reserved_carts(cls):
''' Gets all carts that are 'reserved' '''
return Cart.objects.filter(
(Q(active=True) &
Q(time_last_updated__gt=(
timezone.now()-F('reservation_duration')
))) |
(Q(active=False) & Q(released=False))
)
@python_2_unicode_compatible
class ProductItem(models.Model):
''' Represents a product-quantity pair in a Cart. '''
class Meta:
app_label = "registrasion"
ordering = ("product", )
def __str__(self):
return "product: %s * %d in Cart: %s" % (
self.product, self.quantity, self.cart)
cart = models.ForeignKey(Cart)
product = models.ForeignKey(inventory.Product)
quantity = models.PositiveIntegerField(db_index=True)
@python_2_unicode_compatible
class DiscountItem(models.Model):
''' Represents a discount-product-quantity relation in a Cart. '''
class Meta:
app_label = "registrasion"
ordering = ("product", )
def __str__(self):
return "%s: %s * %d in Cart: %s" % (
self.discount, self.product, self.quantity, self.cart)
cart = models.ForeignKey(Cart)
product = models.ForeignKey(inventory.Product)
discount = models.ForeignKey(conditions.DiscountBase)
quantity = models.PositiveIntegerField()
@python_2_unicode_compatible
class Invoice(models.Model):
''' An invoice. Invoices can be automatically generated when checking out
a Cart, in which case, it is attached to a given revision of a Cart. '''
class Meta:
app_label = "registrasion"
STATUS_UNPAID = 1
STATUS_PAID = 2
STATUS_REFUNDED = 3
STATUS_VOID = 4
STATUS_TYPES = [
(STATUS_UNPAID, _("Unpaid")),
(STATUS_PAID, _("Paid")),
(STATUS_REFUNDED, _("Refunded")),
(STATUS_VOID, _("VOID")),
]
def __str__(self):
return "Invoice #%d" % self.id
def clean(self):
if self.cart is not None and self.cart_revision is None:
raise ValidationError(
"If this is a cart invoice, it must have a revision")
@property
def is_unpaid(self):
return self.status == self.STATUS_UNPAID
@property
def is_void(self):
return self.status == self.STATUS_VOID
@property
def is_paid(self):
return self.status == self.STATUS_PAID
@property
def is_refunded(self):
return self.status == self.STATUS_REFUNDED
# Invoice Number
user = models.ForeignKey(User)
cart = models.ForeignKey(Cart, null=True)
cart_revision = models.IntegerField(
null=True,
db_index=True,
)
# Line Items (foreign key)
status = models.IntegerField(
choices=STATUS_TYPES,
db_index=True,
)
recipient = models.CharField(max_length=1024)
issue_time = models.DateTimeField()
due_time = models.DateTimeField()
value = models.DecimalField(max_digits=8, decimal_places=2)
@python_2_unicode_compatible
class LineItem(models.Model):
''' Line items for an invoice. These are denormalised from the ProductItems
and DiscountItems that belong to a cart (for consistency), but also allow
for arbitrary line items when required. '''
class Meta:
app_label = "registrasion"
ordering = ("id", )
def __str__(self):
return "Line: %s * %d @ %s" % (
self.description, self.quantity, self.price)
invoice = models.ForeignKey(Invoice)
description = models.CharField(max_length=255)
quantity = models.PositiveIntegerField()
price = models.DecimalField(max_digits=8, decimal_places=2)
product = models.ForeignKey(inventory.Product, null=True, blank=True)
@python_2_unicode_compatible
class PaymentBase(models.Model):
''' The base payment type for invoices. Payment apps should subclass this
class to handle implementation-specific issues. '''
class Meta:
ordering = ("time", )
objects = InheritanceManager()
def __str__(self):
return "Payment: ref=%s amount=%s" % (self.reference, self.amount)
invoice = models.ForeignKey(Invoice)
time = models.DateTimeField(default=timezone.now)
reference = models.CharField(max_length=255)
amount = models.DecimalField(max_digits=8, decimal_places=2)
class ManualPayment(PaymentBase):
''' Payments that are manually entered by staff. '''
class Meta:
app_label = "registrasion"
class CreditNote(PaymentBase):
''' Credit notes represent money accounted for in the system that do not
belong to specific invoices. They may be paid into other invoices, or
cashed out as refunds.
Each CreditNote may either be used to pay towards another Invoice in the
system (by attaching a CreditNoteApplication), or may be marked as
refunded (by attaching a CreditNoteRefund).'''
class Meta:
app_label = "registrasion"
@classmethod
def unclaimed(cls):
return cls.objects.filter(
creditnoteapplication=None,
creditnoterefund=None,
)
@property
def status(self):
if self.is_unclaimed:
return "Unclaimed"
if hasattr(self, 'creditnoteapplication'):
destination = self.creditnoteapplication.invoice.id
return "Applied to invoice %d" % destination
elif hasattr(self, 'creditnoterefund'):
reference = self.creditnoterefund.reference
print reference
return "Refunded with reference: %s" % reference
raise ValueError("This should never happen.")
@property
def is_unclaimed(self):
return not (
hasattr(self, 'creditnoterefund') or
hasattr(self, 'creditnoteapplication')
)
@property
def value(self):
''' Returns the value of the credit note. Because CreditNotes are
implemented as PaymentBase objects internally, the amount is a
negative payment against an invoice. '''
return -self.amount
class CleanOnSave(object):
def save(self, *a, **k):
self.full_clean()
super(CleanOnSave, self).save(*a, **k)
class CreditNoteApplication(CleanOnSave, PaymentBase):
''' Represents an application of a credit note to an Invoice. '''
class Meta:
app_label = "registrasion"
def clean(self):
if not hasattr(self, "parent"):
return
if hasattr(self.parent, 'creditnoterefund'):
raise ValidationError(
"Cannot apply a refunded credit note to an invoice"
)
parent = models.OneToOneField(CreditNote)
class CreditNoteRefund(CleanOnSave, models.Model):
''' Represents a refund of a credit note to an external payment.
Credit notes may only be refunded in full. How those refunds are handled
is left as an exercise to the payment app. '''
def clean(self):
if not hasattr(self, "parent"):
return
if hasattr(self.parent, 'creditnoteapplication'):
raise ValidationError(
"Cannot refund a credit note that has been paid to an invoice"
)
parent = models.OneToOneField(CreditNote)
time = models.DateTimeField(default=timezone.now)
reference = models.CharField(max_length=255)
class ManualCreditNoteRefund(CreditNoteRefund):
''' Credit notes that are entered by a staff member. '''
class Meta:
app_label = "registrasion"
entered_by = models.ForeignKey(User)
|