You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abstract_models.py 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. from django.db import models
  2. from django.conf import settings
  3. from django.utils.translation import ugettext_lazy as _, pgettext_lazy
  4. from oscar.core.compat import AUTH_USER_MODEL
  5. from oscar.models.fields import AutoSlugField
  6. from oscar.apps.partner.exceptions import InvalidStockAdjustment
  7. class AbstractPartner(models.Model):
  8. """
  9. A fulfillment partner. An individual or company who can fulfil products.
  10. E.g. for physical goods, somebody with a warehouse and means of delivery.
  11. Creating one or more instances of the Partner model is a required step in
  12. setting up an Oscar deployment. Many Oscar deployments will only have one
  13. fulfillment partner.
  14. """
  15. code = AutoSlugField(_("Code"), max_length=128, unique=True,
  16. populate_from='name')
  17. name = models.CharField(
  18. pgettext_lazy(u"Partner's name", u"Name"), max_length=128, blank=True)
  19. #: A partner can have users assigned to it. This is used
  20. #: for access modelling in the permission-based dashboard
  21. users = models.ManyToManyField(
  22. AUTH_USER_MODEL, related_name="partners",
  23. blank=True, null=True, verbose_name=_("Users"))
  24. @property
  25. def display_name(self):
  26. return self.name or self.code
  27. @property
  28. def primary_address(self):
  29. """
  30. Returns a partners primary address. Usually that will be the
  31. headquarters or similar.
  32. This is a rudimentary implementation that raises an error if there's
  33. more than one address. If you actually want to support multiple
  34. addresses, you will likely need to extend PartnerAddress to have some
  35. field or flag to base your decision on.
  36. """
  37. addresses = self.addresses.all()
  38. if len(addresses) == 0: # intentionally using len() to save queries
  39. return None
  40. elif len(addresses) == 1:
  41. return addresses[0]
  42. else:
  43. raise NotImplementedError(
  44. "Oscar's default implementation of primary_address only "
  45. "supports one PartnerAddress. You need to override the "
  46. "primary_address to look up the right address")
  47. def get_address_for_stockrecord(self, stockrecord):
  48. """
  49. Stock might be coming from different warehouses. Overriding this
  50. function allows selecting the correct PartnerAddress for the record.
  51. That can be useful when determining tax.
  52. """
  53. return self.primary_address
  54. class Meta:
  55. permissions = (('dashboard_access', _('Can access dashboard')), )
  56. verbose_name = _('Fulfillment partner')
  57. verbose_name_plural = _('Fulfillment partners')
  58. abstract = True
  59. def __unicode__(self):
  60. return self.display_name
  61. class AbstractStockRecord(models.Model):
  62. """
  63. A stock record.
  64. This records information about a product from a fulfilment partner, such as
  65. their SKU, the number they have in stock and price information.
  66. Stockrecords are used by 'strategies' to determine availability and pricing
  67. information for the customer.
  68. """
  69. product = models.ForeignKey(
  70. 'catalogue.Product', related_name="stockrecords",
  71. verbose_name=_("Product"))
  72. partner = models.ForeignKey(
  73. 'partner.Partner', verbose_name=_("Partner"),
  74. related_name='stockrecords')
  75. #: The fulfilment partner will often have their own SKU for a product,
  76. #: which we store here. This will sometimes be the same the product's UPC
  77. #: but not always. It should be unique per partner.
  78. #: See also http://en.wikipedia.org/wiki/Stock-keeping_unit
  79. partner_sku = models.CharField(_("Partner SKU"), max_length=128)
  80. # Price info:
  81. price_currency = models.CharField(
  82. _("Currency"), max_length=12, default=settings.OSCAR_DEFAULT_CURRENCY)
  83. # This is the base price for calculations - tax should be applied by the
  84. # appropriate method. We don't store tax here as its calculation is highly
  85. # domain-specific. It is NULLable because some items don't have a fixed
  86. # price but require a runtime calculation (possible from an external
  87. # service).
  88. price_excl_tax = models.DecimalField(
  89. _("Price (excl. tax)"), decimal_places=2, max_digits=12,
  90. blank=True, null=True)
  91. #: Retail price for this item. This is simply the recommended price from
  92. #: the manufacturer. If this is used, it is for display purposes only.
  93. #: This prices is the NOT the price charged to the customer.
  94. price_retail = models.DecimalField(
  95. _("Price (retail)"), decimal_places=2, max_digits=12,
  96. blank=True, null=True)
  97. #: Cost price is the price charged by the fulfilment partner. It is not
  98. #: used (by default) in any price calculations but is often used in
  99. #: reporting so merchants can report on their profit margin.
  100. cost_price = models.DecimalField(
  101. _("Cost Price"), decimal_places=2, max_digits=12,
  102. blank=True, null=True)
  103. #: Number of items in stock
  104. num_in_stock = models.PositiveIntegerField(
  105. _("Number in stock"), blank=True, null=True)
  106. #: The amount of stock allocated to orders but not fed back to the master
  107. #: stock system. A typical stock update process will set the num_in_stock
  108. #: variable to a new value and reset num_allocated to zero
  109. num_allocated = models.IntegerField(
  110. _("Number allocated"), blank=True, null=True)
  111. #: Threshold for low-stock alerts. When stock goes beneath this threshold,
  112. #: an alert is triggered so warehouse managers can order more.
  113. low_stock_threshold = models.PositiveIntegerField(
  114. _("Low Stock Threshold"), blank=True, null=True)
  115. # Date information
  116. date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  117. date_updated = models.DateTimeField(_("Date updated"), auto_now=True,
  118. db_index=True)
  119. def __unicode__(self):
  120. msg = u"Partner: %s, product: %s" % (
  121. self.partner.display_name, self.product,)
  122. if self.partner_sku:
  123. msg = u"%s (%s)" % (msg, self.partner_sku)
  124. return msg
  125. class Meta:
  126. abstract = True
  127. unique_together = ('partner', 'partner_sku')
  128. verbose_name = _("Stock record")
  129. verbose_name_plural = _("Stock records")
  130. @property
  131. def net_stock_level(self):
  132. """
  133. The effective number in stock (eg available to buy).
  134. This is correct property to show the customer, not the num_in_stock
  135. field as that doesn't account for allocations. This can be negative in
  136. some unusual circumstances
  137. """
  138. if self.num_in_stock is None:
  139. return 0
  140. if self.num_allocated is None:
  141. return self.num_in_stock
  142. return self.num_in_stock - self.num_allocated
  143. # 2-stage stock management model
  144. def allocate(self, quantity):
  145. """
  146. Record a stock allocation.
  147. This normally happens when a product is bought at checkout. When the
  148. product is actually shipped, then we 'consume' the allocation.
  149. """
  150. if self.num_allocated is None:
  151. self.num_allocated = 0
  152. self.num_allocated += quantity
  153. self.save()
  154. allocate.alters_data = True
  155. def is_allocation_consumption_possible(self, quantity):
  156. """
  157. Test if a proposed stock consumption is permitted
  158. """
  159. return quantity <= min(self.num_allocated, self.num_in_stock)
  160. def consume_allocation(self, quantity):
  161. """
  162. Consume a previous allocation
  163. This is used when an item is shipped. We remove the original
  164. allocation and adjust the number in stock accordingly
  165. """
  166. if not self.is_allocation_consumption_possible(quantity):
  167. raise InvalidStockAdjustment(
  168. _('Invalid stock consumption request'))
  169. self.num_allocated -= quantity
  170. self.num_in_stock -= quantity
  171. self.save()
  172. consume_allocation.alters_data = True
  173. def cancel_allocation(self, quantity):
  174. # We ignore requests that request a cancellation of more than the
  175. # amount already allocated.
  176. self.num_allocated -= min(self.num_allocated, quantity)
  177. self.save()
  178. cancel_allocation.alters_data = True
  179. @property
  180. def is_below_threshold(self):
  181. if self.low_stock_threshold is None:
  182. return False
  183. return self.net_stock_level < self.low_stock_threshold
  184. class AbstractStockAlert(models.Model):
  185. """
  186. A stock alert. E.g. used to notify users when a product is 'back in stock'.
  187. """
  188. stockrecord = models.ForeignKey(
  189. 'partner.StockRecord', related_name='alerts',
  190. verbose_name=_("Stock Record"))
  191. threshold = models.PositiveIntegerField(_("Threshold"))
  192. OPEN, CLOSED = "Open", "Closed"
  193. status_choices = (
  194. (OPEN, _("Open")),
  195. (CLOSED, _("Closed")),
  196. )
  197. status = models.CharField(_("Status"), max_length=128, default=OPEN,
  198. choices=status_choices)
  199. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  200. date_closed = models.DateTimeField(_("Date Closed"), blank=True, null=True)
  201. def close(self):
  202. self.status = self.CLOSED
  203. self.save()
  204. close.alters_data = True
  205. def __unicode__(self):
  206. return _('<stockalert for "%(stock)s" status %(status)s>') \
  207. % {'stock': self.stockrecord, 'status': self.status}
  208. class Meta:
  209. abstract = True
  210. ordering = ('-date_created',)
  211. verbose_name = _('Stock Alert')
  212. verbose_name_plural = _('Stock Alerts')