internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: dj-stripe/dj-stripe

Issue:
Django 1.10 support
https://github.com/kavdev/dj-stripe/blob/master/djstripe/__init__.py#L19

`'1.10'` is less than `'1.7.x'`



Discussion:

Resolving patch:
diff --git a/djstripe/__init__.py b/djstripe/__init__.py
--- a/djstripe/__init__.py
+++ b/djstripe/__init__.py
@@ -1,7 +1,7 @@
 from __future__ import unicode_literals
 import warnings
 
-from django import get_version as get_django_version
+from django import VERSION as django_version
 
 __title__ = "dj-stripe"
 __summary__ = "Django + Stripe Made Easy"
@@ -16,7 +16,7 @@
 __license__ = "License :: OSI Approved :: BSD License"
 __copyright__ = "Copyright 2016 Alexander Kavanaugh"
 
-if get_django_version() <= '1.7.x':
+if django_version < (1, 8):
     msg = "dj-stripe deprecation notice: Django 1.7 and lower are no longer\n" \
         "supported. Please upgrade to Django 1.8 or higher.\n" \
         "Reference: https://github.com/kavdev/dj-stripe/issues/275"


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
"Received unknown parameter: api_key" on Card.api_list()
How to reproduce:

```py
c = Customer.objects.first()
Card.api_list(customer=c)
```

I don't know what's going on exactly here but it looks like it's passing `api_key` in the json body.

This is in `stripe_objects.py` in `StripeCard.api_list`:

`        return customer.api_retrieve().sources.list(api_key=api_key, object="card", **clean_kwargs).auto_paging_iter()`


Discussion:
Removing `api_key=api_key` fixes it.
I think the `api_key` argument was supposed to be passed to the `api_retrieve()` method rather.
Looks like it was added in 0919fd6c and somehow never hit.

Resolving patch:
diff --git a/djstripe/stripe_objects.py b/djstripe/stripe_objects.py
--- a/djstripe/stripe_objects.py
+++ b/djstripe/stripe_objects.py
@@ -1235,7 +1235,7 @@ def api_list(cls, api_key=settings.STRIPE_SECRET_KEY, **kwargs):
 
         customer, clean_kwargs = cls._get_customer_from_kwargs(**kwargs)
 
-        return customer.api_retrieve().sources.list(api_key=api_key, object="card", **clean_kwargs).auto_paging_iter()
+        return customer.api_retrieve(api_key=api_key).sources.list(object="card", **clean_kwargs).auto_paging_iter()
 
     def str_parts(self):
         return [


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Consider making Customers nullable and allowing orphaned objects
When creating a payment from the Stripe dashboard, no customer is associated to the charge by default. dj-stripe crashes when processing its webhook:

```py
    def _attach_objects_hook(self, cls, data):
        customer = cls._stripe_object_to_customer(target_cls=Customer, data=data)
        if customer:
            self.customer = customer
        else:
            raise ValidationError("A customer was not attached to this charge.")
```


Discussion:

Resolving patch:
diff --git a/djstripe/migrations/0027_auto_20170308_0620.py b/djstripe/migrations/0027_auto_20170308_0620.py
new file mode 100644
--- /dev/null
+++ b/djstripe/migrations/0027_auto_20170308_0620.py
@@ -0,0 +1,20 @@
+# Generated by Django 1.10.6 on 2017-03-08 07:18
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('djstripe', '0026_idempotencykey'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='charge',
+            name='customer',
+            field=models.ForeignKey(help_text='The customer associated with this charge.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='charges', to='djstripe.Customer'),
+        ),
+    ]
diff --git a/djstripe/models.py b/djstripe/models.py
--- a/djstripe/models.py
+++ b/djstripe/models.py
@@ -65,7 +65,7 @@ class Charge(StripeCharge):
     )
 
     customer = ForeignKey(
-        "Customer", on_delete=models.CASCADE,
+        "Customer", on_delete=models.CASCADE, null=True,
         related_name="charges",
         help_text="The customer associated with this charge."
     )
@@ -123,8 +123,6 @@ def _attach_objects_hook(self, cls, data):
         customer = cls._stripe_object_to_customer(target_cls=Customer, data=data)
         if customer:
             self.customer = customer
-        else:
-            raise ValidationError("A customer was not attached to this charge.")
 
         transfer = cls._stripe_object_to_transfer(target_cls=Transfer, data=data)
         if transfer:


