Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce PaymentMethod and Transaction models
Artur Smętde05e0503fa5
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex 64eb7776d7..6682cd5ed3 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -15,7 +15,7 @@ from ..core.utils.taxes import display_gross_prices, get_taxed_shipping_pricefrom ..discount.models import NotApplicable, Voucherfrom ..shipping.models import ShippingMethod, ShippingZonefrom ..shipping.utils import get_shipping_price_estimate-from .models import Cart+from .models import Cart, PaymentMethodclass QuantityField(forms.IntegerField):@@ -23,8 +23,10 @@ class QuantityField(forms.IntegerField):def __init__(self, **kwargs):super().__init__(- min_value=0, max_value=settings.MAX_CART_LINE_QUANTITY,- initial=1, **kwargs)+ min_value=0,+ max_value=settings.MAX_CART_LINE_QUANTITY,+ initial=1,+ **kwargs)class AddToCartForm(forms.Form):@@ -38,10 +40,12 @@ class AddToCartForm(forms.Form):quantity = QuantityField(label=pgettext_lazy('Add to cart form field label', 'Quantity'))error_messages = {- 'not-available': pgettext_lazy(+ 'not-available':+ pgettext_lazy('Add to cart form error','Sorry. This product is currently not available.'),- 'empty-stock': pgettext_lazy(+ 'empty-stock':+ pgettext_lazy('Add to cart form error','Sorry. This product is currently out of stock.'),'variant-does-not-exists': pgettext_lazy(@@ -117,7 +121,8 @@ class ReplaceCartLineForm(AddToCartForm):super().__init__(*args, **kwargs)self.cart_line = self.cart.get_line(self.variant)self.fields['quantity'].widget.attrs = {- 'min': 1, 'max': settings.MAX_CART_LINE_QUANTITY}+ 'min': 1,+ 'max': settings.MAX_CART_LINE_QUANTITY}def clean_quantity(self):"""Clean the quantity field.@@ -130,8 +135,7 @@ class ReplaceCartLineForm(AddToCartForm):self.variant.check_quantity(quantity)except InsufficientStock as e:msg = self.error_messages['insufficient-stock']- raise forms.ValidationError(- msg % e.item.quantity_available)+ raise forms.ValidationError(msg % e.item.quantity_available)return quantitydef clean(self):@@ -208,13 +212,16 @@ class AddressChoiceForm(forms.Form):"""Choose one of user's addresses or to create new one."""NEW_ADDRESS = 'new_address'- CHOICES = [- (NEW_ADDRESS, pgettext_lazy(- 'Shipping addresses form choice', 'Enter a new address'))]+ CHOICES = [(+ NEW_ADDRESS,+ pgettext_lazy('Shipping addresses form choice',+ 'Enter a new address'))]address = forms.ChoiceField(label=pgettext_lazy('Shipping addresses form field label', 'Address'),- choices=CHOICES, initial=NEW_ADDRESS, widget=forms.RadioSelect)+ choices=CHOICES,+ initial=NEW_ADDRESS,+ widget=forms.RadioSelect)def __init__(self, *args, **kwargs):addresses = kwargs.pop('addresses')@@ -228,15 +235,19 @@ class BillingAddressChoiceForm(AddressChoiceForm):NEW_ADDRESS = 'new_address'SHIPPING_ADDRESS = 'shipping_address'- CHOICES = [- (NEW_ADDRESS, pgettext_lazy(- 'Billing addresses form choice', 'Enter a new address')),- (SHIPPING_ADDRESS, pgettext_lazy(- 'Billing addresses form choice', 'Same as shipping'))]+ CHOICES = [(+ NEW_ADDRESS,+ pgettext_lazy('Billing addresses form choice', 'Enter a new address')),+ (+ SHIPPING_ADDRESS,+ pgettext_lazy(+ 'Billing addresses form choice', 'Same as shipping'))]address = forms.ChoiceField(label=pgettext_lazy('Billing addresses form field label', 'Address'),- choices=CHOICES, initial=SHIPPING_ADDRESS, widget=forms.RadioSelect)+ choices=CHOICES,+ initial=SHIPPING_ADDRESS,+ widget=forms.RadioSelect)class ShippingMethodChoiceField(forms.ModelChoiceField):@@ -294,8 +305,12 @@ class CartNoteForm(forms.ModelForm):"""Save note in cart."""note = forms.CharField(- max_length=250, required=False, strip=True, label=False,- widget=forms.Textarea({'rows': 3}))+ max_length=250,+ required=False,+ strip=True,+ label=False,+ widget=forms.Textarea({+ 'rows': 3}))class Meta:model = Cart@@ -305,7 +320,8 @@ class CartNoteForm(forms.ModelForm):class VoucherField(forms.ModelChoiceField):default_error_messages = {- 'invalid_choice': pgettext_lazy(+ 'invalid_choice':+ pgettext_lazy('Voucher form error', 'Discount code incorrect or expired')}@@ -351,3 +367,9 @@ class CartVoucherForm(forms.ModelForm):if voucher.translated.name != voucher.name else '')self.instance.discount_amount = self.cleaned_data['discount_amount']return super().save(commit)+++class PaymentMethodForm(forms.ModelForm):+ class Meta:+ model = PaymentMethod+ fields = ['variant', 'is_active', 'total', 'charge_status']diff --git a/saleor/checkout/migrations/0010_paymentmethod_transaction.py b/saleor/checkout/migrations/0010_paymentmethod_transaction.pynew file mode 100644index 0000000000..172c40b0fa--- /dev/null+++ b/saleor/checkout/migrations/0010_paymentmethod_transaction.py@@ -0,0 +1,60 @@+# Generated by Django 2.0.3 on 2018-08-13 13:14++from django.db import migrations, models+import django.db.models.deletion+import jsonfield.fields+++class Migration(migrations.Migration):++ dependencies = [+ ('order', '0051_merge_20180807_0704'),+ ('checkout', '0009_cart_translated_discount_name'),+ ]++ operations = [+ migrations.CreateModel(+ name='PaymentMethod',+ fields=[+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),+ ('variant', models.CharField(max_length=255)),+ ('is_active', models.BooleanField(default=True)),+ ('created', models.DateTimeField(auto_now_add=True)),+ ('modified', models.DateTimeField(auto_now=True)),+ ('charge_status', models.CharField(choices=[('charged', 'Charged'), ('not-charged', 'Not charged'), ('fully-refunded', 'Fully refunded')], default='not-charged', max_length=15)),+ ('billing_first_name', models.CharField(blank=True, max_length=256)),+ ('billing_last_name', models.CharField(blank=True, max_length=256)),+ ('billing_address_1', models.CharField(blank=True, max_length=256)),+ ('billing_address_2', models.CharField(blank=True, max_length=256)),+ ('billing_city', models.CharField(blank=True, max_length=256)),+ ('billing_postcode', models.CharField(blank=True, max_length=256)),+ ('billing_country_code', models.CharField(blank=True, max_length=2)),+ ('billing_country_area', models.CharField(blank=True, max_length=256)),+ ('billing_email', models.EmailField(blank=True, max_length=254)),+ ('customer_ip_address', models.GenericIPAddressField(blank=True, null=True)),+ ('extra_data', models.TextField(blank=True, default='')),+ ('token', models.CharField(blank=True, default='', max_length=36)),+ ('total', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),+ ('currency', models.CharField(max_length=10)),+ ('captured_amount', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),+ ('tax', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),+ ('checkout', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='payment_methods', to='checkout.Cart')),+ ('order', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='payment_methods', to='order.Order')),+ ],+ ),+ migrations.CreateModel(+ name='Transaction',+ fields=[+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),+ ('token', models.CharField(blank=True, default='', max_length=64)),+ ('transaction_type', models.CharField(choices=[('auth', 'Authorization'), ('charge', 'Charge'), ('refund', 'Refund'), ('void', 'Void')], max_length=10)),+ ('is_success', models.BooleanField(default=False)),+ ('total', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),+ ('currency', models.CharField(max_length=10)),+ ('captured_amount', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),+ ('tax', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),+ ('gateway_response', jsonfield.fields.JSONField()),+ ('payment_method', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='checkout.PaymentMethod')),+ ],+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex d84d991ba2..ce824655c7 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -8,10 +8,13 @@ from django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.utils.encoding import smart_strfrom django_prices.models import MoneyField+from jsonfield import JSONFieldfrom measurement.measures import Weight+from prices import Moneyfrom ..account.models import Addressfrom ..core.utils.taxes import ZERO_TAXED_MONEY+from ..order.models import Orderfrom ..shipping.models import ShippingMethodCENTS = Decimal('0.01')@@ -30,7 +33,8 @@ class CartQueryset(models.QuerySet):'lines__variant__translations','lines__variant__product__translations','lines__variant__product__images',- 'lines__variant__product__product_type__product_attributes__values') # noqa+ 'lines__variant__product__product_type__product_attributes__values'+ ) # noqaclass Cart(models.Model):@@ -39,24 +43,35 @@ class Cart(models.Model):created = models.DateTimeField(auto_now_add=True)last_change = models.DateTimeField(auto_now_add=True)user = models.ForeignKey(- settings.AUTH_USER_MODEL, blank=True, null=True, related_name='carts',+ settings.AUTH_USER_MODEL,+ blank=True,+ null=True,+ related_name='carts',on_delete=models.CASCADE)email = models.EmailField(blank=True, default='')token = models.UUIDField(primary_key=True, default=uuid4, editable=False)quantity = models.PositiveIntegerField(default=0)billing_address = models.ForeignKey(- Address, related_name='+', editable=False, null=True,+ Address,+ related_name='+',+ editable=False,+ null=True,on_delete=models.SET_NULL)shipping_address = models.ForeignKey(- Address, related_name='+', editable=False, null=True,+ Address,+ related_name='+',+ editable=False,+ null=True,on_delete=models.SET_NULL)shipping_method = models.ForeignKey(ShippingMethod, blank=True, null=True, related_name='carts',on_delete=models.SET_NULL)note = models.TextField(blank=True, default='')discount_amount = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0)discount_name = models.CharField(max_length=255, blank=True, null=True)translated_discount_name = models.CharField(max_length=255, blank=True, null=True)@@ -65,10 +80,10 @@ class Cart(models.Model):objects = CartQueryset.as_manager()class Meta:- ordering = ('-last_change',)+ ordering = ('-last_change', )def __repr__(self):- return 'Cart(quantity=%s)' % (self.quantity,)+ return 'Cart(quantity=%s)' % (self.quantity, )def __iter__(self):return iter(self.lines.all())@@ -158,3 +173,126 @@ class CartLine(models.Model):def is_shipping_required(self):"""Return `True` if the related product variant requires shipping."""return self.variant.is_shipping_required()+++class TransactionType:+ AUTH = 'auth'+ CHARGE = 'charge'+ VOID = 'void'+ REFUND = 'refund'++ CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),+ (CHARGE, pgettext_lazy('transaction type', 'Charge')),+ (REFUND, pgettext_lazy('transaction type', 'Refund')),+ (VOID, pgettext_lazy('transaction type', 'Void'))]+++class PaymentMethodChargeStatus:+ CHARGED = 'charged'+ NOT_CHARGED = 'not-charged'+ FULLY_REFUNDED = 'fully-refunded'++ CHOICES = [+ (CHARGED, pgettext_lazy('payment method status', 'Charged')),+ (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')), (+ FULLY_REFUNDED,+ pgettext_lazy('payment method status', 'Fully refunded'))]+++class PaymentMethod(models.Model):+ variant = models.CharField(max_length=255)+ is_active = models.BooleanField(default=True)+ #: Creation date and time+ created = models.DateTimeField(auto_now_add=True)+ #: Date and time of last modification+ modified = models.DateTimeField(auto_now=True)+ charge_status = models.CharField(+ max_length=15,+ choices=PaymentMethodChargeStatus.CHOICES,+ default=PaymentMethodChargeStatus.NOT_CHARGED)+ billing_first_name = models.CharField(max_length=256, blank=True)+ billing_last_name = models.CharField(max_length=256, blank=True)+ billing_address_1 = models.CharField(max_length=256, blank=True)+ billing_address_2 = models.CharField(max_length=256, blank=True)+ billing_city = models.CharField(max_length=256, blank=True)+ billing_postcode = models.CharField(max_length=256, blank=True)+ billing_country_code = models.CharField(max_length=2, blank=True)+ billing_country_area = models.CharField(max_length=256, blank=True)+ billing_email = models.EmailField(blank=True)+ customer_ip_address = models.GenericIPAddressField(blank=True, null=True)+ extra_data = models.TextField(blank=True, default='')+ token = models.CharField(max_length=36, blank=True, default='')++ total = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')+ currency = models.CharField(max_length=10)+ captured_amount = models.DecimalField(+ max_digits=9, decimal_places=2, default='0.0')+ tax = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')++ checkout = models.ForeignKey(+ Cart,+ null=True,+ related_name='payment_methods',+ on_delete=models.SET_NULL)+ order = models.ForeignKey(+ Order,+ null=True,+ related_name='payment_methods',+ on_delete=models.CASCADE)++ def _get_money(self, amount):+ return Money(amount=amount, currency=self.currency)++ def get_total(self):+ return self._get_money(self.total)++ def get_captured_money(self):+ return self._get_money(self.captured_amount)++ def get_tax_money(self):+ return self._get_money(self.tax)++ def authorize(self):+ # Check if payment method is active and create Transaction with AUTH type+ pass++ def void(self):+ # Check if payment method is active and create Transaction with VOID type+ pass++ def charge(self, amount=None):+ # Check if payment method is active and create Transaction with CHARGE type+ pass++ def refund(self, amount=None):+ # Check if payment method is active and create Transaction with REFUND type+ pass+++class Transaction(models.Model):+ payment_method = models.ForeignKey(+ PaymentMethod, related_name='transactions', on_delete=models.CASCADE)+ token = models.CharField(max_length=64, blank=True, default='')+ transaction_type = models.CharField(+ max_length=10, choices=TransactionType.CHOICES)+ is_success = models.BooleanField(default=False)++ total = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')+ currency = models.CharField(max_length=10)+ captured_amount = models.DecimalField(+ max_digits=9, decimal_places=2, default='0.0')+ tax = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')++ gateway_response = JSONField()++ def _get_money(self, amount):+ return Money(amount=amount, currency=self.currency)++ def get_total(self):+ return self._get_money(self.total)++ def get_captured_money(self):+ return self._get_money(self.captured_amount)++ def get_tax_money(self):+ return self._get_money(self.tax)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 3bbfda16b1..5b1fb7c386 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -78,8 +78,7 @@ def remove_unavailable_variants(cart):def get_variant_prices_from_lines(lines):"""Get's price of each individual item within the lines."""return [- line.variant.get_price()- for line in lines+ line.variant.get_price() for line in linesfor item in range(line.quantity)]@@ -103,9 +102,8 @@ def get_prices_of_products_in_discounted_collections(discounted_collections = set(discounted_collections)lines = (line for line in lines- if line.variant and- set(line.variant.product.collections.all()).intersection(- discounted_collections))+ if line.variant and set(line.variant.product.collections.all())+ .intersection(discounted_collections))return get_variant_prices_from_lines(lines)@@ -121,9 +119,8 @@ def get_prices_of_products_in_discounted_categories(if discounted_categories:discounted_categories = set(discounted_categories)lines = (- line for line in lines- if line.variant and- line.variant.product.category in discounted_categories)+ line for line in lines if line.variant+ and line.variant.product.category in discounted_categories)return get_variant_prices_from_lines(lines)@@ -140,6 +137,7 @@ def check_product_availability_and_warn(request, cart):def find_and_assign_anonymous_cart(queryset=Cart.objects.all()):"""Assign cart from cookie to request user."""+def get_cart(view):@wraps(view)def func(request, *args, **kwargs):@@ -161,14 +159,15 @@ def find_and_assign_anonymous_cart(queryset=Cart.objects.all()):return responsereturn func+return get_cartdef get_or_create_anonymous_cart_from_token(token, cart_queryset=Cart.objects.all()):"""Return an open unassigned cart with given token or create a new one."""- return cart_queryset.filter(token=token, user=None).get_or_create(- defaults={'user': None})[0]+ return cart_queryset.filter(+ token=token, user=None).get_or_create(defaults={'user': None})[0]def get_or_create_user_cart(user, cart_queryset=Cart.objects.all()):@@ -222,6 +221,7 @@ def get_or_create_db_cart(cart_queryset=Cart.objects.all()):If no matching cart is found, one will be created and a cookie will be setfor users who are not logged in."""+# FIXME: behave like middleware and assign cart to request insteaddef get_cart(view):@wraps(view)@@ -231,7 +231,9 @@ def get_or_create_db_cart(cart_queryset=Cart.objects.all()):if not request.user.is_authenticated:set_cart_cookie(cart, response)return response+return func+return get_cart@@ -243,13 +245,16 @@ def get_or_empty_db_cart(cart_queryset=Cart.objects.all()):If no matching cart is found, an unsaved `Cart` instance will be used."""+# FIXME: behave like middleware and assign cart to request insteaddef get_cart(view):@wraps(view)def func(request, *args, **kwargs):cart = get_cart_from_request(request, cart_queryset)return view(request, cart, *args, **kwargs)+return func+return get_cart@@ -324,12 +329,15 @@ def add_variant_to_cart(of added to."""line, _ = cart.lines.get_or_create(- variant=variant, defaults={'quantity': 0, 'data': {}})+ variant=variant, defaults={+ 'quantity': 0,+ 'data': {}})new_quantity = quantity if replace else (quantity + line.quantity)if new_quantity < 0:- raise ValueError('%r is not a valid quantity (results in %r)' % (- quantity, new_quantity))+ raise ValueError(+ '%r is not a valid quantity (results in %r)' %+ (quantity, new_quantity))if new_quantity == 0:line.delete()@@ -350,23 +358,21 @@ def get_shipping_address_forms(cart, user_addresses, data, country):if shipping_address and shipping_address in user_addresses:address_form, preview = get_address_form(- data, country_code=country.code,- initial={'country': country})+ data, country_code=country.code, initial={'country': country})addresses_form = AddressChoiceForm(- data, addresses=user_addresses,+ data,+ addresses=user_addresses,initial={'address': shipping_address.id})elif shipping_address:address_form, preview = get_address_form(- data, country_code=shipping_address.country.code,+ data,+ country_code=shipping_address.country.code,instance=shipping_address)- addresses_form = AddressChoiceForm(- data, addresses=user_addresses)+ addresses_form = AddressChoiceForm(data, addresses=user_addresses)else:address_form, preview = get_address_form(- data, country_code=country.code,- initial={'country': country})- addresses_form = AddressChoiceForm(- data, addresses=user_addresses)+ data, country_code=country.code, initial={'country': country})+ addresses_form = AddressChoiceForm(data, addresses=user_addresses)return address_form, addresses_form, preview@@ -400,7 +406,8 @@ def update_shipping_address_in_cart(cart, user_addresses, data, country):def update_shipping_address_in_anonymous_cart(cart, data, country):"""Return shipping address choice forms and if an address was updated."""address_form, preview = get_address_form(- data, country_code=country.code,+ data,+ country_code=country.code,autocomplete_type='shipping',instance=cart.shipping_address,initial={'country': country})@@ -425,29 +432,35 @@ def get_billing_forms_with_shipping(cart, data, user_addresses, country):if not billing_address.id or billing_address == shipping_address:address_form, preview = get_address_form(- data, country_code=shipping_address.country.code,+ data,+ country_code=shipping_address.country.code,autocomplete_type='billing',initial={'country': shipping_address.country})addresses_form = BillingAddressChoiceForm(- data, addresses=user_addresses, initial={- 'address': BillingAddressChoiceForm.SHIPPING_ADDRESS})+ data,+ addresses=user_addresses,+ initial={'address': BillingAddressChoiceForm.SHIPPING_ADDRESS})elif billing_address in user_addresses:address_form, preview = get_address_form(- data, country_code=billing_address.country.code,+ data,+ country_code=billing_address.country.code,autocomplete_type='billing',initial={'country': billing_address.country})addresses_form = BillingAddressChoiceForm(- data, addresses=user_addresses, initial={- 'address': billing_address.id})+ data,+ addresses=user_addresses,+ initial={'address': billing_address.id})else:address_form, preview = get_address_form(- data, country_code=billing_address.country.code,+ data,+ country_code=billing_address.country.code,autocomplete_type='billing',initial={'country': billing_address.country},instance=billing_address)addresses_form = BillingAddressChoiceForm(- data, addresses=user_addresses, initial={- 'address': BillingAddressChoiceForm.NEW_ADDRESS})+ data,+ addresses=user_addresses,+ initial={'address': BillingAddressChoiceForm.NEW_ADDRESS})return address_form, addresses_form, preview@@ -487,12 +500,16 @@ def get_anonymous_summary_without_shipping_forms(cart, data, country):if billing_address:address_form, preview = get_address_form(- data, country_code=billing_address.country.code,- autocomplete_type='billing', instance=billing_address)+ data,+ country_code=billing_address.country.code,+ autocomplete_type='billing',+ instance=billing_address)else:address_form, preview = get_address_form(- data, country_code=country.code,- autocomplete_type='billing', initial={'country': country})+ data,+ country_code=country.code,+ autocomplete_type='billing',+ initial={'country': country})return address_form, preview@@ -584,14 +601,12 @@ def _check_new_cart_address(cart, address, address_type):old_address = cart.shipping_addresshas_address_changed = any([- not address and old_address,- address and not old_address,- address and old_address and address != old_address])+ not address and old_address, address and not old_address, address+ and old_address and address != old_address])remove_old_address = (- has_address_changed and- old_address is not None and- (not cart.user or old_address not in cart.user.addresses.all()))+ has_address_changed and old_address is not None+ and (not cart.user or old_address not in cart.user.addresses.all()))return has_address_changed, remove_old_address@@ -643,14 +658,12 @@ def _get_shipping_voucher_discount_for_cart(voucher, cart):"""Calculate discount value for a voucher of shipping type."""if not cart.is_shipping_required():msg = pgettext(- 'Voucher not applicable',- 'Your order does not require shipping.')+ 'Voucher not applicable', 'Your order does not require shipping.')raise NotApplicable(msg)shipping_method = cart.shipping_methodif not shipping_method:msg = pgettext(- 'Voucher not applicable',- 'Please select a shipping method first.')+ 'Voucher not applicable', 'Please select a shipping method first.')raise NotApplicable(msg)not_valid_for_country = all([voucher.countries, ANY_COUNTRY not in voucher.countries,@@ -693,8 +706,8 @@ def get_voucher_discount_for_cart(voucher, cart):return get_value_voucher_discount(voucher, cart.get_subtotal())if voucher.type == VoucherType.SHIPPING:return _get_shipping_voucher_discount_for_cart(voucher, cart)- if voucher.type in (- VoucherType.PRODUCT, VoucherType.COLLECTION, VoucherType.CATEGORY):+ if voucher.type in (VoucherType.PRODUCT, VoucherType.COLLECTION,+ VoucherType.CATEGORY):return _get_products_voucher_discount(cart, voucher)raise NotImplementedError('Unknown discount type')@@ -732,8 +745,8 @@ def recalculate_cart_discount(cart, discounts, taxes):if voucher.translated.name != voucher.name else '')cart.save(update_fields=[- 'translated_discount_name',- 'discount_amount', 'discount_name'])+ 'translated_discount_name', 'discount_amount',+ 'discount_name'])else:remove_voucher_from_cart(cart)@@ -846,6 +859,10 @@ def _fill_order_with_cart_data(order, cart, discounts, taxes):add_variant_to_order(order, line.variant, line.quantity, discounts, taxes)+ for payment_method in cart.payment_methods.all():+ payment_method.order = order+ payment_method.save(update_fields=['order'])+if cart.note:order.customer_note = cart.noteorder.save(update_fields=['customer_note'])diff --git a/saleor/order/models.py b/saleor/order/models.pyindex c2f4bd92c6..df310d2277 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -59,54 +59,76 @@ class OrderQueryset(models.QuerySet):class Order(models.Model):- created = models.DateTimeField(- default=now, editable=False)+ created = models.DateTimeField(default=now, editable=False)status = models.CharField(- max_length=32, default=OrderStatus.UNFULFILLED,+ max_length=32,+ default=OrderStatus.UNFULFILLED,choices=OrderStatus.CHOICES)user = models.ForeignKey(- settings.AUTH_USER_MODEL, blank=True, null=True, related_name='orders',+ settings.AUTH_USER_MODEL,+ blank=True,+ null=True,+ related_name='orders',on_delete=models.SET_NULL)language_code = models.CharField(max_length=35, default=settings.LANGUAGE_CODE)tracking_client_id = models.CharField(max_length=36, blank=True, editable=False)billing_address = models.ForeignKey(- Address, related_name='+', editable=False, null=True,+ Address,+ related_name='+',+ editable=False,+ null=True,on_delete=models.SET_NULL)shipping_address = models.ForeignKey(- Address, related_name='+', editable=False, null=True,+ Address,+ related_name='+',+ editable=False,+ null=True,on_delete=models.SET_NULL)user_email = models.EmailField(blank=True, default='')shipping_method = models.ForeignKey(ShippingMethod, blank=True, null=True, related_name='orders',on_delete=models.SET_NULL)shipping_price_net = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES,- default=0, editable=False)+ default=0,+ editable=False)shipping_price_gross = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES,- default=0, editable=False)+ default=0,+ editable=False)shipping_price = TaxedMoneyField(net_field='shipping_price_net', gross_field='shipping_price_gross')shipping_method_name = models.CharField(max_length=255, null=True, default=None, blank=True, editable=False)token = models.CharField(max_length=36, unique=True, blank=True)total_net = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0)total_gross = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0)total = TaxedMoneyField(net_field='total_net', gross_field='total_gross')voucher = models.ForeignKey(- Voucher, blank=True, null=True, related_name='+',+ Voucher,+ blank=True,+ null=True,+ related_name='+',on_delete=models.SET_NULL)discount_amount = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,- decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0)+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0)discount_name = models.CharField(max_length=255, default='', blank=True)translated_discount_name = models.CharField(max_length=255, default='', blank=True)@@ -118,10 +140,10 @@ class Order(models.Model):objects = OrderQueryset.as_manager()class Meta:- ordering = ('-pk',)+ ordering = ('-pk', )permissions = (('manage_orders',- pgettext_lazy('Permission description', 'Manage orders.')),)+ pgettext_lazy('Permission description', 'Manage orders.')), )def save(self, *args, **kwargs):if not self.token:@@ -150,10 +172,10 @@ class Order(models.Model):return iter(self.lines.all())def __repr__(self):- return '<Order #%r>' % (self.id,)+ return '<Order #%r>' % (self.id, )def __str__(self):- return '#%d' % (self.id,)+ return '#%d' % (self.id, )def get_absolute_url(self):return reverse('order:details', kwargs={'token': self.token})@@ -175,7 +197,8 @@ class Order(models.Model):return Nonedef is_pre_authorized(self):- return self.payments.filter(status=PaymentStatus.PREAUTH).exists()+ # FIXME: Check for really pre-authorized transactions+ return self.payment_methods.filter(is_active=True).exists()@propertydef quantity_fulfilled(self):@@ -225,10 +248,12 @@ class OrderLine(models.Model):quantity_fulfilled = models.IntegerField(validators=[MinValueValidator(0)], default=0)unit_price_net = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES)unit_price_gross = MoneyField(- currency=settings.DEFAULT_CURRENCY, max_digits=12,+ currency=settings.DEFAULT_CURRENCY,+ max_digits=12,decimal_places=settings.DEFAULT_DECIMAL_PLACES)unit_price = TaxedMoneyField(net_field='unit_price_net', gross_field='unit_price_gross')@@ -249,17 +274,20 @@ class OrderLine(models.Model):class Fulfillment(models.Model):fulfillment_order = models.PositiveIntegerField(editable=False)order = models.ForeignKey(- Order, related_name='fulfillments', editable=False,+ Order,+ related_name='fulfillments',+ editable=False,on_delete=models.CASCADE)status = models.CharField(- max_length=32, default=FulfillmentStatus.FULFILLED,+ max_length=32,+ default=FulfillmentStatus.FULFILLED,choices=FulfillmentStatus.CHOICES)tracking_number = models.CharField(max_length=255, default='', blank=True)shipping_date = models.DateTimeField(default=now, editable=False)def __str__(self):- return pgettext_lazy(- 'Fulfillment str', 'Fulfillment #%s') % (self.composed_id,)+ return pgettext_lazy('Fulfillment str',+ 'Fulfillment #%s') % (self.composed_id, )def __iter__(self):return iter(self.lines.all())@@ -298,7 +326,7 @@ class Payment(BasePayment):Order, related_name='payments', on_delete=models.PROTECT)class Meta:- ordering = ('-pk',)+ ordering = ('-pk', )def get_failure_url(self):return build_absolute_uri(@@ -312,11 +340,11 @@ class Payment(BasePayment):def get_purchased_items(self):lines = [PurchasedItem(- name=line.product_name, sku=line.product_sku,+ name=line.product_name,+ sku=line.product_sku,quantity=line.quantity,price=line.unit_price_net.quantize(Decimal('0.01')).amount,- currency=line.unit_price.currency)- for line in self.order]+ currency=line.unit_price.currency) for line in self.order]voucher = self.order.voucherif voucher is not None:diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 95577612b8..0555e590d1 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -16,6 +16,7 @@ from . import FulfillmentStatusfrom ..account.forms import LoginFormfrom ..account.models import Userfrom ..core.utils import get_client_ip+from ..checkout.models import PaymentMethodfrom .forms import (CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentMethodsForm)from .models import Order, Payment@@ -41,7 +42,9 @@ def details(request, token):fulfillments = order.fulfillments.filter(status=FulfillmentStatus.FULFILLED)ctx = {- 'order': order, 'fulfillments': fulfillments, 'note_form': note_form}+ 'order': order,+ 'fulfillments': fulfillments,+ 'note_form': note_form}return TemplateResponse(request, 'order/details.html', ctx)@@ -74,7 +77,9 @@ def payment(request, token):return redirect('order:payment', token=order.token, variant=payment_method)ctx = {- 'order': order, 'payment_form': payment_form, 'payments': payments,+ 'order': order,+ 'payment_form': payment_form,+ 'payments': payments,'waiting_payment': waiting_payment,'waiting_payment_form': waiting_payment_form}return TemplateResponse(request, 'order/payment.html', ctx)@@ -92,7 +97,6 @@ def start_payment(request, order, variant):'total': total.gross.amount,'tax': total.tax.amount,'currency': total.currency,- 'delivery': order.shipping_price.net.amount,'billing_first_name': billing.first_name,'billing_last_name': billing.last_name,'billing_address_1': billing.street_address_1,@@ -101,33 +105,36 @@ def start_payment(request, order, variant):'billing_postcode': billing.postal_code,'billing_country_code': billing.country.code,'billing_email': order.user_email,- 'description': pgettext_lazy(- 'Payment description', 'Order %(order_number)s') % {- 'order_number': order},'billing_country_area': billing.country_area,'customer_ip_address': get_client_ip(request)}variant_choices = settings.CHECKOUT_PAYMENT_CHOICESif variant not in [code for code, dummy_name in variant_choices]:- raise Http404('%r is not a valid payment variant' % (variant,))+ raise Http404('%r is not a valid payment variant' % (variant, ))with transaction.atomic():- payment, dummy_created = Payment.objects.get_or_create(- variant=variant, status=PaymentStatus.WAITING, order=order,- defaults=defaults)- try:- form = payment.get_form(data=request.POST or None)- except RedirectNeeded as redirect_to:- return redirect(str(redirect_to))- except Exception:- logger.exception('Error communicating with the payment gateway')- msg = pgettext_lazy(- 'Payment gateway error',- 'Oops, it looks like we were unable to contact the selected '- 'payment service')- messages.error(request, msg)- payment.change_status(PaymentStatus.ERROR)- return redirect('order:payment', token=order.token)+ payment_method, dummy_created = PaymentMethod.objects.get_or_create(+ variant=variant, is_active=True, order=order, defaults=defaults)+ from ..checkout.forms import PaymentMethodForm+ form = PaymentMethodForm(+ data=request.POST or None, instance=payment_method)+ form.method = "POST"+ if form.is_valid():+ form.save()+ return redirect(order.get_absolute_url())+ # try:+ # form = payment.get_form(data=request.POST or None)+ # except RedirectNeeded as redirect_to:+ # return redirect(str(redirect_to))+ # except Exception:+ # logger.exception('Error communicating with the payment gateway')+ # msg = pgettext_lazy(+ # 'Payment gateway error',+ # 'Oops, it looks like we were unable to contact the selected '+ # 'payment service')+ # messages.error(request, msg)+ # payment.change_status(PaymentStatus.ERROR)+ # return redirect('order:payment', token=order.token)template = 'order/payment/%s.html' % variant- ctx = {'form': form, 'payment': payment}+ ctx = {'form': form, 'payment': payment_method}return TemplateResponse(request, [template, 'order/payment/default.html'], ctx)@@ -201,7 +208,6 @@ def connect_order_with_user(request, token):return redirect('account:details')attach_order_to_user(order, request.user)msg = pgettext_lazy(- 'storefront message',- 'The order is now assigned to your account')+ 'storefront message', 'The order is now assigned to your account')messages.success(request, msg)return redirect('order:details', token=order.token)