Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add crowdfunding page and stripe_payments app #1029

Merged
merged 3 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions djangogirls/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def gettext(s):
"donations",
"jobboard",
"globalpartners",
"stripe_payments",
"django.contrib.sitemaps",
]

Expand Down
1 change: 1 addition & 0 deletions donations/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
path("success/<str:currency>/<str:amount>/", views.success, name="success"),
path("error/", views.error, name="error"),
path("sponsors/", views.sponsors, name="sponsors"),
path("crowdfunding/", views.crowdfunding, name="crowdfunding"),
]
7 changes: 7 additions & 0 deletions donations/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from stripe.error import APIConnectionError, CardError, StripeError

from patreonmanager.models import FundraisingStatus
from stripe_payments.models import StripeCharge

from .forms import StripeForm

Expand Down Expand Up @@ -83,3 +84,9 @@ def error(request):

def sponsors(request):
return render(request, "donations/sponsors.html")


def crowdfunding(request):
total_raised = StripeCharge.objects.running_total()["total"]
recent_donors = StripeCharge.objects.all().order_by("-charge_created")[:5]
return render(request, "donations/crowdfunding.html", {"total_raised": total_raised, "donors": recent_donors})
Binary file added static/source/img/global/donate/qr_code.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file added stripe_payments/__init__.py
Empty file.
5 changes: 5 additions & 0 deletions stripe_payments/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.contrib import admin

from .models import StripeCharge

admin.site.register(StripeCharge)
6 changes: 6 additions & 0 deletions stripe_payments/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class StripePaymentsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "stripe_payments"
Empty file.
Empty file.
57 changes: 57 additions & 0 deletions stripe_payments/management/commands/fetch_payments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Management command to fetch Stripe charges from the API since the last fetch
# and store them in the database as StripeCharge objects.

import logging
from datetime import datetime

import stripe
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction

from stripe_payments.models import StripeCharge

logger = logging.getLogger(__name__)


class Command(BaseCommand):
help = (
"Fetch Stripe charges from the API since the last fetch and store them in the "
"database as StripeCharge objects."
)

def handle(self, *args, **options):
logger.debug(
"Fetching Stripe charges from the API since the last fetch and storing "
"them in the database as StripeCharge objects."
)
# Get the last StripeCharge fetched.
try:
last_fetched = StripeCharge.objects.order_by("-fetched").first().fetched
except AttributeError:
# No StripeCharge objects exist.
last_fetched = None
# Fetch the Stripe charges.
stripe.api_key = settings.STRIPE_SECRET_KEY
# stripe.api_version = settings.STRIPE_API_VERSION

# Fetch the Stripe charges.
begin = datetime(2024, 8, 1)

stripe_charges = stripe.Charge.list(
limit=100,
created={"gt": int(last_fetched.timestamp())} if last_fetched else {"gt": int(begin.timestamp())},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I didn't test the begin fallback, but it looks correct to me. 👍

expand=[
"data.customer",
],
)
logger.info("Stripe charges fetched: %s", len(stripe_charges))

# Store the Stripe charges in the database.
with transaction.atomic():
for stripe_charge in stripe_charges:
StripeCharge.objects.create_from_stripe_charge_data(stripe_charge)
logger.debug(
"Fetched Stripe charges from the API since the last fetch and stored them "
"in the database as StripeCharge objects."
)
25 changes: 25 additions & 0 deletions stripe_payments/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 3.2.20 on 2024-07-20 17:57

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='StripeCharge',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('charge_id', models.CharField(editable=False, max_length=255, unique=True)),
('amount', models.IntegerField()),
('payment_data', models.JSONField()),
('charge_created', models.DateTimeField()),
('fetched', models.DateTimeField()),
],
),
]
50 changes: 50 additions & 0 deletions stripe_payments/migrations/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Management command to fetch Stripe charges from the API since the last fetch
# and store them in the database as StripeCharge objects.

import logging

import stripe
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction

