Skip to content

Commit

Permalink
Updated bundle form UI and optimized code
Browse files Browse the repository at this point in the history
  • Loading branch information
sab-LC committed Oct 25, 2024
1 parent 3ca68e9 commit 487f5bf
Show file tree
Hide file tree
Showing 12 changed files with 233 additions and 191 deletions.
66 changes: 34 additions & 32 deletions accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,38 +284,40 @@ def clean_inquiry_type(self):


class BundleTypeForm(forms.Form):
bundle_type = forms.MultipleChoiceField(
choices=[],
widget=forms.CheckboxSelectMultiple,
label="Bundle Types",
)
bundle_details = {
'User': {
'label': 'User Bundle',
'description': 'Add 5 more users to this account.',
},
'API': {
'label': 'API Bundle',
'description': 'Add 3 more API keys to this account.',
},
'Project': {
'label': 'Project Bundle',
'description': 'Add 10 more projects to this account.',
},
'Notification': {
'label': 'Notification Bundle',
'description': 'Add 10 more notifications to this account.',
},
}

def __init__(self, *args, **kwargs):
super(BundleTypeForm, self).__init__(*args, **kwargs)

self.bundle_details = {
'User': {
'label': 'User Bundle',
'description': 'Add 5 more users to this account.',
'quantity': 5
},
'API': {
'label': 'API Bundle',
'description': 'Add 3 more API keys to this account.',
'quantity': 3
},
'Project': {
'label': 'Project Bundle',
'description': 'Add 10 more projects to this account.',
'quantity': 10
},
'Notification': {
'label': 'Notification Bundle',
'description': 'Add 10 more notifications to this account.',
'quantity': 10
},
}
super().__init__(*args, **kwargs)

self.fields.update({
f"bundle_{key}": forms.IntegerField(
label=f"{details['label']}",
min_value=0,
required=False,
initial=0,
help_text=details['description']
)
for key, details in self.bundle_details.items()
})

self.fields['bundle_type'].choices = [
(key, details['label']) for key, details in self.bundle_details.items()
]
def clean(self):
return {
key: value for key, value in super().clean().items() if key.startswith('bundle_')
}
5 changes: 0 additions & 5 deletions accounts/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,4 @@
),
name="password_reset_complete"
),
path(
"subscription/<str:pk>/<str:account_type>/",
views.subscription,
name="subscription"
),
]
143 changes: 3 additions & 140 deletions accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from django.contrib import auth, messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.contrib.auth.models import User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.auth.views import (PasswordChangeForm, PasswordResetView, SetPasswordForm)
Expand Down Expand Up @@ -36,22 +35,20 @@
from .forms import (
RegistrationForm, ResendEmailActivationForm, CustomPasswordResetForm, UserCreateProfileForm,
ProfileCreationForm, UserUpdateForm, ProfileUpdateForm, SignUpInvitationForm,
SubscriptionForm, BundleTypeForm
SubscriptionForm
)

from .utils import (
get_next_path, get_users_name, return_registry_accounts, manage_mailing_list,
institute_account_subscription, escape_single_quotes, determine_user_role,
remove_user_from_account
)
from institutions.utils import get_institution
from localcontexts.utils import dev_prod_or_local
from researchers.utils import is_user_researcher
from helpers.utils import (
accept_member_invite, validate_email, validate_recaptcha, check_member_role,
create_bundle_call, get_access_token_of_SF
accept_member_invite, validate_email, validate_recaptcha
)
from .models import SignUpInvitation, Profile, UserAffiliation, Subscription, BundleType
from .models import SignUpInvitation, Profile, UserAffiliation, Subscription
from helpers.models import HubActivity
from projects.models import Project
from communities.models import InviteMember, Community
Expand Down Expand Up @@ -904,137 +901,3 @@ def subscription_inquiry(request):
"service_providers": service_providers,
},
)


@login_required(login_url="login")
def subscription(request, pk, account_type, related=None):
if dev_prod_or_local(request.get_host()) == "SANDBOX":
return redirect("dashboard")

renew = False

form = BundleTypeForm(request.POST or None)
if account_type == 'institution' and (
request.user in get_institution(pk).get_admins()
or
request.user == get_institution(pk).institution_creator
):
institution = get_institution(pk)
member_role = check_member_role(request.user, institution)
try:
subscription = Subscription.objects.get(institution=institution)
except Subscription.DoesNotExist:
subscription = None
if subscription is not None:
if subscription.end_date and subscription.end_date < timezone.now():
renew = True

if request.method == "POST":
if form.is_valid():
try:
access_token = get_access_token_of_SF(request)
for bundle in form.cleaned_data['bundle_type']:
bundle_data = form.bundle_details[bundle]
quantity = bundle_data['quantity']
bundle_data = {
"hubId": str(request.user.id) + "_i",
"isBundle": True,
"BundleType": bundle,
"Quantity": quantity,
}
BundleType.objects.create(institution=institution, bundle_type=bundle)
create_bundle_call(request, bundle_data, access_token)
messages.add_message(
request,
messages.INFO,
(
"Thank you for your submission, "
"our team will review and be in "
"contact with the bundle contract. "
"You will be notified once your "
"request has been processed."
),
)
return redirect("subscription", institution.id, 'institution')
except Exception:
messages.add_message(
request,
messages.ERROR,
"An unexpected error has occurred here."
" Please contact support@localcontexts.org.",
)
return redirect("subscription", institution.id, 'institute')
context = {
"institution": institution,
"subscription": subscription,
"start_date": subscription.start_date.strftime('%d %B %Y')
if subscription and subscription.start_date is not None
else None,
"end_date": subscription.end_date.strftime('%d %B %Y')
if subscription and subscription.end_date is not None
else None,
"renew": renew,
"member_role": member_role,
"form": form,
}
elif account_type == 'researcher':
researcher = Researcher.objects.get(id=pk)
if researcher.is_subscribed:
subscription = Subscription.objects.filter(researcher=researcher).first()
else:
subscription = None
if subscription is not None:
if subscription.end_date and subscription.end_date < timezone.now():
renew = True

