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

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