Test patch:
diff --git a/tests/test_charge.py b/tests/test_charge.py
--- a/tests/test_charge.py
+++ b/tests/test_charge.py
@@ -9,7 +9,6 @@
 from copy import deepcopy
 from decimal import Decimal
 
-from django.core.exceptions import ValidationError
 from django.test.testcases import TestCase
 from mock import patch
 
@@ -101,8 +100,10 @@ def test_sync_from_stripe_data_no_customer(self, default_account_mock):
         fake_charge_copy = deepcopy(FAKE_CHARGE)
         fake_charge_copy.pop("customer", None)
 
-        with self.assertRaisesMessage(ValidationError, "A customer was not attached to this charge."):
-            Charge.sync_from_stripe_data(fake_charge_copy)
+        Charge.sync_from_stripe_data(fake_charge_copy)
+        assert Charge.objects.count() == 1
+        charge = Charge.objects.get()
+        assert charge.customer is None
 
     @patch("stripe.Charge.retrieve")
     @patch("stripe.Transfer.retrieve")
Repository: dj-stripe/dj-stripe

Issue:
Creating customer fails becuase "shipping" is required
Similar to #680 - the shipping field on a Customer object is not required by Stripe but djstripe errors if the field is not present.


Discussion:

Resolving patch:
diff --git a/djstripe/models.py b/djstripe/models.py
--- a/djstripe/models.py
+++ b/djstripe/models.py
@@ -797,7 +797,7 @@ class Customer(StripeObject):
     )
     # </discount>
     email = StripeTextField(null=True)
-    shipping = StripeJSONField(null=True, help_text="Shipping information associated with the customer.")
+    shipping = StripeJSONField(stripe_required=False, help_text="Shipping information associated with the customer.")
 
     # dj-stripe fields
     subscriber = ForeignKey(


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
1.1.0 not compatible with python 2
First of all, thanks a lot for your hard work! We've been using dj-stripe for a long time and it has served us well. Now we're ready to upgrade! Let the fun begin ;).

We're using python 2 and Django 1.11. I'm correct that 1.2 should support that right? Anyway we have to move to 1.1 first for the migrations. There is one problem though in the 1.1 release.

In commit https://github.com/dj-stripe/dj-stripe/commit/6a6f048a3a432a3ba40fba8bf90f8789139daec4 `StripeEnumField` was added with the non python 2 compatible `super()` call:

```name, path, args, kwargs = super().deconstruct()```

What do you guys think? Can we backport a hotfix fix to 1.1.1 or something?



Discussion:

Resolving patch:
diff --git a/djstripe/fields.py b/djstripe/fields.py
--- a/djstripe/fields.py
+++ b/djstripe/fields.py
@@ -174,7 +174,7 @@ def __init__(self, enum, *args, **kwargs):
         super(StripeEnumField, self).__init__(*args, **defaults)
 
     def deconstruct(self):
-        name, path, args, kwargs = super().deconstruct()
+        name, path, args, kwargs = super(StripeEnumField, self).deconstruct()
         kwargs["enum"] = self.enum
         del kwargs["choices"]
         return name, path, args, kwargs


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Cannot specify billing_cycle_anchor attribute for a Subscription
According to the documentation the ` billing_cycle_anchor ` attribute can be used when creating and updating a subscription.

>  billing_cycle_anchor (timestamp)
>
> Determines the date of the first full invoice, and, for plans with month or year intervals, the day of the month for subsequent invoices.

