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.

utils.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. from django.contrib.sites.models import Site
  2. from django.conf import settings
  3. from django.db.models import get_model
  4. from django.utils.translation import ugettext_lazy as _
  5. from oscar.apps.shipping.methods import Free
  6. from oscar.apps.order.exceptions import UnableToPlaceOrder
  7. from oscar.core.loading import get_class
  8. ShippingAddress = get_model('order', 'ShippingAddress')
  9. Order = get_model('order', 'Order')
  10. Line = get_model('order', 'Line')
  11. LinePrice = get_model('order', 'LinePrice')
  12. LineAttribute = get_model('order', 'LineAttribute')
  13. OrderDiscount = get_model('order', 'OrderDiscount')
  14. order_placed = get_class('order.signals', 'order_placed')
  15. class OrderNumberGenerator(object):
  16. """
  17. Simple object for generating order numbers.
  18. We need this as the order number is often required for payment
  19. which takes place before the order model has been created.
  20. """
  21. def order_number(self, basket):
  22. """
  23. Return an order number for a given basket
  24. """
  25. return 100000 + basket.id
  26. class OrderCreator(object):
  27. """
  28. Places the order by writing out the various models
  29. """
  30. def place_order(self, basket, total_incl_tax=None, total_excl_tax=None,
  31. user=None, shipping_method=None, shipping_address=None,
  32. billing_address=None, order_number=None, status=None, **kwargs):
  33. """
  34. Placing an order involves creating all the relevant models based on the
  35. basket and session data.
  36. """
  37. # Only a basket instance is required to place an order - everything else can be set
  38. # to defaults
  39. if basket.is_empty:
  40. raise ValueError(_("Empty baskets cannot be submitted"))
  41. if not shipping_method:
  42. shipping_method = Free()
  43. if total_incl_tax is None or total_excl_tax is None:
  44. total_incl_tax = basket.total_incl_tax + shipping_method.basket_charge_incl_tax()
  45. total_excl_tax = basket.total_excl_tax + shipping_method.basket_charge_excl_tax()
  46. if not order_number:
  47. generator = OrderNumberGenerator()
  48. order_number = generator.order_number(basket)
  49. if not status and hasattr(settings, 'OSCAR_INITIAL_ORDER_STATUS'):
  50. status = getattr(settings, 'OSCAR_INITIAL_ORDER_STATUS')
  51. try:
  52. Order._default_manager.get(number=order_number)
  53. except Order.DoesNotExist:
  54. pass
  55. else:
  56. raise ValueError(_("There is already an order with number %s") % order_number)
  57. # Ok - everything seems to be in order, let's place the order
  58. order = self.create_order_model(
  59. user, basket, shipping_address, shipping_method, billing_address,
  60. total_incl_tax, total_excl_tax, order_number, status, **kwargs)
  61. for line in basket.all_lines():
  62. self.create_line_models(order, line)
  63. self.update_stock_records(line)
  64. for application in basket.offer_applications:
  65. # Trigger any deferred benefits from offers and capture the
  66. # resulting message
  67. application['message'] = application['offer'].apply_deferred_benefit(basket)
  68. # Record offer application results
  69. if application['result'].affects_shipping:
  70. # If a shipping offer, we need to grab the actual discount off
  71. # the shipping method instance
  72. application['discount'] = shipping_method.get_discount()['discount']
  73. self.create_discount_model(order, application)
  74. self.record_discount(application)
  75. for voucher in basket.vouchers.all():
  76. self.record_voucher_usage(order, voucher, user)
  77. # Send signal for analytics to pick up
  78. order_placed.send(sender=self, order=order, user=user)
  79. return order
  80. def create_order_model(self, user, basket, shipping_address, shipping_method,
  81. billing_address, total_incl_tax, total_excl_tax,
  82. order_number, status, **extra_order_fields):
  83. """
  84. Creates an order model.
  85. """
  86. order_data = {'basket_id': basket.id,
  87. 'number': order_number,
  88. 'site': Site._default_manager.get_current(),
  89. 'total_incl_tax': total_incl_tax,
  90. 'total_excl_tax': total_excl_tax,
  91. 'shipping_incl_tax': shipping_method.basket_charge_incl_tax(),
  92. 'shipping_excl_tax': shipping_method.basket_charge_excl_tax(),
  93. 'shipping_method': shipping_method.name}
  94. if shipping_address:
  95. order_data['shipping_address'] = shipping_address
  96. if billing_address:
  97. order_data['billing_address'] = billing_address
  98. if user and user.is_authenticated():
  99. order_data['user_id'] = user.id
  100. if status:
  101. order_data['status'] = status
  102. if extra_order_fields:
  103. order_data.update(extra_order_fields)
  104. order = Order(**order_data)
  105. order.save()
  106. return order
  107. def get_partner_for_product(self, product):
  108. """
  109. Return the partner for a product
  110. """
  111. if product.has_stockrecord:
  112. return product.stockrecord.partner
  113. raise UnableToPlaceOrder(_("No partner found for product '%s'") % product)
  114. def create_line_models(self, order, basket_line, extra_line_fields=None):
  115. """
  116. Create the batch line model.
  117. You can set extra fields by passing a dictionary as the extra_line_fields value
  118. """
  119. partner = self.get_partner_for_product(basket_line.product)
  120. stockrecord = basket_line.product.stockrecord
  121. line_data = {'order': order,
  122. # Partner details
  123. 'partner': partner,
  124. 'partner_name': partner.name,
  125. 'partner_sku': stockrecord.partner_sku,
  126. # Product details
  127. 'product': basket_line.product,
  128. 'title': basket_line.product.get_title(),
  129. 'upc': basket_line.product.upc,
  130. 'quantity': basket_line.quantity,
  131. # Price details
  132. 'line_price_excl_tax': basket_line.line_price_excl_tax_and_discounts,
  133. 'line_price_incl_tax': basket_line.line_price_incl_tax_and_discounts,
  134. 'line_price_before_discounts_excl_tax': basket_line.line_price_excl_tax,
  135. 'line_price_before_discounts_incl_tax': basket_line.line_price_incl_tax,
  136. # Reporting details
  137. 'unit_cost_price': stockrecord.cost_price,
  138. 'unit_price_incl_tax': basket_line.unit_price_incl_tax,
  139. 'unit_price_excl_tax': basket_line.unit_price_excl_tax,
  140. 'unit_retail_price': stockrecord.price_retail,
  141. # Shipping details
  142. 'est_dispatch_date': basket_line.product.stockrecord.dispatch_date
  143. }
  144. extra_line_fields = extra_line_fields or {}
  145. if hasattr(settings, 'OSCAR_INITIAL_LINE_STATUS'):
  146. if not (extra_line_fields and 'status' in extra_line_fields):
  147. extra_line_fields['status'] = getattr(settings, 'OSCAR_INITIAL_LINE_STATUS')
  148. if extra_line_fields:
  149. line_data.update(extra_line_fields)
  150. order_line = Line._default_manager.create(**line_data)
  151. self.create_line_price_models(order, order_line, basket_line)
  152. self.create_line_attributes(order, order_line, basket_line)
  153. self.create_additional_line_models(order, order_line, basket_line)
  154. return order_line
  155. def update_stock_records(self, line):
  156. line.product.stockrecord.allocate(line.quantity)
  157. def create_additional_line_models(self, order, order_line, basket_line):
  158. """
  159. Empty method designed to be overridden.
  160. Some applications require additional information about lines, this
  161. method provides a clean place to create additional models that
  162. relate to a given line.
  163. """
  164. pass
  165. def create_line_price_models(self, order, order_line, basket_line):
  166. """
  167. Creates the batch line price models
  168. """
  169. breakdown = basket_line.get_price_breakdown()
  170. for price_incl_tax, price_excl_tax, quantity in breakdown:
  171. LinePrice._default_manager.create(order=order,
  172. line=order_line,
  173. quantity=quantity,
  174. price_incl_tax=price_incl_tax,
  175. price_excl_tax=price_excl_tax)
  176. def create_line_attributes(self, order, order_line, basket_line):
  177. """
  178. Creates the batch line attributes.
  179. """
  180. for attr in basket_line.attributes.all():
  181. LineAttribute._default_manager.create(line=order_line,
  182. option=attr.option,
  183. type=attr.option.code,
  184. value=attr.value)
  185. def create_discount_model(self, order, discount):
  186. """
  187. Create an order discount model for each offer application attached to
  188. the basket.
  189. """
  190. order_discount = OrderDiscount(
  191. order=order,
  192. message=discount['message'],
  193. offer_id=discount['offer'].id,
  194. frequency=discount['freq'],
  195. amount=discount['discount'])
  196. result = discount['result']
  197. if result.affects_shipping:
  198. order_discount.category = OrderDiscount.SHIPPING
  199. elif result.affects_post_order:
  200. order_discount.category = OrderDiscount.DEFERRED
  201. voucher = discount.get('voucher', None)
  202. if voucher:
  203. order_discount.voucher_id = voucher.id
  204. order_discount.voucher_code = voucher.code
  205. order_discount.save()
  206. def record_discount(self, discount):
  207. discount['offer'].record_usage(discount)
  208. if 'voucher' in discount and discount['voucher']:
  209. discount['voucher'].record_discount(discount)
  210. def record_voucher_usage(self, order, voucher, user):
  211. """
  212. Updates the models that care about this voucher.
  213. """
  214. voucher.record_usage(order, user)