Skip to content

Commit 2d286dd

Browse files
committed
Adding the users commands and API calls
1 parent e03cc17 commit 2d286dd

2 files changed

Lines changed: 175 additions & 1 deletion

File tree

api.py

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ def _load_config(self, config_file: Optional[str]) -> configparser.ConfigParser:
3535
config.read(config_file)
3636
return config
3737

38+
# ALERTS
39+
# =======
40+
3841
def create_alert(self, title: str, description: Optional[str] = None,
3942
team_ids: Optional[List[str]] = None,
4043
destination_router_ids: Optional[List[str]] = None,
@@ -130,4 +133,58 @@ def list_alert_comments(self, alert_id: str, limit: int = 10,
130133
"has_more": data.get("has_more", False),
131134
"limit": limit,
132135
"offset": offset
133-
}
136+
}
137+
138+
# USERS
139+
# ======
140+
141+
def create_user(self, name: str, email: str, roles: Optional[Dict[str, bool]] = None, team_ids: Optional[List[str]] = None) -> Dict[str, Any]:
142+
"""Create a new account user in PagerTree."""
143+
payload = {
144+
"user_attributes": {
145+
"name": name,
146+
"emails_attributes": [{"email": email}]
147+
},
148+
"roles": roles or {},
149+
"team_ids": team_ids or []
150+
}
151+
response = self.session.post(f"{self.base_url}/account_users", json=payload)
152+
response.raise_for_status()
153+
return response.json()
154+
155+
def list_users(self, limit: int = 10, offset: int = 0) -> Dict[str, Any]:
156+
"""List all users in PagerTree."""
157+
params = {k: v for k, v in {"limit": limit, "offset": offset}.items() if v is not None}
158+
response = self.session.get(f"{self.base_url}/account_users", params=params)
159+
response.raise_for_status()
160+
data = response.json()
161+
return {
162+
"data": data.get("data", []),
163+
"total": data.get("total_count", 0),
164+
"has_more": data.get("has_more", False),
165+
"limit": limit,
166+
"offset": offset
167+
}
168+
169+
def show_user(self, user_id: str) -> Dict[str, Any]:
170+
"""Fetch a single user by ID from PagerTree."""
171+
response = self.session.get(f"{self.base_url}/account_users/{user_id}")
172+
response.raise_for_status()
173+
return response.json()
174+
175+
def update_user(self, user_id: str, name: Optional[str] = None) -> Dict[str, Any]:
176+
"""Update an account user in PagerTree."""
177+
payload = {}
178+
if name:
179+
payload["user_attributes"] = {}
180+
payload["user_attributes"]["name"] = name
181+
payload = {k: v for k, v in payload.items() if v}
182+
response = self.session.put(f"{self.base_url}/account_users/{user_id}", json=payload)
183+
response.raise_for_status()
184+
return response.json()
185+
186+
def delete_user(self, user_id: str) -> Dict[str, Any]:
187+
"""Delete a user in PagerTree."""
188+
response = self.session.delete(f"{self.base_url}/account_users/{user_id}")
189+
response.raise_for_status()
190+
return response.json() if response.content else {"message": "User deleted successfully"}

