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.

processing.py 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. from decimal import Decimal as D
  2. from django.db.models.loading import get_model
  3. from django.utils.translation import ugettext_lazy as _
  4. from oscar.apps.order import exceptions
  5. ShippingEventQuantity = get_model('order', 'ShippingEventQuantity')
  6. PaymentEventQuantity = get_model('order', 'PaymentEventQuantity')
  7. class EventHandler(object):
  8. """
  9. Handle requested order events.
  10. This is an important class: it houses the core logic of your shop's order
  11. processing pipeline.
  12. """
  13. # Core API
  14. # --------
  15. def handle_shipping_event(self, order, event_type, lines,
  16. line_quantities, **kwargs):
  17. """
  18. Handle a shipping event for a given order.
  19. This is most common entry point to this class - most of your order
  20. processing should be modelled around shipping events.
  21. This might involve taking payment, sending messages and
  22. creating the event models themeselves. You will generally want to
  23. override this method to implement the specifics of you order processing
  24. pipeline.
  25. """
  26. self.validate_shipping_event(
  27. order, event_type, lines, line_quantities, **kwargs)
  28. self.create_shipping_event(
  29. order, event_type, lines, line_quantities, **kwargs)
  30. def handle_payment_event(self, order, event_type, amount, lines=None,
  31. line_quantities=None, **kwargs):
  32. """
  33. Handle a payment event for a given order.
  34. These should normally be called as part of handling a shipping event.
  35. It is rare to call to this method directly. It does make sense for
  36. refunds though where the payment event may be unrelated to a particualr
  37. shipping event and doesn't directly correspond to a set of lines.
  38. """
  39. self.validate_payment_event(
  40. order, event_type, amount, lines, line_quantities, **kwargs)
  41. self.create_payment_event(order, event_type, amount, lines,
  42. line_quantities, **kwargs)
  43. def handle_order_status_change(self, order, new_status):
  44. """
  45. Handle a requested order status change
  46. """
  47. order.set_status(new_status)
  48. # Validation methods
  49. # ------------------
  50. def validate_shipping_event(self, order, event_type, lines,
  51. line_quantities, **kwargs):
  52. """
  53. Test if the requested shipping event is permitted.
  54. If not, raise InvalidShippingEvent
  55. """
  56. errors = []
  57. for line, qty in zip(lines, line_quantities):
  58. # The core logic should be in the model. Ensure you override
  59. # 'is_shipping_event_permitted' and enforce the correct order of
  60. # shipping events.
  61. if not line.is_shipping_event_permitted(event_type, qty):
  62. msg = _("The selected quantity for line #%(line_id)s is too large") % {
  63. 'line_id': line.id}
  64. errors.append(msg)
  65. if errors:
  66. raise exceptions.InvalidShippingEvent(", ".join(errors))
  67. def validate_payment_event(self, order, event_type, lines,
  68. line_quantities, **kwargs):
  69. errors = []
  70. for line, qty in zip(lines, line_quantities):
  71. if not line.is_payment_event_permitted(event_type, qty):
  72. msg = _("The selected quantity for line #%(line_id)s is too large") % {
  73. 'line_id': line.id}
  74. errors.append(msg)
  75. if errors:
  76. raise exceptions.InvalidPaymentEvent(", ".join(errors))
  77. # Query methods
  78. # -------------
  79. # These are to help determine the status of lines
  80. def have_lines_passed_shipping_event(self, order, lines, line_quantities,
  81. event_type):
  82. """
  83. Test whether the passed lines and quantities have been through the
  84. specified shipping event.
  85. This is useful for validating if certain shipping events are allowed
  86. (ie you can't return something before it has shipped).
  87. """
  88. for line, line_qty in zip(lines, line_quantities):
  89. if line.shipping_event_quantity(event_type) < line_qty:
  90. return False
  91. return True
  92. # Payment stuff
  93. def calculate_payment_event_subtotal(self, event_type, lines,
  94. line_quantities):
  95. """
  96. Calculate the total charge for the passed event type, lines and line
  97. quantities.
  98. This takes into account the previous prices that have been charged for
  99. this event.
  100. """
  101. total = D('0.00')
  102. for line, qty_to_consume in zip(lines, line_quantities):
  103. # This part is quite fiddly. We need to skip the prices that have
  104. # already been settled. This involves keeping a load of counters.
  105. # Count how many of this line have already been involved in an
  106. # event of this type.
  107. qty_to_skip = line.payment_event_quantity(event_type)
  108. # Test if request is sensible
  109. if qty_to_skip + qty_to_consume > line.quantity:
  110. raise exceptions.InvalidPaymentEvent
  111. # Consume prices in order of ID (this is the default but it's
  112. # better to be explicit)
  113. qty_consumed = 0
  114. for price in line.prices.all().order_by('id'):
  115. if qty_consumed == qty_to_consume:
  116. # We've accounted for the asked-for quantity: we're done
  117. break
  118. qty_available = price.quantity - qty_to_skip
  119. if qty_available <= 0:
  120. # Skip the whole quantity of this price instance
  121. qty_to_skip -= price.quantity
  122. else:
  123. # Need to account for some of this price instance and
  124. # track how many we needed to skip and how many we settled
  125. # for.
  126. qty_to_include = min(
  127. qty_to_consume - qty_consumed, qty_available)
  128. total += qty_to_include * price.price_incl_tax
  129. # There can't be any left to skip if we've included some in
  130. # our total
  131. qty_to_skip = 0
  132. qty_consumed += qty_to_include
  133. return total
  134. # Stock stuff
  135. def are_stock_allocations_available(self, lines, line_quantities):
  136. """
  137. Check whether stock records still have enough stock to honour the
  138. requested allocations.
  139. """
  140. for line, qty in zip(lines, line_quantities):
  141. record = line.product.stockrecord
  142. if not record.is_allocation_consumption_possible(qty):
  143. return False
  144. return True
  145. def consume_stock_allocations(self, order, lines, line_quantities):
  146. """
  147. Consume the stock allocations for the passed lines
  148. """
  149. for line, qty in zip(lines, line_quantities):
  150. if line.product:
  151. line.product.stockrecord.consume_allocation(qty)
  152. def cancel_stock_allocations(self, order, lines, line_quantities):
  153. """
  154. Cancel the stock allocations for the passed lines
  155. """
  156. for line, qty in zip(lines, line_quantities):
  157. line.product.stockrecord.cancel_allocation(qty)
  158. # Create event instances
  159. def create_shipping_event(self, order, event_type, lines, line_quantities,
  160. **kwargs):
  161. reference = kwargs.get('reference', None)
  162. event = order.shipping_events.create(
  163. event_type=event_type, notes=reference)
  164. try:
  165. for line, quantity in zip(lines, line_quantities):
  166. event.line_quantities.create(
  167. line=line, quantity=quantity)
  168. except exceptions.InvalidShippingEvent:
  169. event.delete()
  170. raise
  171. return event
  172. def create_payment_event(self, order, event_type, amount, lines=None,
  173. line_quantities=None, **kwargs):
  174. event = order.payment_events.create(
  175. event_type=event_type, amount=amount)
  176. if lines and line_quantities:
  177. for line, quantity in zip(lines, line_quantities):
  178. PaymentEventQuantity.objects.create(
  179. event=event, line=line, quantity=quantity)
  180. return event
  181. def create_communication_event(self, order, event_type):
  182. return order.communication_events.create(event_type=event_type)
  183. def create_note(self, order, message, note_type='System'):
  184. return order.notes.create(message=message, note_type=note_type)