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.

views.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import logging
  2. from django.http import Http404, HttpResponseRedirect, HttpResponseBadRequest
  3. from django.core.urlresolvers import reverse, reverse_lazy
  4. from django.contrib import messages
  5. from django.contrib.auth import login
  6. from django.db.models import get_model
  7. from django.utils.translation import ugettext as _
  8. from django.views.generic import DetailView, TemplateView, FormView, \
  9. DeleteView, UpdateView, CreateView
  10. from oscar.apps.shipping.methods import NoShippingRequired
  11. from oscar.core.loading import get_class, get_classes
  12. ShippingAddressForm, GatewayForm = get_classes('checkout.forms', ['ShippingAddressForm', 'GatewayForm'])
  13. pre_payment, post_payment = get_classes('checkout.signals', ['pre_payment', 'post_payment'])
  14. OrderNumberGenerator, OrderCreator = get_classes('order.utils', ['OrderNumberGenerator', 'OrderCreator'])
  15. UserAddressForm = get_class('address.forms', 'UserAddressForm')
  16. Repository = get_class('shipping.repository', 'Repository')
  17. AccountAuthView = get_class('customer.views', 'AccountAuthView')
  18. RedirectRequired, UnableToTakePayment, PaymentError = get_classes(
  19. 'payment.exceptions', ['RedirectRequired', 'UnableToTakePayment', 'PaymentError'])
  20. UnableToPlaceOrder = get_class('order.exceptions', 'UnableToPlaceOrder')
  21. OrderPlacementMixin = get_class('checkout.mixins', 'OrderPlacementMixin')
  22. CheckoutSessionMixin = get_class('checkout.session', 'CheckoutSessionMixin')
  23. Order = get_model('order', 'Order')
  24. ShippingAddress = get_model('order', 'ShippingAddress')
  25. CommunicationEvent = get_model('order', 'CommunicationEvent')
  26. PaymentEventType = get_model('order', 'PaymentEventType')
  27. PaymentEvent = get_model('order', 'PaymentEvent')
  28. UserAddress = get_model('address', 'UserAddress')
  29. Basket = get_model('basket', 'Basket')
  30. Email = get_model('customer', 'Email')
  31. CommunicationEventType = get_model('customer', 'CommunicationEventType')
  32. # Standard logger for checkout events
  33. logger = logging.getLogger('oscar.checkout')
  34. class IndexView(CheckoutSessionMixin, FormView):
  35. """
  36. First page of the checkout. We prompt user to either sign in, or
  37. to proceed as a guest (where we still collect their email address).
  38. """
  39. template_name = 'checkout/gateway.html'
  40. form_class = GatewayForm
  41. success_url = reverse_lazy('checkout:shipping-address')
  42. def get(self, request, *args, **kwargs):
  43. # We redirect immediately to shipping address stage if the user is
  44. # signed in
  45. if request.user.is_authenticated():
  46. return self.get_success_response()
  47. return super(IndexView, self).get(request, *args, **kwargs)
  48. def get_form_kwargs(self):
  49. kwargs = super(IndexView, self).get_form_kwargs()
  50. email = self.checkout_session.get_guest_email()
  51. if email:
  52. kwargs['initial'] = {
  53. 'username': email,
  54. }
  55. return kwargs
  56. def form_valid(self, form):
  57. if form.is_guest_checkout() or form.is_new_account_checkout():
  58. email = form.cleaned_data['username']
  59. self.checkout_session.set_guest_email(email)
  60. if form.is_new_account_checkout():
  61. messages.info(
  62. self.request,
  63. _("Create your account and then you will be redirected "
  64. "back to the checkout process"))
  65. self.success_url = "%s?next=%s&email=%s" % (
  66. reverse('customer:register'),
  67. reverse('checkout:shipping-address'),
  68. email
  69. )
  70. else:
  71. user = form.get_user()
  72. login(self.request, user)
  73. return self.get_success_response()
  74. def get_success_response(self):
  75. return HttpResponseRedirect(self.get_success_url())
  76. def get_success_url(self):
  77. return self.success_url
  78. # ================
  79. # SHIPPING ADDRESS
  80. # ================
  81. class ShippingAddressView(CheckoutSessionMixin, FormView):
  82. """
  83. Determine the shipping address for the order.
  84. The default behaviour is to display a list of addresses from the users's
  85. address book, from which the user can choose one to be their shipping address.
  86. They can add/edit/delete these USER addresses. This address will be
  87. automatically converted into a SHIPPING address when the user checks out.
  88. Alternatively, the user can enter a SHIPPING address directly which will be
  89. saved in the session and later saved as ShippingAddress model when the order
  90. is sucessfully submitted.
  91. """
  92. template_name = 'checkout/shipping_address.html'
  93. form_class = ShippingAddressForm
  94. def get(self, request, *args, **kwargs):
  95. # Check that the user's basket is not empty
  96. if request.basket.is_empty:
  97. messages.error(request, _("You need to add some items to your basket to checkout"))
  98. return HttpResponseRedirect(reverse('basket:summary'))
  99. # Check that guests have entered an email address
  100. if not request.user.is_authenticated() and not self.checkout_session.get_guest_email():
  101. messages.error(request, _("Please either sign in or enter your email address"))
  102. return HttpResponseRedirect(reverse('checkout:index'))
  103. # Check to see that a shipping address is actually required. It may not be if
  104. # the basket is purely downloads
  105. if not request.basket.is_shipping_required():
  106. messages.info(request, _("Your basket does not require a shipping address to be submitted"))
  107. return HttpResponseRedirect(self.get_success_url())
  108. return super(ShippingAddressView, self).get(request, *args, **kwargs)
  109. def get_initial(self):
  110. return self.checkout_session.new_shipping_address_fields()
  111. def get_context_data(self, **kwargs):
  112. kwargs = super(ShippingAddressView, self).get_context_data(**kwargs)
  113. if self.request.user.is_authenticated():
  114. # Look up address book data
  115. kwargs['addresses'] = self.get_available_addresses()
  116. return kwargs
  117. def get_available_addresses(self):
  118. return UserAddress._default_manager.filter(user=self.request.user).order_by('-is_default_for_shipping')
  119. def post(self, request, *args, **kwargs):
  120. # Check if a shipping address was selected directly (eg no form was
  121. # filled in)
  122. if self.request.user.is_authenticated() and 'address_id' in self.request.POST:
  123. address = UserAddress._default_manager.get(
  124. pk=self.request.POST['address_id'], user=self.request.user)
  125. action = self.request.POST.get('action', None)
  126. if action == 'ship_to':
  127. # User has selected a previous address to ship to
  128. self.checkout_session.ship_to_user_address(address)
  129. return HttpResponseRedirect(self.get_success_url())
  130. elif action == 'delete':
  131. # Delete the selected address
  132. address.delete()
  133. messages.info(self.request, _("Address deleted from your address book"))
  134. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  135. else:
  136. return HttpResponseBadRequest()
  137. else:
  138. return super(ShippingAddressView, self).post(
  139. request, *args, **kwargs)
  140. def form_valid(self, form):
  141. # Store the address details in the session and redirect to next step
  142. address_fields = dict(
  143. (k, v) for (k, v) in form.instance.__dict__.items()
  144. if not k.startswith('_'))
  145. self.checkout_session.ship_to_new_address(address_fields)
  146. return super(ShippingAddressView, self).form_valid(form)
  147. def get_success_url(self):
  148. return reverse('checkout:shipping-method')
  149. class UserAddressUpdateView(CheckoutSessionMixin, UpdateView):
  150. """
  151. Update a user address
  152. """
  153. template_name = 'checkout/user_address_form.html'
  154. form_class = UserAddressForm
  155. def get_queryset(self):
  156. return self.request.user.addresses.all()
  157. def get_form_kwargs(self):
  158. kwargs = super(UserAddressUpdateView, self).get_form_kwargs()
  159. kwargs['user'] = self.request.user
  160. return kwargs
  161. def get_success_url(self):
  162. messages.info(self.request, _("Address saved"))
  163. return reverse('checkout:shipping-address')
  164. class UserAddressDeleteView(CheckoutSessionMixin, DeleteView):
  165. """
  166. Delete an address from a user's addressbook.
  167. """
  168. template_name = 'checkout/user_address_delete.html'
  169. def get_queryset(self):
  170. return self.request.user.addresses.all()
  171. def get_success_url(self):
  172. messages.info(self.request, _("Address deleted"))
  173. return reverse('checkout:shipping-address')
  174. # ===============
  175. # Shipping method
  176. # ===============
  177. class ShippingMethodView(CheckoutSessionMixin, TemplateView):
  178. """
  179. View for allowing a user to choose a shipping method.
  180. Shipping methods are largely domain-specific and so this view
  181. will commonly need to be subclassed and customised.
  182. The default behaviour is to load all the available shipping methods
  183. using the shipping Repository. If there is only 1, then it is
  184. automatically selected. Otherwise, a page is rendered where
  185. the user can choose the appropriate one.
  186. """
  187. template_name = 'checkout/shipping_methods.html'
  188. def get(self, request, *args, **kwargs):
  189. # Check that the user's basket is not empty
  190. if request.basket.is_empty:
  191. messages.error(request, _("You need to add some items to your basket to checkout"))
  192. return HttpResponseRedirect(reverse('basket:summary'))
  193. # Check that shipping is required at all
  194. if not request.basket.is_shipping_required():
  195. self.checkout_session.use_shipping_method(NoShippingRequired().code)
  196. return self.get_success_response()
  197. # Check that shipping address has been completed
  198. if not self.checkout_session.is_shipping_address_set():
  199. messages.error(request, _("Please choose a shipping address"))
  200. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  201. # Save shipping methods as instance var as we need them both here
  202. # and when setting the context vars.
  203. self._methods = self.get_available_shipping_methods()
  204. if len(self._methods) == 0:
  205. # No shipping methods available for given address
  206. messages.warning(request, _("Shipping is unavailable for your chosen address - please choose another"))
  207. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  208. elif len(self._methods) == 1:
  209. # Only one shipping method - set this and redirect onto the next step
  210. self.checkout_session.use_shipping_method(self._methods[0].code)
  211. return self.get_success_response()
  212. # Must be more than one available shipping method, we present them to
  213. # the user to make a choice.
  214. return super(ShippingMethodView, self).get(request, *args, **kwargs)
  215. def get_context_data(self, **kwargs):
  216. kwargs = super(ShippingMethodView, self).get_context_data(**kwargs)
  217. kwargs['methods'] = self._methods
  218. return kwargs
  219. def get_available_shipping_methods(self):
  220. """
  221. Returns all applicable shipping method objects
  222. for a given basket.
  223. """
  224. # Shipping methods can depend on the user, the contents of the basket
  225. # and the shipping address. I haven't come across a scenario that
  226. # doesn't fit this system.
  227. return Repository().get_shipping_methods(
  228. user=self.request.user, basket=self.request.basket,
  229. shipping_addr=self.get_shipping_address(self.request.basket),
  230. request=self.request)
  231. def post(self, request, *args, **kwargs):
  232. # Need to check that this code is valid for this user
  233. method_code = request.POST.get('method_code', None)
  234. is_valid = False
  235. for method in self.get_available_shipping_methods():
  236. if method.code == method_code:
  237. is_valid = True
  238. if not is_valid:
  239. messages.error(request, _("Your submitted shipping method is not permitted"))
  240. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  241. # Save the code for the chosen shipping method in the session
  242. # and continue to the next step.
  243. self.checkout_session.use_shipping_method(method_code)
  244. return self.get_success_response()
  245. def get_success_response(self):
  246. return HttpResponseRedirect(reverse('checkout:payment-method'))
  247. # ==============
  248. # Payment method
  249. # ==============
  250. class PaymentMethodView(CheckoutSessionMixin, TemplateView):
  251. """
  252. View for a user to choose which payment method(s) they want to use.
  253. This would include setting allocations if payment is to be split
  254. between multiple sources.
  255. """
  256. def get(self, request, *args, **kwargs):
  257. # Check that the user's basket is not empty
  258. if request.basket.is_empty:
  259. messages.error(request, _("You need to add some items to your basket to checkout"))
  260. return HttpResponseRedirect(reverse('basket:summary'))
  261. shipping_required = request.basket.is_shipping_required()
  262. # Check that shipping address has been completed
  263. if shipping_required and not self.checkout_session.is_shipping_address_set():
  264. messages.error(request, _("Please choose a shipping address"))
  265. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  266. # Check that shipping method has been set
  267. if shipping_required and not self.checkout_session.is_shipping_method_set(self.request.basket):
  268. messages.error(request, _("Please choose a shipping method"))
  269. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  270. return self.get_success_response()
  271. def get_success_response(self):
  272. return HttpResponseRedirect(reverse('checkout:payment-details'))
  273. # ================
  274. # Order submission
  275. # ================
  276. class PaymentDetailsView(OrderPlacementMixin, TemplateView):
  277. """
  278. For taking the details of payment and creating the order
  279. The class is deliberately split into fine-grained methods, responsible for
  280. only one thing. This is to make it easier to subclass and override just
  281. one component of functionality.
  282. All projects will need to subclass and customise this class.
  283. """
  284. template_name = 'checkout/payment_details.html'
  285. template_name_preview = 'checkout/preview.html'
  286. preview = False
  287. def get(self, request, *args, **kwargs):
  288. error_response = self.get_error_response()
  289. if error_response:
  290. return error_response
  291. return super(PaymentDetailsView, self).get(request, *args, **kwargs)
  292. def post(self, request, *args, **kwargs):
  293. """
  294. This method is designed to be overridden by subclasses which will
  295. validate the forms from the payment details page. If the forms are
  296. valid then the method can call submit()
  297. """
  298. error_response = self.get_error_response()
  299. if error_response:
  300. return error_response
  301. if self.preview:
  302. # We use a custom parameter to indicate if this is an attempt to
  303. # place an order. Without this, we assume a payment form is being
  304. # submitted from the payment-details page
  305. if request.POST.get('action', '') == 'place_order':
  306. # We pull together all the things that are needed to place an
  307. # order.
  308. submission = self.build_submission()
  309. return self.submit(**submission)
  310. return self.render_preview(request)
  311. # Posting to payment-details isn't the right thing to do
  312. return self.get(request, *args, **kwargs)
  313. def get_error_response(self):
  314. # Check that the user's basket is not empty
  315. if self.request.basket.is_empty:
  316. messages.error(self.request, _(
  317. "You need to add some items to your basket to checkout"))
  318. return HttpResponseRedirect(reverse('basket:summary'))
  319. # Check that shipping address has been completed
  320. shipping_required = self.request.basket.is_shipping_required()
  321. if shipping_required and not self.checkout_session.is_shipping_address_set():
  322. messages.error(self.request, _("Please choose a shipping address"))
  323. return HttpResponseRedirect(reverse('checkout:shipping-address'))
  324. # Check that shipping method has been set
  325. if shipping_required and not self.checkout_session.is_shipping_method_set(
  326. self.request.basket):
  327. messages.error(self.request, _("Please choose a shipping method"))
  328. return HttpResponseRedirect(reverse('checkout:shipping-method'))
  329. def build_submission(self, **kwargs):
  330. """
  331. Return a dict of data to submitted to pay for, and create an order
  332. """
  333. basket = self.request.basket
  334. shipping_address = self.get_shipping_address(basket)
  335. shipping_method = self.get_shipping_method(
  336. basket, shipping_address)
  337. total = self.get_order_totals(
  338. basket, shipping_method=shipping_method)
  339. submission = {
  340. 'user': self.request.user,
  341. 'basket': basket,
  342. 'shipping_address': shipping_address,
  343. 'shipping_method': shipping_method,
  344. 'order_total': total,
  345. 'order_kwargs': {},
  346. 'payment_kwargs': {}}
  347. if not submission['user'].is_authenticated():
  348. email = self.checkout_session.get_guest_email()
  349. submission['order_kwargs']['guest_email'] = email
  350. return submission
  351. def get_context_data(self, **kwargs):
  352. # Use the proposed submission as template context data. Flatten the
  353. # order kwargs so they are easily available too.
  354. ctx = self.build_submission(**kwargs)
  355. ctx.update(kwargs)
  356. ctx.update(ctx['order_kwargs'])
  357. return ctx
  358. def get_template_names(self):
  359. return [self.template_name_preview] if self.preview else [
  360. self.template_name]
  361. def render_preview(self, request, **kwargs):
  362. """
  363. Show a preview of the order.
  364. If sensitive data was submitted on the payment details page, you will
  365. need to pass it back to the view here so it can be stored in hidden
  366. form inputs. This avoids ever writing the sensitive data to disk.
  367. """
  368. ctx = self.get_context_data()
  369. ctx.update(kwargs)
  370. return self.render_to_response(ctx)
  371. def can_basket_be_submitted(self, basket):
  372. """
  373. Check if the basket is permitted to be submitted as an order
  374. """
  375. strategy = self.request.strategy
  376. for line in basket.all_lines():
  377. result = strategy.fetch(line.product)
  378. is_permitted, reason = result.availability.is_purchase_permitted(
  379. line.quantity)
  380. if not is_permitted:
  381. return False, reason, reverse('basket:summary')
  382. return True, None, None
  383. def get_default_billing_address(self):
  384. """
  385. Return default billing address for user
  386. This is useful when the payment details view includes a billing address
  387. form - you can use this helper method to prepopulate the form.
  388. Note, this isn't used in core oscar as there is no billing address form
  389. by default.
  390. """
  391. if not self.request.user.is_authenticated():
  392. return None
  393. try:
  394. return self.request.user.addresses.get(is_default_for_billing=True)
  395. except UserAddress.DoesNotExist:
  396. return None
  397. def submit(self, user, basket, shipping_address, shipping_method,
  398. order_total, payment_kwargs=None, order_kwargs=None):
  399. """
  400. Submit a basket for order placement.
  401. The process runs as follows:
  402. * Generate an order number
  403. * Freeze the basket so it cannot be modified any more (important when
  404. redirecting the user to another site for payment as it prevents the
  405. basket being manipulated during the payment process).
  406. * Attempt to take payment for the order
  407. - If payment is successful, place the order
  408. - If a redirect is required (eg PayPal, 3DSecure), redirect
  409. - If payment is unsuccessful, show an appropriate error message
  410. :basket: The basket to submit.
  411. :payment_kwargs: Additional kwargs to pass to the handle_payment method
  412. :order_kwargs: Additional kwargs to pass to the place_order method
  413. """
  414. if payment_kwargs is None:
  415. payment_kwargs = {}
  416. if order_kwargs is None:
  417. order_kwargs = {}
  418. # Taxes must be known at this point
  419. assert basket.is_tax_known, (
  420. "Basket tax must be set before a user can place an order")
  421. assert shipping_method.is_tax_known, (
  422. "Shipping method tax must be set before a user can place an order")
  423. # Domain-specific checks on the basket
  424. is_valid, reason, url = self.can_basket_be_submitted(basket)
  425. if not is_valid:
  426. messages.error(self.request, reason)
  427. return HttpResponseRedirect(url)
  428. # We generate the order number first as this will be used
  429. # in payment requests (ie before the order model has been
  430. # created). We also save it in the session for multi-stage
  431. # checkouts (eg where we redirect to a 3rd party site and place
  432. # the order on a different request).
  433. order_number = self.generate_order_number(basket)
  434. self.checkout_session.set_order_number(order_number)
  435. logger.info("Order #%s: beginning submission process for basket #%d",
  436. order_number, basket.id)
  437. # Freeze the basket so it cannot be manipulated while the customer is
  438. # completing payment on a 3rd party site. Also, store a reference to
  439. # the basket in the session so that we know which basket to thaw if we
  440. # get an unsuccessful payment response when redirecting to a 3rd party
  441. # site.
  442. self.freeze_basket(basket)
  443. self.checkout_session.set_submitted_basket(basket)
  444. # Handle payment. Any payment problems should be handled by the
  445. # handle_payment method raise an exception, which should be caught
  446. # within handle_POST and the appropriate forms redisplayed.
  447. error_msg = _("A problem occurred while processing payment for this "
  448. "order - no payment has been taken. Please "
  449. "contact customer services if this problem persists")
  450. pre_payment.send_robust(sender=self, view=self)
  451. try:
  452. self.handle_payment(order_number, order_total, **payment_kwargs)
  453. except RedirectRequired, e:
  454. # Redirect required (eg PayPal, 3DS)
  455. logger.info("Order #%s: redirecting to %s", order_number, e.url)
  456. return HttpResponseRedirect(e.url)
  457. except UnableToTakePayment, e:
  458. # Something went wrong with payment but in an anticipated way. Eg
  459. # their bankcard has expired, wrong card number - that kind of
  460. # thing. This type of exception is supposed to set a friendly error
  461. # message that makes sense to the customer.
  462. msg = unicode(e)
  463. logger.warning(
  464. "Order #%s: unable to take payment (%s) - restoring basket",
  465. order_number, msg)
  466. self.restore_frozen_basket()
  467. # We re-render the payment details view
  468. self.preview = False
  469. return self.render_to_response(self.get_context_data(error=msg))
  470. except PaymentError, e:
  471. # A general payment error - Something went wrong which wasn't
  472. # anticipated. Eg, the payment gateway is down (it happens), your
  473. # credentials are wrong - that king of thing.
  474. # It makes sense to configure the checkout logger to
  475. # mail admins on an error as this issue warrants some further
  476. # investigation.
  477. msg = unicode(e)
  478. logger.error("Order #%s: payment error (%s)", order_number, msg)
  479. self.restore_frozen_basket()
  480. self.preview = False
  481. return self.render_to_response(
  482. self.get_context_data(error=error_msg))
  483. except Exception, e:
  484. # Unhandled exception - hopefully, you will only ever see this in
  485. # development.
  486. logger.error(
  487. "Order #%s: unhandled exception while taking payment (%s)",
  488. order_number, e)
  489. logger.exception(e)
  490. self.restore_frozen_basket()
  491. self.preview = False
  492. return self.render_to_response(
  493. self.get_context_data(error=error_msg))
  494. post_payment.send_robust(sender=self, view=self)
  495. # If all is ok with payment, try and place order
  496. logger.info("Order #%s: payment successful, placing order",
  497. order_number)
  498. try:
  499. return self.handle_order_placement(
  500. order_number, user, basket, shipping_address, shipping_method,
  501. order_total, **order_kwargs)
  502. except UnableToPlaceOrder, e:
  503. # It's possible that something will go wrong while trying to
  504. # actually place an order. Not a good situation to be in as a
  505. # payment transaction may already have taken place, but needs
  506. # to be handled gracefully.
  507. logger.error("Order #%s: unable to place order - %s",
  508. order_number, e)
  509. logger.exception(e)
  510. msg = unicode(e)
  511. self.restore_frozen_basket()
  512. return self.render_to_response(self.get_context_data(error=msg))
  513. def generate_order_number(self, basket):
  514. """
  515. Return a new order number
  516. """
  517. return OrderNumberGenerator().order_number(basket)
  518. def freeze_basket(self, basket):
  519. """
  520. Freeze the basket so it can no longer be modified
  521. """
  522. # We freeze the basket to prevent it being modified once the payment
  523. # process has started. If your payment fails, then the basket will
  524. # need to be "unfrozen". We also store the basket ID in the session
  525. # so the it can be retrieved by multistage checkout processes.
  526. basket.freeze()
  527. def handle_payment(self, order_number, total, **kwargs):
  528. """
  529. Handle any payment processing and record payment sources and events.
  530. This method is designed to be overridden within your project. The
  531. default is to do nothing as payment is domain-specific.
  532. This method is responsible for handling payment and recording the
  533. payment sources (using the add_payment_source method) and payment
  534. events (using add_payment_event) so they can be
  535. linked to the order when it is saved later on.
  536. """
  537. pass
  538. # =========
  539. # Thank you
  540. # =========
  541. class ThankYouView(DetailView):
  542. """
  543. Displays the 'thank you' page which summarises the order just submitted.
  544. """
  545. template_name = 'checkout/thank_you.html'
  546. context_object_name = 'order'
  547. def get_object(self):
  548. # We allow superusers to force an order thankyou page for testing
  549. order = None
  550. if self.request.user.is_superuser:
  551. if 'order_number' in self.request.GET:
  552. order = Order._default_manager.get(number=self.request.GET['order_number'])
  553. elif 'order_id' in self.request.GET:
  554. order = Order._default_manager.get(id=self.request.GET['orderid'])
  555. if not order:
  556. if 'checkout_order_id' in self.request.session:
  557. order = Order._default_manager.get(pk=self.request.session['checkout_order_id'])
  558. else:
  559. raise Http404(_("No order found"))
  560. return order