Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. if self.request.basket.is_shipping_required():
  320. shipping_address = self.get_shipping_address(
  321. self.request.basket)
  322. shipping_method = self.get_shipping_method(
  323. self.request.basket, shipping_address)
  324. # Check that shipping address has been completed
  325. if not shipping_address:
  326. messages.error(
  327. self.request, _("Please choose a shipping address"))
  328. return HttpResponseRedirect(
  329. reverse('checkout:shipping-address'))
  330. # Check that shipping method has been set
  331. if not shipping_method:
  332. messages.error(
  333. self.request, _("Please choose a shipping method"))
  334. return HttpResponseRedirect(
  335. reverse('checkout:shipping-method'))
  336. def build_submission(self, **kwargs):
  337. """
  338. Return a dict of data to submitted to pay for, and create an order
  339. """
  340. basket = self.request.basket
  341. shipping_address = self.get_shipping_address(basket)
  342. shipping_method = self.get_shipping_method(
  343. basket, shipping_address)
  344. total = self.get_order_totals(
  345. basket, shipping_method=shipping_method)
  346. submission = {
  347. 'user': self.request.user,
  348. 'basket': basket,
  349. 'shipping_address': shipping_address,
  350. 'shipping_method': shipping_method,
  351. 'order_total': total,
  352. 'order_kwargs': {},
  353. 'payment_kwargs': {}}
  354. if not submission['user'].is_authenticated():
  355. email = self.checkout_session.get_guest_email()
  356. submission['order_kwargs']['guest_email'] = email
  357. return submission
  358. def get_context_data(self, **kwargs):
  359. # Use the proposed submission as template context data. Flatten the
  360. # order kwargs so they are easily available too.
  361. ctx = self.build_submission(**kwargs)
  362. ctx.update(kwargs)
  363. ctx.update(ctx['order_kwargs'])
  364. return ctx
  365. def get_template_names(self):
  366. return [self.template_name_preview] if self.preview else [
  367. self.template_name]
  368. def render_preview(self, request, **kwargs):
  369. """
  370. Show a preview of the order.
  371. If sensitive data was submitted on the payment details page, you will
  372. need to pass it back to the view here so it can be stored in hidden
  373. form inputs. This avoids ever writing the sensitive data to disk.
  374. """
  375. ctx = self.get_context_data()
  376. ctx.update(kwargs)
  377. return self.render_to_response(ctx)
  378. def can_basket_be_submitted(self, basket):
  379. """
  380. Check if the basket is permitted to be submitted as an order
  381. """
  382. strategy = self.request.strategy
  383. for line in basket.all_lines():
  384. result = strategy.fetch(line.product)
  385. is_permitted, reason = result.availability.is_purchase_permitted(
  386. line.quantity)
  387. if not is_permitted:
  388. return False, reason, reverse('basket:summary')
  389. return True, None, None
  390. def get_default_billing_address(self):
  391. """
  392. Return default billing address for user
  393. This is useful when the payment details view includes a billing address
  394. form - you can use this helper method to prepopulate the form.
  395. Note, this isn't used in core oscar as there is no billing address form
  396. by default.
  397. """
  398. if not self.request.user.is_authenticated():
  399. return None
  400. try:
  401. return self.request.user.addresses.get(is_default_for_billing=True)
  402. except UserAddress.DoesNotExist:
  403. return None
  404. def submit(self, user, basket, shipping_address, shipping_method,
  405. order_total, payment_kwargs=None, order_kwargs=None):
  406. """
  407. Submit a basket for order placement.
  408. The process runs as follows:
  409. * Generate an order number
  410. * Freeze the basket so it cannot be modified any more (important when
  411. redirecting the user to another site for payment as it prevents the
  412. basket being manipulated during the payment process).
  413. * Attempt to take payment for the order
  414. - If payment is successful, place the order
  415. - If a redirect is required (eg PayPal, 3DSecure), redirect
  416. - If payment is unsuccessful, show an appropriate error message
  417. :basket: The basket to submit.
  418. :payment_kwargs: Additional kwargs to pass to the handle_payment method
  419. :order_kwargs: Additional kwargs to pass to the place_order method
  420. """
  421. if payment_kwargs is None:
  422. payment_kwargs = {}
  423. if order_kwargs is None:
  424. order_kwargs = {}
  425. # Taxes must be known at this point
  426. assert basket.is_tax_known, (
  427. "Basket tax must be set before a user can place an order")
  428. assert shipping_method.is_tax_known, (
  429. "Shipping method tax must be set before a user can place an order")
  430. # Domain-specific checks on the basket
  431. is_valid, reason, url = self.can_basket_be_submitted(basket)
  432. if not is_valid:
  433. messages.error(self.request, reason)
  434. return HttpResponseRedirect(url)
  435. # We generate the order number first as this will be used
  436. # in payment requests (ie before the order model has been
  437. # created). We also save it in the session for multi-stage
  438. # checkouts (eg where we redirect to a 3rd party site and place
  439. # the order on a different request).
  440. order_number = self.generate_order_number(basket)
  441. self.checkout_session.set_order_number(order_number)
  442. logger.info("Order #%s: beginning submission process for basket #%d",
  443. order_number, basket.id)
  444. # Freeze the basket so it cannot be manipulated while the customer is
  445. # completing payment on a 3rd party site. Also, store a reference to
  446. # the basket in the session so that we know which basket to thaw if we
  447. # get an unsuccessful payment response when redirecting to a 3rd party
  448. # site.
  449. self.freeze_basket(basket)
  450. self.checkout_session.set_submitted_basket(basket)
  451. # Handle payment. Any payment problems should be handled by the
  452. # handle_payment method raise an exception, which should be caught
  453. # within handle_POST and the appropriate forms redisplayed.
  454. error_msg = _("A problem occurred while processing payment for this "
  455. "order - no payment has been taken. Please "
  456. "contact customer services if this problem persists")
  457. pre_payment.send_robust(sender=self, view=self)
  458. try:
  459. self.handle_payment(order_number, order_total, **payment_kwargs)
  460. except RedirectRequired, e:
  461. # Redirect required (eg PayPal, 3DS)
  462. logger.info("Order #%s: redirecting to %s", order_number, e.url)
  463. return HttpResponseRedirect(e.url)
  464. except UnableToTakePayment, e:
  465. # Something went wrong with payment but in an anticipated way. Eg
  466. # their bankcard has expired, wrong card number - that kind of
  467. # thing. This type of exception is supposed to set a friendly error
  468. # message that makes sense to the customer.
  469. msg = unicode(e)
  470. logger.warning(
  471. "Order #%s: unable to take payment (%s) - restoring basket",
  472. order_number, msg)
  473. self.restore_frozen_basket()
  474. # We re-render the payment details view
  475. self.preview = False
  476. return self.render_to_response(self.get_context_data(error=msg))
  477. except PaymentError, e:
  478. # A general payment error - Something went wrong which wasn't
  479. # anticipated. Eg, the payment gateway is down (it happens), your
  480. # credentials are wrong - that king of thing.
  481. # It makes sense to configure the checkout logger to
  482. # mail admins on an error as this issue warrants some further
  483. # investigation.
  484. msg = unicode(e)
  485. logger.error("Order #%s: payment error (%s)", order_number, msg,
  486. exc_info=True)
  487. self.restore_frozen_basket()
  488. self.preview = False
  489. return self.render_to_response(
  490. self.get_context_data(error=error_msg))
  491. except Exception, e:
  492. # Unhandled exception - hopefully, you will only ever see this in
  493. # development.
  494. logger.error(
  495. "Order #%s: unhandled exception while taking payment (%s)",
  496. order_number, e, exc_info=True)
  497. self.restore_frozen_basket()
  498. self.preview = False
  499. return self.render_to_response(
  500. self.get_context_data(error=error_msg))
  501. post_payment.send_robust(sender=self, view=self)
  502. # If all is ok with payment, try and place order
  503. logger.info("Order #%s: payment successful, placing order",
  504. order_number)
  505. try:
  506. return self.handle_order_placement(
  507. order_number, user, basket, shipping_address, shipping_method,
  508. order_total, **order_kwargs)
  509. except UnableToPlaceOrder, e:
  510. # It's possible that something will go wrong while trying to
  511. # actually place an order. Not a good situation to be in as a
  512. # payment transaction may already have taken place, but needs
  513. # to be handled gracefully.
  514. logger.error("Order #%s: unable to place order - %s",
  515. order_number, e, exc_info=True)
  516. msg = unicode(e)
  517. self.restore_frozen_basket()
  518. return self.render_to_response(self.get_context_data(error=msg))
  519. def generate_order_number(self, basket):
  520. """
  521. Return a new order number
  522. """
  523. return OrderNumberGenerator().order_number(basket)
  524. def freeze_basket(self, basket):
  525. """
  526. Freeze the basket so it can no longer be modified
  527. """
  528. # We freeze the basket to prevent it being modified once the payment
  529. # process has started. If your payment fails, then the basket will
  530. # need to be "unfrozen". We also store the basket ID in the session
  531. # so the it can be retrieved by multistage checkout processes.
  532. basket.freeze()
  533. def handle_payment(self, order_number, total, **kwargs):
  534. """
  535. Handle any payment processing and record payment sources and events.
  536. This method is designed to be overridden within your project. The
  537. default is to do nothing as payment is domain-specific.
  538. This method is responsible for handling payment and recording the
  539. payment sources (using the add_payment_source method) and payment
  540. events (using add_payment_event) so they can be
  541. linked to the order when it is saved later on.
  542. """
  543. pass
  544. # =========
  545. # Thank you
  546. # =========
  547. class ThankYouView(DetailView):
  548. """
  549. Displays the 'thank you' page which summarises the order just submitted.
  550. """
  551. template_name = 'checkout/thank_you.html'
  552. context_object_name = 'order'
  553. def get_object(self):
  554. # We allow superusers to force an order thankyou page for testing
  555. order = None
  556. if self.request.user.is_superuser:
  557. if 'order_number' in self.request.GET:
  558. order = Order._default_manager.get(number=self.request.GET['order_number'])
  559. elif 'order_id' in self.request.GET:
  560. order = Order._default_manager.get(id=self.request.GET['orderid'])
  561. if not order:
  562. if 'checkout_order_id' in self.request.session:
  563. order = Order._default_manager.get(pk=self.request.session['checkout_order_id'])
  564. else:
  565. raise Http404(_("No order found"))
  566. return order