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 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. from decimal import Decimal as D
  2. from django.contrib.sites.models import Site
  3. from django.conf import settings
  4. from django.utils.translation import ugettext_lazy as _
  5. from oscar.core.loading import get_model
  6. from oscar.core.loading import get_class
  7. from . import exceptions
  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, # noqa (too complex (12))
  31. shipping_method, shipping_charge, user=None,
  32. shipping_address=None, billing_address=None,
  33. order_number=None, status=None, **kwargs):
  34. """
  35. Placing an order involves creating all the relevant models based on the
  36. basket and session data.
  37. """
  38. if basket.is_empty:
  39. raise ValueError(_("Empty baskets cannot be submitted"))
  40. if not order_number:
  41. generator = OrderNumberGenerator()
  42. order_number = generator.order_number(basket)
  43. if not status and hasattr(settings, 'OSCAR_INITIAL_ORDER_STATUS'):
  44. status = getattr(settings, 'OSCAR_INITIAL_ORDER_STATUS')
  45. try:
  46. Order._default_manager.get(number=order_number)
  47. except Order.DoesNotExist:
  48. pass
  49. else:
  50. raise ValueError(_("There is already an order with number %s")
  51. % order_number)
  52. # Ok - everything seems to be in order, let's place the order
  53. order = self.create_order_model(
  54. user, basket, shipping_address, shipping_method, shipping_charge,
  55. billing_address, total, order_number, status, **kwargs)
  56. for line in basket.all_lines():
  57. self.create_line_models(order, line)
  58. self.update_stock_records(line)
  59. # Record any discounts associated with this order
  60. for application in basket.offer_applications:
  61. # Trigger any deferred benefits from offers and capture the
  62. # resulting message
  63. application['message'] \
  64. = application['offer'].apply_deferred_benefit(basket, order,
  65. application)
  66. # Record offer application results
  67. if application['result'].affects_shipping:
  68. # Skip zero shipping discounts
  69. shipping_discount = shipping_method.discount(basket)
  70. if shipping_discount <= D('0.00'):
  71. continue
  72. # If a shipping offer, we need to grab the actual discount off
  73. # the shipping method instance, which should be wrapped in an
  74. # OfferDiscount instance.
  75. application['discount'] = shipping_discount
  76. self.create_discount_model(order, application)
  77. self.record_discount(application)
  78. for voucher in basket.vouchers.all():
  79. self.record_voucher_usage(order, voucher, user)
  80. # Send signal for analytics to pick up
  81. order_placed.send(sender=self, order=order, user=user)
  82. return order
  83. def create_order_model(self, user, basket, shipping_address,
  84. shipping_method, shipping_charge, billing_address,
  85. total, order_number, status, **extra_order_fields):
  86. """
  87. Create an order model.
  88. """
  89. order_data = {'basket': basket,
  90. 'number': order_number,
  91. 'site': Site._default_manager.get_current(),
  92. 'currency': total.currency,
  93. 'total_incl_tax': total.incl_tax,
  94. 'total_excl_tax': total.excl_tax,
  95. 'shipping_incl_tax': shipping_charge.incl_tax,
  96. 'shipping_excl_tax': shipping_charge.excl_tax,
  97. 'shipping_method': shipping_method.name,
  98. 'shipping_code': shipping_method.code}
  99. if shipping_address:
  100. order_data['shipping_address'] = shipping_address
  101. if billing_address:
  102. order_data['billing_address'] = billing_address
  103. if user and user.is_authenticated():
  104. order_data['user_id'] = user.id
  105. if status:
  106. order_data['status'] = status
  107. if extra_order_fields:
  108. order_data.update(extra_order_fields)
  109. order = Order(**order_data)
  110. order.save()
  111. return order
  112. def create_line_models(self, order, basket_line, extra_line_fields=None):
  113. """
  114. Create the batch line model.
  115. You can set extra fields by passing a dictionary as the
  116. extra_line_fields value
  117. """
  118. product = basket_line.product
  119. stockrecord = basket_line.stockrecord
  120. if not stockrecord:
  121. raise exceptions.UnableToPlaceOrder(
  122. "Baket line #%d has no stockrecord" % basket_line.id)
  123. partner = stockrecord.partner
  124. line_data = {
  125. 'order': order,
  126. # Partner details
  127. 'partner': partner,
  128. 'partner_name': partner.name,
  129. 'partner_sku': stockrecord.partner_sku,
  130. 'stockrecord': stockrecord,
  131. # Product details
  132. 'product': product,
  133. 'title': product.get_title(),
  134. 'upc': product.upc,
  135. 'quantity': basket_line.quantity,
  136. # Price details
  137. 'line_price_excl_tax':
  138. basket_line.line_price_excl_tax_incl_discounts,
  139. 'line_price_incl_tax':
  140. basket_line.line_price_incl_tax_incl_discounts,
  141. 'line_price_before_discounts_excl_tax':
  142. basket_line.line_price_excl_tax,
  143. 'line_price_before_discounts_incl_tax':
  144. basket_line.line_price_incl_tax,
  145. # Reporting details
  146. 'unit_cost_price': stockrecord.cost_price,
  147. 'unit_price_incl_tax': basket_line.unit_price_incl_tax,
  148. 'unit_price_excl_tax': basket_line.unit_price_excl_tax,
  149. 'unit_retail_price': stockrecord.price_retail,
  150. # Shipping details
  151. 'est_dispatch_date':
  152. basket_line.purchase_info.availability.dispatch_date
  153. }
  154. extra_line_fields = extra_line_fields or {}
  155. if hasattr(settings, 'OSCAR_INITIAL_LINE_STATUS'):
  156. if not (extra_line_fields and 'status' in extra_line_fields):
  157. extra_line_fields['status'] = getattr(
  158. settings, 'OSCAR_INITIAL_LINE_STATUS')
  159. if extra_line_fields:
  160. line_data.update(extra_line_fields)
  161. order_line = Line._default_manager.create(**line_data)
  162. self.create_line_price_models(order, order_line, basket_line)
  163. self.create_line_attributes(order, order_line, basket_line)
  164. self.create_additional_line_models(order, order_line, basket_line)
  165. return order_line
  166. def update_stock_records(self, line):
  167. """
  168. Update any relevant stock records for this order line
  169. """
  170. if line.product.get_product_class().track_stock:
  171. line.stockrecord.allocate(line.quantity)
  172. def create_additional_line_models(self, order, order_line, basket_line):
  173. """
  174. Empty method designed to be overridden.
  175. Some applications require additional information about lines, this
  176. method provides a clean place to create additional models that
  177. relate to a given line.
  178. """
  179. pass
  180. def create_line_price_models(self, order, order_line, basket_line):
  181. """
  182. Creates the batch line price models
  183. """
  184. breakdown = basket_line.get_price_breakdown()
  185. for price_incl_tax, price_excl_tax, quantity in breakdown:
  186. order_line.prices.create(
  187. order=order,
  188. quantity=quantity,
  189. price_incl_tax=price_incl_tax,
  190. price_excl_tax=price_excl_tax)
  191. def create_line_attributes(self, order, order_line, basket_line):
  192. """
  193. Creates the batch line attributes.
  194. """
  195. for attr in basket_line.attributes.all():
  196. order_line.attributes.create(
  197. option=attr.option,
  198. type=attr.option.code,
  199. value=attr.value)
  200. def create_discount_model(self, order, discount):
  201. """
  202. Create an order discount model for each offer application attached to
  203. the basket.
  204. """
  205. order_discount = OrderDiscount(
  206. order=order,
  207. message=discount['message'] or '',
  208. offer_id=discount['offer'].id,
  209. frequency=discount['freq'],
  210. amount=discount['discount'])
  211. result = discount['result']
  212. if result.affects_shipping:
  213. order_discount.category = OrderDiscount.SHIPPING
  214. elif result.affects_post_order:
  215. order_discount.category = OrderDiscount.DEFERRED
  216. voucher = discount.get('voucher', None)
  217. if voucher:
  218. order_discount.voucher_id = voucher.id
  219. order_discount.voucher_code = voucher.code
  220. order_discount.save()
  221. def record_discount(self, discount):
  222. discount['offer'].record_usage(discount)
  223. if 'voucher' in discount and discount['voucher']:
  224. discount['voucher'].record_discount(discount)
  225. def record_voucher_usage(self, order, voucher, user):
  226. """
  227. Updates the models that care about this voucher.
  228. """
  229. voucher.record_usage(order, user)