This is particularly useful for the use case of [Combining trials with billing cycle anchor](https://stripe.com/docs/billing/subscriptions/trials#combine-trial-anchor).

As I understand, djstripe supports this option:

https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/models/billing.py#L939

However when using `customer.subscribe()` you cannot specify this parameter

https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/models/core.py#L512

I am willing to contribute but need some guidance. Is adding it as a parameter to that function and then when calling `Subscription._api_create` enough?


Discussion:

Resolving patch:
diff --git a/djstripe/models.py b/djstripe/models.py
--- a/djstripe/models.py
+++ b/djstripe/models.py
@@ -915,7 +915,7 @@ def pending_charges(self):
     def subscribe(
         self, plan, charge_immediately=True, application_fee_percent=None, coupon=None,
         quantity=None, metadata=None, tax_percent=None, trial_end=None, trial_from_plan=None,
-        trial_period_days=None
+        trial_period_days=None, billing_cycle_anchor=None
     ):
         """
         Subscribes this customer to a plan.
@@ -935,6 +935,10 @@ def subscribe(
                                         application fee percentage.
         :type application_fee_percent: Decimal. Precision is 2; anything more will be ignored. A positive
                                        decimal between 1 and 100.
+        :param billing_cycle_anchor: A future timestamp to anchor the subscription’s billing cycle.
+                                     This is used to determine the date of the first full invoice, and, for plans
+                                     with months or year intervals, the day of the month for subsequent invoices.
+        :type billing_cycle_anchor: integer
         :param coupon: The code of the coupon to apply to this subscription. A coupon applied to a subscription
                        will only affect invoices created for that particular subscription.
         :type coupon: string
@@ -977,6 +981,7 @@ def subscribe(
             plan=plan,
             customer=self.stripe_id,
             application_fee_percent=application_fee_percent,
+            billing_cycle_anchor=billing_cycle_anchor,
             coupon=coupon,
             quantity=quantity,
             metadata=metadata,


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Irreversible migrations 
It appears that we're unable to migrate backwards, you should be able to remove the dj-stripe db tables painlessly.  Am I missing something?

Django 2.1.9
dj-stripe==2.0.3

To reproduce- install app, migrate, attempt to migrate backwards
```
./manage.py migrate djstripe zero

django.db.migrations.exceptions.IrreversibleError: Operation <RunPython <function postgres_migration_prep at 0x7fdf1bd8fea0>> in djstripe.0003_auto_20181117_2328_squashed_0004_auto_20190227_2114 is not reversible
```


Discussion:

Resolving patch:
diff --git a/djstripe/migrations/0003_auto_20181117_2328_squashed_0004_auto_20190227_2114.py b/djstripe/migrations/0003_auto_20181117_2328_squashed_0004_auto_20190227_2114.py
--- a/djstripe/migrations/0003_auto_20181117_2328_squashed_0004_auto_20190227_2114.py
+++ b/djstripe/migrations/0003_auto_20181117_2328_squashed_0004_auto_20190227_2114.py
@@ -106,7 +106,7 @@ def __init__(self, *args, **kwargs):
 	dependencies = [("djstripe", "0002_auto_20180627_1121")]
 
 	operations = [
-		migrations.RunPython(postgres_migration_prep),
+		migrations.RunPython(postgres_migration_prep, migrations.RunPython.noop),
 		migrations.AlterField(
 			model_name="account",
 			name="display_name",


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Missing values in SubscriptionStatus: incomplete, incomplete_expired
The values in https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/enums.py#L541 do not match the values in https://stripe.com/docs/api/subscriptions/object#subscription_object-status

Specifically, the `incomplete` and `incomplete_expired` values are missing. This raises an `django.db.utils.DataError` when trying to run `Customer.subscribe` with a payment method that requires 3DS, since the `Subscription.status` field is currently limited to 8 chars.

I'm currently working off of `master` instead of a stable release, since I'm trying to get my Stripe-implementation SCA-ready.

Thanks for a great library!


Discussion:
Thanks for the report!

Resolving patch:
diff --git a/djstripe/enums.py b/djstripe/enums.py
--- a/djstripe/enums.py
+++ b/djstripe/enums.py
@@ -539,6 +539,8 @@ class SubmitTypeStatus(Enum):
 
 
 class SubscriptionStatus(Enum):
+    incomplete = _("Incomplete")
+    incomplete_expired = _("Incomplete Expired")
     trialing = _("Trialing")
     active = _("Active")
     past_due = _("Past due")
diff --git a/djstripe/migrations/0014_auto_20190906_2013.py b/djstripe/migrations/0014_auto_20190906_2013.py
new file mode 100644
--- /dev/null
+++ b/djstripe/migrations/0014_auto_20190906_2013.py
@@ -0,0 +1,23 @@
+# Generated by Django 2.2.4 on 2019-09-06 20:13
+
+from django.db import migrations
+
+import djstripe.enums
+import djstripe.fields
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [("djstripe", "0013_auto_20190903_0230")]
+
+    operations = [
+        migrations.AlterField(
+            model_name="subscription",
+            name="status",
+            field=djstripe.fields.StripeEnumField(
+                enum=djstripe.enums.SubscriptionStatus,
+                help_text="The status of this subscription.",
+                max_length=18,
+            ),
+        )
+    ]


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Document our plan to standardise on storing currency in cents
- [x] Add note on field classes that StripeQuantumCurrencyAmountField should be used for new fields
- [x] Update changelog about 3.0 migration to cents

_Originally posted by @therefromhere in https://github.com/dj-stripe/dj-stripe/issues/955#issuecomment-527251976_


Discussion:

Resolving patch:
diff --git a/djstripe/fields.py b/djstripe/fields.py
--- a/djstripe/fields.py
+++ b/djstripe/fields.py
@@ -47,14 +47,22 @@ def __init__(self, *args, **kwargs):
 
 
 class StripeQuantumCurrencyAmountField(models.IntegerField):
+    """
+    A field used to store currency amounts in cents (etc) as per stripe.
+    """
+
     pass
 
 
 class StripeDecimalCurrencyAmountField(models.DecimalField):
     """
-    A field used to define currency according to djstripe logic.
+    A legacy field to store currency amounts in dollars (etc).
+
+    Stripe is always in cents. Historically djstripe stored everything in dollars.
 
-    Stripe is always in cents. djstripe stores everything in dollars.
+    Note: Don't use this for new fields, use StripeQuantumCurrencyAmountField instead.
+    We're planning on migrating existing fields in dj-stripe 3.0,
+    see https://github.com/dj-stripe/dj-stripe/issues/955
     """
 
     def __init__(self, *args, **kwargs):


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Update documentation examples to mention payment methods
eg https://dj-stripe.readthedocs.io/en/stable/usage/subscribing_customers.html

See #1047


Discussion:

Resolving patch:
diff --git a/djstripe/models/core.py b/djstripe/models/core.py
--- a/djstripe/models/core.py
+++ b/djstripe/models/core.py
@@ -916,8 +916,8 @@ def add_payment_method(self, payment_method, set_default=True):
         :param payment_method: PaymentMethod to be attached to the customer
         :type payment_method: str, PaymentMethod
         :param set_default: If true, this will be set as the default_payment_method
-        :type: bool
-        :return:
+        :type set_default: bool
+        :rtype: PaymentMethod
         """
         from .payment_methods import PaymentMethod
 


Test patch:
Repository: dj-stripe/dj-stripe

Issue:
Account model __str__ tracebacks when settings is NULL
The __str__ method appears to assume that `self.settings` will never contain a NULL value, even though the field parameters allow for NULL values.

This is currently blowing up for me after migrating to 2.2 from 2.1 as it appears the Account models already in the DB have NULLs for the settings field.

Simplest reproduction:
```
>>> from djstripe.models.connect import Account
>>> a = Account()
>>> str(a)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/rccausey/workspace/municipal_alarm_tracking/dj-stripe/djstripe/models/connect.py", line 135, in __str__
    self.settings.get("dashboard", {}).get("display_name")
AttributeError: 'NoneType' object has no attribute 'get'
>>> 
```


Discussion:

Resolving patch:
diff --git a/djstripe/models/connect.py b/djstripe/models/connect.py
--- a/djstripe/models/connect.py
+++ b/djstripe/models/connect.py
@@ -131,9 +131,11 @@ def get_default_account(cls):
         return cls._get_or_create_from_stripe_object(account_data)[0]
 
     def __str__(self):
+        settings = self.settings or {}
+        business_profile = self.business_profile or {}
         return (
-            self.settings.get("dashboard", {}).get("display_name")
-            or self.business_profile.get("name")
+            settings.get("dashboard", {}).get("display_name")
+            or business_profile.get("name")
             or super().__str__()
         )
 


Test patch:
diff --git a/tests/test_account.py b/tests/test_account.py
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -156,3 +156,11 @@ def test_account__create_from_stripe_object(
         save=True,
         stripe_account=expected_stripe_account,
     )
+
+
+def test__str__null_settings_null_business_profile():
+    """Test that __str__ doesn't crash when settings and business_profile are NULL."""
+    account = Account()
+    account.settings = None
+    account.business_profile = None
+    assert str(account) == "<id=>"
Repository: dj-stripe/dj-stripe

Issue:
Paginate sync of Subscription.items + Charge.refunds
I suspect we have the same issue in _stripe_object_to_subscription_items and _stripe_object_to_refunds as per #1052.


Discussion:

Resolving patch:
diff --git a/djstripe/models/base.py b/djstripe/models/base.py
--- a/djstripe/models/base.py
+++ b/djstripe/models/base.py
@@ -698,7 +698,7 @@ def _stripe_object_to_subscription_items(cls, target_cls, data, subscription):
             return []
 
         subscriptionitems = []
-        for item_data in items.get("data", []):
+        for item_data in items.auto_paging_iter():
             item, _ = target_cls._get_or_create_from_stripe_object(
                 item_data, refetch=False
             )
@@ -724,7 +724,7 @@ def _stripe_object_to_refunds(cls, target_cls, data, charge):
             return []
 
         refund_objs = []
-        for refund_data in refunds.get("data", []):
+        for refund_data in refunds.auto_paging_iter():
             item, _ = target_cls._get_or_create_from_stripe_object(
                 refund_data, refetch=False
             )


Test patch:
diff --git a/tests/__init__.py b/tests/__init__.py
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -535,7 +535,12 @@ def detach(self):
 }
 
 
