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

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