commands/users.py

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import click
2+
from utils import display_paginated_results, handle_api_error, format_item_details
3+
4+
@click.group()
5+
def users():
6+
"""Commands for managing PagerTree users."""
7+
pass
8+
9+
@users.command(name="create")
10+
@click.option("--name", required=True, help="Full name of the user")
11+
@click.option("--email", required=True, help="Email address of the user")
12+
@click.option("--role", type=click.Choice(["admin", "billing", "broadcaster", "communicator"]), multiple=True, help="Roles for the user (can specify multiple)")
13+
@click.option("--team-id", "team_ids", multiple=True, help="IDs of teams the user should be assigned to")
14+
@click.pass_context
15+
def create_user_cmd(ctx, name, email, role, team_ids):
16+
"""Create a new account user in PagerTree."""
17+
try:
18+
client = ctx.obj # Get PagerTreeClient from context
19+
roles = {r: True for r in role} if role else {}
20+
result = client.create_user(name=name, email=email, roles=roles, team_ids=list(team_ids))
21+
click.echo(f"User created successfully: {result.get('tiny_id')}")
22+
except Exception as e:
23+
handle_api_error(e, action="creating user")
24+
25+
@users.command(name="list")
26+
@click.option("--limit", default=10, type=click.IntRange(1, 100), help="Number of users per page")
27+
@click.option("--offset", default=0, type=click.IntRange(0), help="Starting point for pagination")
28+
@click.pass_context
29+
def list_users_cmd(ctx, limit, offset):
30+
"""List users in PagerTree with pagination."""
31+
try:
32+
client = ctx.obj # Get PagerTreeClient from context
33+
result = client.list_users(limit=limit, offset=offset)
34+
users_list = result["data"]
35+
total = result["total"]
36+
# Prepare table data
37+
headers = ["ID", "Name", "Primary Email", "Primary Phone", "Roles"]
38+
table_data = [
39+
[
40+
user.get("tiny_id"),
41+
user.get("user", {}).get("name", "N/A"),
42+
next((email.get("email") for email in user.get("user", {}).get("emails", []) if email.get("primary")), "N/A"),
43+
next((phone.get("phone") for phone in user.get("user", {}).get("phones", []) if phone.get("primary")), "N/A"),
44+
", ".join(
45+
role for role, enabled in user.get("roles", {}).items() if enabled
46+
) or "None"
47+
]
48+
for user in users_list
49+
]
50+
display_paginated_results(users_list, total, limit, offset, "user", headers, table_data)
51+
except Exception as e:
52+
handle_api_error(e, action="listing users")
53+
54+
@users.command(name="show")
55+
@click.argument("user_id", required=True)
56+
@click.pass_context
57+
def show_user_cmd(ctx, user_id):
58+
"""Show details of a specific user in PagerTree."""
59+
try:
60+
client = ctx.obj # Get PagerTreeClient from context
61+
user = client.show_user(user_id)
62+
fields = {
63+
"user.id": "User ID",
64+
"user.name": "Name",
65+
"user.emails.primary": "Primary Email",
66+
"user.phones.primary": "Primary Phone",
67+
"roles": "Roles",
68+
"created_at": "Created At"
69+
}
70+
formatted_user = {
71+
"user.id": user.get("tiny_id"),
72+
"user.name": user.get("user", {}).get("name", "N/A"),
73+
"user.emails.primary": next(
74+
(email.get("email") for email in user.get("user", {}).get("emails", []) if email.get("primary")),
75+
"N/A"
76+
),
77+
"user.phones.primary": next(
78+
(phone.get("phone") for phone in user.get("user", {}).get("phones", []) if phone.get("primary")),
79+
"N/A"
80+
),
81+
"roles": ", ".join(
82+
role for role, enabled in user.get("roles", {}).items() if enabled
83+
) or "None",
84+
"created_at": user.get("created_at", "N/A")
85+
}
86+
format_item_details(formatted_user, fields)
87+
except Exception as e:
88+
handle_api_error(e, action="showing user")
89+
90+
@users.command(name="update")
91+
@click.argument("user_id", required=True)
92+
@click.option("--name", help="New full name of the user")
93+
@click.pass_context
94+
def update_user_cmd(ctx, user_id, name):
95+
"""Update an account user in PagerTree."""
96+
try:
97+
client = ctx.obj # Get PagerTreeClient from context
98+
result = client.update_user(user_id=user_id, name=name)
99+
click.echo(f"User updated successfully: {result.get('tiny_id')}")
100+
except Exception as e:
101+
handle_api_error(e, action="updating user")
102+
103+
@users.command(name="delete")
104+
@click.argument("user_id", required=True)
105+
@click.option("--force", is_flag=True, help="Delete the user without confirmation")
106+
@click.pass_context
107+
def delete_user_cmd(ctx, user_id, force):
108+
"""Delete a user in PagerTree."""
109+
if not force and not click.confirm(f"Are you sure you want to delete user {user_id}?"):
110+
click.echo("Deletion cancelled.")
111+
return
112+
try:
113+
client = ctx.obj # Get PagerTreeClient from context
114+
result = client.delete_user(user_id)
115+
click.echo(f"User deleted successfully: {user_id}")
116+
except Exception as e:
117+
handle_api_error(e, action="deleting user")

0 commit comments

Comments
 (0)