Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
WIP
Pacu209d9d3785f85
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex ee3c7c5ea3..b76490f06f 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -384,7 +384,7 @@ def create_transactions(payment):if payment.status == PaymentMethodChargeStatus.NOT_CHARGED:if random.randint(0, 1):payment.transactions.create(- transaction_type=TransactionType.RELEASE,+ transaction_type=TransactionType.VOID,is_success=True, amount=payment.total,currency=payment.currency)returndiff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex a5c9fc164f..d36025c16d 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -4,7 +4,7 @@ from django.core.validators import MinValueValidatorfrom django.urls import reverse, reverse_lazyfrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_prices.forms import MoneyField-from payments import PaymentError, PaymentStatus+from payments import PaymentErrorfrom ...account.i18n import (AddressForm as StorefrontAddressForm, PossiblePhoneNumberFormField)@@ -15,12 +15,12 @@ from ...core.utils.taxes import ZERO_TAXED_MONEYfrom ...discount.models import Voucherfrom ...discount.utils import decrease_voucher_usage, increase_voucher_usagefrom ...order import CustomPaymentChoices, OrderStatus-from ...order.models import (- Fulfillment, FulfillmentLine, Order, OrderLine, Payment)+from ...order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ...order.utils import (add_variant_to_order, cancel_fulfillment, cancel_order,change_order_line_quantity, recalculate_order)from ...payment import PaymentMethodChargeStatus+from ...payment.models import PaymentMethodfrom ...product.models import Product, ProductVariantfrom ...product.utils import allocate_stock, deallocate_stockfrom ...shipping.models import ShippingMethod@@ -362,9 +362,9 @@ class OrderMarkAsPaidForm(forms.Form):'Payment description', 'Order %(order)s') % {'order': self.order},'captured_amount': self.order.total.gross.amount}- Payment.objects.get_or_create(+ PaymentMethod.objects.get_or_create(variant=CustomPaymentChoices.MANUAL,- status=PaymentStatus.CONFIRMED, order=self.order,+ status=PaymentMethodChargeStatus.CHARGED, order=self.order,defaults=defaults)@@ -531,7 +531,7 @@ class OrderRemoveVoucherForm(forms.ModelForm):PAYMENT_STATUS_CHOICES = ([('', pgettext_lazy('Payment status field value', 'All'))] +- PaymentStatus.CHOICES)+ PaymentMethodChargeStatus.CHOICES)class PaymentFilterForm(forms.Form):diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 74c86be7db..890b822433 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -21,6 +21,7 @@ from .types import Checkout, CheckoutLinedef clean_shipping_method(checkout, method, errors, discounts, taxes, country_code=None):+ # FIXME Add tests for this functionif not method:return errorsif not checkout.is_shipping_required():@@ -55,6 +56,7 @@ def check_lines_quantity(variants, quantities):"""Check if stock is sufficient for each line in the list of dicts.Return list of errors."""+ # FIXME Add testserrors = []for variant, quantity in zip(variants, quantities):@@ -276,15 +278,24 @@ class CheckoutShippingAddressUpdate(BaseMutation):description = 'Update shipping address in the existing Checkout.'@classmethod- def mutate(cls, root, info, checkout_id, shipping_address):+ def clean_address(cls, address, errors):+ if address:+ address = Address(**address)+ cls.clean_instance(address, errors)+ return address++ @classmethod+ def mutate(+ cls, root, info, checkout_id, shipping_address, billing_adddress):errors = []checkout = cls.get_node_or_error(info, checkout_id, errors, 'checkout_id', only_type=Checkout)-- shipping_address = Address(**shipping_address)- cls.clean_instance(shipping_address, errors)+ if shipping_address:+ shipping_address = cls.clean_address(shipping_address, errors)+ if billing_adddress:+ billing_adddress = cls.clean_address(shipping_address, errors)if errors:- CheckoutShippingAddressUpdate(errors=errors)+ return CheckoutShippingAddressUpdate(errors=errors)clean_shipping_method(checkout, checkout.shipping_method, errors,@@ -322,6 +333,7 @@ class CheckoutEmailUpdate(BaseMutation):class CheckoutShippingMethodUpdate(BaseMutation):+ # FIXME test this mutationscheckout = graphene.Field(Checkout, description='An updated checkout')class Arguments:diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex 0635dca025..4d4e2dd79c 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -1,7 +1,6 @@import graphenefrom django.utils.translation import pgettext_lazyfrom graphql_jwt.decorators import permission_required-from payments import PaymentError, PaymentStatusfrom ....account.models import Userfrom ....core.utils.taxes import ZERO_TAXED_MONEY@@ -13,6 +12,8 @@ from ...core.mutations import BaseMutationfrom ...core.types.common import Decimal, Errorfrom ...order.mutations.draft_orders import DraftOrderUpdatefrom ...order.types import Order, OrderEvent+from ....payment import PaymentError, PaymentMethodChargeStatus+from ....payment.models import PaymentMethodfrom ...shipping.types import ShippingMethod@@ -297,9 +298,9 @@ class OrderMarkAsPaid(BaseMutation):'description': pgettext_lazy('Payment description', 'Order %(order)s') % {'order': order},'captured_amount': order.total.gross.amount}- models.Payment.objects.get_or_create(+ models.PaymentMethod.objects.get_or_create(variant=CustomPaymentChoices.MANUAL,- status=PaymentStatus.CONFIRMED, order=order,+ charge_status=PaymentMethodChargeStatus.CHARGED, order=order,defaults=defaults)order.events.create(diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex c2ca56d4d3..9efa3ff75a 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -213,7 +213,7 @@ class Order(CountableDjangoObjectType):@gql_optimizer.resolver_hints(prefetch_related='payments')def resolve_total_captured(obj, info):payment = obj.get_last_payment()- #FIXME adjust to multiple payments+ # FIXME adjust to multiple paymentsif payment:return payment.get_captured_money()diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex d77a024455..e2e94051ad 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -15,24 +15,20 @@ class TransactionType:source. Money does not change hands until theauthorization is captured.- Charge: Authorization and capture in a single step.- - Void: A cancellation of a pending authorization.+ - Void: A cancellation of a pending authorization or capture.- Capture: A transfer of the money that was reserved during theauthorization stage.- Refund: Full or partial return of captured funds to the customer.- - Release: Release of the funds that were reserved during the authorization- stage to the customer's funding source."""AUTH = 'auth'CHARGE = 'capture'CAPTURE = 'capture'VOID = 'void'REFUND = 'refund'- RELEASE = 'release'CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),(CHARGE, pgettext_lazy('transaction type', 'Charge')),(REFUND, pgettext_lazy('transaction type', 'Refund')),- (RELEASE, pgettext_lazy('transaction type', 'Release')),(CAPTURE, pgettext_lazy('transaction type', 'Capture')),(VOID, pgettext_lazy('transaction type', 'Void'))]@@ -47,6 +43,11 @@ class PaymentMethodChargeStatus:CHARGED = 'charged'NOT_CHARGED = 'not-charged'FULLY_REFUNDED = 'fully-refunded'+ # FIXME+ # We should probably support other statuses, like:+ # pending+ # partially charged+ # partially refundedCHOICES = [(CHARGED, pgettext_lazy('payment method status', 'Charged')),diff --git a/saleor/payment/migrations/0002_auto_20181012_0517.py b/saleor/payment/migrations/0002_auto_20181012_0517.pynew file mode 100644index 0000000000..5612656c7e--- /dev/null+++ b/saleor/payment/migrations/0002_auto_20181012_0517.py@@ -0,0 +1,41 @@+# Generated by Django 2.1.1 on 2018-10-12 10:17++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ('payment', '0001_initial'),+ ]++ operations = [+ migrations.AddField(+ model_name='transaction',+ name='created',+ field=models.DateTimeField(auto_now_add=True, default=None),+ preserve_default=False,+ ),+ migrations.AddField(+ model_name='transaction',+ name='currency',+ field=models.CharField(default=None, editable=False, max_length=10),+ preserve_default=False,+ ),+ migrations.AlterField(+ model_name='paymentmethod',+ name='order',+ field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='payment_methods', to='order.Order'),+ ),+ migrations.AlterField(+ model_name='transaction',+ name='payment_method',+ field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='transactions', to='payment.PaymentMethod'),+ ),+ migrations.AlterField(+ model_name='transaction',+ name='transaction_type',+ field=models.CharField(choices=[('auth', 'Authorization'), ('capture', 'Charge'), ('refund', 'Refund'), ('capture', 'Capture'), ('void', 'Void')], max_length=10),+ ),+ ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 0b58172d7f..53de034ff0 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -22,6 +22,8 @@ class PaymentMethod(models.Model):within a single order."""variant = models.CharField(max_length=255)+ # FIXME probably we should have error/pending/active status instead of+ # a boolis_active = models.BooleanField(default=True)#: Creation date and timecreated = models.DateTimeField(auto_now_add=True)@@ -113,6 +115,8 @@ class Transaction(models.Model):token = models.CharField(max_length=64, blank=True, default='')transaction_type = models.CharField(max_length=10, choices=TransactionType.CHOICES)+ # FIXME probably we should have error/pending/success status instead of+ # a bool, eg for payments with 3d secureis_success = models.BooleanField(default=False)amount = models.DecimalField(max_digits=9, decimal_places=2, default=Decimal('0.0'))diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.pyindex e139eda5af..3c7068f09a 100644--- a/saleor/payment/providers/braintree/__init__.py+++ b/saleor/payment/providers/braintree/__init__.py@@ -97,6 +97,8 @@ def authorize(payment_method, transaction_token, **client_kwargs):def capture(payment_method, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)+ # FIXME we are assuming that appropriate transaction exists without+ # forcing the flowauth_transaction = payment_method.transactions.filter(transaction_type=TransactionType.AUTH).first()if not amount:@@ -118,6 +120,8 @@ def capture(payment_method, amount=None, **client_kwargs):def void(payment_method, **client_kwargs):gateway = get_gateway(**client_kwargs)+ # FIXME we are assuming that appropriate transaction exists without+ # forcing the flowauth_transaction = payment_method.transactions.filter(transaction_type=TransactionType.AUTH).first()result = gateway.transaction.void(transaction_id=auth_transaction.token)@@ -135,6 +139,8 @@ def void(payment_method, **client_kwargs):def refund(payment_method, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)+ # FIXME we are assuming that appropriate transaction exists without+ # forcing the flowauth_transaction = payment_method.transactions.filter(transaction_type=TransactionType.CAPTURE).first()result = gateway.transaction.refund(diff --git a/tests/conftest.py b/tests/conftest.pyindex d4c92e2eda..1dc28b4010 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -492,7 +492,7 @@ def payment_method_txn_preauth(order_with_lines, payment_method_dummy):@pytest.fixture()-def payment_method_txn_charged(order_with_lines, payment_method_dummy):+def payment_method_txn_captured(order_with_lines, payment_method_dummy):order = order_with_linespayment = payment_method_dummypayment.order = order@@ -503,7 +503,7 @@ def payment_method_txn_charged(order_with_lines, payment_method_dummy):payment.transactions.create(amount=payment.total,- transaction_type=TransactionType.CHARGE,+ transaction_type=TransactionType.CAPTURE,gateway_response={},is_success=True)return paymentdiff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex e412cbb592..b794419369 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -84,11 +84,11 @@ def test_view_capture_order_payment_preauth(@pytest.mark.integrationdef test_view_capture_order_invalid_payment_confirmed_status(- admin_client, order_with_lines, payment_method_txn_charged):+ admin_client, order_with_lines, payment_method_txn_captured):order = order_with_linesurl = reverse('dashboard:capture-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_charged.pk})+ 'order_pk': order.pk, 'payment_pk': payment_method_txn_captured.pk})response = admin_client.get(url)assert response.status_code == 200@@ -132,9 +132,9 @@ def test_view_capture_order_invalid_payment_refunded_status(@pytest.mark.integrationdef test_view_refund_order_payment_confirmed(- admin_client, order_with_lines, payment_method_txn_charged):+ admin_client, order_with_lines, payment_method_txn_captured):order = order_with_lines- payment_confirmed = payment_method_txn_charged+ payment_confirmed = payment_method_txn_capturedurl = reverse('dashboard:refund-payment', kwargs={'order_pk': order.pk, 'payment_pk': payment_confirmed.pk})@@ -228,12 +228,12 @@ def test_view_release_order_payment_preauth(@pytest.mark.integrationdef test_view_release_order_invalid_payment_confirmed_status(- admin_client, order_with_lines, payment_method_txn_charged):+ admin_client, order_with_lines, payment_method_txn_captured):order = order_with_linesurl = reverse('dashboard:release-payment', kwargs={- 'order_pk': order.pk, 'payment_pk': payment_method_txn_charged.pk})+ 'order_pk': order.pk, 'payment_pk': payment_method_txn_captured.pk})response = admin_client.get(url)assert response.status_code == 200