from stripe_payments.models import StripeCharge

logger = logging.getLogger(__name__)


class Command(BaseCommand):
help = (
"Fetch Stripe charges from the API since the last fetch and store them in the "
"database as StripeCharge objects."
)

def handle(self, *args, **options):
logger.debug(
"Fetching Stripe charges from the API since the last fetch and storing "
"them in the database as StripeCharge objects."
)
# Get the last StripeCharge fetched.
try:
last_fetched = StripeCharge.objects.order_by("-fetched").first().fetched
except AttributeError:
# No StripeCharge objects exist.
last_fetched = None
# Fetch the Stripe charges.
stripe.api_key = settings.STRIPE_API_KEY
# stripe.api_version = settings.STRIPE_API_VERSION

# Fetch the Stripe charges.
stripe_charges = stripe.Charge.list(
limit=100,
created={"gt": int(last_fetched.timestamp())} if last_fetched else None,
expand=["data.customer", "data.customer.tax_ids"],
)
logger.info(len(stripe_charges), "Stripe charges fetched.")
with transaction.atomic():
for stripe_charge in stripe_charges:
StripeCharge.objects.create_from_stripe_charge_data(stripe_charge)
logger.debug(
"Fetched Stripe charges from the API since the last fetch and stored them "
"in the database as StripeCharge objects."
)
40 changes: 40 additions & 0 deletions stripe_payments/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from datetime import datetime, timezone

from django.db import models


class StripeChargeManager(models.Manager):
def create_from_stripe_charge_data(self, stripe_charge_data):
"""Create a StripeCharge from Stripe Charge data."""
return self.create(
charge_id=stripe_charge_data["id"],
amount=stripe_charge_data["amount"],
payment_data=stripe_charge_data,
charge_created=datetime.fromtimestamp(stripe_charge_data["created"], tz=timezone.utc),
fetched=datetime.now(tz=timezone.utc),
)

def running_total(self, since=None):
qs = self.get_queryset()
if since is not None:
qs = qs.filter(charge_created__gte=since)
return qs.aggregate(total=models.Sum("amount"))


class StripeCharge(models.Model):
"""
Holds Stripe Charge data.

Fetched via the API. Used to populate the Invoice.
"""

charge_id = models.CharField(max_length=255, unique=True, editable=False)
amount = models.IntegerField()
payment_data = models.JSONField()
charge_created = models.DateTimeField()
fetched = models.DateTimeField()

objects = StripeChargeManager()

def __str__(self):
return self.charge_id
78 changes: 78 additions & 0 deletions templates/donations/crowdfunding.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
{% extends "global/base.html" %}
{% load i18n static %}


{% block content %}
<div class="container">
<div class="row clearfix">
<div class="col-md-12">
<h2>{% trans "🎉🎁🎈🎊 We are 10 years old now and crowdfunding 🎂🥂🍾💕!" %}" </h2>
</div>
</div>

<div class="row clearfix">
<div class="col-md-6">
</div>
<div class="col-md-6">
<h3>{% blocktrans trimmed %}
<span class="highlighted-number">${{ total_raised }}</span> of <span class="highlighted-number">$30,000</span> raised.
{% endblocktrans %}
</h3>
</div>
</div>

<br>

<div class="row clearfix">
<div class="col-md-6">
{% blocktrans trimmed %}
<p>We are 10 years now, yay and we are fundraising!</p>
<p>Since the first Django Girls workshop in July 2014, we grew unexpectedly fast and we could not sustain that growth without some help.</p>

<p>In 2015, we introduced a part-time paid position of Awesomeness Ambassador to help provide support to hundreds of volunteers all over
the world.</p>

<p>In 2017, we also introduced the part-time paid position of Fundraising Coordinator to help us raise funds to run our activities.
In 2023, we introduced the part-time paid position of Communications Officer to help us increase outreach following the pandemic
and increase the number of workshops. We also introduced the Chief Emoji Officer (Managing Director) role, increasing the number
of our paid staff.</p>

