intelligence-cloud 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,358 @@
1
+ """Low-level resources: one method per API operation, plus read-merge-write helpers.
2
+
3
+ Every method returns the response with fields the published reference does not list removed.
4
+ List methods return a :class:`Page`; ``iter_*`` methods follow cursors for you.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ import uuid
10
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence
11
+
12
+ import httpx
13
+
14
+ from . import _generated as g
15
+ from ._base import unwrap
16
+ from .errors import (
17
+ ConnectorError,
18
+ ConnectorTimeoutError,
19
+ InvalidRequestError,
20
+ ValidationError,
21
+ )
22
+
23
+ ResellersAPI = g.ResellersAPI
24
+ SsoAPI = g.SsoAPI
25
+ ProductsAPI = g.ProductsAPI
26
+ AfterCallSettingsAPI = g.AfterCallSettingsAPI
27
+ AccountAPI = g.AccountAPI
28
+ CallsAPI = g.CallsAPI
29
+ AlertsAPI = g.AlertsAPI
30
+ TasksAPI = g.TasksAPI
31
+ InsightsAPI = g.InsightsAPI
32
+ WebhooksAPI = g.WebhooksAPI
33
+
34
+ PRODUCT_KEYS = ("after-call-copilot", "first-alert-copilot", "insights-hub")
35
+
36
+
37
+ def _merge(existing: Iterable[str], add: Iterable[str] = (), remove: Iterable[str] = ()) -> List[str]:
38
+ out: List[str] = []
39
+ drop = set(remove)
40
+ for v in list(existing) + list(add):
41
+ if v not in out and v not in drop:
42
+ out.append(v)
43
+ return out
44
+
45
+
46
+ def _clean_numbers(numbers: Iterable[str]) -> List[str]:
47
+ out: List[str] = []
48
+ for n in numbers:
49
+ v = str(n).strip()
50
+ if not v:
51
+ raise InvalidRequestError("numbers: empty entry")
52
+ if v not in out:
53
+ out.append(v)
54
+ return out
55
+
56
+
57
+ def merge_mappings(mappings: Sequence[Mapping[str, Any]], connector_id: str, add: Iterable[str] = (),
58
+ remove: Iterable[str] = ()) -> List[Dict[str, Any]]:
59
+ """Number mappings in request form, with numbers added to / removed from one connector."""
60
+ out: List[Dict[str, Any]] = []
61
+ found = False
62
+ for m in mappings or []:
63
+ nums = list(m.get("monitored_numbers") or [])
64
+ if m.get("connector_id") == connector_id:
65
+ found = True
66
+ nums = _merge(nums, _clean_numbers(add), remove)
67
+ if nums:
68
+ out.append({"connector_id": m["connector_id"], "monitored_numbers": nums})
69
+ if not found:
70
+ nums = _merge([], _clean_numbers(add), remove)
71
+ if nums:
72
+ out.append({"connector_id": connector_id, "monitored_numbers": nums})
73
+ return out
74
+
75
+
76
+ def numbers_for(mappings: Sequence[Mapping[str, Any]], connector_id: Optional[str] = None) -> List[str]:
77
+ out: List[str] = []
78
+ for m in mappings or []:
79
+ if connector_id is None or m.get("connector_id") == connector_id:
80
+ for n in m.get("monitored_numbers") or []:
81
+ if n not in out:
82
+ out.append(n)
83
+ return out
84
+
85
+
86
+ class CompaniesAPI(g.CompaniesAPI):
87
+ def add_products(self, company_id: str, product_keys: Iterable[str]) -> Any:
88
+ """Switch products on for the company (read, merge, PATCH)."""
89
+ current = unwrap(self.get_company(company_id)).get("enabled_products") or []
90
+ return self.update_company(company_id, {"enabled_products": _merge(current, product_keys)})
91
+
92
+ def remove_products(self, company_id: str, product_keys: Iterable[str]) -> Any:
93
+ """Switch products off for the company. At least one product must stay on."""
94
+ current = unwrap(self.get_company(company_id)).get("enabled_products") or []
95
+ keep = _merge(current, remove=product_keys)
96
+ if not keep:
97
+ raise InvalidRequestError("A company keeps at least one product; the API ignores an empty list")
98
+ return self.update_company(company_id, {"enabled_products": keep})
99
+
100
+ def find_company(self, reseller_id: str, company_name: str) -> Optional[Dict[str, Any]]:
101
+ """The first company with exactly this name, or None. Names are not unique: to pick a customer,
102
+ use its id, or ``find_companies`` and compare ``primary_admin_contact_email``."""
103
+ found = self.find_companies(reseller_id, company_name)
104
+ return found[0] if found else None
105
+
106
+ def find_companies(self, reseller_id: str, company_name: str) -> List[Dict[str, Any]]:
107
+ """Every company with exactly this name (search is a name prefix match)."""
108
+ return [c for c in self.iter_companies(reseller_id, search=company_name)
109
+ if c.get("company_name") == company_name]
110
+
111
+
112
+ class LocationsAPI(g.LocationsAPI):
113
+ def add_products(self, company_id: str, location_id: str, product_keys: Iterable[str]) -> Any:
114
+ """Switch products on at the location. They must be on for the company first."""
115
+ current = unwrap(self.get_location(company_id, location_id)).get("enabled_products") or []
116
+ return self.update_location(company_id, location_id, {"enabled_products": _merge(current, product_keys)})
117
+
118
+ def remove_products(self, company_id: str, location_id: str, product_keys: Iterable[str]) -> Any:
119
+ current = unwrap(self.get_location(company_id, location_id)).get("enabled_products") or []
120
+ return self.update_location(company_id, location_id,
121
+ {"enabled_products": _merge(current, remove=product_keys)})
122
+
123
+ def find_location(self, company_id: str, location_name: str) -> Optional[Dict[str, Any]]:
124
+ for loc in self.iter_company_locations(company_id, search=location_name):
125
+ if loc.get("location_name") == location_name:
126
+ return loc
127
+ return None
128
+
129
+
130
+ class GroupsAPI(g.GroupsAPI):
131
+ def add_members(self, location_id: str, group_id: str, user_ids: Iterable[str]) -> Any:
132
+ """Add users to a group (read, merge, PATCH ``member_ids``)."""
133
+ members = unwrap(self.get_user_group(location_id, group_id)).get("members") or []
134
+ current = [m["id"] for m in members]
135
+ return self.update_user_group(location_id, group_id, {"member_ids": _merge(current, user_ids)})
136
+
137
+ def remove_members(self, location_id: str, group_id: str, user_ids: Iterable[str]) -> Any:
138
+ members = unwrap(self.get_user_group(location_id, group_id)).get("members") or []
139
+ current = [m["id"] for m in members]
140
+ return self.update_user_group(location_id, group_id,
141
+ {"member_ids": _merge(current, remove=user_ids)})
142
+
143
+ def user_group_ids(self, location_id: str, user_id: str) -> List[str]:
144
+ rows = unwrap(self.get_user_group_membership(location_id, user_id)) or []
145
+ return [r["id"] for r in rows if r.get("is_member")]
146
+
147
+ def add_user_to_groups(self, location_id: str, user_id: str, group_ids: Iterable[str]) -> Any:
148
+ """Add one user to groups (read, merge, PUT the user's membership)."""
149
+ current = self.user_group_ids(location_id, user_id)
150
+ return self.set_user_group_membership(location_id, user_id, {"group_ids": _merge(current, group_ids)})
151
+
152
+ def remove_user_from_groups(self, location_id: str, user_id: str,
153
+ group_ids: Optional[Iterable[str]] = None) -> Any:
154
+ """Remove one user from the given groups, or from every group at the location."""
155
+ current = self.user_group_ids(location_id, user_id)
156
+ keep = [] if group_ids is None else _merge(current, remove=group_ids)
157
+ return self.set_user_group_membership(location_id, user_id, {"group_ids": keep})
158
+
159
+ def find_group(self, location_id: str, group_name: str) -> Optional[Dict[str, Any]]:
160
+ for grp in self.iter_user_groups(location_id, search=group_name):
161
+ if grp.get("group_name") == group_name:
162
+ return grp
163
+ return None
164
+
165
+
166
+ class ConnectorsAPI(g.ConnectorsAPI):
167
+ """Create, reactivate and deactivate return at once with 202; these methods wait for the result,
168
+ checking the connector every ``check_interval`` seconds (10) for up to ``timeout`` seconds (600)."""
169
+
170
+ check_interval = 10.0
171
+
172
+ def wait_for_status(self, location_id: str, connector_id: str, final: Sequence[str],
173
+ timeout: float = 600.0, raise_on_error: bool = True) -> Dict[str, Any]:
174
+ start = time.monotonic()
175
+ while True:
176
+ conn = unwrap(self.get_connector(location_id, connector_id))
177
+ status = conn.get("status")
178
+ if status == "error" and raise_on_error:
179
+ raise ConnectorError(conn)
180
+ if status in final:
181
+ return conn
182
+ waited = time.monotonic() - start
183
+ if waited >= timeout:
184
+ raise ConnectorTimeoutError(conn, waited)
185
+ self._c._sleep(self.check_interval)
186
+
187
+ def create_connector(self, location_id: str, body: Mapping[str, Any], *, wait: bool = True,
188
+ timeout: float = 600.0) -> Any:
189
+ """Create a connector and wait until it is ``active``. Raises ConnectorError on ``error``."""
190
+ resp = super().create_connector(location_id, body)
191
+ if not wait:
192
+ return resp
193
+ conn = unwrap(resp)
194
+ final = self.wait_for_status(location_id, conn["id"], ("active", "error"), timeout)
195
+ return {"data": final}
196
+
197
+ def reactivate_connector(self, location_id: str, connector_id: str, *, wait: bool = True,
198
+ timeout: float = 600.0) -> Any:
199
+ resp = super().reactivate_connector(location_id, connector_id)
200
+ if not wait:
201
+ return resp
202
+ return {"data": self.wait_for_status(location_id, connector_id, ("active", "error"), timeout)}
203
+
204
+ def deactivate_connector(self, location_id: str, connector_id: str, *, wait: bool = True,
205
+ timeout: float = 600.0) -> Any:
206
+ resp = super().deactivate_connector(location_id, connector_id)
207
+ if not wait:
208
+ return resp
209
+ return {"data": self.wait_for_status(location_id, connector_id, ("inactive",), timeout,
210
+ raise_on_error=False)}
211
+
212
+ def find_connector(self, location_id: str, name: str) -> Optional[Dict[str, Any]]:
213
+ for c in self.iter_location_connectors(location_id, search=name):
214
+ if c.get("name") == name:
215
+ return c
216
+ return None
217
+
218
+
219
+ class FirstAlertAPI(g.FirstAlertAPI):
220
+ def _config(self, location_id: str) -> Dict[str, Any]:
221
+ return unwrap(self.get_first_alert_config(location_id)) or {}
222
+
223
+ def _save(self, location_id: str, webhook_url: Optional[str], mappings: List[Dict[str, Any]]) -> Any:
224
+ return self.save_first_alert_config(location_id, {"webhook_url": webhook_url, "connector_mappings": mappings})
225
+
226
+ def add_monitored_numbers(self, location_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
227
+ """Add numbers to First Alert at the location. Keeps the webhook URL and other numbers."""
228
+ cfg = self._config(location_id)
229
+ mappings = merge_mappings(cfg.get("connector_mappings") or [], connector_id, add=numbers)
230
+ return self._save(location_id, cfg.get("webhook_url"), mappings)
231
+
232
+ def remove_monitored_numbers(self, location_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
233
+ cfg = self._config(location_id)
234
+ mappings = merge_mappings(cfg.get("connector_mappings") or [], connector_id, remove=numbers)
235
+ return self._save(location_id, cfg.get("webhook_url"), mappings)
236
+
237
+ def set_monitored_numbers(self, location_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
238
+ """Replace the numbers for one connector. Keeps the webhook URL and other connectors' numbers."""
239
+ cfg = self._config(location_id)
240
+ others = [m for m in cfg.get("connector_mappings") or [] if m.get("connector_id") != connector_id]
241
+ mappings = merge_mappings(others, connector_id, add=numbers)
242
+ return self._save(location_id, cfg.get("webhook_url"), mappings)
243
+
244
+ def add_rule_groups(self, location_id: str, rule_id: str, group_ids: Iterable[str]) -> Any:
245
+ rule = unwrap(self.get_alert_rule(location_id, rule_id))
246
+ current = [grp["id"] for grp in rule.get("groups") or []]
247
+ return self.update_alert_rule(location_id, rule_id, {"group_ids": _merge(current, group_ids)})
248
+
249
+ def remove_rule_groups(self, location_id: str, rule_id: str, group_ids: Iterable[str]) -> Any:
250
+ rule = unwrap(self.get_alert_rule(location_id, rule_id))
251
+ current = [grp["id"] for grp in rule.get("groups") or []]
252
+ return self.update_alert_rule(location_id, rule_id, {"group_ids": _merge(current, remove=group_ids)})
253
+
254
+ def find_rule(self, location_id: str, name: str) -> Optional[Dict[str, Any]]:
255
+ for r in self.iter_alert_rules(location_id):
256
+ if r.get("name") == name:
257
+ return r
258
+ return None
259
+
260
+
261
+ class InsightsHubAPI(g.InsightsHubAPI):
262
+ def _setup(self, location_id: str) -> Dict[str, Any]:
263
+ return unwrap(self.get_insights_hub_setup(location_id)) or {}
264
+
265
+ def add_numbers(self, location_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
266
+ """Add numbers to the location's Insights Hub (read, merge, PATCH ``connector_mappings``)."""
267
+ setup = self._setup(location_id)
268
+ mappings = merge_mappings(setup.get("connector_mappings") or [], connector_id, add=numbers)
269
+ return self.update_insights_hub_setup(location_id, {"connector_mappings": mappings})
270
+
271
+ def remove_numbers(self, location_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
272
+ setup = self._setup(location_id)
273
+ mappings = merge_mappings(setup.get("connector_mappings") or [], connector_id, remove=numbers)
274
+ return self.update_insights_hub_setup(location_id, {"connector_mappings": mappings})
275
+
276
+ def set_numbers(self, location_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
277
+ setup = self._setup(location_id)
278
+ others = [m for m in setup.get("connector_mappings") or [] if m.get("connector_id") != connector_id]
279
+ return self.update_insights_hub_setup(
280
+ location_id, {"connector_mappings": merge_mappings(others, connector_id, add=numbers)})
281
+
282
+ def add_groups(self, location_id: str, group_ids: Iterable[str]) -> Any:
283
+ """Give groups Insights Hub access (read, merge, PATCH ``group_access``)."""
284
+ current = self._setup(location_id).get("group_access") or []
285
+ return self.update_insights_hub_setup(location_id, {"group_access": _merge(current, group_ids)})
286
+
287
+ def remove_groups(self, location_id: str, group_ids: Iterable[str]) -> Any:
288
+ current = self._setup(location_id).get("group_access") or []
289
+ return self.update_insights_hub_setup(location_id, {"group_access": _merge(current, remove=group_ids)})
290
+
291
+
292
+ class UsersAPI(g.UsersAPI):
293
+ def create_company_user(self, company_id: str, body: Mapping[str, Any], *,
294
+ idempotency_key: Optional[str] = None) -> Any:
295
+ """Create a user. Sends an ``Idempotency-Key`` (reused on retries).
296
+
297
+ A 422 can leave the user behind; the SDK then finds the user by email and applies
298
+ ``location_ids`` with PATCH. The response never includes the one-time sign-in link.
299
+ """
300
+ key = idempotency_key or str(uuid.uuid4())
301
+ email = body.get("email") if isinstance(body, Mapping) else None
302
+ try:
303
+ return self._c._call("createCompanyUser", path={"companyId": company_id}, query={}, body=body,
304
+ headers={"Idempotency-Key": key})
305
+ except ValidationError as exc:
306
+ if exc.status != 422 or not email:
307
+ raise
308
+ user = self.find_user_by_email(company_id, email)
309
+ if user is None:
310
+ raise
311
+ if body.get("location_ids"):
312
+ self.update_company_user(company_id, user["id"], {"location_ids": list(body["location_ids"])})
313
+ return self.get_company_user(company_id, user["id"])
314
+ except httpx.DecodingError:
315
+ # A replayed create can come back with a body that cannot be decoded: read the user instead.
316
+ user = self.find_user_by_email(company_id, email) if email else None
317
+ if user is None:
318
+ raise
319
+ return self.get_company_user(company_id, user["id"])
320
+
321
+ def find_user_by_email(self, company_id: str, email: str) -> Optional[Dict[str, Any]]:
322
+ want = email.strip().lower()
323
+ for u in self.iter_company_users(company_id, search=email.strip()):
324
+ if (u.get("email") or "").lower() == want:
325
+ return u
326
+ return None
327
+
328
+ def add_locations(self, company_id: str, user_id: str, location_ids: Iterable[str]) -> Any:
329
+ user = unwrap(self.get_company_user(company_id, user_id))
330
+ current = [loc["location_id"] for loc in user.get("locations") or []]
331
+ return self.update_company_user(company_id, user_id, {"location_ids": _merge(current, location_ids)})
332
+
333
+ def remove_locations(self, company_id: str, user_id: str, location_ids: Iterable[str]) -> Any:
334
+ user = unwrap(self.get_company_user(company_id, user_id))
335
+ current = [loc["location_id"] for loc in user.get("locations") or []]
336
+ return self.update_company_user(company_id, user_id,
337
+ {"location_ids": _merge(current, remove=location_ids)})
338
+
339
+ def user_numbers(self, company_id: str, user_id: str, connector_id: Optional[str] = None) -> List[str]:
340
+ return numbers_for(unwrap(self.get_user_number_mappings(company_id, user_id)) or [], connector_id)
341
+
342
+ def add_numbers(self, company_id: str, user_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
343
+ """Map numbers to the user (read, merge, PUT). The connector must be ``active``."""
344
+ current = unwrap(self.get_user_number_mappings(company_id, user_id)) or []
345
+ return self.set_user_number_mappings(
346
+ company_id, user_id, {"mappings": merge_mappings(current, connector_id, add=numbers)})
347
+
348
+ def remove_numbers(self, company_id: str, user_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
349
+ current = unwrap(self.get_user_number_mappings(company_id, user_id)) or []
350
+ return self.set_user_number_mappings(
351
+ company_id, user_id, {"mappings": merge_mappings(current, connector_id, remove=numbers)})
352
+
353
+ def set_numbers(self, company_id: str, user_id: str, connector_id: str, numbers: Iterable[str]) -> Any:
354
+ """Replace the user's numbers on one connector; other connectors are kept."""
355
+ current = unwrap(self.get_user_number_mappings(company_id, user_id)) or []
356
+ others = [m for m in current if m.get("connector_id") != connector_id]
357
+ return self.set_user_number_mappings(
358
+ company_id, user_id, {"mappings": merge_mappings(others, connector_id, add=numbers)})