-class ChargeDict(dict):
+class ChargeDict(StripeItem):
+    def __init__(self, *args, **kwargs):
+        """Match Stripe's behavior: return a stripe iterable on `charge.refunds`."""
+        super().__init__(*args, **kwargs)
+        self.refunds = StripeList(self.refunds)
+
     def refund(self, amount=None, reason=None):
         self.update({"refunded": True, "amount_refunded": amount})
         return self
@@ -766,7 +771,12 @@ def capture(self):
 }
 
 
-class SubscriptionDict(dict):
+class SubscriptionDict(StripeItem):
+    def __init__(self, *args, **kwargs):
+        """Match Stripe's behavior: return a stripe iterable on `subscription.items`."""
+        super().__init__(*args, **kwargs)
+        self["items"] = StripeList(self["items"])
+
     def __setattr__(self, name, value):
         if type(value) == datetime:
             value = datetime_to_unix(value)
Repository: dj-stripe/dj-stripe

Issue:
Quick fix of BaseInvoice.paid.help_text
https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/models/billing.py#L408

    paid = models.BooleanField(
        default=False, help_text="The time at which payment will next be attempted."
    )

Should probably be something like:

    paid = models.BooleanField(
        default=False, help_text="Whether this invoice has been fully paid."
    )


Discussion:
Thanks for reporting, looks like a copy-paste error.