<p>Our mission for 2024 is to improve outreach and visibility following the pandemic which saw a reduction in the number of
workshops being organized per year. We have therefore introduced a new part-time Communications Officer to help us achieve
this. We will also continue working with the advisory board to tackle diversity and inclusion issues in our systems and
workshop guidance to ensure that voices of all people, especially those from marginalized communities, can contribute to
our future.
</p>
<p>
Help us see this through. Support our work!
</p>
{% endblocktrans %}
</div>
<div class="col-md-6">
<img class="img-responsive center-block" src="{% static 'img/photos/crowdfunding.jpg' %}" alt="Django Girls Hohoe">
<br>
<p><a class="btn" href="https://donate.stripe.com/14kdTJ8PT6Fa3CwaEF">Donate now</a> or scan the QR code to donate to us <img class="img-responsive center-block" style="width: 100px;" src="{% static 'img/global/donate/qr_code.png' %}" alt="Stripe QR Code">
</p>
<hr>
<h3>Recent donations</h3>

{% for donor in donors %}
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-2">
<img src="{% static 'img/global/donate/django_crowdfunding_heart.png' %}" alt="Donor" style="width: 50px;">
</div>
<div class="col-md-10">
<h4><strong>{{ donor.payment_data.customer.name }}</strong> - ${{ donor.amount}}</h4>
</div>
</div>
</div>
</div>
<br>
{% endfor %}
</div>
</div>
</div>

{% endblock %}
2 changes: 2 additions & 0 deletions templates/global/menu.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="{% url 'donations:index' %}">{% trans "Corporate Sponsorships" %}</a></li>
<li><a class="dropdown-item" href="{% url 'donations:crowdfunding' %}" target="_blank">{% trans "Crowdfunding" %}</a></li>
<li><a class="dropdown-item" href="{% url 'donations:donate' %}">{% trans "Donate to us" %}</a></li>
<li><a class="dropdown-item" href="https://www.patreon.com/djangogirls">{% trans "Our Patreon Page" %}</a></li>
<li><hr class="dropdown-divider"></li>
Expand Down Expand Up @@ -42,6 +43,7 @@
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="{% url 'core:events' %}">{% trans "Events" %}</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{% url 'donations:crowdfunding' %}" target="_blank">{% trans "Crowdfunding" %}</a></li>
<li><a class="dropdown-item" href="https://django-girls.myspreadshop.co.uk" target="_blank">{% trans "Shop" %}</a></li>
<li><a class="dropdown-item" href="{% url 'core:newsletter' %}">{% trans "Newsletter" %}</a></li>
<li><a class="dropdown-item" href="https://blog.djangogirls.org/">{% trans "Our blog" %}</a></li>
Expand Down
5 changes: 5 additions & 0 deletions tests/donations/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,8 @@ def test_charge_post_api_connection_error(client):
# Check if the expected session variable is set
assert "stripe_message" in client.session
assert client.session["stripe_message"] == "A Network Connection error occured."


def test_crowdfunding_page(client):
response = client.get(reverse("donations:crowdfunding"))
assert response.status_code == 200
Empty file.
24 changes: 24 additions & 0 deletions tests/stripe_payments/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from datetime import datetime

import pytest

from stripe_payments.models import StripeCharge


@pytest.fixture
def donation():
return StripeCharge.objects.create(
charge_id="ch_19rVRuBN9GADq2YjQsQCfDHQ",
amount=10,
payment_data={
"id": "ch_19rVRuBN9GADq2YjQsQCfDHQ",
"paid": True,
"order": "",
"amount": 10,
"object": "charge",
"review": "",
"source": {},
},
charge_created=datetime.now(),
fetched=datetime.now(),
)
Empty file.
2 changes: 2 additions & 0 deletions tests/stripe_payments/test_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def test_stripe_charge_model_str_presentation(donation):
assert str(donation) == donation.charge_id
Loading