Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

views.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. from decimal import Decimal
  2. import logging
  3. from django.conf import settings
  4. from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseBadRequest
  5. from django.template import RequestContext
  6. from django.shortcuts import get_object_or_404
  7. from django.core.urlresolvers import reverse
  8. from django.forms import ModelForm
  9. from django.contrib import messages
  10. from django.core.urlresolvers import resolve
  11. from django.core.exceptions import ObjectDoesNotExist
  12. from django.utils.translation import ugettext as _
  13. from django.template.response import TemplateResponse
  14. from django.core.mail import EmailMessage
  15. from django.views.generic import DetailView, TemplateView, FormView, \
  16. DeleteView, UpdateView, CreateView
  17. from oscar.apps.shipping.methods import FreeShipping
  18. from oscar.core.loading import import_module
  19. import_module('checkout.forms', ['ShippingAddressForm'], locals())
  20. import_module('checkout.calculators', ['OrderTotalCalculator'], locals())
  21. import_module('checkout.utils', ['CheckoutSessionData'], locals())
  22. import_module('checkout.signals', ['pre_payment', 'post_payment'], locals())
  23. import_module('order.models', ['Order', 'ShippingAddress',
  24. 'CommunicationEvent'], locals())
  25. import_module('order.utils', ['OrderNumberGenerator', 'OrderCreator'], locals())
  26. import_module('address.models', ['UserAddress'], locals())
  27. import_module('address.forms', ['UserAddressForm'], locals())
  28. import_module('shipping.repository', ['Repository'], locals())
  29. import_module('customer.models', ['Email', 'CommunicationEventType'], locals())
  30. import_module('customer.views', ['AccountAuthView'], locals())
  31. import_module('payment.exceptions', ['RedirectRequired', 'UnableToTakePayment',
  32. 'PaymentError'], locals())
  33. import_module('basket.models', ['Basket'], locals())
  34. # Standard logger for checkout events
  35. logger = logging.getLogger('oscar.checkout')
  36. class IndexView(AccountAuthView):
  37. """
  38. First page of the checkout. If the user is signed in then we forward
  39. straight onto the next step. Otherwise, we provide options to login, register and
  40. (if the option is enabled) proceed anonymously.
  41. """
  42. template_name = 'checkout/gateway.html'
  43. def get_logged_in_redirect(self):
  44. return reverse('checkout:shipping-address')
  45. class CheckoutSessionMixin(object):
  46. """
  47. Mixin to provide common functionality shared between checkout views.
  48. """
  49. def dispatch(self, request, *args, **kwargs):
  50. self.checkout_session = CheckoutSessionData(request)
  51. return super(CheckoutSessionMixin, self).dispatch(request, *args, **kwargs)
  52. def get_shipping_address(self):
  53. """
  54. Return the current shipping address for this checkout session.
  55. This could either be a ShippingAddress model which has been
  56. pre-populated (not saved), or a UserAddress model which will
  57. need converting into a ShippingAddress model at submission
  58. """
  59. addr_data = self.checkout_session.new_shipping_address_fields()
  60. if addr_data:
  61. # Load address data into a blank address model
  62. return ShippingAddress(**addr_data)
  63. addr_id = self.checkout_session.user_address_id()
  64. if addr_id:
  65. try:
  66. return UserAddress._default_manager.get(pk=addr_id)
  67. except UserAddress.DoesNotExist:
  68. # This can happen if you reset all your tables and you still have
  69. # session data that refers to addresses that no longer exist
  70. pass
  71. return None
  72. def get_shipping_method(self, basket=None):
  73. method = self.checkout_session.shipping_method()
  74. if method:
  75. if not basket:
  76. basket = self.request.basket
  77. method.set_basket(basket)
  78. else:
  79. # We default to using free shipping
  80. method = FreeShipping()
  81. return method
  82. def get_order_totals(self, basket=None, shipping_method=None):
  83. """
  84. Returns the total for the order with and without tax (as a tuple)
  85. """
  86. calc = OrderTotalCalculator(self.request)
  87. if not basket:
  88. basket = self.request.basket
  89. if not shipping_method:
  90. shipping_method = self.get_shipping_method(basket)
  91. total_incl_tax = calc.order_total_incl_tax(basket, shipping_method)
  92. total_excl_tax = calc.order_total_excl_tax(basket, shipping_method)
  93. return total_incl_tax, total_excl_tax
  94. def get_context_data(self, **kwargs):
  95. """
  96. Assign common template variables to the context.
  97. """
  98. ctx = super(CheckoutSessionMixin, self).get_context_data(**kwargs)
  99. ctx['shipping_address'] = self.get_shipping_address()
  100. method = self.get_shipping_method()
  101. if method:
  102. ctx['shipping_method'] = method
  103. ctx['shipping_total_excl_tax'] = method.basket_charge_excl_tax()
  104. ctx['shipping_total_incl_tax'] = method.basket_charge_incl_tax()
  105. ctx['order_total_incl_tax'], ctx['order_total_excl_tax'] = self.get_order_totals()
  106. return ctx
  107. # ================
  108. # SHIPPING ADDRESS
  109. # ================
  110. class ShippingAddressView(CheckoutSessionMixin, FormView):
  111. """
  112. Determine the shipping address for the order.
  113. The default behaviour is to display a list of addresses from the users's
  114. address book, from which the user can choose one to be their shipping address.
  115. They can add/edit/delete these USER addresses. This address will be
  116. automatically converted into a SHIPPING address when the user checks out.
  117. Alternatively, the user can enter a SHIPPING address directly which will be
  118. saved in the session and saved as a model when the order is sucessfully submitted.
  119. """
  120. template_name = 'checkout/shipping_address.html'
  121. form_class = ShippingAddressForm
  122. def get_initial(self):
  123. return self.checkout_session.new_shipping_address_fields()
  124. def get_context_data(self, **kwargs):
  125. if self.request.user.is_authenticated():
  126. # Look up address book data
  127. kwargs['addresses'] = UserAddress._default_manager.filter(user=self.request.user)
  128. return kwargs
  129. def post(self, request, *args, **kwargs):
  130. # Check if a shipping address was selected directly (eg no form was filled in)
  131. if self.request.user.is_authenticated and 'address_id' in self.request.POST:
  132. address = UserAddress._default_manager.get(pk=self.request.POST['address_id'])
  133. if 'action' in self.request.POST and self.request.POST['action'] == 'ship_to':
  134. # User has selected a previous address to ship to
  135. self.checkout_session.ship_to_user_address(address)
  136. return HttpResponseRedirect(self.get_success_url())
  137. elif 'action' in self.request.POST and self.request.POST['action'] == 'delete':
  138. address.delete()
  139. messages.info(self.request, "Address deleted from your address book")
  140. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  141. else:
  142. return HttpResponseBadRequest()
  143. else:
  144. return super(ShippingAddressView, self).post(request, *args, **kwargs)
  145. def form_valid(self, form):
  146. self.checkout_session.ship_to_new_address(form.clean())
  147. return super(ShippingAddressView, self).form_valid(form)
  148. def get_success_url(self):
  149. return reverse('checkout:shipping-method')
  150. class UserAddressCreateView(CreateView):
  151. """
  152. Add a USER address to the user's addressbook.
  153. This is not the same as creating a SHIPPING Address, although if used for the order,
  154. it will be converted into a shipping address at submission-time.
  155. """
  156. template_name = 'checkout/user_address_form.html'
  157. form_class = UserAddressForm
  158. def get_context_data(self, **kwargs):
  159. kwargs = super(UserAddressCreateView, self).get_context_data(**kwargs)
  160. kwargs['form_url'] = reverse('checkout:user-address-create')
  161. return kwargs
  162. def form_valid(self, form):
  163. self.object = form.save(commit=False)
  164. self.object.user = self.request.user
  165. self.object.save()
  166. return self.get_success_response()
  167. def get_success_response(self):
  168. messages.info(self.request, _("Address saved"))
  169. # We redirect back to the shipping address page
  170. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  171. class UserAddressUpdateView(UpdateView):
  172. """
  173. Update a user address
  174. """
  175. template_name = 'checkout/user_address_form.html'
  176. form_class = UserAddressForm
  177. def get_queryset(self):
  178. return UserAddress._default_manager.filter(user=self.request.user)
  179. def get_context_data(self, **kwargs):
  180. kwargs = super(UserAddressUpdateView, self).get_context_data(**kwargs)
  181. kwargs['form_url'] = reverse('checkout:user-address-update', args=(str(kwargs['object'].id)))
  182. return kwargs
  183. def get_success_url(self):
  184. messages.info(self.request, _("Address saved"))
  185. return reverse('checkout:shipping-address')
  186. class UserAddressDeleteView(DeleteView):
  187. """
  188. Delete an address from a user's addressbook.
  189. """
  190. def get_queryset(self):
  191. return UserAddress._default_manager.filter(user=self.request.user)
  192. def get_success_url(self):
  193. messages.info(self.request, _("Address deleted"))
  194. return reverse('checkout:shipping-address')
  195. # ===============
  196. # Shipping method
  197. # ===============
  198. class ShippingMethodView(CheckoutSessionMixin, TemplateView):
  199. """
  200. View for allowing a user to choose a shipping method.
  201. Shipping methods are largely domain-specific and so this view
  202. will commonly need to be subclassed and customised.
  203. The default behaviour is to load all the available shipping methods
  204. using the shipping Repository. If there is only 1, then it is
  205. automatically selected. Otherwise, a page is rendered where
  206. the user can choose the appropriate one.
  207. """
  208. template_name = 'checkout/shipping_methods.html';
  209. def get(self, request, *args, **kwargs):
  210. # Save shipping methods as instance var as we need them both here
  211. # and when setting the context vars.
  212. self._methods = self.get_available_shipping_methods()
  213. if len(self._methods) == 1:
  214. # Only one shipping method - set this and redirect onto the next step
  215. self.checkout_session.use_shipping_method(self._methods[0].code)
  216. return self.get_success_response()
  217. return super(ShippingMethodView, self).get(request, *args, **kwargs)
  218. def get_context_data(self, **kwargs):
  219. kwargs = super(ShippingMethodView, self).get_context_data(**kwargs)
  220. kwargs['methods'] = self._methods
  221. return kwargs
  222. def get_available_shipping_methods(self):
  223. """
  224. Returns all applicable shipping method objects
  225. for a given basket.
  226. """
  227. repo = Repository()
  228. # Shipping methods can depend on the user, the contents of the basket
  229. # and the shipping address. I haven't come across a scenario that doesn't
  230. # fit this system.
  231. return repo.get_shipping_methods(self.request.user, self.request.basket,
  232. self.get_shipping_address())
  233. def post(self, request, *args, **kwargs):
  234. method_code = request.POST['method_code']
  235. # Save the code for the chosen shipping method in the session
  236. # and continue to the next step.
  237. self.checkout_session.use_shipping_method(method_code)
  238. return self.get_success_response()
  239. def get_success_response(self):
  240. return HttpResponseRedirect(reverse('checkout:payment-method'))
  241. class PaymentMethodView(CheckoutSessionMixin, TemplateView):
  242. """
  243. View for a user to choose which payment method(s) they want to use.
  244. This would include setting allocations if payment is to be split
  245. between multiple sources.
  246. """
  247. def get(self, request, *args, **kwargs):
  248. return self.get_success_response()
  249. def get_success_response(self):
  250. return HttpResponseRedirect(reverse('checkout:preview'))
  251. class OrderPreviewView(CheckoutSessionMixin, TemplateView):
  252. """
  253. View a preview of the order before submitting.
  254. """
  255. template_name = 'checkout/preview.html'
  256. def get_success_response(self):
  257. return HttpResponseRedirect(reverse('checkout:payment-details'))
  258. class OrderPlacementMixin(CheckoutSessionMixin):
  259. """
  260. Mixin for providing functionality for placing orders.
  261. """
  262. # Any payment sources should be added to this list as part of the
  263. # _handle_payment method. If the order is placed successfully, then
  264. # they will be persisted.
  265. payment_sources = []
  266. def handle_order_placement(self, order_number, basket, total_incl_tax, total_excl_tax, **kwargs):
  267. """
  268. Place the order into the database and return the appropriate HTTP response
  269. We deliberately pass the basket in here as the one tied to the request
  270. isn't necessarily the correct one to use in placing the order. This can
  271. happen when a basket gets frozen.
  272. """
  273. # Write out all order and payment models
  274. order = self.place_order(order_number, basket, total_incl_tax, total_excl_tax, **kwargs)
  275. basket.set_as_submitted()
  276. return self.handle_successful_order(order)
  277. def handle_successful_order(self, order):
  278. """
  279. Handle the various steps required after an order has been successfully placed.
  280. """
  281. # Send confirmation message (normally an email)
  282. self.send_confirmation_message(order)
  283. # Flush all session data
  284. self.checkout_session.flush()
  285. # Save order id in session so thank-you page can load it
  286. self.request.session['checkout_order_id'] = order.id
  287. return HttpResponseRedirect(reverse('checkout:thank-you'))
  288. def place_order(self, order_number, basket, total_incl_tax, total_excl_tax, **kwargs):
  289. """
  290. Writes the order out to the DB including the payment models
  291. """
  292. shipping_address = self.create_shipping_address()
  293. shipping_method = self.get_shipping_method(basket)
  294. billing_address = self.create_billing_address(shipping_address)
  295. if 'status' not in kwargs:
  296. status = self.get_initial_order_status(basket)
  297. else:
  298. status = kwargs['status']
  299. order = OrderCreator().place_order(self.request.user,
  300. basket,
  301. shipping_address,
  302. shipping_method,
  303. billing_address,
  304. total_incl_tax,
  305. total_excl_tax,
  306. order_number,
  307. status)
  308. self.save_payment_details(order)
  309. return order
  310. def create_shipping_address(self):
  311. """
  312. Create and returns the shipping address for the current order.
  313. If the shipping address was entered manually, then we simply
  314. write out a ShippingAddress model with the appropriate form data. If
  315. the user is authenticated, then we create a UserAddress from this data
  316. too so it can be re-used in the future.
  317. If the shipping address was selected from the user's address book,
  318. then we convert the UserAddress to a ShippingAddress.
  319. """
  320. addr_data = self.checkout_session.new_shipping_address_fields()
  321. addr_id = self.checkout_session.user_address_id()
  322. if addr_data:
  323. addr = self.create_shipping_address_from_form_fields(addr_data)
  324. self.create_user_address(addr_data)
  325. elif addr_id:
  326. addr = self.create_shipping_address_from_user_address(addr_id)
  327. else:
  328. raise AttributeError("No shipping address data found")
  329. return addr
  330. def create_shipping_address_from_form_fields(self, addr_data):
  331. """Creates a shipping address model from the saved form fields"""
  332. shipping_addr = ShippingAddress(**addr_data)
  333. shipping_addr.save()
  334. return shipping_addr
  335. def create_user_address(self, addr_data):
  336. """
  337. For signed-in users, we create a user address model which will go
  338. into their address book.
  339. """
  340. if self.request.user.is_authenticated():
  341. addr_data['user_id'] = self.request.user.id
  342. user_addr = UserAddress(**addr_data)
  343. # Check that this address isn't already in the db as we don't want
  344. # to fill up the customer address book with duplicate addresses
  345. try:
  346. UserAddress._default_manager.get(hash=user_addr.generate_hash())
  347. except ObjectDoesNotExist:
  348. user_addr.save()
  349. def create_shipping_address_from_user_address(self, addr_id):
  350. """Creates a shipping address from a user address"""
  351. address = UserAddress._default_manager.get(pk=addr_id)
  352. # Increment the number of orders to help determine popularity of orders
  353. address.num_orders += 1
  354. address.save()
  355. shipping_addr = ShippingAddress()
  356. address.populate_alternative_model(shipping_addr)
  357. shipping_addr.save()
  358. return shipping_addr
  359. def create_billing_address(self, shipping_address=None):
  360. """
  361. Saves any relevant billing data (eg a billing address).
  362. """
  363. return None
  364. def save_payment_details(self, order):
  365. """
  366. Saves all payment-related details. This could include a billing
  367. address, payment sources and any order payment events.
  368. """
  369. self.save_payment_events(order)
  370. self.save_payment_sources(order)
  371. def save_payment_events(self, order):
  372. """
  373. Saves any relevant payment events for this order
  374. """
  375. pass
  376. def save_payment_sources(self, order):
  377. """
  378. Saves any payment sources used in this order.
  379. When the payment sources are created, the order model does not exist and
  380. so they need to have it set before saving.
  381. """
  382. for source in self.payment_sources:
  383. source.order = order
  384. source.save()
  385. def get_initial_order_status(self, basket):
  386. return None
  387. def get_submitted_basket(self):
  388. basket_id = self.checkout_session.get_submitted_basket_id()
  389. return Basket._default_manager.get(pk=basket_id)
  390. def restore_frozen_basket(self):
  391. """
  392. Restores a frozen basket as the sole OPEN basket. Note that this also merges
  393. in any new products that have been added to a basket that has been created while payment.
  394. """
  395. fzn_basket = self.get_submitted_basket()
  396. fzn_basket.thaw()
  397. fzn_basket.merge(self.request.basket)
  398. self.request.basket = fzn_basket
  399. def send_confirmation_message(self, order):
  400. # Create order communication event
  401. try:
  402. event_type = CommunicationEventType._default_manager.get(code='ORDER_PLACED')
  403. except CommunicationEventType.DoesNotExist:
  404. logger.error(_("Order #%s: unable to find 'order_placed' comms event" % order.number))
  405. else:
  406. if self.request.user.is_authenticated() and event_type.has_email_templates():
  407. logger.info(_("Order #%s: sending confirmation email" % order.number))
  408. # Send the email
  409. subject = event_type.get_email_subject_for_order(order)
  410. body = event_type.get_email_body_for_order(order)
  411. email = EmailMessage(subject, body, to=[self.request.user.email])
  412. email.send()
  413. # Record email against user for their email history
  414. Email._default_manager.create(user=self.request.user,
  415. subject=email.subject,
  416. body_text=email.body)
  417. # Record communication event against order
  418. CommunicationEvent._default_manager.create(order=order, type=event_type)
  419. class PaymentDetailsView(OrderPlacementMixin, TemplateView):
  420. """
  421. For taking the details of payment and creating the order
  422. The class is deliberately split into fine-grained methods, responsible for only one
  423. thing. This is to make it easier to subclass and override just one component of
  424. functionality.
  425. Almost all projects will need to subclass and customise this class.
  426. """
  427. def post(self, request, *args, **kwargs):
  428. """
  429. This method is designed to be overridden by subclasses which will
  430. validate the forms from the payment details page. If the forms are valid
  431. then the method can call submit()."""
  432. return self.submit(request.basket, **kwargs)
  433. def submit(self, basket, **kwargs):
  434. """
  435. Submit a basket for order placement.
  436. The process runs as follows:
  437. * Generate an order number
  438. * Freeze the basket so it cannot be modified any more.
  439. * Attempt to take payment for the order
  440. - If payment is successful, place the order
  441. - If a redirect is required (eg PayPal, 3DSecure), redirect
  442. - If payment is unsuccessful, show an appropriate error message
  443. """
  444. # We generate the order number first as this will be used
  445. # in payment requests (ie before the order model has been
  446. # created). We also save it in the session for multi-stage
  447. # checkouts (eg where we redirect to a 3rd party site and place
  448. # the order on a different request).
  449. order_number = self.generate_order_number(basket)
  450. logger.info(_("Order #%s: beginning submission process" % order_number))
  451. # We freeze the basket to prevent it being modified once the payment
  452. # process has started. If your payment fails, then the basket will
  453. # need to be "unfrozen". We also store the basket ID in the session
  454. # so the it can be retrieved by multistage checkout processes.
  455. basket.freeze()
  456. self.checkout_session.set_submitted_basket(basket)
  457. # Handle payment. Any payment problems should be handled by the
  458. # handle_payment method raise an exception, which should be caught
  459. # within handle_POST and the appropriate forms redisplayed.
  460. try:
  461. pre_payment.send_robust(sender=self, view=self)
  462. total_incl_tax, total_excl_tax = self.get_order_totals(basket)
  463. self.handle_payment(order_number, total_incl_tax, **kwargs)
  464. post_payment.send_robust(sender=self, view=self)
  465. except RedirectRequired, e:
  466. # Redirect required (eg PayPal, 3DS)
  467. logger.info(_("Order #%s: redirecting to %s" % (order_number, e.url)))
  468. return HttpResponseRedirect(e.url)
  469. except UnableToTakePayment, e:
  470. # Something went wrong with payment, need to show
  471. # error to the user. This type of exception is supposed
  472. # to set a friendly error message.
  473. logger.info(_("Order #%s: unable to take payment (%s)" % (order_number, e)))
  474. return self.render_to_response(self.get_context_data(error=str(e)))
  475. except PaymentError, e:
  476. # Something went wrong which wasn't anticipated.
  477. logger.error(_("Order #%s: payment error (%s)" % (order_number, e)))
  478. return self.render_to_response(self.get_context_data(error="A problem occurred processing payment."))
  479. else:
  480. # If all is ok with payment, place order
  481. logger.error(_("Order #%s: payment successful, placing order" % order_number))
  482. return self.handle_order_placement(order_number, basket, total_incl_tax, total_excl_tax, **kwargs)
  483. def generate_order_number(self, basket):
  484. generator = OrderNumberGenerator()
  485. order_number = generator.order_number(basket)
  486. self.checkout_session.set_order_number(order_number)
  487. return order_number
  488. def handle_payment(self, order_number, total, **kwargs):
  489. """
  490. Handle any payment processing.
  491. This method is designed to be overridden within your project. The
  492. default is to do nothing.
  493. """
  494. pass
  495. class ThankYouView(DetailView):
  496. """
  497. Displays the 'thank you' page which summarises the order just submitted.
  498. """
  499. template_name = 'checkout/thank_you.html'
  500. context_object_name = 'order'
  501. def get_object(self):
  502. # We allow superusers to force an order thankyou page for testing
  503. order = None
  504. if self.request.user.is_superuser:
  505. if 'order_number' in self.request.GET:
  506. order = Order._default_manager.get(number=self.request.GET['order_number'])
  507. elif 'order_id' in self.request.GET:
  508. order = Order._default_manager.get(id=self.request.GET['orderid'])
  509. if not order:
  510. order = Order._default_manager.get(pk=self.request.session['checkout_order_id'])
  511. return order