-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
293 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
# -*- coding: utf-8 -*- | ||
# Generated by Django 1.11.5 on 2017-12-11 15:44 | ||
from __future__ import unicode_literals | ||
|
||
import django.core.validators | ||
import django.db.models.deletion | ||
import jsonfield.fields | ||
from django.db import migrations, models | ||
|
||
|
||
def migrate_old_cards(apps, schema_editor): | ||
StripeCard = apps.get_model("aa_stripe", "StripeCard") | ||
StripeCustomer = apps.get_model("aa_stripe", "StripeCustomer") | ||
for customer in StripeCustomer.objects.exclude(stripe_js_response=""): | ||
try: | ||
card_data = customer.stripe_js_response["card"] | ||
card = StripeCard.objects.create(stripe_card_id=card_data["id"], last4=card_data["last4"], | ||
exp_month=card_data["exp_month"], exp_year=card_data["exp_year"], | ||
stripe_response=customer.stripe_js_response, customer=customer) | ||
customer.default_card = card | ||
customer.save() | ||
except KeyError as e: | ||
print("Cannot migrate customer card, key error: {}".format(e)) | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('aa_stripe', '0017_stripecharge_manual_charge'), | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='StripeCard', | ||
fields=[ | ||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||
('is_deleted', models.BooleanField(default=False)), | ||
('created', models.DateTimeField(auto_now_add=True)), | ||
('updated', models.DateTimeField(auto_now=True)), | ||
('stripe_response', jsonfield.fields.JSONField(default=dict)), | ||
('stripe_card_id', models.CharField(help_text='Unique card id in Stripe', db_index=True, max_length=255)), | ||
('last4', models.CharField(help_text='Last 4 digits of the card', max_length=4)), | ||
('exp_month', models.PositiveIntegerField(help_text='Two digit number representing the card’s expiration month', validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(12)])), | ||
('exp_year', models.PositiveIntegerField(help_text='Four digit number representing the card’s expiration year', validators=[django.core.validators.MinValueValidator(1900)])), | ||
('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aa_stripe.StripeCustomer')), | ||
], | ||
options={ | ||
'abstract': False, | ||
}, | ||
), | ||
migrations.AddField( | ||
model_name='stripecustomer', | ||
name='default_card', | ||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='aa_stripe.StripeCard'), | ||
), | ||
migrations.RunPython(migrate_old_cards) | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,36 @@ | ||
from datetime import datetime | ||
|
||
from django.db import models | ||
from django.utils import timezone | ||
|
||
|
||
def timestamp_to_timezone_aware_date(timestamp): | ||
return timezone.make_aware(datetime.fromtimestamp(timestamp)) | ||
|
||
|
||
class SafeDeleteModel(models.Model): | ||
is_deleted = models.BooleanField(default=False) | ||
|
||
class Meta: | ||
abstract = True | ||
|
||
|
||
class SafeDeleteQuerySet(models.query.QuerySet): | ||
def delete(self): | ||
deleted_counter = 0 | ||
for obj in self: | ||
obj.delete() | ||
deleted_counter = deleted_counter + 1 | ||
|
||
return deleted_counter, {self.model._meta.label: deleted_counter} | ||
|
||
|
||
class SafeDeleteManager(models.Manager): | ||
def all_with_deleted(self): | ||
return SafeDeleteQuerySet(self.model, using=self._db) | ||
|
||
def deleted(self): | ||
return self.all_with_deleted().filter(is_deleted=True) | ||
|
||
def get_queryset(self): | ||
return self.all_with_deleted().filter(is_deleted=False) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import requests_mock | ||
import simplejson as json | ||
from tests.test_utils import BaseTestCase | ||
|
||
from aa_stripe.models import StripeCard | ||
|
||
|
||
class TestCards(BaseTestCase): | ||
def _setup_customer_api_mock(self, m): | ||
stripe_customer_response = { | ||
"id": "cus_xyz", | ||
"object": "customer", | ||
"created": 1513013595, | ||
"currency": "usd", | ||
"default_source": None, | ||
"metadata": { | ||
}, | ||
"sources": { | ||
"object": "list", | ||
"data": [ | ||
{"exp_month": 8, "exp_year": 2018, "last4": "4242"} | ||
], | ||
"has_more": False, | ||
"total_count": 0, | ||
"url": "/v1/customers/cus_xyz/sources" | ||
} | ||
} | ||
m.register_uri("GET", "https://api.stripe.com/v1/customers/cus_xyz", status_code=200, | ||
text=json.dumps(stripe_customer_response)) | ||
|
||
def setUp(self): | ||
self._create_user() | ||
self._create_customer("cus_xyz") | ||
|
||
def test_save(self): | ||
# test creating from JS response, Stripe API should not be called | ||
self.assertIsNone(self.customer.default_card) | ||
card = self._create_card() | ||
self.customer.refresh_from_db() | ||
self.assertEqual(self.customer.default_card, card) | ||
|
||
# test creating another card from JS response | ||
# default_card for the customer is already set and should not be updated | ||
card = self._create_card() | ||
self.customer.refresh_from_db() | ||
self.assertNotEqual(self.customer.default_card, card) | ||
|
||
@requests_mock.Mocker() | ||
def test_update(self, m): | ||
card = self._create_card(stripe_card_id="card_xyz") | ||
# test updating a card that no longer exists at Stripe | ||
stripe_card_response = {"id": "card_xyz", "object": "card", "customer": "cus_xyz"} | ||
self._setup_customer_api_mock(m) | ||
m.register_uri( | ||
"GET", "https://api.stripe.com/v1/customers/cus_xyz/sources/card_xyz", [ | ||
{"status_code": 404, "text": json.dumps({"error": {"type": "invalid_request_error"}})}, | ||
{"status_code": 200, "text": json.dumps(stripe_card_response)} | ||
]) | ||
m.register_uri( | ||
"POST", "https://api.stripe.com/v1/customers/cus_xyz/sources/card_xyz", status_code=200, | ||
text=json.dumps(stripe_card_response) | ||
) | ||
card.exp_year = 2020 | ||
card.save() | ||
deleted_qs = StripeCard.objects.deleted() | ||
self.assertTrue(deleted_qs.filter(pk=card.pk).exists()) | ||
|
||
# test correct update (card exists) | ||
card = self._create_card(stripe_card_id="card_xyz") | ||
card.exp_year = 2017 | ||
card.save() | ||
self.assertFalse(deleted_qs.filter(pk=card.pk).exists()) | ||
|
||
@requests_mock.Mocker() | ||
def test_delete(self, m): | ||
# try deleting card that does not exist at Stripe API - should not call Stripe (DELETE) | ||
self._setup_customer_api_mock(m) | ||
m.register_uri( | ||
"GET", "https://api.stripe.com/v1/customers/cus_xyz/sources/card_xyz", status_code=404, | ||
text=json.dumps({"error": {"type": "invalid_request_error"}})) | ||
self._create_card(stripe_card_id="card_xyz") | ||
StripeCard.objects.filter(pk=self.card.pk).update(is_deleted=True) | ||
StripeCard.objects.all_with_deleted().get(pk=self.card.pk).delete() |
Oops, something went wrong.