Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

settings: Add "can_manage_billing_group" realm setting.

Vector73158fd58cde80
diff --git a/api_docs/unmerged.d/ZF-51430d b/api_docs/unmerged.d/ZF-51430d
new file mode 100644
index 00000000000..621b56398f5
--- /dev/null
+++ b/api_docs/unmerged.d/ZF-51430d
@@ -0,0 +1,8 @@
+* `PATCH /realm`, [`GET /events`](/api/get-events),
+ [`POST /register`](/api/register-queue):
+ Added `can_manage_billing_group` realm setting which is a
+ [group-setting value](/api/group-setting-values) describing the set of users
+ with permission manage plans and billing for the organization.
+* [`POST /register`](/api/register-queue): Added a new `realm_billing` object
+ containing additional information about the organization's billing state,
+ such as sponsorship request status.
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py
index 533906722d4..8d5026b4bae 100644
--- a/corporate/lib/stripe.py
+++ b/corporate/lib/stripe.py
@@ -49,7 +49,7 @@ from zerver.lib.logging_util import log_to_file
from zerver.lib.send_email import (
FromAddress,
send_email,
- send_email_to_billing_admins_and_realm_owners,
+ send_email_to_users_with_billing_access_and_realm_owners,
)
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
from zerver.lib.url_encoding import append_url_query_string
@@ -3407,7 +3407,7 @@ class BillingSession(ABC):
session.type == Session.CARD_UPDATE_FROM_BILLING_PAGE
and not self.has_billing_access()
):
- raise JsonableError(_("Must be a billing administrator or an organization owner"))
+ raise JsonableError(_("Insufficient permission"))
return {"session": session.to_dict()}
stripe_invoice_id = event_status_request.stripe_invoice_id
@@ -4170,7 +4170,7 @@ class RealmBillingSession(BillingSession):
event_type=BillingSessionEventType.SPONSORSHIP_APPROVED, event_time=timezone_now()
)
notification_bot = get_system_bot(settings.NOTIFICATION_BOT, self.realm.id)
- for user in self.realm.get_human_billing_admin_and_realm_owner_users():
+ for user in self.realm.get_human_users_with_billing_access_and_realm_owner_users():
with override_language(user.default_language):
# Using variable to make life easier for translators if these details change.
message = _(
@@ -4185,7 +4185,7 @@ class RealmBillingSession(BillingSession):
end_link="](/help/linking-to-zulip-website)",
)
internal_send_private_message(notification_bot, user, message)
- return f"Sponsorship approved for {self.billing_entity_display_name}; Emailed organization owners and billing admins."
+ return f"Sponsorship approved for {self.billing_entity_display_name}; Emailed organization owners and users with billing permission."
@override
def is_sponsored(self) -> bool:
@@ -5575,7 +5575,7 @@ def downgrade_small_realms_behind_on_payments_as_needed() -> None:
"upgrade_url": f"{realm.url}{reverse('upgrade_page')}",
"realm": realm,
}
- send_email_to_billing_admins_and_realm_owners(
+ send_email_to_users_with_billing_access_and_realm_owners(
"zerver/emails/realm_auto_downgraded",
realm,
from_name=FromAddress.security_email_from_name(language=realm.default_language),
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index 0406688473a..ab38f4bcb6f 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -441,10 +441,11 @@ class StripeTestCase(ZulipTestCase):
self.next_month = datetime(2012, 2, 2, 3, 4, 5, tzinfo=timezone.utc)
self.next_year = datetime(2013, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
- # Make hamlet billing admin for testing.
+ # Add hamlet in `can_manage_billing_group` for testing.
hamlet = self.example_user("hamlet")
- hamlet.is_billing_admin = True
- hamlet.save(update_fields=["is_billing_admin"])
+ iago = self.example_user("iago")
+ do_change_user_role(hamlet, UserProfile.ROLE_REALM_OWNER, acting_user=None)
+ do_change_user_role(iago, UserProfile.ROLE_REALM_OWNER, acting_user=None)
self.billing_session: (
RealmBillingSession | RemoteRealmBillingSession | RemoteServerBillingSession
@@ -2193,9 +2194,9 @@ class StripeTest(StripeTestCase):
@mock_stripe()
def test_upgrade_race_condition_during_card_upgrade(self, *mocks: Mock) -> None:
hamlet = self.example_user("hamlet")
- othello = self.example_user("othello")
- self.login_user(othello)
- othello_upgrade_page_response = self.client_get("/upgrade/")
+ iago = self.example_user("iago")
+ self.login_user(iago)
+ iago_upgrade_page_response = self.client_get("/upgrade/")
self.login_user(hamlet)
self.add_card_to_customer_for_upgrade()
@@ -2220,9 +2221,9 @@ class StripeTest(StripeTestCase):
assert customer.stripe_customer_id is not None
[hamlet_invoice] = iter(stripe.Invoice.list(customer=customer.stripe_customer_id))
- self.login_user(othello)
+ self.login_user(iago)
with self.settings(CLOUD_FREE_TRIAL_DAYS=60):
- # Othello completed the upgrade while we were waiting on success payment event for Hamlet.
+ # Iago completed the upgrade while we were waiting on success payment event for Hamlet.
# NOTE: Used free trial to avoid creating any stripe invoice events.
self.client_billing_post(
"/billing/upgrade",
@@ -2230,9 +2231,9 @@ class StripeTest(StripeTestCase):
"billing_modality": "charge_automatically",
"schedule": "annual",
"signed_seat_count": self.get_signed_seat_count_from_response(
- othello_upgrade_page_response
+ iago_upgrade_page_response
),
- "salt": self.get_salt_from_response(othello_upgrade_page_response),
+ "salt": self.get_salt_from_response(iago_upgrade_page_response),
"license_management": "automatic",
},
)
@@ -2608,7 +2609,7 @@ class StripeTest(StripeTestCase):
self.assertEqual(message.reply_to, ["[email protected]"])
self.assertEqual(self.email_envelope_from(message), settings.NOREPLY_EMAIL_ADDRESS)
self.assertIn("Zulip support request <noreply-", self.email_display_from(message))
- self.assertIn("Requested by: King Hamlet (Member)", message.body)
+ self.assertIn("Requested by: King Hamlet (Organization owner)", message.body)
self.assertIn(
"Support URL: http://zulip.testserver/activity/support?q=zulip", message.body
)
@@ -2660,7 +2661,7 @@ class StripeTest(StripeTestCase):
self.assertEqual(message.reply_to, ["[email protected]"])
self.assertEqual(self.email_envelope_from(message), settings.NOREPLY_EMAIL_ADDRESS)
self.assertIn("Zulip sponsorship request <noreply-", self.email_display_from(message))
- self.assertIn("Requested by: King Hamlet (Member)", message.body)
+ self.assertIn("Requested by: King Hamlet (Organization owner)", message.body)
self.assertIn(
"Support URL: http://zulip.testserver/activity/support?q=zulip", message.body
)
@@ -2689,7 +2690,7 @@ class StripeTest(StripeTestCase):
self.login_user(self.example_user("othello"))
response = self.client_get("/billing/")
self.assert_in_success_response(
- ["You must be an organization owner or a billing administrator to view this page."],
+ ["You do not have permission to view this page."],
response,
)
@@ -2719,12 +2720,10 @@ class StripeTest(StripeTestCase):
)
def test_redirect_for_billing_page(self) -> None:
- user = self.example_user("iago")
+ user = self.example_user("othello")
self.login_user(user)
response = self.client_get("/billing/")
- not_admin_message = (
- "You must be an organization owner or a billing administrator to view this page."
- )
+ not_admin_message = "You do not have permission to view this page."
self.assert_in_success_response([not_admin_message], response)
user.realm.plan_type = Realm.PLAN_TYPE_STANDARD_FREE
@@ -2851,6 +2850,13 @@ class StripeTest(StripeTestCase):
def test_redirect_for_upgrade_page(self) -> None:
user = self.example_user("iago")
+ cordelia = self.example_user("cordelia")
+ self.login_user(cordelia)
+ # Cordelia is not in `can_manage_billing_group`, so can't access the page.
+ response = self.client_get("/upgrade/")
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response["Location"], "/billing/")
+
self.login_user(user)
response = self.client_get("/upgrade/")
@@ -3077,14 +3083,12 @@ class StripeTest(StripeTestCase):
},
)
- self.login_user(self.example_user("iago"))
+ self.login_user(self.example_user("othello"))
response = self.client_billing_get(
"/billing/event/status",
{"stripe_session_id": response_dict["stripe_session_id"]},
)
- self.assert_json_error_contains(
- response, "Must be a billing administrator or an organization owner"
- )
+ self.assert_json_error_contains(response, "Insufficient permission")
self.login_user(self.example_user("hamlet"))
response = self.client_get("/billing/")
@@ -4754,6 +4758,10 @@ class StripeTest(StripeTestCase):
)
users.append(user)
+ user = users[0]
+ user.role = UserProfile.ROLE_REALM_OWNER
+ user.save(update_fields=["role"])
+
customer = None
if create_stripe_customer:
billing_session = RealmBillingSession(users[0])
@@ -5201,11 +5209,6 @@ class RequiresBillingAccessTest(StripeTestCase):
def test_json_endpoints_permissions(self) -> None:
guest = self.example_user("polonius")
member = self.example_user("othello")
- realm_admin = self.example_user("iago")
-
- billing_admin = self.example_user("hamlet")
- billing_admin.is_billing_admin = True
- billing_admin.save(update_fields=["is_billing_admin"])
tested_endpoints = set()
@@ -5249,16 +5252,16 @@ class RequiresBillingAccessTest(StripeTestCase):
)
check_users_cant_access(
- [guest, member, realm_admin],
- "Must be a billing administrator or an organization owner",
+ [guest, member],
+ "Insufficient permission",
"/json/billing/plan",
"PATCH",
{},
)
check_users_cant_access(
- [guest, member, realm_admin],
- "Must be a billing administrator or an organization owner",
+ [guest, member],
+ "Insufficient permission",
"/json/billing/session/start_card_update_session",
"POST",
{},
@@ -5298,37 +5301,19 @@ class RequiresBillingAccessTest(StripeTestCase):
response = self.client_get("/upgrade/", follow=True)
self.assertEqual(response.status_code, 404)
- non_owner_non_billing_admin = self.example_user("othello")
- self.login_user(non_owner_non_billing_admin)
- response = self.client_get("/billing/")
- self.assert_in_success_response(
- ["You must be an organization owner or a billing administrator to view this page."],
- response,
- )
- # Check that non-admins can sign up and pay
- self.add_card_and_upgrade(non_owner_non_billing_admin)
- # Check that the non-admin othello can still access /billing
- response = self.client_get("/billing/")
- self.assert_in_success_response(["Zulip Cloud Standard"], response)
- self.assert_not_in_success_response(
- ["You must be an organization owner or a billing administrator to view this page."],
- response,
- )
-
- # Check realm owners can access billing, even though they are not a billing admin
+ # Check user in `can_manage_billing_group` has access
desdemona = self.example_user("desdemona")
desdemona.role = UserProfile.ROLE_REALM_OWNER
desdemona.save(update_fields=["role"])
self.login_user(self.example_user("desdemona"))
+ self.add_card_and_upgrade(desdemona)
response = self.client_get("/billing/")
self.assert_in_success_response(["Zulip Cloud Standard"], response)
- # Check that member who is not a billing admin does not have access
+ # Check that member who is not in `can_manage_billing_group` does not have access
self.login_user(self.example_user("cordelia"))
response = self.client_get("/billing/")
- self.assert_in_success_response(
- ["You must be an organization owner or a billing administrator"], response
- )
+ self.assert_in_success_response(["You do not have permission to view this page."], response)
class BillingHelpersTest(ZulipTestCase):
@@ -6813,14 +6798,14 @@ class TestSupportBillingHelpers(StripeTestCase):
self.assertEqual(message_to_owner.content, expected_message)
self.assertEqual(message_to_owner.recipient.type, Recipient.PERSONAL)
- # Organization billing admins get the notification bot message
+ # Hamlet is in `can_manage_billing_group` so should get the notification bot message
hamlet_recipient = self.example_user("hamlet").recipient
- message_to_billing_admin = Message.objects.filter(
+ message_to_hamlet = Message.objects.filter(
realm_id=realm.id, sender=sender.id, recipient=hamlet_recipient
).first()
- assert message_to_billing_admin is not None
- self.assertEqual(message_to_billing_admin.content, expected_message)
- self.assertEqual(message_to_billing_admin.recipient.type, Recipient.PERSONAL)
+ assert message_to_hamlet is not None
+ self.assertEqual(message_to_hamlet.content, expected_message)
+ self.assertEqual(message_to_hamlet.recipient.type, Recipient.PERSONAL)
def test_update_realm_sponsorship_status(self) -> None:
lear = get_realm("lear")
diff --git a/corporate/views/portico.py b/corporate/views/portico.py
index 8c234bb0d38..e51e17af42e 100644
--- a/corporate/views/portico.py
+++ b/corporate/views/portico.py
@@ -112,6 +112,8 @@ def plans_view(request: HttpRequest) -> HttpResponse:
return redirect_to_login(next="/plans/")
if request.user.is_guest:
return TemplateResponse(request, "404.html", status=404)
+ if not request.user.has_billing_access:
+ return HttpResponseRedirect(reverse("billing_page"))
customer = get_customer_by_realm(realm)
context.on_free_tier = customer is None and not context.is_sponsored
diff --git a/corporate/views/sponsorship.py b/corporate/views/sponsorship.py
index f0d4a2fb790..6a5dee89c9c 100644
--- a/corporate/views/sponsorship.py
+++ b/corporate/views/sponsorship.py
@@ -25,7 +25,7 @@ def sponsorship_page(request: HttpRequest) -> HttpResponse:
billing_session = RealmBillingSession(user)
context = billing_session.get_sponsorship_request_context()
- if context is None:
+ if context is None or not user.has_billing_access:
return HttpResponseRedirect(reverse("billing_page"))
return render(request, "corporate/billing/sponsorship.html", context=context)
diff --git a/corporate/views/upgrade.py b/corporate/views/upgrade.py
index a49f82af65b..1458e4419bf 100644
--- a/corporate/views/upgrade.py
+++ b/corporate/views/upgrade.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING
from django.conf import settings
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
+from django.urls import reverse
from pydantic import Json
from corporate.lib.billing_types import BillingModality, BillingSchedule, LicenseManagement
@@ -207,6 +208,9 @@ def upgrade_page(
if redirect_url:
return HttpResponseRedirect(redirect_url)
+ if not user.has_billing_access:
+ return HttpResponseRedirect(reverse("billing_page"))
+
response = render(request, "corporate/billing/upgrade.html", context=context)
return response
diff --git a/templates/corporate/billing/billing.html b/templates/corporate/billing/billing.html
index ea384ae6d96..3b3c654b354 100644
--- a/templates/corporate/billing/billing.html
+++ b/templates/corporate/billing/billing.html
@@ -397,7 +397,7 @@
</div>
<div class="white-box">
<p>
- You must be an organization owner or a billing administrator to view this page.
+ You do not have permission to view this page.
</p>
</div>
</div>
diff --git a/web/src/admin.ts b/web/src/admin.ts
index 7e52114bc49..1ba4d5c7ce3 100644
--- a/web/src/admin.ts
+++ b/web/src/admin.ts
@@ -259,6 +259,7 @@ export function build_page(): void {
group_setting_labels: settings_config.all_group_setting_labels.realm,
server_can_summarize_topics: realm.server_can_summarize_topics,
is_plan_self_hosted: realm.realm_plan_type === 1,
+ has_billing_access: settings_data.user_has_billing_access(),
};
const rendered_admin_tab = render_admin_tab(options);
@@ -280,11 +281,17 @@ export function build_page(): void {
const is_plan_self_hosted = realm.realm_plan_type === 1;
if (current_user.is_admin && !(is_plan_plus || is_plan_self_hosted)) {
$("#realm_can_access_all_users_group_widget").prop("disabled", true);
- const opts = {
- content: $t({
+
+ const opts: {content?: string} = {};
+ if (settings_data.user_has_billing_access()) {
+ opts.content = $t({
defaultMessage: "This feature is available on Zulip Cloud Plus. Upgrade to access.",
- }),
- };
+ });
+ } else {
+ opts.content = $t({
+ defaultMessage: "This feature is available on Zulip Cloud Plus.",
+ });
+ }
tippy.default(the($("#realm_can_access_all_users_group_widget_container")), opts);
}
diff --git a/web/src/base_page_params.ts b/web/src/base_page_params.ts
index 7e6424fb4b8..ade0bb021a7 100644
--- a/web/src/base_page_params.ts
+++ b/web/src/base_page_params.ts
@@ -43,11 +43,7 @@ const home_params_schema = default_params_schema
// it isn't displayed for logged-in users and requires markdown
// processor time to compute.
realm_rendered_description: z.optional(z.string()),
- show_billing: z.boolean(),
- show_remote_billing: z.boolean(),
- show_plans: z.boolean(),
show_webathena: z.boolean(),
- sponsorship_pending: z.boolean(),
state_data: state_data_schema.nullable(),
translation_data: z.record(z.string()),
})
diff --git a/web/src/group_permission_settings.ts b/web/src/group_permission_settings.ts
index 39bc6c4f74a..a69e9a05386 100644
--- a/web/src/group_permission_settings.ts
+++ b/web/src/group_permission_settings.ts
@@ -54,6 +54,7 @@ export const realm_group_setting_name_schema = z.enum([
"can_delete_own_message_group",
"can_invite_users_group",
"can_manage_all_groups",
+ "can_manage_billing_group",
"can_mention_many_users_group",
"can_move_messages_between_channels_group",
"can_move_messages_between_topics_group",
diff --git a/web/src/invite.ts b/web/src/invite.ts
index c6fa636b456..ce722c5219e 100644
--- a/web/src/invite.ts
+++ b/web/src/invite.ts
@@ -208,7 +208,7 @@ function submit_invitation_form(): void {
is_admin: current_user.is_admin,
is_invitee_deactivated,
license_limit_reached: parsed.data.license_limit_reached,
- has_billing_access: current_user.is_owner || current_user.is_billing_admin,
+ has_billing_access: settings_data.user_has_billing_access(),
daily_limit_reached: parsed.data.daily_limit_reached,
});
ui_report.message(error_response, $invite_status, "alert-error");
diff --git a/web/src/popover_menus_data.ts b/web/src/popover_menus_data.ts
index f4805b1daf1..d21f5a177de 100644
--- a/web/src/popover_menus_data.ts
+++ b/web/src/popover_menus_data.ts
@@ -19,7 +19,7 @@ import * as settings_config from "./settings_config.ts";
import type {ColorSchemeValues} from "./settings_config.ts";
import * as settings_data from "./settings_data.ts";
import * as starred_messages from "./starred_messages.ts";
-import {current_user, realm} from "./state_data.ts";
+import {current_user, realm, realm_billing} from "./state_data.ts";
import * as stream_data from "./stream_data.ts";
import * as sub_store from "./sub_store.ts";
import {num_unread_for_topic} from "./unread.ts";
@@ -133,6 +133,12 @@ type GearMenuContext = {
color_scheme_values: ColorSchemeValues;
};
+type BillingInfo = {
+ show_billing: boolean;
+ show_remote_billing: boolean;
+ show_plans: boolean;
+};
+
export function get_actions_popover_content_context(message_id: number): ActionPopoverContext {
assert(message_lists.current !== undefined);
const message = message_lists.current.get(message_id);
@@ -334,11 +340,33 @@ export function get_personal_menu_content_context(): PersonalMenuContext {
};
}
+function get_billing_info(): BillingInfo {
+ const billing_info = {
+ show_remote_billing: false,
+ show_billing: false,
+ show_plans: false,
+ };
+ if (!settings_data.user_has_billing_access()) {
+ return billing_info;
+ }
+
+ const is_plan_standard = realm.realm_plan_type === 3;
+ const is_plan_plus = realm.realm_plan_type === 10;
+ const is_org_on_paid_plan = is_plan_standard || is_plan_plus;
+
+ billing_info.show_remote_billing = !page_params.corporate_enabled;
+ billing_info.show_plans = !realm.zulip_plan_is_not_limited;
+ billing_info.show_billing = is_org_on_paid_plan;
+
+ return billing_info;
+}
+
export function get_gear_menu_content_context(): GearMenuContext {
- const user_has_billing_access = current_user.is_billing_admin || current_user.is_owner;
+ const user_has_billing_access = settings_data.user_has_billing_access();
const is_plan_standard = realm.realm_plan_type === 3;
const is_plan_plus = realm.realm_plan_type === 10;
const is_org_on_paid_plan = is_plan_standard || is_plan_plus;
+ const billing_info = get_billing_info();
return {
realm_name: realm.realm_name,
realm_url: new URL(realm.realm_url).hostname,
@@ -363,11 +391,11 @@ export function get_gear_menu_content_context(): GearMenuContext {
is_guest: current_user.is_guest,
login_link: page_params.development_environment ? "/devlogin/" : "/login/",
promote_sponsoring_zulip: page_params.promote_sponsoring_zulip,
- show_billing: page_params.show_billing,
- show_remote_billing: page_params.show_remote_billing,
- show_plans: page_params.show_plans,
+ show_billing: billing_info.show_billing,
+ show_remote_billing: billing_info.show_remote_billing,
+ show_plans: billing_info.show_plans,
show_webathena: page_params.show_webathena,
- sponsorship_pending: page_params.sponsorship_pending,
+ sponsorship_pending: realm_billing.has_pending_sponsorship_request,
user_has_billing_access,
// user color scheme
user_color_scheme: user_settings.color_scheme,
diff --git a/web/src/settings_components.ts b/web/src/settings_components.ts
index 01dd9df24ad..bec139bff99 100644
--- a/web/src/settings_components.ts
+++ b/web/src/settings_components.ts
@@ -812,6 +812,7 @@ export function check_realm_settings_property_changed(elem: HTMLElement): boolea
case "realm_can_delete_own_message_group":
case "realm_can_invite_users_group":
case "realm_can_manage_all_groups":
+ case "realm_can_manage_billing_group":
case "realm_can_mention_many_users_group":
case "realm_can_move_messages_between_channels_group":
case "realm_can_move_messages_between_topics_group":
@@ -1061,6 +1062,7 @@ export function populate_data_for_realm_settings_request(
"can_create_web_public_channel_group",
"can_create_write_only_bots_group",
"can_manage_all_groups",
+ "can_manage_billing_group",
"can_delete_any_message_group",
"can_delete_own_message_group",
"can_invite_users_group",
@@ -1536,6 +1538,7 @@ export const group_setting_widget_map = new Map<string, GroupSettingPillContaine
["realm_can_delete_own_message_group", null],
["realm_can_invite_users_group", null],
["realm_can_manage_all_groups", null],
+ ["realm_can_manage_billing_group", null],
["realm_can_mention_many_users_group", null],
["realm_can_move_messages_between_channels_group", null],
["realm_can_move_messages_between_topics_group", null],
diff --git a/web/src/settings_config.ts b/web/src/settings_config.ts
index 9f9b7424ad3..a996f1be68a 100644
--- a/web/src/settings_config.ts
+++ b/web/src/settings_config.ts
@@ -651,6 +651,7 @@ export const all_group_setting_labels = {
defaultMessage: "Who can start a direct message conversation",
}),
can_manage_all_groups: $t({defaultMessage: "Who can administer all user groups"}),
+ can_manage_billing_group: $t({defaultMessage: "Who can manage plans and billing"}),
can_create_groups: $t({defaultMessage: "Who can create user groups"}),
can_move_messages_between_topics_group: $t({
defaultMessage: "Who can move messages to another topic",
@@ -748,6 +749,7 @@ export const realm_group_permission_settings: {
subsection_heading: $t({defaultMessage: "Other permissions"}),
subsection_key: "org-other-permissions",
settings: [
+ "can_manage_billing_group",
"can_summarize_topics_group",
"can_create_write_only_bots_group",
"can_create_bots_group",
diff --git a/web/src/settings_data.ts b/web/src/settings_data.ts
index b338eccd8ba..c78ec3f39a7 100644
--- a/web/src/settings_data.ts
+++ b/web/src/settings_data.ts
@@ -254,6 +254,14 @@ export function user_can_add_custom_emoji(): boolean {
);
}
+export function user_has_billing_access(): boolean {
+ return user_has_permission_for_group_setting(
+ realm.realm_can_manage_billing_group,
+ "can_manage_billing_group",
+ "realm",
+ );
+}
+
export function user_can_move_messages_to_another_topic(): boolean {
return user_has_permission_for_group_setting(
realm.realm_can_move_messages_between_topics_group,
diff --git a/web/src/settings_org.ts b/web/src/settings_org.ts
index 92b75b0169f..5ef904f6a4c 100644
--- a/web/src/settings_org.ts
+++ b/web/src/settings_org.ts
@@ -145,6 +145,7 @@ export function enable_or_disable_group_permission_settings(): void {
"realm_create_multiuse_invite_group",
"realm_can_create_groups",
"realm_can_manage_all_groups",
+ "realm_can_manage_billing_group",
];
for (const setting_name of owner_editable_settings) {
const $permission_pill_container = $(`#id_${CSS.escape(setting_name)}`);
@@ -527,6 +528,7 @@ export function discard_realm_property_element_changes(elem: HTMLElement): void
case "realm_can_delete_own_message_group":
case "realm_can_invite_users_group":
case "realm_can_manage_all_groups":
+ case "realm_can_manage_billing_group":
case "realm_can_mention_many_users_group":
case "realm_can_move_messages_between_channels_group":
case "realm_can_move_messages_between_topics_group":
diff --git a/web/src/state_data.ts b/web/src/state_data.ts
index 96968bc3c72..188ea2b12d0 100644
--- a/web/src/state_data.ts
+++ b/web/src/state_data.ts
@@ -175,6 +175,10 @@ export const presence_schema = z.object({
idle_timestamp: z.number().optional(),
});
+export const realm_billing_schema = z.object({
+ has_pending_sponsorship_request: z.boolean(),
+});
+
export const saved_snippet_schema = z.object({
id: z.number(),
title: z.string(),
@@ -305,6 +309,7 @@ export const realm_schema = z.object({
realm_can_delete_own_message_group: group_setting_value_schema,
realm_can_invite_users_group: group_setting_value_schema,
realm_can_manage_all_groups: group_setting_value_schema,
+ realm_can_manage_billing_group: group_setting_value_schema,
realm_can_mention_many_users_group: group_setting_value_schema,
realm_can_move_messages_between_channels_group: group_setting_value_schema,
realm_can_move_messages_between_topics_group: group_setting_value_schema,
@@ -434,6 +439,11 @@ export const state_data_schema = z
.object({alert_words: z.array(z.string())})
.transform((alert_words) => ({alert_words}))
.and(z.object({realm_emoji: realm_emoji_map_schema}).transform((emoji) => ({emoji})))
+ .and(
+ z
+ .object({realm_billing: realm_billing_schema})
+ .transform((realm_billing) => ({realm_billing})),
+ )
.and(z.object({realm_bots: z.array(server_add_bot_schema)}).transform((bot) => ({bot})))
.and(
z
@@ -557,9 +567,11 @@ export type StateData = z.infer<typeof state_data_schema>;
export type CurrentUser = StateData["current_user"];
export type Realm = StateData["realm"];
+export type RealmBilling = StateData["realm_billing"]["realm_billing"];
export let current_user: CurrentUser;
export let realm: Realm;
+export let realm_billing: RealmBilling;
export function set_current_user(initial_current_user: CurrentUser): void {
current_user = initial_current_user;
@@ -568,3 +580,7 @@ export function set_current_user(initial_current_user: CurrentUser): void {
export function set_realm(initial_realm: Realm): void {
realm = initial_realm;
}
+
+export function set_realm_billing(params: StateData["realm_billing"]): void {
+ realm_billing = params.realm_billing;
+}
diff --git a/web/src/stream_edit.ts b/web/src/stream_edit.ts
index d264751d439..67f06fe0fea 100644
--- a/web/src/stream_edit.ts
+++ b/web/src/stream_edit.ts
@@ -30,6 +30,7 @@ import {postprocess_content} from "./postprocess_content.ts";
import * as scroll_util from "./scroll_util.ts";
import * as settings_components from "./settings_components.ts";
import * as settings_config from "./settings_config.ts";
+import * as settings_data from "./settings_data.ts";
import * as settings_org from "./settings_org.ts";
import type {CurrentUser} from "./state_data.ts";
import {current_user, realm} from "./state_data.ts";
@@ -269,6 +270,7 @@ export function show_settings_for(node: HTMLElement): void {
org_level_message_retention_setting: get_display_text_for_realm_message_retention_setting(),
can_access_stream_email: stream_data.can_access_stream_email(sub),
group_setting_labels: settings_config.all_group_setting_labels.stream,
+ has_billing_access: settings_data.user_has_billing_access(),
});
scroll_util.get_content_element($("#stream_settings")).html(html);
diff --git a/web/src/stream_settings_ui.ts b/web/src/stream_settings_ui.ts
index 73560ea93c1..c3c4bd515c0 100644
--- a/web/src/stream_settings_ui.ts
+++ b/web/src/stream_settings_ui.ts
@@ -832,6 +832,7 @@ function setup_page(callback: () => void): void {
!realm.zulip_plan_is_not_limited || !current_user.is_owner,
group_setting_labels: settings_config.all_group_setting_labels.stream,
realm_has_archived_channels,
+ has_billing_access: settings_data.user_has_billing_access(),
};
const rendered = render_stream_settings_overlay(template_data);
diff --git a/web/src/ui_init.js b/web/src/ui_init.js
index 91a1b9c2ebc..a44a912a193 100644
--- a/web/src/ui_init.js
+++ b/web/src/ui_init.js
@@ -117,7 +117,14 @@ import * as sidebar_ui from "./sidebar_ui.ts";
import * as spoilers from "./spoilers.ts";
import * as starred_messages from "./starred_messages.ts";
import * as starred_messages_ui from "./starred_messages_ui.ts";
-import {current_user, realm, set_current_user, set_realm, state_data_schema} from "./state_data.ts";
+import {
+ current_user,
+ realm,
+ set_current_user,
+ set_realm,
+ set_realm_billing,
+ state_data_schema,
+} from "./state_data.ts";
import * as stream_card_popover from "./stream_card_popover.ts";
import * as stream_create from "./stream_create.ts";
import * as stream_data from "./stream_data.ts";
@@ -423,6 +430,7 @@ export function initialize_everything(state_data) {
set_current_user(state_data.current_user);
set_realm(state_data.realm);
+ set_realm_billing(state_data.realm_billing);
/* To store theme data for spectators, we need to initialize
user_settings before setting the theme. Because information
diff --git a/web/src/user_group_edit.ts b/web/src/user_group_edit.ts
index 6da9ce3206e..3d6a5678a5e 100644
--- a/web/src/user_group_edit.ts
+++ b/web/src/user_group_edit.ts
@@ -1704,6 +1704,7 @@ export function setup_page(callback: () => void): void {
realm.realm_org_type === settings_config.all_org_type_values.business.code,
max_user_group_name_length: user_groups.max_user_group_name_length,
all_group_setting_labels: settings_config.all_group_setting_labels,
+ has_billing_access: settings_data.user_has_billing_access(),
};
const groups_overlay_html = render_user_group_settings_overlay(template_data);
diff --git a/web/templates/invitation_failed_error.hbs b/web/templates/invitation_failed_error.hbs
index 668cfa1740e..c235ffd2ae4 100644
--- a/web/templates/invitation_failed_error.hbs
+++ b/web/templates/invitation_failed_error.hbs
@@ -32,7 +32,7 @@
{{/tr}}
{{else}}
{{#tr}}
- Please ask a billing administrator to <z-link-billing>increase the number of licenses</z-link-billing> or <z-link-help-page>deactivate inactive users</z-link-help-page>, and try again.
+ Please ask a user with billing permission to <z-link-billing>increase the number of licenses</z-link-billing> or <z-link-help-page>deactivate inactive users</z-link-help-page>, and try again.
{{#*inline "z-link-billing"}}<a href="/billing/">{{> @partial-block}}</a>{{/inline}}
{{#*inline "z-link-help-page"}}<a href="/help/deactivate-or-reactivate-a-user" target="_blank" rel="noopener noreferrer">{{> @partial-block}}</a>{{/inline}}
{{/tr}}
diff --git a/web/templates/popovers/navbar/navbar_gear_menu_popover.hbs b/web/templates/popovers/navbar/navbar_gear_menu_popover.hbs
index 79bd926117e..6047850f81d 100644
--- a/web/templates/popovers/navbar/navbar_gear_menu_popover.hbs
+++ b/web/templates/popovers/navbar/navbar_gear_menu_popover.hbs
@@ -128,7 +128,7 @@
<span class="popover-menu-label">{{t 'API documentation' }}</span>
</a>
</li>
- {{#if show_billing}}
+ {{#if (and user_has_billing_access show_billing)}}
<li role="none" class="link-item popover-menu-list-item">
<a role="menuitem" href="/billing/" target="_blank" rel="noopener noreferrer" class="navigate-link-on-enter popover-menu-link">
<i class="popover-menu-icon zulip-icon zulip-icon-credit-card" aria-hidden="true"></i>
@@ -144,6 +144,7 @@
</a>
</li>
{{/if}}
+ {{#if user_has_billing_access}}
{{#if show_remote_billing }}
<li role="none" class="link-item popover-menu-list-item">
<a role="menuitem" href="/self-hosted-billing/" id="open-self-hosted-billing" target="_blank" rel="noopener noreferrer" class="navigate-link-on-enter popover-menu-link">
@@ -161,6 +162,7 @@
</a>
</li>
{{/if}}
+ {{/if}}
{{!-- Group 3 --}}
{{#if (or can_invite_users_by_email can_create_multiuse_invite is_spectator show_webathena)}}
<li role="separator" class="popover-menu-separator"></li>
diff --git a/web/templates/settings/organization_permissions_admin.hbs b/web/templates/settings/organization_permissions_admin.hbs
index 1fe7f8e9957..c3a35423d95 100644
--- a/web/templates/settings/organization_permissions_admin.hbs
+++ b/web/templates/settings/organization_permissions_admin.hbs
@@ -338,6 +338,10 @@
{{> settings_save_discard_widget section_name="other-permissions" }}
</div>
<div class="m-10 inline-block organization-permissions-parent">
+ {{> group_setting_value_pill_input
+ setting_name="realm_can_manage_billing_group"
+ label=group_setting_labels.can_manage_billing_group}}
+
<div class="disabled-unfinished-feature" style="display: none">
{{#unless server_can_summarize_topics}}
<div class="tip">
diff --git a/web/templates/settings/upgrade_tip_widget.hbs b/web/templates/settings/upgrade_tip_widget.hbs
index 301b8fc9bea..35ed4e470d8 100644
--- a/web/templates/settings/upgrade_tip_widget.hbs
+++ b/web/templates/settings/upgrade_tip_widget.hbs
@@ -2,16 +2,26 @@
{{#unless is_guest}}
{{#unless zulip_plan_is_not_limited}}
{{#if is_business_type_org}}
+ {{#if has_billing_access}}
<a href="/upgrade/" class="upgrade-tip" target="_blank" rel="noopener noreferrer">
{{upgrade_text_for_wide_organization_logo}}
</a>
+ {{else}}
+ <div class="upgrade-tip">
+ {{upgrade_text_for_wide_organization_logo}}
+ </div>
+ {{/if}}
{{else}}
<div class="upgrade-or-sponsorship-tip">
+ {{#if has_billing_access}}
{{#tr}}
Available on Zulip Cloud Standard. <z-link-upgrade>Upgrade</z-link-upgrade> or <z-link-sponsorship>request sponsorship</z-link-sponsorship> to access.
{{#*inline "z-link-upgrade"}}<a href="/upgrade/" target="_blank" rel="noopener noreferrer">{{> @partial-block}}</a>{{/inline}}
{{#*inline "z-link-sponsorship"}}<a href="/sponsorship/" target="_blank" rel="noopener noreferrer">{{> @partial-block}}</a>{{/inline}}
{{/tr}}
+ {{else}}
+ {{t 'Available on Zulip Cloud Standard.'}}
+ {{/if}}
</div>
{{/if}}
{{/unless}}
diff --git a/web/templates/stream_settings/stream_settings.hbs b/web/templates/stream_settings/stream_settings.hbs
index 5cd72350bf7..4df93d90a81 100644
--- a/web/templates/stream_settings/stream_settings.hbs
+++ b/web/templates/stream_settings/stream_settings.hbs
@@ -64,6 +64,7 @@
zulip_plan_is_not_limited=../zulip_plan_is_not_limited
upgrade_text_for_wide_organization_logo=../upgrade_text_for_wide_organization_logo
is_business_type_org=../is_business_type_org
+ has_billing_access=../has_billing_access
org_level_message_retention_setting=../org_level_message_retention_setting
is_stream_edit=true
prefix="id_"
diff --git a/web/tests/settings_data.test.cjs b/web/tests/settings_data.test.cjs
index d076d2eef28..8673c5596b9 100644
--- a/web/tests/settings_data.test.cjs
+++ b/web/tests/settings_data.test.cjs
@@ -218,6 +218,8 @@ test_realm_group_settings(
settings_data.user_can_invite_users_by_email,
);
+test_realm_group_settings("realm_can_manage_billing_group", settings_data.user_has_billing_access);
+
test_realm_group_settings(
"realm_can_move_messages_between_channels_group",
settings_data.user_can_move_messages_between_streams,
diff --git a/zerver/decorator.py b/zerver/decorator.py
index 34f5b37fad6..a12a434f9d3 100644
--- a/zerver/decorator.py
+++ b/zerver/decorator.py
@@ -206,7 +206,7 @@ def require_billing_access(
**kwargs: ParamT.kwargs,
) -> HttpResponse:
if not user_profile.has_billing_access:
- raise JsonableError(_("Must be a billing administrator or an organization owner"))
+ raise JsonableError(_("Insufficient permission"))
return func(request, user_profile, *args, **kwargs)
return wrapper
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index 067ff02a303..8c8cd4943d4 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -41,6 +41,7 @@ from zerver.lib.event_types import (
EventPresence,
EventReactionAdd,
EventReactionRemove,
+ EventRealmBilling,
EventRealmBotAdd,
EventRealmBotDelete,
EventRealmBotUpdate,
@@ -175,6 +176,7 @@ check_muted_users = make_checker(EventMutedUsers)
check_onboarding_steps = make_checker(EventOnboardingSteps)
check_reaction_add = make_checker(EventReactionAdd)
check_reaction_remove = make_checker(EventReactionRemove)
+check_realm_billing = make_checker(EventRealmBilling)
check_realm_bot_delete = make_checker(EventRealmBotDelete)
check_realm_deactivated = make_checker(EventRealmDeactivated)
check_realm_domains_add = make_checker(EventRealmDomainsAdd)
diff --git a/zerver/lib/event_types.py b/zerver/lib/event_types.py
index ba0b562ed99..3ba4222c06e 100644
--- a/zerver/lib/event_types.py
+++ b/zerver/lib/event_types.py
@@ -522,6 +522,7 @@ class GroupSettingUpdateData(GroupSettingUpdateDataCore):
can_delete_own_message_group: int | UserGroupMembersDict | None = None
can_invite_users_group: int | UserGroupMembersDict | None = None
can_manage_all_groups: int | UserGroupMembersDict | None = None
+ can_manage_billing_group: int | UserGroupMembersDict | None = None
can_mention_many_users_group: int | UserGroupMembersDict | None = None
can_move_messages_between_channels_group: int | UserGroupMembersDict | None = None
can_move_messages_between_topics_group: int | UserGroupMembersDict | None = None
@@ -683,6 +684,12 @@ class EventRealmUserUpdate(BaseEvent):
)
+class EventRealmBilling(BaseEvent):
+ type: Literal["realm_billing"]
+ property: str
+ value: bool
+
+
class EventRestart(BaseEvent):
type: Literal["restart"]
zulip_version: str
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index 8e7ad43d67e..c97cdc9d136 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -126,6 +126,24 @@ def always_want(msg_type: str) -> bool:
return True
+def has_pending_sponsorship_request(
+ user_profile: UserProfile | None, user_has_billing_access: bool | None = None
+) -> bool:
+ sponsorship_pending = False
+
+ if user_has_billing_access is None:
+ user_has_billing_access = user_profile is not None and user_profile.has_billing_access
+
+ if settings.CORPORATE_ENABLED and user_profile is not None and user_has_billing_access:
+ from corporate.models import get_customer_by_realm
+
+ customer = get_customer_by_realm(user_profile.realm)
+ if customer is not None:
+ sponsorship_pending = customer.sponsorship_pending
+
+ return sponsorship_pending
+
+
def fetch_initial_state_data(
user_profile: UserProfile | None,
*,
@@ -586,6 +604,23 @@ def fetch_initial_state_data(
# Set home view to recent conversations for spectators regardless of default.
web_home_view="recent_topics",
)
+
+ settings_user_recursive_group_ids = set()
+
+ if want("realm_billing") or want("realm_user"):
+ settings_user_recursive_group_ids = set(
+ get_recursive_membership_groups(settings_user).values_list("id", flat=True)
+ )
+
+ if want("realm_billing"):
+ state["realm_billing"] = {}
+ user_has_billing_access = (
+ realm.can_manage_billing_group_id in settings_user_recursive_group_ids
+ )
+ state["realm_billing"]["has_pending_sponsorship_request"] = has_pending_sponsorship_request(
+ settings_user, user_has_billing_access
+ )
+
if want("realm_user"):
state["raw_users"] = get_users_for_api(
realm,
@@ -614,10 +649,6 @@ def fetch_initial_state_data(
client_gravatar=False,
)
- settings_user_recursive_group_ids = set(
- get_recursive_membership_groups(settings_user).values_list("id", flat=True)
- )
-
state["can_create_private_streams"] = (
realm.can_create_private_channel_group_id in settings_user_recursive_group_ids
)
diff --git a/zerver/lib/home.py b/zerver/lib/home.py
index 2fce1214b53..346a5b1a44f 100644
--- a/zerver/lib/home.py
+++ b/zerver/lib/home.py
@@ -58,45 +58,6 @@ def promote_sponsoring_zulip_in_realm(realm: Realm) -> bool:
return realm.plan_type in [Realm.PLAN_TYPE_STANDARD_FREE, Realm.PLAN_TYPE_SELF_HOSTED]
-def get_billing_info(user_profile: UserProfile | None) -> BillingInfo:
- # See https://zulip.com/help/user-roles for clarity.
- show_billing = False
- show_plans = False
- sponsorship_pending = False
-
- # We want to always show the remote billing option as long as the user is authorized,
- # except on zulipchat.com where it's not applicable.
- show_remote_billing = (
- (not settings.CORPORATE_ENABLED)
- and user_profile is not None
- and user_profile.has_billing_access
- )
-
- # This query runs on home page load, so we want to avoid
- # hitting the database if possible. So, we only run it for the user
- # types that can actually see the billing info.
- if settings.CORPORATE_ENABLED and user_profile is not None and user_profile.has_billing_access:
- from corporate.models import CustomerPlan, get_customer_by_realm
-
- customer = get_customer_by_realm(user_profile.realm)
- if customer is not None:
- if customer.sponsorship_pending:
- sponsorship_pending = True
-
- if CustomerPlan.objects.filter(customer=customer).exists():
- show_billing = True
-
- if user_profile.realm.plan_type == Realm.PLAN_TYPE_LIMITED:
- show_plans = True
-
- return BillingInfo(
- show_billing=show_billing,
- show_plans=show_plans,
- sponsorship_pending=sponsorship_pending,
- show_remote_billing=show_remote_billing,
- )
-
-
def get_user_permission_info(user_profile: UserProfile | None) -> UserPermissionInfo:
if user_profile is not None:
return UserPermissionInfo(
@@ -180,7 +141,6 @@ def build_page_params_for_home_page_load(
furthest_read_time = get_furthest_read_time(user_profile)
two_fa_enabled = settings.TWO_FACTOR_AUTHENTICATION_ENABLED and user_profile is not None
- billing_info = get_billing_info(user_profile)
user_permission_info = get_user_permission_info(user_profile)
# Pass parameters to the client-side JavaScript code.
@@ -202,11 +162,7 @@ def build_page_params_for_home_page_load(
embedded_bots_enabled=settings.EMBEDDED_BOTS_ENABLED,
two_fa_enabled=two_fa_enabled,
apps_page_url=get_apps_page_url(),
- show_billing=billing_info.show_billing,
- show_remote_billing=billing_info.show_remote_billing,
promote_sponsoring_zulip=promote_sponsoring_zulip_in_realm(realm),
- show_plans=billing_info.show_plans,
- sponsorship_pending=billing_info.sponsorship_pending,
show_webathena=user_permission_info.show_webathena,
# Adding two_fa_enabled as condition saves us 3 queries when
# 2FA is not enabled.
diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.py
index a88b223d164..e1afd8db961 100644
--- a/zerver/lib/send_email.py
+++ b/zerver/lib/send_email.py
@@ -434,7 +434,7 @@ def send_email_to_admins(
)
-def send_email_to_billing_admins_and_realm_owners(
+def send_email_to_users_with_billing_access_and_realm_owners(
template_prefix: str,
realm: Realm,
from_name: str | None = None,
@@ -444,7 +444,9 @@ def send_email_to_billing_admins_and_realm_owners(
) -> None:
send_email(
template_prefix,
- to_user_ids=[user.id for user in realm.get_human_billing_admin_and_realm_owner_users()],
+ to_user_ids=[
+ user.id for user in realm.get_human_users_with_billing_access_and_realm_owner_users()
+ ],
from_name=from_name,
from_address=from_address,
language=language,
diff --git a/zerver/migrations/0681_realm_can_manage_billing_group.py b/zerver/migrations/0681_realm_can_manage_billing_group.py
new file mode 100644
index 00000000000..25deb91dd58
--- /dev/null
+++ b/zerver/migrations/0681_realm_can_manage_billing_group.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.0.10 on 2025-02-17 16:11
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("zerver", "0680_rename_general_chat_to_empty_string_topic"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="realm",
+ name="can_manage_billing_group",
+ field=models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.RESTRICT,
+ related_name="+",
+ to="zerver.usergroup",
+ ),
+ ),
+ ]
diff --git a/zerver/migrations/0682_set_default_value_for_can_manage_billing_group.py b/zerver/migrations/0682_set_default_value_for_can_manage_billing_group.py
new file mode 100644
index 00000000000..762ada1de67
--- /dev/null
+++ b/zerver/migrations/0682_set_default_value_for_can_manage_billing_group.py
@@ -0,0 +1,51 @@
+from django.db import migrations
+from django.db.backends.base.schema import BaseDatabaseSchemaEditor
+from django.db.migrations.state import StateApps
+
+
+def set_default_value_for_can_manage_billing_group(
+ apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
+) -> None:
+ Realm = apps.get_model("zerver", "Realm")
+ UserProfile = apps.get_model("zerver", "UserProfile")
+ UserGroup = apps.get_model("zerver", "UserGroup")
+ NamedUserGroup = apps.get_model("zerver", "NamedUserGroup")
+
+ OWNERS_GROUP_NAME = "role:owners"
+
+ for realm in Realm.objects.all():
+ if realm.can_manage_billing_group is not None:
+ continue
+
+ owners_system_group = NamedUserGroup.objects.get(
+ name=OWNERS_GROUP_NAME, realm=realm, is_system_group=True
+ )
+ billing_admins = UserProfile.objects.filter(
+ realm=realm, is_billing_admin=True, is_bot=False, is_active=True
+ )
+
+ if billing_admins.exists():
+ user_group = UserGroup.objects.create(realm=realm)
+ user_group.direct_members.set(list(billing_admins))
+ user_group.direct_subgroups.set([owners_system_group])
+ realm.can_manage_billing_group = user_group
+ else:
+ realm.can_manage_billing_group = owners_system_group
+
+ realm.save(update_fields=["can_manage_billing_group"])
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("zerver", "0681_realm_can_manage_billing_group"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ set_default_value_for_can_manage_billing_group,
+ elidable=True,
+ reverse_code=migrations.RunPython.noop,
+ )
+ ]
diff --git a/zerver/migrations/0683_alter_realm_can_manage_billing_group.py b/zerver/migrations/0683_alter_realm_can_manage_billing_group.py
new file mode 100644
index 00000000000..fa262f9cb5c
--- /dev/null
+++ b/zerver/migrations/0683_alter_realm_can_manage_billing_group.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.0.10 on 2025-02-17 16:18
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("zerver", "0682_set_default_value_for_can_manage_billing_group"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="realm",
+ name="can_manage_billing_group",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.RESTRICT,
+ related_name="+",
+ to="zerver.usergroup",
+ ),
+ ),
+ ]
diff --git a/zerver/models/realms.py b/zerver/models/realms.py
index 1ddd5ca97b8..2b6ce6f697a 100644
--- a/zerver/models/realms.py
+++ b/zerver/models/realms.py
@@ -367,6 +367,11 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
"UserGroup", on_delete=models.RESTRICT, related_name="+"
)
+ # UserGroup which is allowed to manage plans and billing.
+ can_manage_billing_group = models.ForeignKey(
+ "UserGroup", on_delete=models.RESTRICT, related_name="+"
+ )
+
# UserGroup which is allowed to use wildcard mentions in large channels.
can_mention_many_users_group = models.ForeignKey(
"UserGroup", on_delete=models.RESTRICT, related_name="+"
@@ -804,6 +809,13 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
allow_everyone_group=False,
default_group_name=SystemGroups.OWNERS,
),
+ can_manage_billing_group=GroupPermissionSetting(
+ require_system_group=False,
+ allow_internet_group=False,
+ allow_nobody_group=True,
+ allow_everyone_group=False,
+ default_group_name=SystemGroups.ADMINISTRATORS,
+ ),
can_mention_many_users_group=GroupPermissionSetting(
require_system_group=False,
allow_internet_group=False,
@@ -955,12 +967,17 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
role__in=roles,
)
- def get_human_billing_admin_and_realm_owner_users(self) -> QuerySet["UserProfile"]:
+ def get_human_users_with_billing_access_and_realm_owner_users(self) -> QuerySet["UserProfile"]:
+ from zerver.lib.user_groups import get_recursive_group_members
+
+ can_manage_billing_group_members = get_recursive_group_members(
+ self.can_manage_billing_group.id
+ )
+
return UserProfile.objects.filter(
- Q(role=UserProfile.ROLE_REALM_OWNER) | Q(is_billing_admin=True),
- realm=self,
+ Q(id__in=can_manage_billing_group_members)
+ | Q(role=UserProfile.ROLE_REALM_OWNER, realm=self, is_active=True),
is_bot=False,
- is_active=True,
)
def get_active_users(self) -> QuerySet["UserProfile"]:
diff --git a/zerver/models/users.py b/zerver/models/users.py
index 576e2fcdb77..1b12373fb9e 100644
--- a/zerver/models/users.py
+++ b/zerver/models/users.py
@@ -750,7 +750,7 @@ class UserProfile(AbstractBaseUser, PermissionsMixin, UserBaseSettings):
@property
def has_billing_access(self) -> bool:
- return self.is_realm_owner or self.is_billing_admin
+ return self.has_permission("can_manage_billing_group")
@property
def is_realm_owner(self) -> bool:
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index fbc5cbfd8f7..fdde4591e3b 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -4819,6 +4819,16 @@ paths:
create and edit user groups.
[calc-full-member]: /api/roles-and-permissions#determining-if-a-user-is-a-full-member
+ can_manage_billing_group:
+ allOf:
+ - description: |
+ A [group-setting value](/api/group-setting-values) defining the set of
+ users who have permission to manage plans and billing in the organization.
+
+ **Changes**: New in Zulip 10.0 (feature level ZF-51430d). Previously, only owners
+ and users with `is_billing_admin` property set to `true` were allowed to
+ manage plans and billing.
+ - $ref: "#/components/schemas/GroupSettingValue"
can_summarize_topics_group:
allOf:
- $ref: "#/components/schemas/GroupSettingValue"
@@ -17128,6 +17138,16 @@ paths:
create and edit user groups.
[calc-full-member]: /api/roles-and-permissions#determining-if-a-user-is-a-full-member
+ realm_can_manage_billing_group:
+ allOf:
+ - $ref: "#/components/schemas/GroupSettingValue"
+ - description: |
+ A [group-setting value](/api/group-setting-values) defining the set of
+ users who have permission to manage plans and billing in the organization.
+
+ **Changes**: New in Zulip 10.0 (feature level ZF-51430d). Previously, only owners
+ and users with `is_billing_admin` property set to `true` were allowed to
+ manage plans and billing.
realm_can_create_public_channel_group:
allOf:
- $ref: "#/components/schemas/GroupSettingValue"
@@ -18279,6 +18299,23 @@ paths:
**Changes**: New in Zulip 5.0 (feature level 74). Previously,
this was hardcoded to 90 seconds, and clients should use that as a fallback
value when interacting with servers where this field is not present.
+ realm_billing:
+ type: object
+ additionalProperties: false
+ description: |
+ Present if `realm_billing` is present in `fetch_event_types`.
+
+ A dictionary containing billing information of the organization.
+
+ **Changes**: New in Zulip 10.0 (feature level ZF-51430d).
+ properties:
+ has_pending_sponsorship_request:
+ type: boolean
+ description: |
+ Whether there is a pending sponsorship request for the organization. Note that
+ this field will always be `false` if the user is not in `can_manage_billing_group`.
+
+ **Changes**: New in Zulip 10.0 (feature level ZF-51430d).
realm_moderation_request_channel_id:
type: integer
description: |
diff --git a/zerver/tests/test_docs.py b/zerver/tests/test_docs.py
index 02025ca212c..e2b02052380 100644
--- a/zerver/tests/test_docs.py
+++ b/zerver/tests/test_docs.py
@@ -595,9 +595,8 @@ class PlansPageTest(ZulipTestCase):
organization_member = "hamlet"
self.login(organization_member)
result = self.client_get("/plans/", subdomain="zulip")
- self.assert_in_success_response(["Current plan"], result)
- self.assert_in_success_response(["/sponsorship/"], result)
- self.assert_not_in_success_response(["/accounts/go/?next=%2Fsponsorship%2F"], result)
+ self.assertEqual(result.status_code, 302)
+ self.assertEqual("/billing/", result["Location"])
# Test root domain, with login on different domain
result = self.client_get("/plans/", subdomain="")
diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.py
index cbe7e0f03ef..0d5401df9a6 100644
--- a/zerver/tests/test_event_system.py
+++ b/zerver/tests/test_event_system.py
@@ -1231,6 +1231,7 @@ class FetchQueriesTest(ZulipTestCase):
presence=1,
# 2 of the 3 queries here are for fetching 'realm_user_groups' data.
realm=3,
+ realm_billing=1,
realm_bot=1,
realm_domains=1,
realm_embedded_bots=0,
diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.py
index 2c31455cd95..a1fe01e2c47 100644
--- a/zerver/tests/test_home.py
+++ b/zerver/tests/test_home.py
@@ -16,11 +16,8 @@ from zerver.actions.create_user import do_create_user
from zerver.actions.realm_settings import do_change_realm_plan_type, do_set_realm_property
from zerver.actions.users import change_user_is_active
from zerver.lib.compatibility import LAST_SERVER_UPGRADE_TIME, is_outdated_server
-from zerver.lib.home import (
- get_billing_info,
- get_furthest_read_time,
- promote_sponsoring_zulip_in_realm,
-)
+from zerver.lib.events import has_pending_sponsorship_request
+from zerver.lib.home import get_furthest_read_time, promote_sponsoring_zulip_in_realm
from zerver.lib.soft_deactivation import do_soft_deactivate_users
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import (
@@ -60,11 +57,7 @@ class HomeTest(ZulipTestCase):
"presence_history_limit_days_for_web_app",
"promote_sponsoring_zulip",
"request_language",
- "show_billing",
- "show_plans",
- "show_remote_billing",
"show_webathena",
- "sponsorship_pending",
"state_data",
"test_suite",
"translation_data",
@@ -140,6 +133,7 @@ class HomeTest(ZulipTestCase):
"realm_can_delete_own_message_group",
"realm_can_invite_users_group",
"realm_can_manage_all_groups",
+ "realm_can_manage_billing_group",
"realm_can_mention_many_users_group",
"realm_can_move_messages_between_channels_group",
"realm_can_move_messages_between_topics_group",
@@ -244,6 +238,7 @@ class HomeTest(ZulipTestCase):
"server_typing_stopped_wait_period_milliseconds",
"server_web_public_streams_enabled",
"settings_send_digest_emails",
+ "realm_billing",
"starred_messages",
"stop_words",
"subscriptions",
@@ -379,11 +374,7 @@ class HomeTest(ZulipTestCase):
"promote_sponsoring_zulip",
"realm_rendered_description",
"request_language",
- "show_billing",
- "show_plans",
- "show_remote_billing",
"show_webathena",
- "sponsorship_pending",
"state_data",
"test_suite",
"translation_data",
@@ -586,7 +577,7 @@ class HomeTest(ZulipTestCase):
# Verify number of queries for Realm admin isn't much higher than for normal users.
self.login("iago")
with (
- self.assert_database_query_count(52),
+ self.assert_database_query_count(53),
patch("zerver.lib.cache.cache_set") as cache_mock,
):
result = self._get_home_page()
@@ -1004,19 +995,14 @@ class HomeTest(ZulipTestCase):
self.assertEqual(page_params["state_data"]["max_message_id"], -1)
@activate_push_notification_service()
- def test_get_billing_info(self) -> None:
+ def test_has_pending_sponsorship_request(self) -> None:
user = self.example_user("desdemona")
- user.role = UserProfile.ROLE_REALM_OWNER
- user.save(update_fields=["role"])
- # realm owner, but no CustomerPlan and realm plan_type SELF_HOSTED -> neither billing link or plans
+ shiva = self.example_user("shiva")
+ # realm owner, but no CustomerPlan and realm plan_type SELF_HOSTED -> don't show any links
with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
+ sponsorship_pending = has_pending_sponsorship_request(user)
+ self.assertFalse(sponsorship_pending)
- # realm owner, with inactive CustomerPlan and realm plan_type SELF_HOSTED -> show only billing link
customer = Customer.objects.create(realm=get_realm("zulip"), stripe_customer_id="cus_id")
CustomerPlan.objects.create(
customer=customer,
@@ -1026,142 +1012,28 @@ class HomeTest(ZulipTestCase):
tier=CustomerPlan.TIER_CLOUD_STANDARD,
status=CustomerPlan.ENDED,
)
+ # realm admin, with sponsorship pending and realm plan_type SELF_HOSTED -> show sponsorship pending link
+ customer.sponsorship_pending = True
+ customer.save(update_fields=["sponsorship_pending"])
with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertTrue(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # realm owner, with inactive CustomerPlan and realm plan_type LIMITED -> show billing link and plans
- do_change_realm_plan_type(user.realm, Realm.PLAN_TYPE_LIMITED, acting_user=None)
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertTrue(billing_info.show_billing)
- self.assertTrue(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
+ sponsorship_pending = has_pending_sponsorship_request(user)
+ self.assertTrue(sponsorship_pending)
# Always false without CORPORATE_ENABLED
with self.settings(CORPORATE_ENABLED=False):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- # show_remote_billing is independent of CORPORATE_ENABLED
- self.assertTrue(billing_info.show_remote_billing)
+ sponsorship_pending = has_pending_sponsorship_request(user)
+ self.assertFalse(sponsorship_pending)
# Always false without a UserProfile
with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(None)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # realm admin, with CustomerPlan and realm plan_type LIMITED -> don't show any links
- # Only billing admin and realm owner have access to billing.
- user.role = UserProfile.ROLE_REALM_ADMINISTRATOR
- user.save(update_fields=["role"])
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # Self-hosted servers show remote billing, but not for a user without
- # billing access permission.
- with self.settings(CORPORATE_ENABLED=False):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_remote_billing)
-
- # billing admin, with CustomerPlan and realm plan_type STANDARD -> show only billing link
- user.role = UserProfile.ROLE_MEMBER
- user.is_billing_admin = True
- do_change_realm_plan_type(user.realm, Realm.PLAN_TYPE_STANDARD, acting_user=None)
- user.save(update_fields=["role", "is_billing_admin"])
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertTrue(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # Self-hosted servers show remote billing for billing admins.
- with self.settings(CORPORATE_ENABLED=False):
- billing_info = get_billing_info(user)
- self.assertTrue(billing_info.show_remote_billing)
+ sponsorship_pending = has_pending_sponsorship_request(None)
+ self.assertFalse(sponsorship_pending)
- # billing admin, with CustomerPlan and realm plan_type PLUS -> show only billing link
- do_change_realm_plan_type(user.realm, Realm.PLAN_TYPE_PLUS, acting_user=None)
- user.save(update_fields=["role", "is_billing_admin"])
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertTrue(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # member, with CustomerPlan and realm plan_type STANDARD -> neither billing link or plans
- do_change_realm_plan_type(user.realm, Realm.PLAN_TYPE_STANDARD, acting_user=None)
- user.is_billing_admin = False
- user.save(update_fields=["is_billing_admin"])
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # guest, with CustomerPlan and realm plan_type SELF_HOSTED -> neither billing link or plans
- user.role = UserProfile.ROLE_GUEST
- user.save(update_fields=["role"])
- do_change_realm_plan_type(user.realm, Realm.PLAN_TYPE_SELF_HOSTED, acting_user=None)
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # billing admin, but no CustomerPlan and realm plan_type SELF_HOSTED -> neither billing link or plans
- user.role = UserProfile.ROLE_MEMBER
- user.is_billing_admin = True
- user.save(update_fields=["role", "is_billing_admin"])
- CustomerPlan.objects.all().delete()
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # billing admin, with sponsorship pending and realm plan_type SELF_HOSTED -> show only sponsorship pending link
- customer.sponsorship_pending = True
- customer.save(update_fields=["sponsorship_pending"])
- with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertTrue(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # billing admin, no customer object and realm plan_type SELF_HOSTED -> no links
- customer.delete()
+ # realm moderator, with CustomerPlan and realm plan_type LIMITED -> don't show any links
+ # Only realm admin and realm owner have access to billing.
with self.settings(CORPORATE_ENABLED=True):
- billing_info = get_billing_info(user)
- self.assertFalse(billing_info.show_billing)
- self.assertFalse(billing_info.show_plans)
- self.assertFalse(billing_info.sponsorship_pending)
- self.assertFalse(billing_info.show_remote_billing)
-
- # If the server doesn't have the push bouncer configured,
- # remote billing should be shown anyway, as the billing endpoint
- # is supposed show a useful error page.
- with self.settings(ZULIP_SERVICE_PUSH_NOTIFICATIONS=False, CORPORATE_ENABLED=False):
- billing_info = get_billing_info(user)
- self.assertTrue(billing_info.show_remote_billing)
+ sponsorship_pending = has_pending_sponsorship_request(shiva)
+ self.assertFalse(sponsorship_pending)
def test_promote_sponsoring_zulip_in_realm(self) -> None:
realm = get_realm("zulip")
diff --git a/zerver/views/realm.py b/zerver/views/realm.py
index 54de67a0f62..a27441366b8 100644
--- a/zerver/views/realm.py
+++ b/zerver/views/realm.py
@@ -153,6 +153,7 @@ def update_realm(
can_create_write_only_bots_group: Json[GroupSettingChangeRequest] | None = None,
can_invite_users_group: Json[GroupSettingChangeRequest] | None = None,
can_manage_all_groups: Json[GroupSettingChangeRequest] | None = None,
+ can_manage_billing_group: Json[GroupSettingChangeRequest] | None = None,
can_mention_many_users_group: Json[GroupSettingChangeRequest] | None = None,
can_move_messages_between_channels_group: Json[GroupSettingChangeRequest] | None = None,
can_move_messages_between_topics_group: Json[GroupSettingChangeRequest] | None = None,
@@ -241,6 +242,7 @@ def update_realm(
or can_create_groups is not None
or can_invite_users_group is not None
or can_manage_all_groups is not None
+ or can_manage_billing_group is not None
) and not user_profile.is_realm_owner:
raise OrganizationOwnerRequiredError