您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

abstract_models.py 10KB

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