Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Split formset into separate forms
Paweł Kowalewski4e2c7a01b329
diff --git a/Gruntfile.js b/Gruntfile.jsindex 9b3cf61905..26bd295838 100644--- a/Gruntfile.js+++ b/Gruntfile.js@@ -4,6 +4,9 @@ module.exports = function(grunt) {dist: {files: {'saleor/static/js/storefront_fromjsx.js': 'saleor/static/js_src/storefront.jsx'+ },+ options: {+ stage: 0}}},@@ -129,10 +132,14 @@ module.exports = function(grunt) {],"saleor/static/js/storefront.js": ["saleor/static/components/jquery/dist/jquery.js",- "saleor/static/components/react/react.js",+ "saleor/static/components/jquery-cookie/jquery.cookie.js",+ "saleor/static/components/react/react-with-addons.js","saleor/static/components/bootstrap-sass/assets/javascripts/bootstrap.js","saleor/static/js/storefront_fromjsx.js","saleor/static/js_src/storefront.js"+ ],+ "saleor/static/js/storefront_head.js": [+ "saleor/static/components/modernizr/modernizr.js"]}}diff --git a/bower.json b/bower.jsonindex 1a05715ffc..54285ef288 100644--- a/bower.json+++ b/bower.json@@ -6,18 +6,19 @@"Mirumee Software"],"license": "BSD",- "devDependencies": {+ "dependencies": {"bootstrap-sass": "~3.3.5","components-font-awesome": "~4.3.0","dotdotdot": "~1.7.3","dropzone": "~4.0.1","jquery": "~2.1.4",+ "jquery-cookie": "~1.4.1","jquery.equalheights": "~1.5.2","less": "~2.4.0","materialize": "~0.97.0","modernizr": "~2.8.3",+ "react": "~0.13.3","select2": "~4.0.0",- "Sortable": "~1.2.0",- "react": "~0.13.3"+ "Sortable": "~1.2.0"}}diff --git a/package.json b/package.jsonindex 898653a985..a01f76af80 100644--- a/package.json+++ b/package.json@@ -15,11 +15,12 @@"engines": {"node": "0.10.x"},- "devDependencies": {+ "dependencies": {"autoprefixer-core": "~5.2.0","bower": "^1.3.12","csswring": "~3.0.5","grunt": "~0.4.5",+ "grunt-babel": "~5.0.1","grunt-browser-sync": "~2.1.3","grunt-cli": "^0.1.13","grunt-contrib-copy": "~0.6.0",@@ -28,7 +29,6 @@"grunt-contrib-watch": "~0.6.1","grunt-postcss": "~0.4.0","grunt-sass": "~1.0.0",- "load-grunt-tasks": "~3.2.0",- "grunt-babel": "~5.0.1"+ "load-grunt-tasks": "~3.2.0"}}diff --git a/saleor/cart/forms.py b/saleor/cart/forms.pyindex 2fcc3394e9..120c5c9f4d 100644--- a/saleor/cart/forms.py+++ b/saleor/cart/forms.py@@ -84,6 +84,7 @@ class ReplaceCartLineForm(AddToCartForm):def __init__(self, *args, **kwargs):super(ReplaceCartLineForm, self).__init__(*args, **kwargs)self.cart_line = self.cart.get_line(self.product)+ self.fields['quantity'].widget.attrs = {'min': 1, 'max': self.cart_line.product.get_stock_quantity()}def clean_quantity(self):quantity = self.cleaned_data['quantity']@@ -105,6 +106,7 @@ class ReplaceCartLineForm(AddToCartForm):"""Replace quantity."""+ print repr(self.cart), repr(self.product), repr(self.cleaned_data)return self.cart.add(self.product, self.cleaned_data['quantity'],replace=True)diff --git a/saleor/cart/templates/cart/index.html b/saleor/cart/templates/cart/index.htmlindex 1bea3268b5..ee62453bb0 100644--- a/saleor/cart/templates/cart/index.html+++ b/saleor/cart/templates/cart/index.html@@ -13,60 +13,63 @@{% block content %}{% if cart %}-<form role="form" action="." method="post" class="form-cart">- {% csrf_token %}{{ formset.management_form }}<table class="table table-striped cart" id="cart-items"><thead>- <tr>- <th class="col-sm-6">{% trans "Product" %}</th>- <th class="col-sm-2">{% trans "Quantity" %}</th>- <th class="col-sm-2 text-right">{% trans "Price" %}</th>- <th class="col-sm-2 text-right">{% trans "Subtotal" %}</th>- </tr>+ <tr>+ <th class="col-sm-6">{% trans "Product" %}</th>+ <th class="col-sm-2">{% trans "Quantity" %}</th>+ <th class="col-sm-2 text-right">{% trans "Price" %}</th>+ <th class="col-sm-2 text-right">{% trans "Subtotal" %}</th>+ </tr></thead><tfoot>- <tr>- <td class="col-sm-10 text-right lead" colspan="3">{% trans "Total" %}:- <td class="col-sm-2 text-right lead"><b>{% gross cart.get_total %}</b></td>- </tr>+ <tr>+ <td class="col-sm-10 text-right lead" colspan="3">{% trans "Total" %}:+ <td class="col-sm-2 text-right lead"><b>{% gross cart.get_total %}</b></td>+ </tr></tfoot><tbody>- {% for form in formset %}- <tr class="cart-item">- <td>- <a href="{{ form.cart_line.product.get_absolute_url }}">- {% if form.cart_line.product.product.images.first %}- <img class="cart-item-image" itemprop="image" src="{{ form.cart_line.product.product.images.first.image.crop.100x100 }}" alt="">- {% else %}- <img class="cart-item-image" src="{% static 'images/product-image-placeholder.png' %}" alt="">- {% endif %}- {{ form.cart_line.product.product }} - {{ form.cart_line.product.display_variant }}- </a>- </td>- <td>- <div>- <div class="input-group cart-item-quantity hidden{% if form.quantity.errors %} has-error{% endif %}">- {{ form.quantity }}- <span class="input-group-btn">- <button class="btn btn-info" type="submit">{% trans "Update" %}</button>- </span>+ {% for group in cart %}+ {% for line in group %}+ <tr class="cart-item">+ <td>+ <a href="{{ line.product.get_absolute_url }}">+ {% if line.product.product.images.first %}+ <img class="cart-item-image" itemprop="image" src="{{ line.product.product.images.first.image.crop.100x100 }}" alt="">+ {% else %}+ <img class="cart-item-image" src="{% static 'images/product-image-placeholder.png' %}" alt="">+ {% endif %}+ {{ line.product.product }} - {{ line.product.display_variant }}+ </a>+ </td>+ <td>+ <div class="cart-item-amount">+ <form role="form" action="{% url "cart:update_line" product_id=line.product.pk %}" method="post" class="form-cart">+ <div class="input-group cart-item-quantity js-hidden{% if line.form.quantity.errors %} has-error{% endif %}">+ {{ line.form.quantity }}+ <span class="input-group-btn">+ <button class="btn btn-info" type="submit">{% trans "Update" %}</button>+ </span>+ </div>+ {% if line.form.quantity.errors %}+ {% for error in line.form.quantity.errors %}+ <span class="text-danger">{{ error }}</span>+ {% endfor %}+ {% endif %}+ {% csrf_token %}+ </form></div>- </div>- {% if form.quantity.errors %}- {% for error in form.quantity.errors %}- <span class="text-danger">{{ error }}</span>- {% endfor %}- {% endif %}- <button type="submit" class="btn btn-link btn-sm cart-item-remove">- <span class="text-muted">{% trans "Remove from cart" %}</span>- </button>- </td>- <td class="text-right">{% gross form.cart_line.get_price_per_item %}</td>- <td class="text-right cart-item-subtotal">- {% gross form.cart_line.get_total %}- </td>- </tr>+ <button type="submit" class="btn btn-link btn-sm cart-item-remove">+ <span class="text-muted">{% trans "Remove from cart" %}</span>+ </button>+ </td>+ <td class="text-right">{% gross line.get_price_per_item %}</td>+ <td class="text-right cart-item-subtotal">+ {% gross line.get_total %}+ </td>+ </tr>+ {% endfor %}{% endfor %}</tbody></table>@@ -75,7 +78,6 @@<a href="{% url "checkout:index" %}" class="btn btn-primary btn-lg pull-right">{% trans "Proceed to checkout" %}</a></div></div>-</form>{% else %}<p>{% trans 'Your cart is empty' %}diff --git a/saleor/cart/test_cart.py b/saleor/cart/test_cart.pyindex a2cafe61b7..3c30ee4d26 100755--- a/saleor/cart/test_cart.py+++ b/saleor/cart/test_cart.py@@ -188,7 +188,7 @@ def test_cart_contains_products_on_stock():cart = Cart(session_cart=SessionCart())cart.add(stocked_variant, quantity=12, check_quantity=False)assert cart.count() == 12- cart = remove_unavailable_products(cart)+ remove_unavailable_products(cart)assert cart.count() == 10@@ -197,8 +197,8 @@ def test_cart_doesnt_contain_empty_products():stocked_variant.get_stock_quantity = MagicMock(return_value=0)cart = Cart(session_cart=SessionCart())cart.add(stocked_variant, quantity=10, check_quantity=False)- updated_cart = remove_unavailable_products(cart)- assert len(updated_cart) == 0+ remove_unavailable_products(cart)+ assert len(cart) == 0@patch.object(Cart, 'for_session_cart')diff --git a/saleor/cart/urls.py b/saleor/cart/urls.pyindex eda8f5eb3c..dd94e88f29 100644--- a/saleor/cart/urls.py+++ b/saleor/cart/urls.py@@ -4,5 +4,6 @@ from . import viewsurlpatterns = [- url(r'^$', views.index, name='index')+ url(r'^$', views.index, name='index'),+ url(r'^update/(?P<product_id>\d+)/$', views.index, name='update_line')]diff --git a/saleor/cart/utils.py b/saleor/cart/utils.pyindex c4943bab96..8aeaf1fabd 100644--- a/saleor/cart/utils.py+++ b/saleor/cart/utils.py@@ -16,4 +16,3 @@ def remove_unavailable_products(cart):except InsufficientStock as e:quantity = e.item.get_stock_quantity()cart.add(item.product, quantity=quantity, replace=True)- return cartdiff --git a/saleor/cart/views.py b/saleor/cart/views.pyindex b9c210231e..430f150332 100755--- a/saleor/cart/views.py+++ b/saleor/cart/views.py@@ -1,32 +1,44 @@from __future__ import unicode_literalsfrom django.contrib import messages+from django.http import HttpResponse, JsonResponsefrom django.shortcuts import redirectfrom django.template.response import TemplateResponsefrom django.utils.translation import ugettext as _-from .forms import ReplaceCartLineFormSet+from .forms import ReplaceCartLineFormfrom . import Cartfrom ..cart.utils import (contains_unavailable_products, remove_unavailable_products)-def index(request):+def index(request, product_id=None):+ if product_id is not None:+ product_id = int(product_id)cart = Cart.for_session_cart(request.cart, discounts=request.discounts)- cart_partitioner = cart.partition()if contains_unavailable_products(cart):msg = _('Sorry. We don\'t have that many items in stock. ''Quantity was set to maximum available for now.')messages.warning(request, msg)- cart = remove_unavailable_products(cart)- formset = ReplaceCartLineFormSet(request.POST or None,- cart=cart)- if formset.is_valid():- msg = _('Successfully updated product quantities.')- messages.success(request, msg)- formset.save()- return redirect('cart:index')+ remove_unavailable_products(cart)+ for line in cart:+ data = None+ if line.product.pk == product_id:+ data = request.POST+ initial = {'quantity': line.get_quantity()}+ form = ReplaceCartLineForm(data, cart=cart, product=line.product,+ initial=initial)+ line.form = form+ if form.is_valid():+ form.save()+ if request.is_ajax():+ return HttpResponse('')+ return redirect('cart:index')+ elif data is not None:+ if request.is_ajax():+ response = {'error': form.errors}+ return JsonResponse(response, status=400)+ cart_partitioner = cart.partition()return TemplateResponse(request, 'cart/index.html', {- 'cart': cart_partitioner,- 'formset': formset})+ 'cart': cart_partitioner})diff --git a/saleor/checkout/templates/checkout/details.html b/saleor/checkout/templates/checkout/details.htmlindex d832afa123..90bde69f2c 100644--- a/saleor/checkout/templates/checkout/details.html+++ b/saleor/checkout/templates/checkout/details.html@@ -23,7 +23,7 @@<ul class="nav nav-pills nav-justified">{% for stepitem in checkout %}<li class="{% if stepitem == step %}active{% endif %}">- <a href="{{ stepitem.get_absolute_url }}">{% if stepitem %}<i class="glyphicon glyphicon-ok-sign"></i> {% endif %}{{ stepitem.title }}</a>+ <a href="{{ stepitem.get_absolute_url }}">{% if stepitem %}<i class="fa fa-check-circle"></i> {% endif %}{{ stepitem.title }}</a></li>{% endfor %}</ul>diff --git a/saleor/core/templates/bootstrap/_field_vertical.html b/saleor/core/templates/bootstrap/_field_vertical.htmlindex dd274b5e30..fde2d4b723 100644--- a/saleor/core/templates/bootstrap/_field_vertical.html+++ b/saleor/core/templates/bootstrap/_field_vertical.html@@ -43,7 +43,7 @@{% if bound_field.errors %}{% for error in bound_field.errors %}{% if input_type == "input" %}- <span class="glyphicon glyphicon-remove form-control-feedback"></span>+ <span class="fa fa-times form-control-feedback"></span>{% endif %}<span class="text-danger">{{ error }}</span>{% endfor %}diff --git a/saleor/static/js_src/storefront.jsx b/saleor/static/js_src/storefront.jsxindex c852e28e61..c2ff0f49fa 100644--- a/saleor/static/js_src/storefront.jsx+++ b/saleor/static/js_src/storefront.jsx@@ -1,36 +1,110 @@-var CartItemAmount = React.createClass({- componentDidMount: function() {- this.parent = this.getDOMNode().parentNode;- },- getInitialState: function() {- return {- value: this.props.value+class CartItemAmount extends React.Component {+ state = {+ error: null,+ lastSavedValue: this.props.value,+ renderSelect: false,+ renderSubmit: false,+ result: null,+ sending: false,+ value: this.props.value+ };++ componentDidMount() {+ if (this.state.value < this.props.thresholdValue) {+ this.setState({renderSelect: true});+ }+ }++ change(event){+ let newValue = event.target.value;+ this.setState({result: null});+ if (newValue != this.props.thresholdValue || !this.state.renderSelect) {+ this.setState({value: newValue});+ }+ if (newValue >= this.props.thresholdValue) {+ this.setState({renderSelect: false});}- },- change: function(event){- if (event.target.value == this.lastOptionValue) {- React.unmountComponentAtNode(this.parent);- this.parent.appendChild(textInput[this.props.name]);- } else {- this.setState({value: event.target.value});- this.submitForm();+ if (newValue < this.props.thresholdValue && this.state.renderSelect) {+ this.sendQuantity(newValue);}- },- submitForm: function() {- $(".form-cart").submit();- },- render: function() {- this.lastOptionValue = this.props.options[this.props.options.length - 1];- var that = this;- return <div className={this.props.className}>- <select name={this.props.name} onChange={this.change} value={this.state.value} className="form-control cart-item-quantity-select">- {this.props.options.map(function(option) {- return <CartItemAmountOption key={option} value={option} label={option == that.lastOptionValue ? option+" +" : option} />- })}- </select>++ if (!this.state.renderSelect && !this.state.sending) {+ this.setState({renderSubmit: true});+ }+ }++ valueChanged() {+ return this.state.lastSavedValue != this.state.value;+ }++ checkKey(event) {+ if (event.key == "Enter" && this.valueChanged()) {+ this.sendQuantityWrapper();+ }+ }++ sendQuantityWrapper() {+ this.sendQuantity(this.refs.inputQuantity.props.value);+ }++ sendQuantity(quantity) {+ this.setState({renderSubmit: false});+ this.setState({sending: true});++ $.ajax({+ url: this.props.url,+ method: "post",+ data: {quantity: quantity},+ complete: () => {+ this.setState({sending: false});+ if (quantity < this.props.thresholdValue) {+ this.setState({renderSelect: true});+ }+ },+ success: () => {+ this.setState({result: "success", lastSavedValue: quantity});+ setTimeout(() => {+ this.setState({result: null});+ }, 1000);+ },+ error: (response) => {+ this.setState({error: response.responseJSON.error.quantity, result: "error"});+ }+ });+ }++ render() {+ let classNames = React.addons.classSet({+ [this.props.className]: true,+ "has-success": this.state.result == "success",+ "has-error": this.state.result == "error"+ });++ let select = <select onChange={this.change.bind(this)} value={this.state.value} className="form-control cart-item-quantity-select">+ {this.props.options.map(option =>+ <CartItemAmountOption key={option} value={option} label={option == this.props.thresholdValue ? option+" +" : option} />)}+ </select>;++ let classNamesInput = React.addons.classSet({+ "input-group": true,+ "cart-item-quantity": true,+ "no-submit": (!this.state.renderSubmit || !this.valueChanged()) && !(this.state.result == "error")+ });+ let input =+ <div className={classNamesInput}>+ <input onKeyUp={this.checkKey.bind(this)} onChange={this.change.bind(this)} id="id_quantity" max={this.props.max} min="1" ref="inputQuantity"+ name="quantity" type="number" value={this.state.value} />+ <span className="input-group-btn">+ <button onClick={this.sendQuantityWrapper.bind(this)} className="btn btn-info" type="submit">Update</button>+ </span>+ </div>;+ return <div className={classNames}>+ {this.state.renderSelect ? select : input}+ {this.state.sending && !(this.state.result == "error")? <i className="fa fa-circle-o-notch fa-spin"></i> : ""}+ {this.state.result == "error" ? <span className="error text-danger">{this.state.error}</span> : ""}</div>;}-});+}class CartItemAmountOption extends React.Component {render() {@@ -41,41 +115,57 @@ class CartItemAmountOption extends React.Component {}var textInput = [];-$(".cart-item-quantity").each(function() {+var options = [1,2,3,4,5,6,7,8,9,10];+var csrftoken = $.cookie('csrftoken');+function csrfSafeMethod(method) {+ return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));+}+$.ajaxSetup({+ beforeSend: function(xhr, settings) {+ if (!csrfSafeMethod(settings.type) && !this.crossDomain) {+ xhr.setRequestHeader("X-CSRFToken", csrftoken);+ }+ }+});++$(".cart-item-amount").each(function(index) {var $input = $(this).find("input");var $button = $(this).find("button");var value = $input.val();var name = $input.attr("name");- var hasErrors = $(this).hasClass("has-error");-- var options = [1,2,3,4,5,6,7,8,9,10];-- if (options.indexOf(parseInt(value)) != -1 && !hasErrors) {- React.render(<CartItemAmount options={options} value={value} name={name}/>, this.parentNode);- }+ var max = $input.attr("max");+ var props = {+ className: "",+ index: index,+ max: max,+ options: options.slice(0, max),+ thresholdValue: options[options.length - 1],+ url: $(this).find("form").attr("action"),+ value: value+ };- $(this).removeClass("hidden");+ $(this).find(".cart-item-quantity").removeClass("js-hidden");$button.addClass("invisible");- textInput[name] = this;-}).on("keyup change", function() {- $(this).find("input").addClass("input-left");- $(this).find("button").removeClass("invisible");+ textInput.push(this.firstElementChild);++ React.render(<CartItemAmount {...props} />, this);});-var FormShippingToggler = React.createClass({- componentDidMount: function() {+class FormShippingToggler extends React.Component {+ state = {+ value: true+ };++ componentDidMount() {$(".form-full").hide();- },- getInitialState: function() {- return {- value: true- }- },- formFullToggle: function() {+ }++ formFullToggle() {this.setState({value: event.target.checked});$(".form-full").toggle();- },- render: function() {+ }++ render() {return <div className="checkbox"><label><input checked={this.state.value} type="checkbox" onChange={this.formFullToggle} name="shipping_same_as_billing" />@@ -83,7 +173,7 @@ var FormShippingToggler = React.createClass({</label></div>;}-});+}var $formFullToggle = $("#form-full-toggle");if ($formFullToggle.length) {diff --git a/saleor/static/scss/_app.scss b/saleor/static/scss/_app.scssindex bc042fbe5c..0b83e9d66b 100644--- a/saleor/static/scss/_app.scss+++ b/saleor/static/scss/_app.scss@@ -1,5 +1,6 @@$icon-font-path: "../fonts/";@import "bootstrap-sass/assets/stylesheets/bootstrap";+@import "components-font-awesome/scss/font-awesome";.navbar {margin-bottom: $grid-gutter-width;@@ -77,14 +78,19 @@ $icon-font-path: "../fonts/";input {@extend .form-control;- &.input-left {- border-bottom-right-radius: 0;- border-top-right-radius: 0;- }+ border-bottom-right-radius: 0;+ border-top-right-radius: 0;}&-select {+ display: inline-block;width: calc(100% - 71px);++ option {+ &:last-child {+ color: lighten($text-color, 33%);+ }+ }}&.has-error {@@ -94,6 +100,29 @@ $icon-font-path: "../fonts/";}}+ &-amount {+ .input-group {+ &.no-submit {+ display: inline-block;+ width: calc(100% - 71px);++ input {+ border-bottom-right-radius: $input-border-radius;+ border-top-right-radius: $input-border-radius;+ }++ .btn {+ display: none;+ }+ }+ }++ .fa {+ margin-left: 6px;+ padding-left: 1px;+ }+ }+&-subtotal {position: relative;}@@ -102,12 +131,8 @@ $icon-font-path: "../fonts/";padding-left: 0;}- select {- option {- &:last-child {- color: lighten($text-color, 33%);- }- }+ .error {+ display: block;}}}@@ -153,3 +178,10 @@ $icon-font-path: "../fonts/";}}}+++.js {+ .js-hidden {+ display: none;+ }+}diff --git a/templates/base.html b/templates/base.htmlindex 9122374f6c..1faeb5744c 100644--- a/templates/base.html+++ b/templates/base.html@@ -2,7 +2,7 @@{% load i18n %}{% load staticfiles %}-<html lang="en">+<html lang="en" class="no-js"><head><title>{% block title %}Saleor{% endblock %}</title>{% block meta %}@@ -12,6 +12,7 @@<meta name="author" content="{% trans "Mirumee Software" %}">{% endblock meta %}+ <script src="{% static "js/storefront_head.js" %}"></script><link rel="stylesheet" type="text/css" href="{% static "css/storefront.css" %}">{% block stylesheet %}{% endblock stylesheet %}@@ -47,7 +48,7 @@</ul><ul class="nav navbar-nav navbar-right"><li class="dropdown">- <a data-toggle="dropdown" class="dropdown-toggle" href="{% url "cart:index" %}"><i class="glyphicon glyphicon-shopping-cart"></i> {% trans "Shopping cart" %} {% if request.cart %}<span class="badge">{{ request.cart.count }}</span>{% endif %} <b class="caret"></b></a>+ <a data-toggle="dropdown" class="dropdown-toggle" href="{% url "cart:index" %}"><i class="fa fa-shopping-cart"></i> {% trans "Shopping cart" %} {% if request.cart %}<span class="badge">{{ request.cart.count }}</span>{% endif %} <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="{% url "cart:index" %}">{% trans "View cart contents" %}</a></li>{% if request.cart %}@@ -129,7 +130,6 @@</div></footer>{% endblock %}- {% block third-party-js %}{% endblock third-party-js %}{% block footer_scripts %}<script src="{% static "js/storefront.js" %}"></script>{% endblock footer_scripts %}