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

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