def process_view(self, request, view_func, view_args, view_kwargs): if view_func in checkviews: cart = Cart.objects.from_request(request, create=False) outofstock = False product_vars = {} for cartitem in cart: product_vars[cartitem.product.productvariation.parent.product.name] = {'count': 0, 'delete': False, 'parent_product': cartitem.product.productvariation.parent.product} for cartitem in cart: stock = cartitem.product.productvariation.parent.product.items_in_stock - cartitem.product.productvariation.parent.product.total_sold product_vars[cartitem.product.productvariation.parent.product.name]['count'] += int(cartitem.quantity) if not cartitem.product.productvariation.parent.product.in_stock() \ or not cartitem.product.productvariation.parent.product.active \ or stock < product_vars[cartitem.product.productvariation.parent.product.name]['count']: product_vars[cartitem.product.productvariation.parent.product.name]['delete'] = True outofstock = True for k, v in product_vars.items(): if v['delete']: tour_product = cartitem.product.productvariation.parent.product.tourproduct cart.cartitem_set.filter(product__productvariation__parent__product=v['parent_product']).delete() if SessionManager(request).do_record_overbook_attempt(tour_product): overbooked_amount = fabs(cartitem.product.productvariation.parent.product.items_in_stock - cartitem.product.productvariation.parent.product.total_sold - v['count']) tour_product.overbooking_attempts += overbooked_amount tour_product.save() overbooking = OverbookingAttempt.objects.create(tour=tour_product, num_overbooked=overbooked_amount) overbooking.save() if outofstock: messages.error(request, 'Out-of-stock items have been removed from your cart. Please review your order before checking out again. Thank you.') satchmo_cart_changed.send(cart, cart=cart, request=request) return HttpResponseRedirect(reverse('satchmo_cart')) return None
def add_ticket(request, quantity=1, redirect_to='satchmo_cart'): formdata = request.POST.copy() details = [] form1 = SelectEventDateForm(request.POST) form1.fields['datetime'].queryset = EventDate.objects.all() if form1.is_valid(): datetime = form1.cleaned_data['datetime'] form2 = SelectPlaceForm(request.POST) form2.fields['seat'].queryset = datetime.event.hallscheme.seats.all() if form2.is_valid(): seat = form2.cleaned_data['seat'] ticket = Ticket.objects.get(seat=seat, datetime=datetime) cart = Cart.objects.from_request(request, create=True) satchmo_cart_details_query.send( cart, product=ticket.product, quantity=quantity, details=details, request=request, form=formdata ) try: added_item = cart.add_item(ticket.product, number_added=1, details=details) added_item.quantity = 1 added_item.save() except CartAddProhibited, cap: return _product_error(request, ticket.product, cap.message) # got to here with no error, now send a signal so that listeners can also operate on this form. satchmo_cart_add_complete.send(cart, cart=cart, cartitem=added_item, product=ticket.product, request=request, form=formdata) satchmo_cart_changed.send(cart, cart=cart, request=request) if request.is_ajax(): data = { 'id': ticket.product.id, 'slug': seat.slug, 'name': ticket.product.translated_name(), 'item_id': added_item.id, 'item_qty': str(round_decimal(quantity, 2)), 'item_price': str(added_item.line_total) or "0.00", 'cart_count': str(round_decimal(cart.numItems, 2)), 'cart_total': str(round_decimal(cart.total, 2)), # Legacy result, for now 'results': _("Success"), } return _json_response(data) else: return redirect(redirect_to) else: return _json_response({'errors': form2.errors, 'results': _("Error")}, True)
def _set_quantity(request, force_delete=False): """Set the quantity for a specific cartitem. Checks to make sure the item is actually in the user's cart. """ cart = Cart.objects.from_request(request, create=False) if isinstance(cart, NullCart): return (False, None, None, _("No cart to update.")) cartplaces = config_value('SHOP', 'CART_PRECISION') if decimal_too_big(request.POST.get('quantity', 0)): return (False,cart,None,_("Bad quantity.")) if force_delete: qty = Decimal('0') else: try: roundfactor = config_value('SHOP', 'CART_ROUNDING') qty = round_decimal(request.POST.get('quantity', 0), places=cartplaces, roundfactor=roundfactor, normalize=True) except RoundedDecimalError as P: return (False, cart, None, _("Bad quantity.")) if qty < Decimal('0'): qty = Decimal('0') try: itemid = int(request.POST.get('cartitem')) except (TypeError, ValueError): return (False, cart, None, _("Bad item number.")) try: cartitem = CartItem.objects.get(pk=itemid, cart=cart) except CartItem.DoesNotExist: return (False, cart, None, _("No such item in your cart.")) if qty == Decimal('0'): cartitem.delete() cartitem = NullCartItem(itemid) else: if config_value('PRODUCT','NO_STOCK_CHECKOUT') == False: stock = cartitem.product.items_in_stock log.debug('checking stock quantity. Have %d, need %d', stock, qty) if stock < qty: return (False, cart, cartitem, _("Unfortunately we only have %(stock)d '%(cartitem_name)s' in stock.") % {'stock': stock, 'cartitem_name': cartitem.product.translated_name()}) cartitem.quantity = round_decimal(qty, places=cartplaces) cartitem.save() satchmo_cart_changed.send(cart, cart=cart, request=request) return (True, cart, cartitem, "")
def wishlist_move_to_cart(request): wish, msg = _wish_from_post(request) if wish: cart = Cart.objects.from_request(request, create=True) try: cart.add_item(wish.product, number_added=1, details=wish.details) except CartAddProhibited, cap: msg = _("Wishlist product '%(product)s' could't be added to the cart. %(details)s") % { "product": wish.product.translated_name, "detail": cap.message, } return wishlist_view(request, message=msg) url = urlresolvers.reverse("satchmo_cart") satchmo_cart_changed.send(cart, cart=cart, request=request) return HttpResponseRedirect(url)
def wishlist_move_to_cart(request): wish, msg = _wish_from_post(request) if wish: cart = Cart.objects.from_request(request, create=True) try: cart.add_item(wish.product, number_added=1, details=wish.details) except CartAddProhibited, cap: msg = _("Wishlist product '%(product)s' could't be added to the cart. %(details)s") % { 'product' : wish.product.translated_name(), 'details' : cap.message } return wishlist_view(request, message=msg) url = urlresolvers.reverse('satchmo_cart') satchmo_cart_changed.send(cart, cart=cart, request=request) return HttpResponseRedirect(url)
def add_multiple(request, redirect_to='satchmo_cart', products=None, template="shop/multiple_product_form.html"): """Add multiple items to the cart. """ if request.method == "POST": log.debug('FORM: %s', request.POST) formdata = request.POST.copy() form = forms.MultipleProductForm(formdata, products=products) if form.is_valid(): cart = Cart.objects.from_request(request, create=True) form.save(cart, request) satchmo_cart_changed.send(cart, cart=cart, request=request) url = urlresolvers.reverse(redirect_to) return HttpResponseRedirect(url) else: form = forms.MultipleProductForm(products=products) return render_to_response(template, context_instance=RequestContext(request, {'form' : form}))
def add_multiple(request, redirect_to='satchmo_cart', products=None, template="shop/multiple_product_form.html"): """Add multiple items to the cart. """ if request.method == "POST": log.debug('FORM: %s', request.POST) formdata = request.POST.copy() form = forms.MultipleProductForm(formdata, products=products) if form.is_valid(): cart = Cart.objects.from_request(request, create=True) form.save(cart, request) satchmo_cart_changed.send(cart, cart=cart, request=request) url = urlresolvers.reverse(redirect_to) return HttpResponseRedirect(url) else: form = forms.MultipleProductForm(products=products) return render(template, {'form' : form})
def form_valid(self, form): cart = Cart.objects.from_request(self.request, create=True) form.save(cart, self.request) satchmo_cart_changed.send(cart, cart=cart, request=self.request) return super(AddMultipleView, self).form_valid(form)
def add(request, id=0, redirect_to='satchmo_cart'): """Add an item to the cart.""" log.debug('FORM: %s', request.POST) formdata = request.POST.copy() productslug = None cartplaces = config_value('SHOP', 'CART_PRECISION') roundfactor = config_value('SHOP', 'CART_ROUNDING') if 'productname' in formdata: productslug = formdata['productname'] try: product, details = product_from_post(productslug, formdata) if not (product and product.active): log.debug("product %s is not active" % productslug) return bad_or_missing(request, _("That product is not available at the moment.")) else: log.debug("product %s is active" % productslug) except (Product.DoesNotExist, MultiValueDictKeyError): log.debug("Could not find product: %s", productslug) return bad_or_missing(request, _('The product you have requested does not exist.')) # First we validate that the number isn't too big. if decimal_too_big(formdata['quantity']): return _product_error(request, product, _("Please enter a smaller number.")) # Then we validate that we can round it appropriately. try: quantity = round_decimal(formdata['quantity'], places=cartplaces, roundfactor=roundfactor) except RoundedDecimalError: return _product_error(request, product, _("Invalid quantity.")) if quantity <= Decimal('0'): return _product_error(request, product, _("Please enter a positive number.")) cart = Cart.objects.from_request(request, create=True) # send a signal so that listeners can update product details before we add it to the cart. satchmo_cart_details_query.send( cart, product=product, quantity=quantity, details=details, request=request, form=formdata ) try: added_item = cart.add_item(product, number_added=quantity, details=details) except CartAddProhibited as cap: return _product_error(request, product, cap.message) # got to here with no error, now send a signal so that listeners can also operate on this form. satchmo_cart_add_complete.send(cart, cart=cart, cartitem=added_item, product=product, request=request, form=formdata) satchmo_cart_changed.send(cart, cart=cart, request=request) if request.is_ajax(): data = { 'id': product.id, 'name': product.translated_name(), 'item_id': added_item.id, 'item_qty': str(round_decimal(quantity, 2)), 'item_price': six.text_type(moneyfmt(added_item.line_total)) or "0.00", 'cart_count': str(round_decimal(cart.numItems, 2)), 'cart_total': six.text_type(moneyfmt(cart.total)), # Legacy result, for now 'results': _("Success"), } log.debug('CART AJAX: %s', data) return _json_response(data) else: url = reverse(redirect_to) return HttpResponseRedirect(url)
return (False, cart, None, _("No such item in your cart.")) if qty == Decimal('0'): cartitem.delete() cartitem = NullCartItem(itemid) else: if config_value('PRODUCT','NO_STOCK_CHECKOUT') == False: stock = cartitem.product.items_in_stock log.debug('checking stock quantity. Have %d, need %d', stock, qty) if stock < qty: return (False, cart, cartitem, _("Unfortunately we only have %(stock)d '%(cartitem_name)s' in stock.") % {'stock': stock, 'cartitem_name': cartitem.product.translated_name()}) cartitem.quantity = round_decimal(qty, places=cartplaces) cartitem.save() satchmo_cart_changed.send(cart, cart=cart, request=request) return (True, cart, cartitem, "") def display(request, cart=None, error_message='', default_view_tax=None): """Display the items in the cart.""" if default_view_tax is None: default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') if not cart: cart = Cart.objects.from_request(request) if cart.numItems > 0: products = [item.product for item in cart.cartitem_set.all()] sale = find_best_auto_discount(products) else: