From fe2ced25ddb91eae8044e32ad9a456960e910411 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Tue, 24 Nov 2026 13:01:38 +0100 Subject: [PATCH] Guide first-time setup in each panel workspace --- docs/deployment.md | 22 ++- .../hosting/account_administration.py | 102 ++++++++-- .../migrations/0079_onboarding_dismissal.py | 45 +++++ src/coulobre/hosting/models.py | 14 ++ src/coulobre/hosting/panel_roles.py | 11 +- .../templates/hosting/account_list.html | 3 +- .../hosting/templates/hosting/all_users.html | 6 +- .../templates/hosting/workspace_form.html | 3 + .../hosting/workspace_onboarding.html | 34 ++++ src/coulobre/hosting/test_account_setup.py | 4 + src/coulobre/hosting/test_workspaces.py | 119 +++++++++++- src/coulobre/hosting/urls.py | 18 +- src/coulobre/hosting/views.py | 17 +- src/coulobre/hosting/workspace_onboarding.py | 179 ++++++++++++++++++ src/coulobre/hosting/workspaces.py | 10 +- 15 files changed, 551 insertions(+), 36 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0079_onboarding_dismissal.py create mode 100644 src/coulobre/hosting/templates/hosting/workspace_onboarding.html create mode 100644 src/coulobre/hosting/workspace_onboarding.py diff --git a/docs/deployment.md b/docs/deployment.md index b665ced..5f6cd5e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2750,12 +2750,22 @@ changes to manager policy and account assignments made through the panel. ### Onboard customers -Managers can open **Add User** to create a customer login and its first -hosting account together. Choose an allowed hosting package and give the -customer's email address to send a welcome email with a link to set their -password. Preview the email before creating the account. To add a login -for an existing unassigned hosting account, open the account and choose -**Add customer login** or **Link existing customer**. +Operators and managers can open **Add User** to create a customer login and +its first hosting account together. Choose a hosting package and enter the +customer's email address to send a welcome email with a password setup link. +Use **Preview** to review the email before creating the account. Operators +can assign a manager during setup or use **Create a login only** to stage +access separately. Managers choose from their assigned hosting packages. +To add a login for an existing unassigned hosting account, open the account +and choose **Add customer login** or **Link existing customer**. + +**Getting started** on the hosting overview shows setup steps for the active +workspace. Dismiss or reopen the checklist independently in each workspace. +Operators and managers can use **Enable Customer workspace** to access their +own hosting through the same login. A server administrator verifies their +second factor before enabling the role. An operator can also select **For my +own hosting** when adding a hosting account. Coulobre uses the operator's +manager profile by default. Operators can open **Contact and invitation** from **Show All Users** to review the welcome email and send a fresh password setup link to a pending diff --git a/src/coulobre/hosting/account_administration.py b/src/coulobre/hosting/account_administration.py index 11097a5..9e3e2a8 100644 --- a/src/coulobre/hosting/account_administration.py +++ b/src/coulobre/hosting/account_administration.py @@ -46,7 +46,7 @@ from .reseller_accounts import ( from .resource_requests import lock_hosting_account, require_open_account -class ManagerOnboardingForm(InviteLoginForm): +class CustomerOnboardingForm(InviteLoginForm): primary_domain = HostingAccount._meta.get_field( "primary_domain" ).formfield(required=True) @@ -77,14 +77,36 @@ class ManagerOnboardingForm(InviteLoginForm): help_text="Leave blank to use a password setup link.", ) - def __init__(self, *args, manager, defaults, **kwargs): + def __init__( + self, + *args, + manager, + defaults, + capabilities, + may_assign_manager, + **kwargs, + ): super().__init__(*args, **kwargs) - self.fields["plan"].queryset = manager.hosting_plans.order_by("name") - self.fields["manage_dns"].disabled = not default_dns_zones_allowed( - defaults + plans = manager.hosting_plans if manager else HostingPlan.objects + self.fields["plan"].queryset = plans.order_by("name") + if may_assign_manager: + self.fields["manager"] = forms.ModelChoiceField( + queryset=Reseller.objects.filter(user__is_active=True) + .select_related("user") + .order_by("user__username"), + required=False, + empty_label="Direct customer", + help_text="Give this manager access to the new account.", + ) + self.order_fields( + ["username", "email", "primary_domain", "plan", "manager"] + ) + self.fields["manage_dns"].disabled = not ( + capabilities["manage_dns"] and default_dns_zones_allowed(defaults) ) - self.fields["manage_mail"].disabled = not panel_feature_allowed( - "LOCAL_MAILBOX_PROVISIONING" + self.fields["manage_mail"].disabled = not ( + capabilities["manage_mail"] + and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING") ) def clean_primary_domain(self): @@ -118,8 +140,8 @@ class ManagerOnboardingForm(InviteLoginForm): @method_decorator( sensitive_post_parameters("initial_password"), name="dispatch" ) -class ManagerOnboardingView(UserPassesTestMixin, FormView): - form_class = ManagerOnboardingForm +class CustomerOnboardingView(UserPassesTestMixin, FormView): + form_class = CustomerOnboardingForm template_name = "hosting/workspace_form.html" extra_context = { "title": "Add user", @@ -129,12 +151,38 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView): def test_func(self): self.manager = reseller_for_user(self.request.user) - return self.manager is not None + return self.manager is not None or can_onboard_customer( + self.request.user + ) + + def get_context_data(self, **kwargs): + return super().get_context_data( + login_only_url=reverse_lazy("panel:customer_create") + if self.manager is None + else None, + **kwargs, + ) + + def capabilities(self): + from .views import ACTIVATE_WEB, PROVISION_MAILBOX, PUBLISH_DNS + + actor = self.request.user + return { + key: self.manager is not None or actor.has_perms(required) + for key, required in ( + ("website", ACTIVATE_WEB), + ("manage_dns", (*PUBLISH_DNS, "hosting.add_hostingdnszone")), + ("manage_mail", PROVISION_MAILBOX), + ) + } def get_form_kwargs(self): return super().get_form_kwargs() | { "manager": self.manager, "defaults": zone_defaults(), + "capabilities": self.capabilities(), + "may_assign_manager": self.manager is None + and self.request.user.has_perm("hosting.view_reseller"), } def form_valid(self, form): @@ -156,21 +204,27 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView): self.get_context_data(form=form, welcome_preview=preview) ) try: + capabilities = self.capabilities() + manager = self.manager or data.get("manager") with transaction.atomic(): user = form.save(commit=False) if data["initial_password"]: user.set_password(data["initial_password"]) user.save() - customer = Customer.objects.create( - user=user, reseller=self.manager - ) + customer = Customer.objects.create(user=user, reseller=manager) account = HostingAccount( name=user.get_username(), primary_domain=data["primary_domain"], customer=customer, hosting_plan=data["plan"], + reseller=manager, ) - create_reseller_account(self.manager, account) + if self.manager is not None: + create_reseller_account(self.manager, account) + else: + save_operator_account( + account, self.request.user.get_username() + ) DomainServicePolicy.objects.create( account=account, domain=account.primary_domain, @@ -181,9 +235,8 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView): setup_new_account( account, { - "setup_website": panel_feature_allowed( - "LOCAL_WEB_ACTIVATION" - ), + "setup_website": capabilities["website"] + and panel_feature_allowed("LOCAL_WEB_ACTIVATION"), "setup_dns": data["manage_dns"], "setup_email": data["manage_mail"], "setup_www": defaults.include_www, @@ -215,6 +268,18 @@ class ManagerOnboardingView(UserPassesTestMixin, FormView): return redirect(account) +def can_onboard_customer(user): + return user.has_perms( + ( + "hosting.view_customer", + "hosting.add_customer", + "hosting.view_hostingaccount", + "hosting.add_hostingaccount", + "hosting.view_hostingplan", + ) + ) + + class ManagerPackagesView(UserPassesTestMixin, ListView): template_name = "hosting/manager_packages.html" context_object_name = "plans" @@ -265,6 +330,9 @@ class AllUsersView(OperatorOnlyMixin, PermissionRequiredMixin, ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) + context["has_combined_onboarding"] = can_onboard_customer( + self.request.user + ) profiles = [ getattr(user, "hosting_customer", None) for user in context["logins"] diff --git a/src/coulobre/hosting/migrations/0079_onboarding_dismissal.py b/src/coulobre/hosting/migrations/0079_onboarding_dismissal.py new file mode 100644 index 0000000..18e9595 --- /dev/null +++ b/src/coulobre/hosting/migrations/0079_onboarding_dismissal.py @@ -0,0 +1,45 @@ +# Generated by Django 5.2.19 on 2026-11-24 11:58 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0078_manager_labels"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="OnboardingDismissal", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("role", models.CharField(max_length=16)), + ( + "user", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "constraints": [ + models.UniqueConstraint( + fields=("user", "role"), + name="hosting_onboarding_dismissal", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 77a99ce..97d9cf6 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1540,6 +1540,20 @@ class PanelFactorEnrollment(models.Model): expires_at = models.DateTimeField(db_index=True) +class OnboardingDismissal(models.Model): + user = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + role = models.CharField(max_length=16) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("user", "role"), name="hosting_onboarding_dismissal" + ) + ] + + class PanelRecoveryCode(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE diff --git a/src/coulobre/hosting/panel_roles.py b/src/coulobre/hosting/panel_roles.py index fc9ae7a..890cf9f 100644 --- a/src/coulobre/hosting/panel_roles.py +++ b/src/coulobre/hosting/panel_roles.py @@ -38,11 +38,18 @@ def assigned_roles(user): roles = {} if user.is_superuser: roles[PanelRole.ADMIN] = user.pk + manager = getattr(user, "hosting_reseller", None) customer = getattr(user, "hosting_customer", None) + own_customer = ( + customer is not None + and manager is not None + and customer.reseller_id == manager.pk + ) + if manager is not None and own_customer: + roles[PanelRole.MANAGER] = manager.pk if customer is not None: roles[PanelRole.CUSTOMER] = customer.pk - manager = getattr(user, "hosting_reseller", None) - if manager is not None: + if manager is not None and not own_customer: roles[PanelRole.MANAGER] = manager.pk return roles diff --git a/src/coulobre/hosting/templates/hosting/account_list.html b/src/coulobre/hosting/templates/hosting/account_list.html index 0906651..058452c 100644 --- a/src/coulobre/hosting/templates/hosting/account_list.html +++ b/src/coulobre/hosting/templates/hosting/account_list.html @@ -4,7 +4,7 @@

{% if is_customer %}My hosting{% elif is_reseller %}Customer hosting{% else %}Hosting accounts{% endif %}

- {% if is_operator %}

Manage domains and their hosting services. Link a customer to give them access.

{% endif %} + {% if is_operator %}

Manage domains and their hosting services. A linked customer login can manage them in the panel.

{% endif %}

{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}

{% if account_allowance %}

{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated

{% endif %}
@@ -27,6 +27,7 @@ {% endblock %} {% block page_content %} + {% include "hosting/workspace_onboarding.html" %} {% if is_reseller %}

Manage the logins for your assigned customers.

diff --git a/src/coulobre/hosting/templates/hosting/all_users.html b/src/coulobre/hosting/templates/hosting/all_users.html index 3303601..d2e5885 100644 --- a/src/coulobre/hosting/templates/hosting/all_users.html +++ b/src/coulobre/hosting/templates/hosting/all_users.html @@ -2,7 +2,9 @@ {% block title %}All users · Coulobre Panel{% endblock %} {% block page_title %}All users{% endblock %} {% block page_actions %} - {% if perms.hosting.add_customer %} + {% if has_combined_onboarding %} + Add user + {% elif perms.hosting.add_customer %} Add user {% endif %} {% endblock %} @@ -24,7 +26,7 @@ {{ login.get_username }} {% if login.is_superuser %}Operator{% elif login.hosting_reseller %}Manager{% else %}Customer{% endif %} - {{ login.hosting_customer.reseller|default:"Unassigned" }} + {% if login.hosting_customer %}{{ login.hosting_customer.reseller|default_if_none:"Unassigned" }}{% else %}—{% endif %} {{ login.account_count }} {% include "hosting/account_metrics_cells.html" %} {{ login.date_joined|date:"j M Y" }} diff --git a/src/coulobre/hosting/templates/hosting/workspace_form.html b/src/coulobre/hosting/templates/hosting/workspace_form.html index 6836e5d..a395bee 100644 --- a/src/coulobre/hosting/templates/hosting/workspace_form.html +++ b/src/coulobre/hosting/templates/hosting/workspace_form.html @@ -2,6 +2,9 @@ {% block title %}{{ title }} · Coulobre Panel{% endblock %} {% block page_title %}{{ title }}{% endblock %} {% block page_content %} + {% if login_only_url %} +

Create a panel login and set up the customer’s first domain on a hosting package. Create a login only

+ {% endif %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/workspace_onboarding.html b/src/coulobre/hosting/templates/hosting/workspace_onboarding.html new file mode 100644 index 0000000..b4a8ede --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/workspace_onboarding.html @@ -0,0 +1,34 @@ +{% if onboarding.dismissed %} + + {% csrf_token %} + +
+{% elif onboarding.steps or onboarding.enable_customer %} +
+
+

{{ onboarding.title }}

+
+ {% csrf_token %} + +
+
+
    + {% for label, url, complete in onboarding.steps %} +
  • + {% if complete %}Done · {% endif %} + {% if url %}{{ label }}{% else %}{{ label }}{% endif %} + {% if not url and not complete %} + {% if onboarding.role == "manager" %} · Ask your operator for an assigned package and available account allocation.{% else %} · Ask your hosting provider to link your hosting account.{% endif %} + {% endif %} +
  • + {% endfor %} +
+ {% if onboarding.enable_customer %} +
+ {% csrf_token %} + + Use this login to manage your own hosting. +
+ {% endif %} +
+{% endif %} diff --git a/src/coulobre/hosting/test_account_setup.py b/src/coulobre/hosting/test_account_setup.py index a37fa2a..7935aaa 100644 --- a/src/coulobre/hosting/test_account_setup.py +++ b/src/coulobre/hosting/test_account_setup.py @@ -143,6 +143,10 @@ class OperatorOwnHostingTests(TestCase): account = HostingAccount.objects.get(primary_domain=domain) self.assertRedirects(response, account.get_absolute_url()) self.assertEqual(account.customer.user_id, self.operator.pk) + self.assertEqual( + account.customer.reseller.user_id, self.operator.pk + ) + self.assertEqual(account.reseller_id, account.customer.reseller_id) self.assertEqual( Customer.objects.filter(user=self.operator).count(), 1 ) diff --git a/src/coulobre/hosting/test_workspaces.py b/src/coulobre/hosting/test_workspaces.py index f76a3ae..4f7e496 100644 --- a/src/coulobre/hosting/test_workspaces.py +++ b/src/coulobre/hosting/test_workspaces.py @@ -5,6 +5,7 @@ from django.contrib.auth.models import Permission from django.test import TestCase, override_settings from django.urls import reverse from django.utils import timezone +from django_otp.plugins.otp_totp.models import TOTPDevice from .models import ( Customer, @@ -17,6 +18,120 @@ from .models import ( class WorkspaceTests(TestCase): + def test_operator_creates_and_links_the_first_hosting_account(self): + users = get_user_model().objects + operator = users.create_superuser("operator") + manager = Reseller.objects.create(user=users.create_user("manager")) + plan = HostingPlan.objects.create(name="Shared") + self.client.force_login(operator) + url = reverse("panel:customer_onboarding") + self.assertContains(self.client.get(url), "Create a login only") + data = { + "username": "new-customer", + "email": "customer@example.test", + "primary_domain": "first.example.test", + "plan": plan.pk, + "manager": manager.pk, + "send_invitation": "on", + } + with patch( + "coulobre.hosting.account_administration.queue_invitation" + ) as invite: + preview = self.client.post(url, data | {"action": "preview"}) + self.assertContains(preview, "first.example.test") + self.assertFalse(Customer.objects.exists()) + response = self.client.post(url, data) + account = HostingAccount.objects.get( + primary_domain="first.example.test" + ) + self.assertRedirects(response, account.get_absolute_url()) + self.assertEqual(account.hosting_plan, plan) + self.assertEqual(account.reseller, manager) + self.assertEqual(account.customer.reseller, manager) + self.assertEqual( + account.customer.user.get_username(), "new-customer" + ) + invite.assert_called_once_with( + account.customer.user, welcome_message="" + ) + self.client.force_login(account.customer.user) + self.assertEqual(self.client.get(url).status_code, 403) + + def test_onboarding_follows_the_current_workspace_across_sign_ins(self): + operator = get_user_model().objects.create_superuser("operator") + device = TOTPDevice.objects.create(user=operator, name="Panel") + home = reverse("panel:accounts") + preference = reverse("panel:onboarding_preference") + enable = reverse("panel:enable_customer_workspace") + switch = reverse("panel:switch_panel_role") + self.client.force_login(operator) + self.assertEqual(self.client.post(enable).status_code, 403) + session = self.client.session + session["otp_device_id"] = device.persistent_id + session.save() + self.assertContains( + self.client.get(home), "Getting started as server administrator" + ) + self.assertRedirects(self.client.post(enable), home) + self.assertRedirects(self.client.post(enable), home) + customer = Customer.objects.get(user=operator) + self.assertEqual(customer.reseller.user_id, operator.pk) + self.assertRedirects( + self.client.post(preference, {"action": "dismiss"}), home + ) + self.assertTrue( + self.client.get(home).context["onboarding"]["dismissed"] + ) + for role in ("manager", "customer"): + self.assertRedirects( + self.client.post(switch, {"role": role}), home + ) + self.assertContains( + self.client.get(home), f"Getting started as {role}" + ) + self.assertEqual(self.client.post(enable).status_code, 403) + self.client.logout() + self.client.force_login(operator) + self.assertTrue( + self.client.get(home).context["onboarding"]["dismissed"] + ) + self.assertRedirects( + self.client.post(preference, {"action": "show"}), home + ) + self.assertContains( + self.client.get(home), "Getting started as server administrator" + ) + + def test_manager_can_enable_customer_workspace_and_keeps_manager_default( + self, + ): + user = get_user_model().objects.create_user("manager") + manager = Reseller.objects.create(user=user) + self.client.force_login(user) + home = reverse("panel:accounts") + self.assertContains( + self.client.get(home), "Getting started as manager" + ) + self.assertRedirects( + self.client.post(reverse("panel:enable_customer_workspace")), home + ) + self.assertEqual(Customer.objects.get(user=user).reseller, manager) + self.assertContains( + self.client.get(home), "Getting started as manager" + ) + self.assertRedirects( + self.client.post( + reverse("panel:switch_panel_role"), {"role": "customer"} + ), + home, + ) + self.assertContains( + self.client.get(home), "Getting started as customer" + ) + self.assertNotContains( + self.client.get(home), "Get an assigned hosting package" + ) + def test_operator_navigation_keeps_creation_and_package_links_together( self, ): @@ -25,7 +140,7 @@ class WorkspaceTests(TestCase): landing = self.client.get(reverse("panel:accounts")) links = dict(landing.context["navigation_groups"])["Account Manager"] actions = [ - (reverse("panel:customer_create"), "Add User"), + (reverse("panel:customer_onboarding"), "Add User"), (reverse("panel:reseller_create"), "Add Manager"), (reverse("panel:operator_create"), "Add Operator"), (reverse("panel:hosting_plans"), "Hosting Packages"), @@ -214,8 +329,6 @@ class WorkspaceTests(TestCase): ) for label in ("first", "second") ] - from django_otp.plugins.otp_totp.models import TOTPDevice - device = TOTPDevice.objects.create(user=operator, name="test") self.client.force_login(operator) session = self.client.session diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 5791574..932c68e 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -4,7 +4,7 @@ from django.urls import path from . import themes, views from .account_administration import ( AllUsersView, - ManagerOnboardingView, + CustomerOnboardingView, ManagerPackagesView, MoveHostingView, OperatorCreateView, @@ -106,6 +106,10 @@ from .update_views import ChangelogView, UpdateView from .website_file_views import WebsiteFilesView from .website_job_views import WebsiteJobEditor, WebsiteJobList from .website_usage_views import WebsiteUsageView +from .workspace_onboarding import ( + enable_customer_workspace, + onboarding_preference, +) from .workspaces import customer_workspace, system_workspace app_name = "panel" @@ -236,7 +240,7 @@ urlpatterns = [ path("users/", AllUsersView.as_view(), name="all_users"), path( "users/new/", - ManagerOnboardingView.as_view(), + CustomerOnboardingView.as_view(), name="customer_onboarding", ), path("users/move/", MoveHostingView.as_view(), name="move_accounts"), @@ -293,6 +297,16 @@ urlpatterns = [ name="operator_settings", ), path("account/role/", switch_panel_role, name="switch_panel_role"), + path( + "account/getting-started/", + onboarding_preference, + name="onboarding_preference", + ), + path( + "account/customer-workspace/", + enable_customer_workspace, + name="enable_customer_workspace", + ), path( "logins/assign-role/", AssignPanelRoleView.as_view(), diff --git a/src/coulobre/hosting/views.py b/src/coulobre/hosting/views.py index 24b79ac..fee7bfc 100644 --- a/src/coulobre/hosting/views.py +++ b/src/coulobre/hosting/views.py @@ -180,6 +180,7 @@ from .website_aliases import ( from .website_file_views import can_manage_website_files from .website_job_views import can_manage_website_jobs from .website_jobs import website_job_limit +from .workspace_onboarding import onboarding_context VIEW_ACCOUNTS = "hosting.view_hostingaccount" CHANGE_ACCOUNTS = "hosting.change_hostingaccount" @@ -390,6 +391,8 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView): def get_context_data(self, **kwargs): context = super().get_context_data(search=self.search, **kwargs) + if not self.search and not self.request.GET.get("customer"): + context["onboarding"] = onboarding_context(self.request) context["show_customer_website_link"] = settings.WEBSITE_USAGE reseller = reseller_for_user(self.request.user) if reseller is not None: @@ -468,6 +471,7 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): "in the Customer workspace." ), required=False, + initial=self.request.GET.get("own") == "1", ) reseller = reseller_for_user(actor) is not None defaults = zone_defaults() @@ -543,9 +547,18 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView): try: with transaction.atomic(): if own_hosting: - customer, created = Customer.objects.get_or_create( - user_id=actor.pk + manager = self.object.reseller or actor.hosting_reseller + customer, created = ( + Customer.objects.select_for_update().get_or_create( + user_id=actor.pk, + defaults={"reseller": manager}, + ) ) + if customer.reseller_id is None: + customer.reseller = manager + customer.save(update_fields=["reseller"]) + if self.object.reseller_id is None: + self.object.reseller_id = customer.reseller_id self.object.customer = customer if created: LogEntry.objects.log_actions( diff --git a/src/coulobre/hosting/workspace_onboarding.py b/src/coulobre/hosting/workspace_onboarding.py new file mode 100644 index 0000000..fd0e9c6 --- /dev/null +++ b/src/coulobre/hosting/workspace_onboarding.py @@ -0,0 +1,179 @@ +from django.contrib.admin.models import ADDITION, LogEntry +from django.contrib.auth.decorators import login_required +from django.core.exceptions import PermissionDenied +from django.db import transaction +from django.http import HttpResponseBadRequest +from django.shortcuts import redirect +from django.urls import reverse +from django.views.decorators.http import require_POST + +from .access import PanelRole, customer_for_user, reseller_for_user +from .account_administration import can_onboard_customer +from .models import ( + Customer, + HostingAccount, + HostingPlan, + OnboardingDismissal, + PanelRecoveryCode, + ServiceHealth, +) +from .panel_roles import ROLE_LABELS + + +def workspace_role(request): + if getattr(request, "impersonation", None): + return None + if customer_for_user(request.user): + return PanelRole.CUSTOMER + if reseller_for_user(request.user): + return PanelRole.MANAGER + if request.user.has_perm("hosting.view_hostingaccount"): + return PanelRole.ADMIN + return None + + +def customer_workspace_manager(user): + if user.is_superuser and user.is_verified(): + return getattr(user, "hosting_reseller", None) + return reseller_for_user(user) + + +def onboarding_context(request): + role = workspace_role(request) + if role is None: + return None + user = request.user + title = f"Getting started as {ROLE_LABELS[role].lower()}" + if OnboardingDismissal.objects.filter(user_id=user.pk, role=role).exists(): + return {"title": title, "dismissed": True} + + active = HostingAccount.objects.filter(retired_at__isnull=True) + steps = [] + if role == PanelRole.ADMIN: + if user.has_perm("hosting.view_servicehealth"): + steps.append( + ( + "Check that services report their status", + reverse("panel:service_health"), + ServiceHealth.objects.exists(), + ) + ) + if user.has_perms( + ("hosting.view_hostingplan", "hosting.add_hostingplan") + ): + steps.append( + ( + "Create a hosting package", + reverse("panel:hosting_plan_create"), + HostingPlan.objects.exists(), + ) + ) + if can_onboard_customer(user): + steps.append( + ( + "Create a customer login and hosting account", + reverse("panel:customer_onboarding"), + active.filter(customer__user__is_superuser=False).exists(), + ) + ) + if user.is_superuser and user.is_verified(): + steps.append( + ( + "Set up hosting for your own login", + reverse("panel:account_create", query={"own": "1"}), + active.filter(customer__user_id=user.pk).exists(), + ) + ) + elif role == PanelRole.MANAGER: + manager = reseller_for_user(user) + has_packages = manager.hosting_plans.exists() + accounts = active.filter(reseller=manager) + may_create = ( + has_packages + and manager.hostingaccount_set.count() < manager.account_limit + ) + steps.extend( + ( + ( + "Get an assigned hosting package", + reverse("panel:manager_packages"), + has_packages, + ), + ( + "Create a customer login and hosting account", + reverse("panel:customer_onboarding") if may_create else "", + accounts.exclude(customer__user_id=user.pk) + .filter(customer__isnull=False) + .exists(), + ), + ) + ) + else: + customer = customer_for_user(user) + account = active.filter(customer=customer).order_by("pk").first() + steps.extend( + ( + ( + "Set up recovery codes", + reverse("panel:account_security"), + PanelRecoveryCode.objects.filter(user_id=user.pk).exists(), + ), + ( + "Get a hosting account", + account.get_absolute_url() if account else "", + account is not None, + ), + ) + ) + + enable_customer = ( + role != PanelRole.CUSTOMER + and not hasattr(user, "hosting_customer") + and customer_workspace_manager(user) is not None + ) + return { + "title": title, + "steps": steps, + "enable_customer": enable_customer, + "role": role, + } + + +@login_required +@require_POST +def onboarding_preference(request): + role = workspace_role(request) + if role is None: + raise PermissionDenied + action = request.POST.get("action") + if action == "dismiss": + OnboardingDismissal.objects.get_or_create( + user_id=request.user.pk, role=role + ) + elif action == "show": + OnboardingDismissal.objects.filter( + user_id=request.user.pk, role=role + ).delete() + else: + return HttpResponseBadRequest() + return redirect("panel:accounts") + + +@login_required +@require_POST +@transaction.atomic +def enable_customer_workspace(request): + if getattr(request, "impersonation", None): + raise PermissionDenied + user = request.user + manager = customer_workspace_manager(user) + if manager is None: + raise PermissionDenied + customer, created = Customer.objects.get_or_create( + user_id=user.pk, defaults={"reseller": manager} + ) + if created: + LogEntry.objects.log_actions( + user.pk, [customer], ADDITION, "Enabled own Customer workspace." + ) + return redirect("panel:accounts") diff --git a/src/coulobre/hosting/workspaces.py b/src/coulobre/hosting/workspaces.py index cbdf48d..b602755 100644 --- a/src/coulobre/hosting/workspaces.py +++ b/src/coulobre/hosting/workspaces.py @@ -369,12 +369,20 @@ def groups_for(request, *, customer, manager): ) ] else: + from .account_administration import can_onboard_customer + accounts = [] for permission, route, label in ( (("view_hostingaccount",), "accounts", "Hosting accounts"), (("view_customer",), "all_users", "Show All Users"), (("view_reseller",), "resellers", "Managers"), - (("view_customer", "add_customer"), "customer_create", "Add User"), + ( + ("view_customer", "add_customer"), + "customer_onboarding" + if can_onboard_customer(user) + else "customer_create", + "Add User", + ), ( ("view_reseller", "add_reseller"), "reseller_create", -- 2.43.0