It should be: "Whether payment was successfully collected for this invoice. An invoice can be paid (most commonly) with a charge or with credit from the customer’s account balance."

https://stripe.com/docs/api/invoices/object#invoice_object-paid


Resolving patch:
diff --git a/djstripe/migrations/0001_initial.py b/djstripe/migrations/0001_initial.py
--- a/djstripe/migrations/0001_initial.py
+++ b/djstripe/migrations/0001_initial.py
@@ -1438,7 +1438,7 @@ class Migration(migrations.Migration):
                     "paid",
                     models.BooleanField(
                         default=False,
-                        help_text="The time at which payment will next be attempted.",
+                        help_text="Whether payment was successfully collected for this invoice. An invoice can be paid (most commonly) with a charge or with credit from the customer’s account balance.",
                     ),
                 ),
                 (
diff --git a/djstripe/migrations/0005_2_2.py b/djstripe/migrations/0005_2_2.py
--- a/djstripe/migrations/0005_2_2.py
+++ b/djstripe/migrations/0005_2_2.py
@@ -608,7 +608,7 @@ class Migration(migrations.Migration):
                     "paid",
                     models.BooleanField(
                         default=False,
-                        help_text="The time at which payment will next be attempted.",
+                        help_text="Whether payment was successfully collected for this invoice. An invoice can be paid (most commonly) with a charge or with credit from the customer’s account balance.",
                     ),
                 ),
                 (
diff --git a/djstripe/models/billing.py b/djstripe/models/billing.py
--- a/djstripe/models/billing.py
+++ b/djstripe/models/billing.py
@@ -405,7 +405,12 @@ class BaseInvoice(StripeModel):
         ),
     )
     paid = models.BooleanField(
-        default=False, help_text="The time at which payment will next be attempted."
+        default=False,
+        help_text=(
+            "Whether payment was successfully collected for this invoice. An invoice "
+            "can be paid (most commonly) with a charge or with credit from the "
+            "customer’s account balance."
+        ),
     )
     payment_intent = models.OneToOneField(
         "PaymentIntent",


Test patch: