選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

abstract_models.py 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. from decimal import Decimal as D
  2. from django.conf import settings
  3. from django.db import models
  4. from django.utils.translation import ugettext_lazy as _
  5. from django.utils.importlib import import_module as django_import_module
  6. from oscar.core.loading import get_class
  7. from oscar.apps.partner.exceptions import InvalidStockAdjustment
  8. DefaultWrapper = get_class('partner.wrappers', 'DefaultWrapper')
  9. # Cache the partners for quicklookups
  10. default_wrapper = DefaultWrapper()
  11. partner_wrappers = {}
  12. for partner, class_str in settings.OSCAR_PARTNER_WRAPPERS.items():
  13. bits = class_str.split('.')
  14. class_name = bits.pop()
  15. module_str = '.'.join(bits)
  16. module = django_import_module(module_str)
  17. partner_wrappers[partner] = getattr(module, class_name)()
  18. def get_partner_wrapper(partner_name):
  19. """
  20. Returns the appropriate partner wrapper given the partner name
  21. """
  22. return partner_wrappers.get(partner_name, default_wrapper)
  23. class AbstractPartner(models.Model):
  24. """
  25. Fulfillment partner
  26. """
  27. name = models.CharField(max_length=128, unique=True)
  28. # A partner can have users assigned to it. These can be used
  29. # to provide authentication for webservices etc.
  30. users = models.ManyToManyField('auth.User', related_name="partners", blank=True, null=True)
  31. class Meta:
  32. verbose_name_plural = 'Fulfillment partners'
  33. abstract = True
  34. permissions = (
  35. ("can_edit_stock_records", "Can edit stock records"),
  36. ("can_view_stock_records", "Can view stock records"),
  37. ("can_edit_product_range", "Can edit product range"),
  38. ("can_view_product_range", "Can view product range"),
  39. ("can_edit_order_lines", "Can edit order lines"),
  40. ("can_view_order_lines", "Can view order lines"),
  41. )
  42. def __unicode__(self):
  43. return self.name
  44. class AbstractStockRecord(models.Model):
  45. """
  46. A basic stock record.
  47. This links a product to a partner, together with price and availability
  48. information. Most projects will need to subclass this object to add custom
  49. fields such as lead_time, report_code, min_quantity.
  50. We deliberately don't store tax information to allow each project
  51. to subclass this model and put its own fields for convey tax.
  52. """
  53. product = models.OneToOneField('catalogue.Product', related_name="stockrecord")
  54. partner = models.ForeignKey('partner.Partner')
  55. # The fulfilment partner will often have their own SKU for a product, which
  56. # we store here.
  57. partner_sku = models.CharField(_("Partner SKU"), max_length=128)
  58. # Price info:
  59. price_currency = models.CharField(max_length=12, default=settings.OSCAR_DEFAULT_CURRENCY)
  60. # This is the base price for calculations - tax should be applied
  61. # by the appropriate method. We don't store it here as its calculation is
  62. # highly domain-specific. It is NULLable because some items don't have a fixed
  63. # price.
  64. price_excl_tax = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True)
  65. # Retail price for this item
  66. price_retail = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True)
  67. # Cost price is optional as not all partners supply it
  68. cost_price = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True)
  69. # Stock level information
  70. num_in_stock = models.PositiveIntegerField(default=0, blank=True, null=True)
  71. # Threshold for low-stock alerts
  72. low_stock_threshold = models.PositiveIntegerField(blank=True, null=True)
  73. # The amount of stock allocated to orders but not fed back to the master
  74. # stock system. A typical stock update process will set the num_in_stock
  75. # variable to a new value and reset num_allocated to zero
  76. num_allocated = models.IntegerField(default=0, blank=True, null=True)
  77. # Date information
  78. date_created = models.DateTimeField(auto_now_add=True)
  79. date_updated = models.DateTimeField(auto_now=True, db_index=True)
  80. class Meta:
  81. abstract = True
  82. unique_together = ('partner', 'partner_sku')
  83. # 2-stage stock management model
  84. def allocate(self, quantity):
  85. """
  86. Record a stock allocation.
  87. This normally happens when a product is bought at checkout. When the
  88. product is actually shipped, then we 'consume' the allocation.
  89. """
  90. self.num_allocated = int(self.num_allocated)
  91. self.num_allocated += quantity
  92. self.save()
  93. def is_allocation_consumption_possible(self, quantity):
  94. return quantity <= min(self.num_allocated, self.num_in_stock)
  95. def consume_allocation(self, quantity):
  96. """
  97. Consume a previous allocation
  98. This is used when an item is shipped. We remove the original allocation
  99. and adjust the number in stock accordingly
  100. """
  101. if not self.is_allocation_consumption_possible(quantity):
  102. raise InvalidStockAdjustment('Invalid stock consumption request')
  103. self.num_allocated -= quantity
  104. self.num_in_stock -= quantity
  105. self.save()
  106. def cancel_allocation(self, quantity):
  107. # We ignore requests that request a cancellation of more than the amount already
  108. # allocated.
  109. self.num_allocated -= min(self.num_allocated, quantity)
  110. self.save()
  111. @property
  112. def net_stock_level(self):
  113. """
  114. Return the effective number in stock. This is correct property to show
  115. the customer, not the num_in_stock field as that doesn't account for
  116. allocations. This can be negative in some unusual circumstances
  117. """
  118. if self.num_in_stock is None:
  119. return 0
  120. if self.num_allocated is None:
  121. return self.num_in_stock
  122. return self.num_in_stock - self.num_allocated
  123. def set_discount_price(self, price):
  124. """
  125. A setter method for setting a new price.
  126. This is called from within the "discount" app, which is responsible
  127. for applying fixed-discount offers to products. We use a setter method
  128. so that this behaviour can be customised in projects.
  129. """
  130. self.price_excl_tax = price
  131. self.save()
  132. # Price retrieval methods - these default to no tax being applicable
  133. # These are intended to be overridden.
  134. @property
  135. def is_available_to_buy(self):
  136. """
  137. Return whether this stockrecord allows the product to be purchased
  138. """
  139. return get_partner_wrapper(self.partner.name).is_available_to_buy(self)
  140. def is_purchase_permitted(self, user=None, quantity=1):
  141. """
  142. Return whether this stockrecord allows the product to be purchased by a
  143. specific user and quantity
  144. """
  145. return get_partner_wrapper(self.partner.name).is_purchase_permitted(self, user, quantity)
  146. @property
  147. def is_below_threshold(self):
  148. if self.low_stock_threshold is None:
  149. return False
  150. return self.net_stock_level < self.low_stock_threshold
  151. @property
  152. def availability_code(self):
  153. """
  154. Return an product's availability as a code for use in CSS to add icons
  155. to the overall availability mark-up. For example, "instock",
  156. "unavailable".
  157. """
  158. return get_partner_wrapper(self.partner.name).availability_code(self)
  159. @property
  160. def availability(self):
  161. """
  162. Return a product's availability as a string that can be displayed to the
  163. user. For example, "In stock", "Unavailabl".
  164. """
  165. return get_partner_wrapper(self.partner.name).availability(self)
  166. def max_purchase_quantity(self, user=None):
  167. """
  168. Return an item's availability as a string
  169. :param user: (optional) The user who wants to purchase
  170. """
  171. return get_partner_wrapper(self.partner.name).max_purchase_quantity(self, user)
  172. @property
  173. def dispatch_date(self):
  174. """
  175. Return the estimated dispatch date for a line
  176. """
  177. return get_partner_wrapper(self.partner.name).dispatch_date(self)
  178. @property
  179. def lead_time(self):
  180. return get_partner_wrapper(self.partner.name).lead_time(self)
  181. @property
  182. def price_incl_tax(self):
  183. """
  184. Return a product's price including tax.
  185. This defaults to the price_excl_tax as tax calculations are
  186. domain specific. This class needs to be subclassed and tax logic
  187. added to this method.
  188. """
  189. if self.price_excl_tax is None:
  190. return D('0.00')
  191. return self.price_excl_tax + self.price_tax
  192. @property
  193. def price_tax(self):
  194. """
  195. Return a product's tax value
  196. """
  197. return get_partner_wrapper(self.partner.name).calculate_tax(self)
  198. def __unicode__(self):
  199. if self.partner_sku:
  200. return "%s (%s): %s" % (self.partner.name, self.partner_sku, self.product.title)
  201. else:
  202. return "%s: %s" % (self.partner.name, self.product.title)
  203. class AbstractStockAlert(models.Model):
  204. stockrecord = models.ForeignKey('partner.StockRecord', related_name='alerts')
  205. threshold = models.PositiveIntegerField()
  206. OPEN, CLOSED = 'Open', 'Closed'
  207. status_choices = (
  208. (OPEN, _('Open')),
  209. (CLOSED, _('Closed')),
  210. )
  211. status = models.CharField(max_length=128, default=OPEN, choices=status_choices)
  212. date_created = models.DateTimeField(auto_now_add=True)
  213. date_closed = models.DateTimeField(blank=True, null=True)
  214. def close(self):
  215. self.status = self.CLOSED
  216. self.save()
  217. def __unicode__(self):
  218. return u'<stockalert for "%s" status %s>' % (self.stockrecord,
  219. self.status)
  220. class Meta:
  221. ordering = ('-date_created',)