Files
coulobre/src/coulobre/hosting/reseller_onboarding_views.py
T

188 lines
6.0 KiB
Python

from django import forms
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import (
PermissionRequiredMixin,
UserPassesTestMixin,
)
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import IntegrityError, transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.utils.functional import cached_property
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from django.views.generic import FormView
from .access import reseller_for_user
from .invitations import InviteLoginForm, queue_invitation
from .models import HostingAccount, HostingPlan
from .reseller_accounts import save_operator_account
from .reseller_onboarding import (
claim_customer_hosting,
create_reseller_customer,
link_reseller_customer,
lock_reseller_account,
scoped_customers,
)
class ResellerCustomerLinkForm(forms.Form):
customer = forms.ModelChoiceField(queryset=None)
def __init__(self, *args, customers, **kwargs):
super().__init__(*args, **kwargs)
self.fields["customer"].queryset = customers
class ResellerCustomerEditor(PermissionRequiredMixin, FormView):
template_name = "hosting/customer_form.html"
@cached_property
def reseller(self):
return reseller_for_user(self.request.user)
@cached_property
def account(self):
return get_object_or_404(
HostingAccount,
pk=self.kwargs["pk"],
reseller=self.reseller,
retired_at__isnull=True,
customer__isnull=True,
)
def has_permission(self):
return self.reseller is not None
def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs)
class ResellerCustomerCreate(ResellerCustomerEditor):
form_class = InviteLoginForm
extra_context = {"title": "Add customer login"}
def form_valid(self, form):
account = self.account
try:
account = create_reseller_customer(self.reseller, account.pk, form)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
except IntegrityError:
user = form.instance
if (
not get_user_model()
.objects.filter(username__iexact=user.username)
.exists()
):
raise
form.add_error(
"username", user.unique_error_message(type(user), ["username"])
)
return self.form_invalid(form)
queue_invitation(account.customer.user)
return redirect(account)
class ResellerCustomerLink(ResellerCustomerEditor):
form_class = ResellerCustomerLinkForm
extra_context = {"title": "Link existing customer"}
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"customers": scoped_customers(self.reseller)
.filter(user__is_active=True)
.select_related("user")
.order_by("user__username")
}
def form_valid(self, form):
account = self.account
try:
account = link_reseller_customer(
self.reseller, account.pk, form.cleaned_data["customer"].pk
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(account)
@require_POST
@never_cache
def claim_own_customer_hosting(request, pk):
manager = reseller_for_user(request.user)
if manager is None:
raise PermissionDenied
try:
account = claim_customer_hosting(manager, pk)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
messages.error(request, " ".join(error.messages))
return redirect("panel:account", pk=pk)
messages.success(
request, "This hosting account is now in your Customer workspace."
)
return redirect(account)
class ManagerHostingPlanForm(forms.Form):
plan = forms.ModelChoiceField(queryset=HostingPlan.objects.none())
def __init__(self, *args, manager, **kwargs):
super().__init__(*args, **kwargs)
self.fields["plan"].queryset = manager.hosting_plans.order_by("name")
class ManagerHostingPlanView(UserPassesTestMixin, FormView):
form_class = ManagerHostingPlanForm
template_name = "hosting/workspace_form.html"
extra_context = {
"title": "Assign hosting plan",
"submit_label": "Assign plan",
}
def test_func(self):
self.manager = reseller_for_user(self.request.user)
return self.manager is not None
@cached_property
def account(self):
return get_object_or_404(
self.manager.hostingaccount_set.filter(retired_at__isnull=True),
pk=self.kwargs["pk"],
)
def get_form_kwargs(self):
return super().get_form_kwargs() | {"manager": self.manager}
def get_initial(self):
return {"plan": self.account.hosting_plan_id}
@transaction.atomic
def form_valid(self, form):
try:
account, manager = lock_reseller_account(
self.manager, self.account.pk
)
except HostingAccount.DoesNotExist:
raise Http404 from None
chosen = form.cleaned_data["plan"]
if not manager.hosting_plans.filter(pk=chosen.pk).exists():
form.add_error("plan", "This plan is no longer available.")
return self.form_invalid(form)
account.hosting_plan = chosen
save_operator_account(
account,
self.request.user.get_username(),
changed_fields=["hosting_plan"],
)
return redirect(account)