Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

processing.py 9.2KB

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