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,791 @@
1
+ """Base Intelligence Seat lifecycle: provision a customer, add and remove users, keep numbers in sync.
2
+
3
+ A Seat customer is one company with one location, two alert rules ("Upset Customer", "Customer
4
+ Threat") routed to a "Manager Alerts" group, and an "Insights Hub Access" group.
5
+
6
+ - **End users** (frontline) have After Call on their own line.
7
+ - **Managers** have After Call on all lines, First Alert and Insights Hub. A manager's own phone
8
+ line is never captured on the Seat: their mapping is exactly the end users' lines.
9
+ - **Integration users** (``add_integration_user``) read data for another system. They hold every
10
+ line like a manager but are tagged ``department: "integration"``, are never counted as seats or
11
+ managers, and removing one never takes a line off anyone else.
12
+
13
+ Every workflow is safe to run again. Store the returned ``company_id`` and pass it in
14
+ ``SeatCustomerSpec.company_id`` on re-runs: a company is never adopted by its name alone.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
20
+
21
+ from ._base import Namespace, unwrap
22
+ from ._spec import is_uuid
23
+ from .errors import (
24
+ ApiError,
25
+ ConflictError,
26
+ ConnectorError,
27
+ ConnectorTimeoutError,
28
+ ExtensionMappingError,
29
+ InvalidRequestError,
30
+ ValidationError,
31
+ )
32
+ from .resources import PRODUCT_KEYS, numbers_for
33
+
34
+ AFTER_CALL = "after-call-copilot"
35
+ FIRST_ALERT = "first-alert-copilot"
36
+ INSIGHTS_HUB = "insights-hub"
37
+ INTEGRATION_DEPARTMENT = "integration"
38
+ COMPANY_NAME_CONFLICT = "company_name_conflict"
39
+ MANAGER_ALERTS_GROUP = "Manager Alerts"
40
+ INSIGHTS_HUB_GROUP = "Insights Hub Access"
41
+ UPSET_CUSTOMER_RULE = "Upset Customer"
42
+ CUSTOMER_THREAT_RULE = "Customer Threat"
43
+ UPSET_CUSTOMER_THRESHOLD = -40
44
+ THREAT_PHRASES_MISSING = "Customer Threat phrases are provided by your Tresic contact."
45
+ CUSTOMER_THREAT_THRESHOLD = -20
46
+
47
+
48
+ def upset_customer_rule(group_ids: List[str], enabled: bool = False) -> Dict[str, Any]:
49
+ return {
50
+ "name": UPSET_CUSTOMER_RULE, "priority": "high", "match_logic": "any", "enabled": enabled,
51
+ "triggers": [{"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": UPSET_CUSTOMER_THRESHOLD}}],
52
+ "group_ids": group_ids,
53
+ }
54
+
55
+
56
+ def customer_threat_rule(group_ids: List[str], phrases: List[str], enabled: bool = False) -> Dict[str, Any]:
57
+ """The Customer Threat alert: sentiment below -20 and any of the phrases. Phrases come from your
58
+ Tresic contact."""
59
+ if not phrases:
60
+ raise InvalidRequestError(THREAT_PHRASES_MISSING)
61
+ return {
62
+ "name": CUSTOMER_THREAT_RULE, "priority": "critical", "match_logic": "all", "enabled": enabled,
63
+ "triggers": [
64
+ {"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": CUSTOMER_THREAT_THRESHOLD}},
65
+ {"trigger_type": "keyword_match", "config": {"keywords": phrases, "match_logic": "any"}},
66
+ ],
67
+ "group_ids": group_ids,
68
+ }
69
+
70
+
71
+ @dataclass
72
+ class LocationSpec:
73
+ name: str
74
+ street: str
75
+ city: str
76
+ state: str
77
+ country: str
78
+ zipcode: str
79
+ vertical: str # vertical id, or its key from list_verticals (e.g. the key for service providers)
80
+
81
+
82
+ @dataclass
83
+ class ConnectorSpec:
84
+ api_url: str # full API root ending in /ns-api/v2
85
+ domain: str
86
+ api_key: str = field(repr=False) # read/write key
87
+ name: Optional[str] = None # default "<location name> - NetSapiens"
88
+ timeout: float = 600.0 # seconds to wait for the connector to settle
89
+
90
+
91
+ @dataclass
92
+ class SeatCustomerSpec:
93
+ company_name: str
94
+ admin_name: str # primary contact; invited as customer admin by email
95
+ admin_email: str
96
+ admin_phone: str
97
+ location: LocationSpec
98
+ reseller_id: Optional[str] = None # default: the signed-in reseller
99
+ company_code: Optional[str] = None
100
+ mfa_off: bool = False # True for a company whose users include an integration user
101
+ threat_phrases: Optional[List[str]] = None # required to create the Customer Threat alert (from your Tresic contact)
102
+ connector: Optional[ConnectorSpec] = None
103
+ sso_domain: Optional[str] = None
104
+ reactivate: bool = False # reactivate a company or location found inactive
105
+ # The company to use, from an earlier run. Without it, a company with the same name is reused only
106
+ # when its primary contact email is admin_email; otherwise ConflictError is raised.
107
+ company_id: Optional[str] = None
108
+
109
+
110
+ @dataclass
111
+ class SeatCustomer:
112
+ company_id: str
113
+ location_id: str
114
+ manager_alerts_group_id: Optional[str] = None
115
+ insights_hub_group_id: Optional[str] = None
116
+ upset_customer_rule_id: Optional[str] = None
117
+ customer_threat_rule_id: Optional[str] = None
118
+ connector_id: Optional[str] = None
119
+ connector_status: Optional[str] = None
120
+ connector_state_reason: Optional[str] = None
121
+ sso_domain_id: Optional[str] = None
122
+ sso_txt_record: Optional[Dict[str, str]] = None # {"name": ..., "value": ...} for the customer's DNS
123
+ created: List[str] = field(default_factory=list)
124
+ existing: List[str] = field(default_factory=list)
125
+ # Users every workflow ignores (not seats, managers or integration users; their lines don't count).
126
+ exclude_user_ids: List[str] = field(default_factory=list)
127
+ exclude_emails: List[str] = field(default_factory=list)
128
+
129
+
130
+ @dataclass
131
+ class UserSpec:
132
+ email: str
133
+ first_name: str
134
+ last_name: str
135
+ phone_number: Optional[str] = None
136
+ # Email the invitation once the user is fully set up (lines mapped, groups and products on).
137
+ # False: create the user without an invitation; send one later with users.resend_invitation.
138
+ send_invitation: bool = True
139
+ auth_method: str = "password"
140
+
141
+
142
+ @dataclass
143
+ class SeatUser:
144
+ user_id: str
145
+ email: str
146
+ kind: str # "frontline", "manager" or "integration"
147
+ numbers: List[str] = field(default_factory=list)
148
+ created: bool = False
149
+ invited: bool = False # an invitation was emailed by this call
150
+ alerts_activated: List[str] = field(default_factory=list) # rule ids switched on by this call
151
+
152
+
153
+ def _products(row: Dict[str, Any]) -> set:
154
+ return set(row.get("enabled_products") or [])
155
+
156
+
157
+ def is_integration(row: Dict[str, Any]) -> bool:
158
+ """An integration (data-reading) user: tagged ``department: "integration"``."""
159
+ return (row.get("department") or "").strip().lower() == INTEGRATION_DEPARTMENT
160
+
161
+
162
+ def _active_frontline(row: Dict[str, Any]) -> bool:
163
+ return row.get("status") != "deactivated" and row.get("role") == "frontline_user"
164
+
165
+
166
+ def is_manager(row: Dict[str, Any]) -> bool:
167
+ """A manager: all three products (After Call, First Alert, Insights Hub), not an integration user."""
168
+ return _active_frontline(row) and not is_integration(row) and set(PRODUCT_KEYS) <= _products(row)
169
+
170
+
171
+ def is_frontline(row: Dict[str, Any]) -> bool:
172
+ """An end user (a seat): After Call only, not an integration user."""
173
+ return _active_frontline(row) and not is_integration(row) and _products(row) == {AFTER_CALL}
174
+
175
+
176
+ def _uniq(values: Iterable[str]) -> List[str]:
177
+ out: List[str] = []
178
+ for v in values:
179
+ if v not in out:
180
+ out.append(v)
181
+ return out
182
+
183
+
184
+ class Workflows(Namespace):
185
+ """Base Intelligence Seat lifecycle (admin credentials)."""
186
+
187
+ # ------------------------------------------------------------------ provisioning
188
+
189
+ def provision_seat_customer(self, spec: SeatCustomerSpec) -> SeatCustomer:
190
+ c = self._c
191
+ phrases = [p.strip() for p in (spec.threat_phrases or []) if p and p.strip()]
192
+ created: List[str] = []
193
+ existing: List[str] = []
194
+ reseller_id = spec.reseller_id or unwrap(c.account.get_me()).get("reseller_id")
195
+ if not reseller_id:
196
+ raise InvalidRequestError("reseller_id is required (this login has none)")
197
+
198
+ # 1. company: by id, or by name AND primary contact email; never by name alone
199
+ company = self._find_seat_company(reseller_id, spec)
200
+ if company is None and not phrases:
201
+ raise InvalidRequestError(THREAT_PHRASES_MISSING)
202
+ if company is None:
203
+ body: Dict[str, Any] = {
204
+ "company_name": spec.company_name,
205
+ "primary_admin_contact_name": spec.admin_name,
206
+ "primary_admin_contact_email": spec.admin_email,
207
+ "primary_admin_contact_phone": spec.admin_phone,
208
+ "enabled_products": list(PRODUCT_KEYS),
209
+ }
210
+ if spec.company_code:
211
+ body["company_code"] = spec.company_code
212
+ company = unwrap(c.companies.create_company(reseller_id, body))
213
+ created.append("company")
214
+ else:
215
+ existing.append("company")
216
+ if not company.get("is_active"):
217
+ if not spec.reactivate:
218
+ raise InvalidRequestError(f"Company {spec.company_name!r} exists but is inactive "
219
+ "(set reactivate=True to reactivate it)")
220
+ c.companies.reactivate_company(company["id"])
221
+ if not set(PRODUCT_KEYS) <= set(company.get("enabled_products") or []):
222
+ c.companies.add_products(company["id"], PRODUCT_KEYS)
223
+ company_id = company["id"]
224
+
225
+ # 2. MFA off for an integration-user company, then verify
226
+ if spec.mfa_off:
227
+ current = unwrap(c.companies.get_company(company_id))
228
+ if current.get("mfa_enforced"):
229
+ c.companies.update_company(company_id, {"mfa_enforced": False})
230
+ if unwrap(c.companies.get_company(company_id)).get("mfa_enforced"):
231
+ text = "MFA is still on for the company after the update"
232
+ raise ApiError(200, None, text, public_message=text)
233
+
234
+ # 3. location
235
+ loc = c.locations.find_location(company_id, spec.location.name)
236
+ if loc is None:
237
+ loc = unwrap(c.locations.create_location(company_id, {
238
+ "location_name": spec.location.name, "street": spec.location.street, "city": spec.location.city,
239
+ "state": spec.location.state, "country": spec.location.country, "zipcode": spec.location.zipcode,
240
+ "vertical_id": self._vertical_id(spec.location.vertical),
241
+ "enabled_products": list(PRODUCT_KEYS),
242
+ }))
243
+ created.append("location")
244
+ else:
245
+ existing.append("location")
246
+ if not loc.get("is_active"):
247
+ if not spec.reactivate:
248
+ raise InvalidRequestError(f"Location {spec.location.name!r} exists but is inactive "
249
+ "(set reactivate=True to reactivate it)")
250
+ c.locations.reactivate_location(company_id, loc["id"])
251
+ if not set(PRODUCT_KEYS) <= set(loc.get("enabled_products") or []):
252
+ c.locations.add_products(company_id, loc["id"], PRODUCT_KEYS)
253
+ location_id = loc["id"]
254
+ result = SeatCustomer(company_id=company_id, location_id=location_id, created=created, existing=existing)
255
+
256
+ # 4. groups
257
+ result.manager_alerts_group_id = self._ensure_group(location_id, MANAGER_ALERTS_GROUP, result)
258
+ result.insights_hub_group_id = self._ensure_group(location_id, INSIGHTS_HUB_GROUP, result)
259
+
260
+ # 5. rules, created disabled and routed to Manager Alerts
261
+ groups = [result.manager_alerts_group_id]
262
+ result.upset_customer_rule_id = self._ensure_rule(location_id, upset_customer_rule(groups), result)
263
+ if phrases:
264
+ threat = customer_threat_rule(groups, phrases)
265
+ elif c.first_alert.find_rule(location_id, CUSTOMER_THREAT_RULE) is not None:
266
+ threat = {"name": CUSTOMER_THREAT_RULE, "group_ids": groups} # keep its configured phrases
267
+ else:
268
+ raise InvalidRequestError(THREAT_PHRASES_MISSING)
269
+ result.customer_threat_rule_id = self._ensure_rule(location_id, threat, result)
270
+
271
+ # 6. connector (optional)
272
+ if spec.connector is not None:
273
+ self._ensure_connector(location_id, spec, result)
274
+
275
+ # 7. Insights Hub: group access + every call at the location
276
+ setup = unwrap(c.insights_hub.get_insights_hub_setup(location_id)) or {}
277
+ access = setup.get("group_access") or []
278
+ if result.insights_hub_group_id not in access:
279
+ if not access and not setup.get("connector_mappings"):
280
+ c.insights_hub.save_insights_hub_setup(
281
+ location_id, {"connector_mappings": [], "group_access": [result.insights_hub_group_id]})
282
+ else:
283
+ c.insights_hub.add_groups(location_id, [result.insights_hub_group_id])
284
+ cfg = unwrap(c.insights_hub.get_insights_hub_config(location_id)) or {}
285
+ if not cfg.get("monitor_all_numbers"):
286
+ c.insights_hub.update_insights_hub_config(location_id, {"monitor_all_numbers": True})
287
+
288
+ # 8. SSO domain claim (optional): the customer publishes the TXT record, then verify
289
+ if spec.sso_domain:
290
+ dom = unwrap(c.sso.claim_company_domain(company_id, {"domain": spec.sso_domain})) or {}
291
+ result.sso_domain_id = dom.get("id")
292
+ ver = dom.get("verification") or {}
293
+ result.sso_txt_record = {"name": ver.get("name"), "value": ver.get("value")}
294
+
295
+ # The two rules stay off until a manager is in place: add_manager switches them on
296
+ # (activate_alerts=True), or call activate_seat_alerts yourself.
297
+ return result
298
+
299
+ def _find_seat_company(self, reseller_id: str, spec: SeatCustomerSpec) -> Optional[Dict[str, Any]]:
300
+ """The company to provision into: ``spec.company_id``, or the one company with this exact name
301
+ whose primary contact email is ``spec.admin_email``. Raises ConflictError when the name is taken
302
+ by any other company. Nothing has been written when it raises."""
303
+ c = self._c
304
+ if spec.company_id:
305
+ return unwrap(c.companies.get_company(spec.company_id))
306
+ same_name = c.companies.find_companies(reseller_id, spec.company_name)
307
+ if not same_name:
308
+ return None
309
+ want = (spec.admin_email or "").strip().lower()
310
+ matches = []
311
+ for row in same_name:
312
+ detail = unwrap(c.companies.get_company(row["id"])) or {}
313
+ if (detail.get("primary_admin_contact_email") or "").strip().lower() == want:
314
+ matches.append(detail)
315
+ if len(matches) == 1:
316
+ return matches[0]
317
+ text = (f"A company named {spec.company_name!r} already exists with a different primary contact. "
318
+ "Pass company_id to use an existing company, or choose a different company name.")
319
+ raise ConflictError(409, COMPANY_NAME_CONFLICT, text, public_message=text)
320
+
321
+ def activate_seat_alerts(self, customer: SeatCustomer) -> List[str]:
322
+ """Switch on the customer's two alert rules (Upset Customer, Customer Threat). Rules already on
323
+ are left as they are. Returns the ids of the rules this call switched on."""
324
+ fa = self._c.first_alert
325
+ switched: List[str] = []
326
+ for rule_id in (customer.upset_customer_rule_id, customer.customer_threat_rule_id):
327
+ if not rule_id:
328
+ continue
329
+ rule = unwrap(fa.get_alert_rule(customer.location_id, rule_id))
330
+ if not rule.get("enabled"):
331
+ fa.update_alert_rule(customer.location_id, rule_id, {"enabled": True})
332
+ switched.append(rule_id)
333
+ return switched
334
+
335
+ def _vertical_id(self, vertical: str) -> str:
336
+ if is_uuid(vertical):
337
+ return vertical
338
+ for v in unwrap(self._c.locations.list_verticals()) or []:
339
+ if vertical in (v.get("key"), v.get("name")):
340
+ return v["id"]
341
+ raise InvalidRequestError(f"Unknown vertical {vertical!r}: use an id or key from list_verticals()")
342
+
343
+ def _ensure_group(self, location_id: str, name: str, result: SeatCustomer) -> str:
344
+ grp = self._c.groups.find_group(location_id, name)
345
+ if grp is None:
346
+ grp = unwrap(self._c.groups.create_user_group(location_id, {"group_name": name}))
347
+ result.created.append(f"group:{name}")
348
+ else:
349
+ result.existing.append(f"group:{name}")
350
+ return grp["id"]
351
+
352
+ def _ensure_rule(self, location_id: str, body: Dict[str, Any], result: SeatCustomer) -> str:
353
+ fa = self._c.first_alert
354
+ found = fa.find_rule(location_id, body["name"])
355
+ if found is None:
356
+ rule = unwrap(fa.create_alert_rule(location_id, body))
357
+ result.created.append(f"rule:{body['name']}")
358
+ return rule["id"]
359
+ result.existing.append(f"rule:{body['name']}")
360
+ rule = unwrap(fa.get_alert_rule(location_id, found["id"]))
361
+ have = {g["id"] for g in rule.get("groups") or []}
362
+ if not set(body["group_ids"]) <= have:
363
+ fa.add_rule_groups(location_id, rule["id"], body["group_ids"])
364
+ if "triggers" in body:
365
+ current = [{"trigger_type": t.get("trigger_type"), "config": t.get("config")} for t in rule.get("triggers") or []]
366
+ if current != body["triggers"]:
367
+ fa.update_alert_rule(location_id, rule["id"], {"triggers": body["triggers"]}) # e.g. a new phrase list
368
+ return rule["id"]
369
+
370
+ def _find_seat_connector(self, location_id: str, domain: str, name: str) -> Optional[Dict[str, Any]]:
371
+ """The location's connector for this NetSapiens domain (best status first), else one with this
372
+ name."""
373
+ conns = self._c.connectors
374
+ rank = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4}
375
+ rows = sorted(conns.iter_location_connectors(location_id), key=lambda x: rank.get(x.get("status"), 5))
376
+ by_name = None
377
+ for row in rows:
378
+ detail = unwrap(conns.get_connector(location_id, row["id"])) or {}
379
+ cfg = detail.get("config") or {}
380
+ if (cfg.get("domain") or "").strip().lower() == domain.strip().lower():
381
+ return detail
382
+ if by_name is None and detail.get("name") == name:
383
+ by_name = detail
384
+ return by_name
385
+
386
+ def _ensure_connector(self, location_id: str, spec: SeatCustomerSpec, result: SeatCustomer) -> None:
387
+ cs = spec.connector
388
+ assert cs is not None
389
+ name = cs.name or f"{spec.location.name} - NetSapiens"
390
+ conns = self._c.connectors
391
+ found = self._find_seat_connector(location_id, cs.domain, name)
392
+ if found is not None:
393
+ cfg = found.get("config") or {}
394
+ unchanged = (cfg.get("api_url") == cs.api_url and cfg.get("domain") == cs.domain
395
+ and found.get("name") == name)
396
+ if found.get("status") in ("active", "connecting") and unchanged:
397
+ result.existing.append("connector")
398
+ result.connector_id = found["id"]
399
+ result.connector_status = found.get("status")
400
+ result.connector_state_reason = found.get("state_reason")
401
+ return
402
+ try:
403
+ if found is not None:
404
+ # In error, stopped or changed: apply the settings (and key) given now, then restart.
405
+ result.existing.append("connector")
406
+ result.existing.append("connector:updated")
407
+ conns.update_connector(location_id, found["id"], {
408
+ "name": name, "config": {"api_url": cs.api_url, "domain": cs.domain, "api_key": cs.api_key}})
409
+ if found.get("status") == "inactive":
410
+ conn = unwrap(conns.reactivate_connector(location_id, found["id"], timeout=cs.timeout))
411
+ else:
412
+ conn = conns.wait_for_status(location_id, found["id"], ("active", "error"), cs.timeout,
413
+ raise_on_error=False)
414
+ if conn.get("status") == "error":
415
+ conns.deactivate_connector(location_id, found["id"], timeout=cs.timeout)
416
+ conn = unwrap(conns.reactivate_connector(location_id, found["id"], timeout=cs.timeout))
417
+ else:
418
+ conn = unwrap(conns.create_connector(location_id, {
419
+ "name": name, "type": "netsapiens",
420
+ "config": {"api_url": cs.api_url, "domain": cs.domain, "api_key": cs.api_key},
421
+ }, timeout=cs.timeout))
422
+ result.created.append("connector")
423
+ except ConnectorError as exc:
424
+ conn = exc.connector
425
+ if found is None:
426
+ result.created.append("connector")
427
+ except ConnectorTimeoutError as exc:
428
+ conn = exc.connector
429
+ if found is None:
430
+ result.created.append("connector")
431
+ result.connector_id = conn.get("id")
432
+ result.connector_status = conn.get("status")
433
+ result.connector_state_reason = conn.get("state_reason")
434
+
435
+ def get_seat_customer(self, company_id: str) -> SeatCustomer:
436
+ """Rebuild the customer object (location, groups, rules, connector) from what is configured."""
437
+ c = self._c
438
+ locations = list(c.locations.iter_company_locations(company_id))
439
+ if not locations:
440
+ raise InvalidRequestError(f"Company {company_id} has no location")
441
+ loc = next((x for x in locations if x.get("is_active")), locations[0])
442
+ lid = loc["id"]
443
+ result = SeatCustomer(company_id=company_id, location_id=lid)
444
+ ma = c.groups.find_group(lid, MANAGER_ALERTS_GROUP)
445
+ ih = c.groups.find_group(lid, INSIGHTS_HUB_GROUP)
446
+ result.manager_alerts_group_id = ma and ma["id"]
447
+ result.insights_hub_group_id = ih and ih["id"]
448
+ for r in c.first_alert.iter_alert_rules(lid):
449
+ if r.get("name") == UPSET_CUSTOMER_RULE:
450
+ result.upset_customer_rule_id = r["id"]
451
+ elif r.get("name") == CUSTOMER_THREAT_RULE:
452
+ result.customer_threat_rule_id = r["id"]
453
+ rank = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4}
454
+ conns = sorted(c.connectors.iter_location_connectors(lid), key=lambda x: rank.get(x.get("status"), 5))
455
+ if conns and conns[0].get("status") != "inactive":
456
+ result.connector_id = conns[0]["id"]
457
+ result.connector_status = conns[0].get("status")
458
+ result.connector_state_reason = conns[0].get("state_reason")
459
+ return result
460
+
461
+ # ------------------------------------------------------------------ users
462
+
463
+ def _ensure_user(self, customer: SeatCustomer, user: UserSpec) -> Tuple[str, bool, Optional[str]]:
464
+ """Find or create the user, never emailing an invitation here. Returns (id, created, status)."""
465
+ users = self._c.users
466
+ found = users.find_user_by_email(customer.company_id, user.email)
467
+ if found is None:
468
+ body: Dict[str, Any] = {
469
+ "email": user.email, "first_name": user.first_name, "last_name": user.last_name,
470
+ "role": "frontline_user", "location_ids": [customer.location_id],
471
+ "send_invitation": False, "auth_method": user.auth_method,
472
+ }
473
+ if user.phone_number:
474
+ body["phone_number"] = user.phone_number
475
+ row = unwrap(users.create_company_user(customer.company_id, body))
476
+ return row["id"], True, row.get("status") or "invited"
477
+ uid = found["id"]
478
+ if found.get("status") == "deactivated":
479
+ users.reactivate_company_user(customer.company_id, uid)
480
+ detail = unwrap(users.get_company_user(customer.company_id, uid))
481
+ if detail.get("role") != "frontline_user":
482
+ raise InvalidRequestError(f"{user.email} is a {detail.get('role')}; Seat users are frontline users")
483
+ if customer.location_id not in [x["location_id"] for x in detail.get("locations") or []]:
484
+ users.add_locations(customer.company_id, uid, [customer.location_id])
485
+ return uid, False, detail.get("status")
486
+
487
+ def _invite(self, customer: SeatCustomer, user: UserSpec, user_id: str, status: Optional[str]) -> bool:
488
+ """The last step: email the invitation to a user who has not accepted one yet."""
489
+ if not user.send_invitation or status != "invited":
490
+ return False
491
+ self._c.users.resend_invitation(customer.company_id, user_id)
492
+ return True
493
+
494
+ def _map(self, customer: SeatCustomer, user_id: str, numbers: List[str]) -> None:
495
+ if not customer.connector_id:
496
+ raise InvalidRequestError("This customer has no connector; numbers cannot be mapped yet")
497
+ try:
498
+ self._c.users.set_numbers(customer.company_id, user_id, customer.connector_id, numbers)
499
+ except (ValidationError, ConflictError) as exc:
500
+ raise ExtensionMappingError(user_id, exc) from exc
501
+
502
+ def add_frontline_user(self, customer: SeatCustomer, user: UserSpec, extension: str) -> SeatUser:
503
+ """Create an end user with After Call on their own line, and add the line to every manager,
504
+ First Alert and Insights Hub. The invitation is emailed last, once all of that has worked
505
+ (unless ``user.send_invitation`` is False). If the line cannot be mapped,
506
+ ExtensionMappingError is raised and no invitation has been sent."""
507
+ c = self._c
508
+ ext = str(extension).strip()
509
+ if not ext:
510
+ raise InvalidRequestError("extension is required")
511
+ if not customer.connector_id:
512
+ raise InvalidRequestError("This customer has no connector; add one before adding end users")
513
+ uid, created, status = self._ensure_user(customer, user)
514
+ c.products.enable_user_product(customer.location_id, uid, AFTER_CALL)
515
+ c.first_alert.set_alert_email_preferences(customer.location_id, uid, {"masterEnabled": False, "alerts": []})
516
+ self._map(customer, uid, [ext])
517
+ for m in self._line_holders(customer):
518
+ if ext not in c.users.user_numbers(customer.company_id, m["id"], customer.connector_id):
519
+ try:
520
+ c.users.add_numbers(customer.company_id, m["id"], customer.connector_id, [ext])
521
+ except (ValidationError, ConflictError) as exc:
522
+ raise ExtensionMappingError(m["id"], exc) from exc
523
+ c.first_alert.add_monitored_numbers(customer.location_id, customer.connector_id, [ext])
524
+ c.insights_hub.add_numbers(customer.location_id, customer.connector_id, [ext])
525
+ invited = self._invite(customer, user, uid, status)
526
+ return SeatUser(user_id=uid, email=user.email, kind="frontline", numbers=[ext], created=created,
527
+ invited=invited)
528
+
529
+ def add_manager(self, customer: SeatCustomer, user: UserSpec, *, activate_alerts: bool = True) -> SeatUser:
530
+ """Create a manager: After Call on all lines, First Alert, Insights Hub, both groups, alert email on.
531
+
532
+ The manager reads every end-user line at the location. Their own phone line is not captured
533
+ on the Seat: it is never mapped, nor added to First Alert or Insights Hub, and a third
534
+ positional argument raises TypeError (``activate_alerts`` is keyword-only).
535
+
536
+ Then, with ``activate_alerts=True`` (the default), switch the customer's two alert rules on
537
+ (see activate_seat_alerts), and last email the invitation (unless ``user.send_invitation`` is
538
+ False). If the lines cannot be mapped, ExtensionMappingError is raised, the rules stay as they
539
+ were and no invitation has been sent."""
540
+ c = self._c
541
+ uid, created, status = self._ensure_user(customer, user)
542
+ for key in PRODUCT_KEYS:
543
+ c.products.enable_user_product(customer.location_id, uid, key)
544
+ groups = [g for g in (customer.manager_alerts_group_id, customer.insights_hub_group_id) if g]
545
+ if groups:
546
+ c.groups.add_user_to_groups(customer.location_id, uid, groups)
547
+ prefs = c.first_alert.get_alert_notification_preferences(customer.location_id, uid) or {}
548
+ alerts = ((prefs.get("emailNotifications") or {}).get("alerts")) or []
549
+ c.first_alert.set_alert_email_preferences(customer.location_id, uid, {
550
+ "masterEnabled": True, "alerts": [{"alertId": a["alertId"], "emailEnabled": True} for a in alerts]})
551
+ numbers = self._lines(customer)
552
+ if numbers:
553
+ self._map(customer, uid, numbers)
554
+ activated = self.activate_seat_alerts(customer) if activate_alerts else []
555
+ invited = self._invite(customer, user, uid, status)
556
+ return SeatUser(user_id=uid, email=user.email, kind="manager", numbers=numbers, created=created,
557
+ invited=invited, alerts_activated=activated)
558
+
559
+ def add_integration_user(self, customer: SeatCustomer, user: UserSpec) -> SeatUser:
560
+ """Create the customer's integration (data-reading) user: password sign-in, tagged
561
+ ``department: "integration"``, all three products, both groups, alert email off, every line.
562
+
563
+ It is never counted as a seat or a manager, later end users' lines are added to it, and
564
+ ``remove_user`` on it never takes a line off anyone else. It never switches alerts on. The
565
+ invitation (to set its password) is emailed last unless ``user.send_invitation`` is False.
566
+ The company needs MFA off (``SeatCustomerSpec.mfa_off``) for it to sign in."""
567
+ c = self._c
568
+ if user.auth_method != "password":
569
+ raise InvalidRequestError("An integration user signs in with a password: set auth_method='password'")
570
+ uid, created, status = self._ensure_user(customer, user)
571
+ detail = unwrap(c.users.get_company_user(customer.company_id, uid)) or {}
572
+ if not is_integration(detail):
573
+ c.users.update_company_user(customer.company_id, uid, {"department": INTEGRATION_DEPARTMENT})
574
+ for key in PRODUCT_KEYS:
575
+ c.products.enable_user_product(customer.location_id, uid, key)
576
+ groups = [g for g in (customer.manager_alerts_group_id, customer.insights_hub_group_id) if g]
577
+ if groups:
578
+ c.groups.add_user_to_groups(customer.location_id, uid, groups)
579
+ c.first_alert.set_alert_email_preferences(customer.location_id, uid, {"masterEnabled": False, "alerts": []})
580
+ numbers = self._lines(customer)
581
+ if numbers:
582
+ self._map(customer, uid, numbers)
583
+ invited = self._invite(customer, user, uid, status)
584
+ return SeatUser(user_id=uid, email=user.email, kind="integration", numbers=numbers, created=created,
585
+ invited=invited)
586
+
587
+ def change_user_extension(self, customer: SeatCustomer, user_id: str, old: str, new: str) -> Dict[str, Any]:
588
+ """Move an end user from ``old`` to ``new``: their mapping, every manager, First Alert, Insights Hub."""
589
+ c = self._c
590
+ old, new = str(old).strip(), str(new).strip()
591
+ if not customer.connector_id:
592
+ raise InvalidRequestError("This customer has no connector")
593
+ conn = customer.connector_id
594
+ mine = c.users.user_numbers(customer.company_id, user_id, conn)
595
+ self._map(customer, user_id, _uniq([new if n == old else n for n in mine] + [new]))
596
+ for m in self._line_holders(customer):
597
+ if m["id"] == user_id:
598
+ continue
599
+ cur = c.users.user_numbers(customer.company_id, m["id"], conn)
600
+ target = _uniq([n for n in cur if n != old] + [new])
601
+ if target != cur:
602
+ self._map(customer, m["id"], target)
603
+ fa = self._fa_numbers(customer)
604
+ c.first_alert.set_monitored_numbers(customer.location_id, conn, _uniq([n for n in fa if n != old] + [new]))
605
+ ih = self._ih_numbers(customer)
606
+ c.insights_hub.set_numbers(customer.location_id, conn, _uniq([n for n in ih if n != old] + [new]))
607
+ return {"user_id": user_id, "old": old, "new": new}
608
+
609
+ def remove_user(self, customer: SeatCustomer, user_id: str, keep_extensions: bool = False) -> Dict[str, Any]:
610
+ """Deactivate a user: they leave every group and their number mapping is cleared.
611
+
612
+ Only an end user's line is released, and only when no other end user at the location holds
613
+ it: it comes off managers, integration users, First Alert and Insights Hub (unless
614
+ ``keep_extensions``). Removing a manager, an integration user, or any user holding several
615
+ lines never takes a line off anyone else."""
616
+ c = self._c
617
+ conn = customer.connector_id
618
+ rows = self._location_rows(customer, include_excluded=True)
619
+ row = next((r for r in rows if r.get("id") == user_id), None)
620
+ if row is None:
621
+ row = dict(unwrap(c.users.get_location_user(customer.location_id, user_id)) or {})
622
+ row["department"] = (unwrap(c.users.get_company_user(customer.company_id, user_id)) or {}).get("department")
623
+ mine = c.users.user_numbers(customer.company_id, user_id, conn) if conn else []
624
+ if is_integration(row):
625
+ kind = "integration"
626
+ elif set(PRODUCT_KEYS) <= _products(row):
627
+ kind = "manager"
628
+ elif len(mine) > 1:
629
+ kind = "integration" # holds several lines and is not a manager: not a seat
630
+ else:
631
+ kind = "frontline"
632
+ released: List[str] = []
633
+ if conn and kind == "frontline" and not self._excluded(customer, row):
634
+ held_by_others = set()
635
+ for u in self.list_frontline_users(customer):
636
+ if u["id"] != user_id:
637
+ held_by_others.update(c.users.user_numbers(customer.company_id, u["id"], conn))
638
+ released = [n for n in mine if n not in held_by_others]
639
+ c.groups.remove_user_from_groups(customer.location_id, user_id)
640
+ if unwrap(c.users.get_user_number_mappings(customer.company_id, user_id)):
641
+ c.users.set_user_number_mappings(customer.company_id, user_id, {"mappings": []})
642
+ if released and not keep_extensions:
643
+ for m in self._line_holders(customer):
644
+ if m["id"] == user_id:
645
+ continue
646
+ cur = c.users.user_numbers(customer.company_id, m["id"], conn)
647
+ if set(released) & set(cur):
648
+ self._map(customer, m["id"], [n for n in cur if n not in released])
649
+ c.first_alert.remove_monitored_numbers(customer.location_id, conn, released)
650
+ c.insights_hub.remove_numbers(customer.location_id, conn, released)
651
+ try:
652
+ c.users.deactivate_company_user(customer.company_id, user_id)
653
+ except ConflictError:
654
+ pass # already deactivated
655
+ return {"user_id": user_id, "released_numbers": [] if keep_extensions else released, "kind": kind}
656
+
657
+ @staticmethod
658
+ def _excluded(customer: SeatCustomer, row: Dict[str, Any]) -> bool:
659
+ emails = {e.strip().lower() for e in customer.exclude_emails}
660
+ return row.get("id") in customer.exclude_user_ids or (row.get("email") or "").strip().lower() in emails
661
+
662
+ def _location_rows(self, customer: SeatCustomer, include_excluded: bool = False) -> List[Dict[str, Any]]:
663
+ """Users at the location, each with its company-level ``department`` joined in."""
664
+ c = self._c
665
+ departments = {u["id"]: u.get("department")
666
+ for u in c.users.iter_company_users(customer.company_id, location_id=customer.location_id)}
667
+ rows = []
668
+ for r in c.users.iter_location_users(customer.location_id):
669
+ row = dict(r, department=departments.get(r.get("id")))
670
+ if include_excluded or not self._excluded(customer, row):
671
+ rows.append(row)
672
+ return rows
673
+
674
+ def list_frontline_users(self, customer: SeatCustomer) -> List[Dict[str, Any]]:
675
+ """Active end users (After Call only, not integration users) at the customer's location."""
676
+ return [r for r in self._location_rows(customer) if is_frontline(r)]
677
+
678
+ def list_managers(self, customer: SeatCustomer) -> List[Dict[str, Any]]:
679
+ """Active managers (all three products, not integration users) at the customer's location."""
680
+ return [r for r in self._location_rows(customer) if is_manager(r)]
681
+
682
+ def list_integration_users(self, customer: SeatCustomer) -> List[Dict[str, Any]]:
683
+ """Active integration users (tagged ``department: "integration"``) at the customer's location."""
684
+ return [r for r in self._location_rows(customer) if _active_frontline(r) and is_integration(r)]
685
+
686
+ def _line_holders(self, customer: SeatCustomer) -> List[Dict[str, Any]]:
687
+ """Users who hold every line: managers and integration users."""
688
+ return [r for r in self._location_rows(customer)
689
+ if is_manager(r) or (_active_frontline(r) and is_integration(r))]
690
+
691
+ # ------------------------------------------------------------------ numbers
692
+
693
+ def _lines(self, customer: SeatCustomer) -> List[str]:
694
+ """The location's lines: the number of every end user who holds exactly one."""
695
+ if not customer.connector_id:
696
+ return []
697
+ out: List[str] = []
698
+ for u in self.list_frontline_users(customer):
699
+ nums = self._c.users.user_numbers(customer.company_id, u["id"], customer.connector_id)
700
+ if len(nums) == 1:
701
+ out = _uniq(out + nums)
702
+ return out
703
+
704
+ def _fa_numbers(self, customer: SeatCustomer) -> List[str]:
705
+ cfg = unwrap(self._c.first_alert.get_first_alert_config(customer.location_id)) or {}
706
+ return numbers_for(cfg.get("connector_mappings") or [], customer.connector_id)
707
+
708
+ def _ih_numbers(self, customer: SeatCustomer) -> List[str]:
709
+ setup = unwrap(self._c.insights_hub.get_insights_hub_setup(customer.location_id)) or {}
710
+ return numbers_for(setup.get("connector_mappings") or [], customer.connector_id)
711
+
712
+ def sync_numbers(self, customer: SeatCustomer, dry_run: bool = False) -> Dict[str, Any]:
713
+ """Recompute the location's lines (every end user's extension) and push them to managers,
714
+ integration users, First Alert and Insights Hub. Managers and integration users hold exactly
715
+ the lines: any other number on their mapping is removed.
716
+ ``dry_run=True`` returns the changes without making them."""
717
+ c = self._c
718
+ diff: Dict[str, Any] = {"lines": [], "managers": {}, "first_alert": {"add": [], "remove": []},
719
+ "insights_hub": {"add": [], "remove": []}, "applied": False}
720
+ if not customer.connector_id:
721
+ return diff
722
+ conn = customer.connector_id
723
+ lines = self._lines(customer)
724
+ diff["lines"] = lines
725
+ fa = self._fa_numbers(customer)
726
+ ih = self._ih_numbers(customer)
727
+ diff["first_alert"] = {"add": [n for n in lines if n not in fa], "remove": [n for n in fa if n not in lines]}
728
+ diff["insights_hub"] = {"add": [n for n in lines if n not in ih], "remove": [n for n in ih if n not in lines]}
729
+ targets: Dict[str, List[str]] = {}
730
+ for m in self._line_holders(customer):
731
+ cur = c.users.user_numbers(customer.company_id, m["id"], conn)
732
+ target = list(lines)
733
+ add = [n for n in target if n not in cur]
734
+ remove = [n for n in cur if n not in target]
735
+ if add or remove:
736
+ diff["managers"][m["id"]] = {"add": add, "remove": remove}
737
+ targets[m["id"]] = target
738
+ if dry_run:
739
+ return diff
740
+ for uid, target in targets.items():
741
+ self._map(customer, uid, target)
742
+ if diff["first_alert"]["add"] or diff["first_alert"]["remove"]:
743
+ c.first_alert.set_monitored_numbers(customer.location_id, conn, lines)
744
+ if diff["insights_hub"]["add"] or diff["insights_hub"]["remove"]:
745
+ c.insights_hub.set_numbers(customer.location_id, conn, lines)
746
+ diff["applied"] = True
747
+ return diff
748
+
749
+ # ------------------------------------------------------------------ offboarding
750
+
751
+ def offboard_customer(self, customer: SeatCustomer, deactivate_company: bool = True) -> Dict[str, Any]:
752
+ """Stop everything for a customer who leaves, in this order: pause the After Call webhook (its
753
+ URL is kept; it can't be deleted), clear the First Alert webhook, stop the connector (ends the
754
+ phone-system subscription), deactivate the integration users, then deactivate the company.
755
+
756
+ Safe to run again. Ask your Tresic contact about retention of the customer's data."""
757
+ c = self._c
758
+ lid = customer.location_id
759
+ out: Dict[str, Any] = {"webhook_paused": False, "first_alert_webhook_cleared": False,
760
+ "connector_deactivated": False, "integration_users_deactivated": [],
761
+ "company_deactivated": False}
762
+ hook = c.intelligence.get_after_call_webhook(lid) or {}
763
+ if hook.get("webhook_url") and hook.get("enabled"):
764
+ c.intelligence.set_after_call_webhook(lid, hook["webhook_url"], enabled=False)
765
+ out["webhook_paused"] = True
766
+ if c.intelligence.get_first_alert_webhook(lid):
767
+ c.intelligence.set_first_alert_webhook(lid, None)
768
+ out["first_alert_webhook_cleared"] = True
769
+ if customer.connector_id:
770
+ conn = unwrap(c.connectors.get_connector(lid, customer.connector_id)) or {}
771
+ if conn.get("status") not in ("inactive", "deactivating"):
772
+ try:
773
+ c.connectors.deactivate_connector(lid, customer.connector_id)
774
+ except ConflictError:
775
+ pass # already inactive
776
+ out["connector_deactivated"] = True
777
+ for u in self.list_integration_users(customer):
778
+ try:
779
+ c.users.deactivate_company_user(customer.company_id, u["id"])
780
+ except ConflictError:
781
+ continue # already deactivated
782
+ out["integration_users_deactivated"].append(u["id"])
783
+ if deactivate_company:
784
+ company = unwrap(c.companies.get_company(customer.company_id)) or {}
785
+ if company.get("is_active", True):
786
+ try:
787
+ c.companies.deactivate_company(customer.company_id)
788
+ except ConflictError:
789
+ pass # already inactive
790
+ out["company_deactivated"] = True
791
+ return out