if request.method == "POST":
if form.is_valid():
try:
access_token = get_access_token_of_SF(request)
for bundle in form.cleaned_data['bundle_type']:
bundle_data = BundleTypeForm().bundle_details[bundle]
quantity = bundle_data['quantity']
bundle_data = {
"hubId": str(request.user.id) + "_r",
"isBundle": True,
"BundleType": bundle,
"Quantity": quantity,
}
BundleType.objects.create(researcher=researcher, bundle_type=bundle)
create_bundle_call(request, bundle_data, access_token)
messages.add_message(
request,
messages.INFO,
(
"Thank you for your submission, "
"our team will review and be in "
"contact with the bundle contract. "
"You will be notified once your "
"request has been processed."
),
)
return redirect("subscription", researcher.id, 'researcher')
except Exception:
messages.add_message(
request,
messages.ERROR,
"An unexpected error has occurred here."
" Please contact support@localcontexts.org.",
)
return redirect("subscription", researcher.id, 'researcher')
context = {
"researcher": researcher,
"subscription": subscription,
"start_date": subscription.start_date.strftime('%d %B %Y')
if subscription and subscription.start_date is not None
else None,
"end_date": subscription.end_date.strftime('%d %B %Y')
if subscription and subscription.end_date is not None
else None,
"renew": renew,
"form": form,
}
return render(
request, 'account_settings_pages/_subscription.html',
context
)
60 changes: 58 additions & 2 deletions helpers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from django.conf import settings
from django.template.loader import get_template ,render_to_string
from io import BytesIO
from accounts.models import UserAffiliation, Subscription
from accounts.models import UserAffiliation, Subscription, BundleType
from tklabels.models import TKLabel
from bclabels.models import BCLabel
from helpers.models import (
Expand All @@ -28,7 +28,7 @@
from .models import Notice
from notifications.models import *

from accounts.forms import UserCreateProfileForm, SubscriptionForm
from accounts.forms import UserCreateProfileForm, SubscriptionForm, BundleTypeForm

from accounts.utils import get_users_name, confirm_subscription
from notifications.utils import send_user_notification_member_invite_accept
Expand Down Expand Up @@ -897,3 +897,59 @@ def get_certified_service_providers(request):
results = service_providers

return results


def fetch_subscription(entity, entity_type):
try:
subscription = Subscription.objects.filter(**{entity_type: entity}).first()
renew = subscription.end_date < timezone.now() if subscription and subscription.end_date else False
return subscription, renew
except:
return None, None


def process_bundles(request, entity, entity_id, entity_prefix, entity_type):
access_token = get_access_token_of_SF(request)
for key, quantity in request.POST.items():
if key.startswith('bundle_') and int(quantity) > 0:
bundle_type = key[7:]
bundle_data = {
"hubId": f"{entity_id}_{entity_prefix}",
"isBundle": True,
"BundleType": bundle_type,
"Quantity": int(quantity),
}
BundleType.objects.create(**{entity_type: entity, "bundle_type": bundle_type, "quantity": int(quantity)})
create_bundle_call(request, bundle_data, access_token)


def handle_post_request(request, entity, entity_id, entity_prefix, entity_type, redirect_name):
form = BundleTypeForm(request.POST)
if form.is_valid():
try:
process_bundles(request, entity, entity_id, entity_prefix, entity_type)
messages.add_message(
request,
messages.INFO,
(
"Thank you for your submission, "
"our team will review and be in contact with the bundle contract. "
"You will be notified once your request has been processed."
),
)
return redirect(redirect_name, entity_id)
except Exception:
messages.add_message(
request,
messages.ERROR,
"An unexpected error has occurred here. Please contact support@localcontexts.org.",
)
return redirect(redirect_name, entity_id)
else:
messages.add_message(
request,
messages.ERROR,
"An unexpected error has occurred here. Please contact support@localcontexts.org.",
)
return redirect(redirect_name, entity_id)

1 change: 1 addition & 0 deletions institutions/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
path('update/<str:pk>/', views.update_institution, name="update-institution"),
path('preferences/<str:pk>/', views.account_preferences, name="preferences-institution"),
path('api-key/<str:pk>/', views.api_keys, name="institution-api-key"),
path('subscription/<str:pk>/', views.institution_subscription, name="institution-subscription"),
path('connect-service-provider/<str:pk>/', views.connect_service_provider, name="institution-connect-service-provider"),
path('subscription-form/<str:pk>/', views.create_institution_subscription, name="institution-create-subscription-form"),

Expand Down
Loading

0 comments on commit 487f5bf

Please sign in to comment.