From 51b762115b3cd486eb08350e35202157d722a608 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 13:58:45 -0700 Subject: [PATCH 01/12] Add the account and conversation layers; remove the workflows namespace client.accounts creates and maintains a customer on Base User and Base Manager licenses: teams plus a Management location, five groups and three alert rules per team, a connector per location, and helpers for people, licenses, lines and offboarding. Every helper finds before it writes, so a re-run writes nothing; a partial stop raises AccountError. client.conversations gives a signed-in person their own calls, tasks and alerts with masked caller numbers, bounded windows and limits, and briefs that print only their id and time. parse_first_alert_event parses the First Alert webhook. New errors: AccountError and WrongLoginError. client.workflows and its types are removed without aliases. Version 0.2.0. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 2 +- src/intelligence_cloud/__init__.py | 50 +- src/intelligence_cloud/_version.py | 2 +- src/intelligence_cloud/accounts.py | 1741 +++++++++++++++++++++++ src/intelligence_cloud/client.py | 16 +- src/intelligence_cloud/conversations.py | 491 +++++++ src/intelligence_cloud/errors.py | 42 +- src/intelligence_cloud/receiver.py | 86 +- src/intelligence_cloud/workflows.py | 791 ---------- tests/live/test_live.py | 256 ++-- tests/unit/fake_api.py | 158 +- tests/unit/test_accounts.py | 618 ++++++++ tests/unit/test_conversations.py | 202 +++ tests/unit/test_review2.py | 213 +-- tests/unit/test_workflows.py | 369 ----- 15 files changed, 3514 insertions(+), 1523 deletions(-) create mode 100644 src/intelligence_cloud/accounts.py create mode 100644 src/intelligence_cloud/conversations.py delete mode 100644 src/intelligence_cloud/workflows.py create mode 100644 tests/unit/test_accounts.py create mode 100644 tests/unit/test_conversations.py delete mode 100644 tests/unit/test_workflows.py diff --git a/pyproject.toml b/pyproject.toml index 9517191..9567bd1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "intelligence-cloud" -version = "0.1.1" +version = "0.2.0" description = "Python client for the Intelligence Cloud partner API: customer lifecycle and conversation intelligence." readme = "README.md" requires-python = ">=3.10" diff --git a/src/intelligence_cloud/__init__.py b/src/intelligence_cloud/__init__.py index f8a5363..c1d9560 100644 --- a/src/intelligence_cloud/__init__.py +++ b/src/intelligence_cloud/__init__.py @@ -1,14 +1,39 @@ """Intelligence Cloud partner API client. -Customer lifecycle with admin credentials (``client.companies``, ``client.users``, ..., -``client.workflows``) and conversation intelligence with frontline credentials -(``client.intelligence``). +Customers with an administrator login (``client.accounts``, and ``client.companies``, +``client.users``, ...) and conversations with a user login (``client.conversations`` and +``client.intelligence``). """ from ._base import Page, unwrap from ._version import __version__ +from .accounts import ( + AlertSetting, + AlertSettings, + ConnectorSpec, + Customer, + CustomerSpec, + Member, + PersonSpec, + Team, + TeamGroups, + TeamRules, + TeamSpec, +) from .auth import FileTokenStore, MemoryTokenStore, Tokens, TokenStore from .client import DEFAULT_BASE_URL, Client +from .conversations import ( + AlertBrief, + CallBrief, + Me, + Reference, + TaskBrief, + TeamRef, + TeamView, + TopicsView, + mask_number, +) from .errors import ( + AccountError, ApiError, AuthError, ConflictError, @@ -25,6 +50,7 @@ RateLimitError, ValidationError, WebhookPayloadError, + WrongLoginError, ) from .intelligence import RecordingLink, WebhookTestResult from .receiver import ( @@ -34,18 +60,12 @@ AfterCallSummary, Deduplicator, DedupStore, + FirstAlertEvent, MAX_EVENT_BYTES, MemoryDedupStore, UnknownEvent, parse_after_call_event, -) -from .workflows import ( - ConnectorSpec, - LocationSpec, - SeatCustomer, - SeatCustomerSpec, - SeatUser, - UserSpec, + parse_first_alert_event, ) __all__ = [ @@ -54,9 +74,11 @@ "IntelligenceCloudError", "InvalidRequestError", "ApiError", "AuthError", "PasswordExpiredError", "NotFoundError", "ConflictError", "ValidationError", "RateLimitError", "MfaRequiredError", "FrontlineRequiredError", "ConnectorError", "ConnectorTimeoutError", "ExtensionMappingError", - "WebhookPayloadError", "PayloadTooLargeError", "WebhookTestResult", "RecordingLink", + "AccountError", "WrongLoginError", "WebhookPayloadError", "PayloadTooLargeError", "WebhookTestResult", "RecordingLink", "AfterCallEvent", "AfterCallCall", "AfterCallSummary", "AfterCallLocation", "UnknownEvent", - "parse_after_call_event", "MAX_EVENT_BYTES", + "parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event", "Deduplicator", "DedupStore", "MemoryDedupStore", - "SeatCustomerSpec", "LocationSpec", "ConnectorSpec", "UserSpec", "SeatCustomer", "SeatUser", + "CustomerSpec", "TeamSpec", "ConnectorSpec", "PersonSpec", "AlertSetting", "AlertSettings", + "Customer", "Team", "TeamGroups", "TeamRules", "Member", + "CallBrief", "AlertBrief", "TaskBrief", "TeamRef", "TeamView", "TopicsView", "Reference", "Me", "mask_number", ] diff --git a/src/intelligence_cloud/_version.py b/src/intelligence_cloud/_version.py index 485f44a..d3ec452 100644 --- a/src/intelligence_cloud/_version.py +++ b/src/intelligence_cloud/_version.py @@ -1 +1 @@ -__version__ = "0.1.1" +__version__ = "0.2.0" diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py new file mode 100644 index 0000000..ad74093 --- /dev/null +++ b/src/intelligence_cloud/accounts.py @@ -0,0 +1,1741 @@ +"""The account layer: create and maintain a customer on Base User and Base Manager licenses. + +A customer is one company with teams and a Management location. "Team" is the packaging word; in +the API each team is a location. + +- Every team has five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub + Access, Insights Hub Weekly Reports), three alert rules (Customer Threat, Upset Customer, Low + Sentiment), each routed to its group, and its own connector to the phone system. +- `` - Management`` holds the managers' own lines and the company-wide weekly reports + group. It has no alert rules. +- A **Base User** has After Call on their own line at one team. +- A **Base Manager** has all three products, is on Management (own line there) and on each team + they run, holds those teams' lines and is in their alert, Insights Hub and weekly reports groups. +- An **integration user** reads data for another system: tagged ``department: "integration"``. + +Every helper finds what exists before it writes, so running it again with the same input writes +nothing. Lists that the API replaces in full are read, merged and written back. A helper that stops +part-way raises :class:`AccountError` with the step it reached and the result so far. Alert email is +off for every person the helpers create, and Insights Hub "monitor all numbers" stays off. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +import httpx + +from ._base import Namespace, unwrap +from ._spec import is_uuid +from .errors import ( + AccountError, + ApiError, + ConflictError, + ConnectorError, + ConnectorTimeoutError, + ExtensionMappingError, + IntelligenceCloudError, + InvalidRequestError, + ValidationError, + WrongLoginError, +) +from .resources import PRODUCT_KEYS, merge_mappings, numbers_for + +AFTER_CALL = "after-call-copilot" +FIRST_ALERT = "first-alert-copilot" +INSIGHTS_HUB = "insights-hub" +INTEGRATION_DEPARTMENT = "integration" +COMPANY_NAME_CONFLICT = "company_name_conflict" +MANAGEMENT_SUFFIX = " - Management" + +# Team groups: Team.groups field -> group name. Management has only weekly_reports. +TEAM_GROUPS: Dict[str, str] = { + "customer_threats": "Customer Threats", + "upset_customers": "Upset Customers", + "low_sentiment_calls": "Low Sentiment Calls", + "insights_hub_access": "Insights Hub Access", + "weekly_reports": "Insights Hub Weekly Reports", +} +ALERT_GROUPS = ("customer_threats", "upset_customers", "low_sentiment_calls") + + +@dataclass(frozen=True) +class _RuleDef: + name: str + priority: str + has_phrases: bool + default_level: int + group: str + + +# Team.rules field -> the rule. Priorities are fixed; levels are the defaults in the API guide. +RULES: Dict[str, _RuleDef] = { + "customer_threat": _RuleDef("Customer Threat", "high", True, -20, "customer_threats"), + "upset_customer": _RuleDef("Upset Customer", "medium", True, -20, "upset_customers"), + "low_sentiment": _RuleDef("Low Sentiment", "low", False, -40, "low_sentiment_calls"), +} +PHRASE_ALERTS = ("customer_threat", "upset_customer") +LICENSES = ("base_user", "base_manager", "integration", "other") +_SECRET_WORDS = ("key", "secret", "token", "password") +_RANK = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4} + + +# ---------------------------------------------------------------------- specs + + +@dataclass +class TeamSpec: + """A team's location. ``vertical`` is a vertical id, or its key from ``locations.list_verticals()``.""" + + name: str + street: str + city: str + state: str + country: str + zipcode: str + vertical: str + + +def _is_secret(name: Any) -> bool: + low = str(name).lower() + return any(w in low for w in _SECRET_WORDS) + + +class _Config(dict): + """A connector's settings. Values whose names contain key, secret, token or password are hidden + when printed.""" + + def __repr__(self) -> str: + return "{" + ", ".join(f"{k!r}: {'***' if _is_secret(k) else repr(v)}" for k, v in self.items()) + "}" + + __str__ = __repr__ + + +@dataclass(repr=False) +class ConnectorSpec: + """A connection to a phone system. ``type`` is the platform as the API names it + (``connectors.list_connector_types()``); ``config`` is that platform's own settings, sent to the API + as given. The connection key is sent when the connector is created or repaired and is never kept, + logged or shown: give it in full each time.""" + + type: str + config: Dict[str, Any] + name: Optional[str] = None # default " phone system" + timeout: float = 600.0 # seconds to wait for a new connector to settle + + def __post_init__(self) -> None: + if not isinstance(self.config, Mapping): + raise InvalidRequestError("ConnectorSpec.config must be a mapping") + self.config = _Config(self.config) + + def __repr__(self) -> str: + return (f"ConnectorSpec(type={self.type!r}, config={self.config!r}, name={self.name!r}, " + f"timeout={self.timeout!r})") + + @classmethod + def netsapiens(cls, api_url: str, domain: str, api_key: str, name: Optional[str] = None, + timeout: float = 600.0) -> "ConnectorSpec": + """The documented phone system: its API root (ending in /ns-api/v2), domain and a read/write key.""" + return cls(type="netsapiens", config={"api_url": api_url, "domain": domain, "api_key": api_key}, + name=name, timeout=timeout) + + +@dataclass +class PersonSpec: + email: str + first_name: str + last_name: str + phone_number: Optional[str] = None + auth_method: str = "password" # "sso" once the customer's single sign-on is connected + + +@dataclass +class AlertSetting: + """One alert's settings. ``None`` keeps what the rule has (or the default level on a new rule).""" + + phrases: Optional[List[str]] = None + sentiment_below: Optional[int] = None # a whole number from -100 to -1 + + +@dataclass +class AlertSettings: + customer_threat: Optional[AlertSetting] = None + upset_customer: Optional[AlertSetting] = None + low_sentiment: Optional[AlertSetting] = None # level only; it has no phrases + + +@dataclass +class CustomerSpec: + company_name: str + admin: PersonSpec # primary contact, invited as company admin; phone_number is required + team: TeamSpec # the first team + connector: Optional[ConnectorSpec] = None # used for the team and for Management + alerts: Optional[AlertSettings] = None + reseller_id: Optional[str] = None # default: the signed-in reseller + company_code: Optional[str] = None + # The company to use, from an earlier run. Without it, a company with the same name is used only + # when its primary contact email is admin.email; otherwise ConflictError is raised. + company_id: Optional[str] = None + mfa_off: bool = False # True for a company whose users include an integration user + sso_domain: Optional[str] = None + reactivate: bool = False # reactivate a company or location found inactive + + +# ---------------------------------------------------------------------- results + + +@dataclass +class TeamGroups: + customer_threats: Optional[str] = None + upset_customers: Optional[str] = None + low_sentiment_calls: Optional[str] = None + insights_hub_access: Optional[str] = None + weekly_reports: Optional[str] = None + + +@dataclass +class TeamRules: + customer_threat: Optional[str] = None + upset_customer: Optional[str] = None + low_sentiment: Optional[str] = None + + +@dataclass +class Team: + location_id: str + name: str + kind: str = "team" # "team" or "management" + groups: TeamGroups = field(default_factory=TeamGroups) + rules: TeamRules = field(default_factory=TeamRules) + connector_id: Optional[str] = None + connector_status: Optional[str] = None + connector_state_reason: Optional[str] = None + + +@dataclass +class Customer: + company_id: str + management: Optional[Team] = None + teams: List[Team] = field(default_factory=list) + # Items still to do: "customer_threat" and "upset_customer" until their phrases arrive (set_alerts), + # and, for a layout this SDK does not recognise, what is missing. + pending: List[str] = field(default_factory=list) + sso_domain_id: Optional[str] = None + sso_txt_record: Optional[Dict[str, str]] = None # {"name": ..., "value": ...} for the customer's DNS + created: List[str] = field(default_factory=list) + existing: List[str] = field(default_factory=list) + + +@dataclass +class Member: + user_id: str + email: str + license: str # "base_user", "base_manager", "integration" or "other" + teams: List[str] = field(default_factory=list) # location ids (Management not listed) + lines: List[str] = field(default_factory=list) + created: bool = False + invited: bool = False # an invitation was emailed by this call + notes: List[str] = field(default_factory=list) + + +CustomerRef = Union[Customer, str] +TeamRef = Union[Team, str] + + +# ---------------------------------------------------------------------- helpers + + +def _uniq(values: Iterable[str]) -> List[str]: + out: List[str] = [] + for v in values: + if v not in out: + out.append(v) + return out + + +def _line(value: Any, name: str = "line") -> str: + v = str(value).strip() if value is not None else "" + if not v: + raise InvalidRequestError(f"{name} is required") + return v + + +def _check_setting(key: str, s: Optional[AlertSetting]) -> None: + if s is None: + return + if not isinstance(s, AlertSetting): + raise InvalidRequestError(f"alerts.{key} must be an AlertSetting") + if s.sentiment_below is not None: + lvl = s.sentiment_below + if isinstance(lvl, bool) or not isinstance(lvl, int) or not -100 <= lvl <= -1: + raise InvalidRequestError(f"alerts.{key}.sentiment_below: a whole number from -100 to -1") + if s.phrases is not None: + if not RULES[key].has_phrases: + raise InvalidRequestError(f"alerts.{key} has no phrases; set sentiment_below only") + if isinstance(s.phrases, str) or not all(isinstance(p, str) for p in s.phrases): + raise InvalidRequestError(f"alerts.{key}.phrases must be a list of strings") + if not [p for p in s.phrases if p.strip()]: + raise InvalidRequestError(f"alerts.{key}.phrases is empty; pass None to keep the current phrases") + + +def _check_alerts(alerts: Optional[AlertSettings]) -> None: + if alerts is None: + return + if not isinstance(alerts, AlertSettings): + raise InvalidRequestError("alerts must be an AlertSettings") + for key in RULES: + _check_setting(key, getattr(alerts, key)) + + +def _clean_phrases(phrases: Optional[List[str]]) -> Optional[List[str]]: + if phrases is None: + return None + return _uniq(p.strip() for p in phrases if p and p.strip()) + + +def _rule_settings(rule: Mapping[str, Any]) -> Tuple[Optional[List[str]], Optional[int]]: + """(phrases, sentiment level) on a rule as read back.""" + phrases = level = None + for t in rule.get("triggers") or []: + cfg = t.get("config") or {} + if t.get("trigger_type") == "sentiment" and isinstance(cfg.get("threshold"), int): + level = cfg["threshold"] + elif t.get("trigger_type") == "keyword_match": + phrases = list(cfg.get("keywords") or []) + return phrases, level + + +def _triggers(key: str, phrases: Optional[List[str]], level: int) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [{"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": level}}] + if RULES[key].has_phrases: + out.append({"trigger_type": "keyword_match", "config": {"keywords": list(phrases or []), "match_logic": "any"}}) + return out + + +def rule_body(key: str, group_id: str, phrases: Optional[List[str]] = None, level: Optional[int] = None, + enabled: bool = False) -> Dict[str, Any]: + """The create body for one of the three team rules (``customer_threat``, ``upset_customer``, + ``low_sentiment``). Phrase rules need phrases, which the caller provides.""" + d = RULES[key] + if d.has_phrases and not phrases: + raise InvalidRequestError(f"{d.name} needs its phrases") + return {"name": d.name, "priority": d.priority, "match_logic": "all" if d.has_phrases else "any", + "enabled": enabled, "triggers": _triggers(key, phrases, level if level is not None else d.default_level), + "group_ids": [group_id]} + + +def _norm_triggers(rule: Mapping[str, Any]) -> List[Dict[str, Any]]: + return [{"trigger_type": t.get("trigger_type"), "config": t.get("config")} for t in rule.get("triggers") or []] + + +def _is_integration(row: Mapping[str, Any]) -> bool: + return (row.get("department") or "").strip().lower() == INTEGRATION_DEPARTMENT + + +@dataclass +class _Person: + """One person across the customer's locations, as read back.""" + + id: str + email: str + status: Optional[str] + department: Optional[str] = None + invited_at: Optional[str] = None + invite_expires_at: Optional[str] = None + locs: Dict[str, Dict[str, set]] = field(default_factory=dict) # location id -> {"products", "groups"} + mappings: List[Dict[str, Any]] = field(default_factory=list) + license: str = "other" + teams: List[str] = field(default_factory=list) + + def numbers(self, connector_id: Optional[str] = None) -> List[str]: + return numbers_for(self.mappings, connector_id) + + @property + def active(self) -> bool: + return self.status != "deactivated" + + +class _Run: + def __init__(self, client: Any, result: Any): + self.client = client + self.start = client._writes + self.result = result + self.step = "start" + + +# ---------------------------------------------------------------------- the namespace + + +class Accounts(Namespace): + """Create and maintain customers (administrator login).""" + + def __init__(self, client: Any): + super().__init__(client) + self._me: Optional[Dict[str, Any]] = None + self._verticals: Optional[List[Dict[str, Any]]] = None + self._connector_types: Optional[List[str]] = None + + # ------------------------------------------------------------------ plumbing + + def _require_admin(self) -> Dict[str, Any]: + if self._me is None: + self._me = unwrap(self._c.account.get_me()) or {} + if self._me.get("role") == "frontline_user": + raise WrongLoginError(self._me.get("role"), "admin") + return self._me + + def _run(self, result: Any) -> _Run: + return _Run(self._c, result) + + def _stop(self, run: _Run, exc: BaseException) -> None: + """Re-raise ``exc`` as it is when nothing was written yet; otherwise as AccountError.""" + if isinstance(exc, AccountError) or self._c._writes == run.start: + raise exc + raise AccountError(run.step, run.result, exc) from exc + + def _resolve(self, customer: CustomerRef) -> Customer: + if isinstance(customer, Customer): + return customer + if isinstance(customer, str) and customer.strip(): + return self.get_customer(customer.strip()) + raise InvalidRequestError("customer: a Customer or a company id") + + @staticmethod + def _team(cust: Customer, team: TeamRef) -> Team: + if isinstance(team, Team): + want = team.location_id + for t in cust.teams: + if t.location_id == want: + return t + raise InvalidRequestError("team is not one of this customer's teams") + for t in cust.teams: + if team in (t.location_id, t.name): + return t + raise InvalidRequestError(f"Unknown team {team!r}: use a Team, its location id or its name") + + def _teams(self, cust: Customer, team: Optional[TeamRef]) -> List[Team]: + return [self._team(cust, team)] if team is not None else list(cust.teams) + + @staticmethod + def _locations(cust: Customer) -> List[Team]: + return ([cust.management] if cust.management else []) + list(cust.teams) + + def _vertical_id(self, vertical: str) -> str: + if is_uuid(vertical): + return vertical + if self._verticals is None: + self._verticals = unwrap(self._c.locations.list_verticals()) or [] + for v in self._verticals: + if vertical in (v.get("key"), v.get("name")): + return v["id"] + raise InvalidRequestError(f"Unknown vertical {vertical!r}: use an id or key from list_verticals()") + + def _check_connector(self, cs: Optional[ConnectorSpec], required: bool = False) -> None: + if cs is None: + if required: + raise InvalidRequestError("A connector is required: pass a ConnectorSpec") + return + if not isinstance(cs, ConnectorSpec): + raise InvalidRequestError("connector must be a ConnectorSpec") + if self._connector_types is None: + rows = unwrap(self._c.connectors.list_connector_types()) or [] + self._connector_types = [r.get("key") for r in rows if isinstance(r, dict) and r.get("key")] + if cs.type not in self._connector_types: + raise InvalidRequestError(f"Unknown connector type {cs.type!r}: one of {self._connector_types}") + + # ------------------------------------------------------------------ reading the layout + + def get_customer(self, company_id: str) -> Customer: + """Read the customer's layout back: Management, teams, groups, rules, connectors and what is + pending. A layout this SDK does not recognise (for example one built with 0.1.x) is returned with + what is missing listed in ``pending``.""" + self._require_admin() + c = self._c + company = unwrap(c.companies.get_company(company_id)) or {} + name = company.get("company_name") or "" + mgmt_name = name + MANAGEMENT_SUFFIX + locs = [x for x in c.locations.iter_company_locations(company_id) if x.get("is_active", True)] + locs.sort(key=lambda x: (x.get("created_at") or "", x.get("location_name") or "")) + cust = Customer(company_id=company_id) + for loc in locs: + kind = "management" if loc.get("location_name") == mgmt_name else "team" + team = self._read_team(loc["id"], loc.get("location_name") or "", kind) + if kind == "management" and cust.management is None: + cust.management = team + else: + cust.teams.append(team) + cust.pending = self._pending(cust) + for dom in unwrap(c.sso.list_company_domains(company_id)) or []: + cust.sso_domain_id = dom.get("id") + ver = dom.get("verification") or {} + cust.sso_txt_record = {"name": ver.get("name"), "value": ver.get("value")} + break + return cust + + def _read_team(self, location_id: str, name: str, kind: str) -> Team: + c = self._c + team = Team(location_id=location_id, name=name, kind=kind) + by_name = {g.get("group_name"): g["id"] for g in c.groups.iter_user_groups(location_id)} + for f, gname in TEAM_GROUPS.items(): + setattr(team.groups, f, by_name.get(gname)) + rules = {r.get("name"): r["id"] for r in c.first_alert.iter_alert_rules(location_id)} + for key, d in RULES.items(): + setattr(team.rules, key, rules.get(d.name)) + self._read_connector(team) + return team + + def _read_connector(self, team: Team) -> None: + conns = sorted(self._c.connectors.iter_location_connectors(team.location_id), + key=lambda x: _RANK.get(x.get("status"), 5)) + if conns and conns[0].get("status") != "inactive": + team.connector_id = conns[0]["id"] + team.connector_status = conns[0].get("status") + team.connector_state_reason = conns[0].get("state_reason") + + @staticmethod + def _pending(cust: Customer) -> List[str]: + out: List[str] = [] + for key in PHRASE_ALERTS: + if any(getattr(t.rules, key) is None for t in cust.teams): + out.append(key) + if cust.management is None: + out.append("management location") + else: + if cust.management.groups.weekly_reports is None: + out.append(f"{cust.management.name}: group {TEAM_GROUPS['weekly_reports']}") + if any(getattr(cust.management.rules, k) for k in RULES): + out.append(f"{cust.management.name}: has alert rules (Management has none)") + if not cust.teams: + out.append("team") + for t in cust.teams: + for f, gname in TEAM_GROUPS.items(): + if getattr(t.groups, f) is None: + out.append(f"{t.name}: group {gname}") + if t.rules.low_sentiment is None: + out.append(f"{t.name}: rule {RULES['low_sentiment'].name}") + return out + + # ------------------------------------------------------------------ create + + def create_customer(self, spec: CustomerSpec) -> Customer: + """Create the customer, or finish one an earlier run started. + + The company with all three products; the SSO domain claim (if ``sso_domain``); the first team + and `` - Management``; the connector at each (if given); five groups on the team and + the weekly reports group at Management; the Low Sentiment rule, plus Customer Threat and Upset + Customer when their phrases are given, all switched off; Insights Hub with "monitor all + numbers" off. Alerts without phrases are listed in ``Customer.pending`` and follow with + ``set_alerts``. Store ``company_id`` and pass it on later runs: a company is never adopted by + its name alone.""" + me = self._require_admin() + c = self._c + if not isinstance(spec, CustomerSpec): + raise InvalidRequestError("spec must be a CustomerSpec") + if not spec.admin or not (spec.admin.phone_number or "").strip(): + raise InvalidRequestError("admin.phone_number is required for the primary contact") + _check_alerts(spec.alerts) + self._check_connector(spec.connector) + reseller_id = spec.reseller_id or me.get("reseller_id") + if not reseller_id: + raise InvalidRequestError("reseller_id is required (this login has none)") + mgmt_name = spec.company_name + MANAGEMENT_SUFFIX + if spec.team.name == mgmt_name: + raise InvalidRequestError(f"{mgmt_name!r} is the Management location; name the team differently") + self._vertical_id(spec.team.vertical) # unknown verticals are refused before any write + + result = Customer(company_id="") + run = self._run(result) + try: + run.step = "company" + company = self._find_company(reseller_id, spec) + if company is None: + body: Dict[str, Any] = { + "company_name": spec.company_name, + "primary_admin_contact_name": f"{spec.admin.first_name} {spec.admin.last_name}".strip(), + "primary_admin_contact_email": spec.admin.email, + "primary_admin_contact_phone": spec.admin.phone_number, + "enabled_products": list(PRODUCT_KEYS), + } + if spec.company_code: + body["company_code"] = spec.company_code + company = unwrap(c.companies.create_company(reseller_id, body)) + result.created.append("company") + else: + result.existing.append("company") + if not company.get("is_active", True): + if not spec.reactivate: + raise InvalidRequestError(f"Company {spec.company_name!r} exists but is inactive " + "(set reactivate=True to reactivate it)") + c.companies.reactivate_company(company["id"]) + company_id = result.company_id = company["id"] + + run.step = "mfa" + if spec.mfa_off: + current = unwrap(c.companies.get_company(company_id)) or {} + if current.get("mfa_enforced"): + c.companies.update_company(company_id, {"mfa_enforced": False}) + if (unwrap(c.companies.get_company(company_id)) or {}).get("mfa_enforced"): + text = "MFA is still on for the company after the update" + raise ApiError(200, None, text, public_message=text) + + run.step = "sso" + if spec.sso_domain: + self._ensure_domain(company_id, spec.sso_domain, result) + + run.step = "products" + current = unwrap(c.companies.get_company(company_id)) or {} + if not set(PRODUCT_KEYS) <= set(current.get("enabled_products") or []): + c.companies.add_products(company_id, PRODUCT_KEYS) + + run.step = "locations" + team = self._ensure_location(company_id, spec.team.name, spec.team, "team", spec.reactivate, result) + mgmt = self._ensure_location(company_id, mgmt_name, spec.team, "management", spec.reactivate, result) + result.teams = [team] + result.management = mgmt + + run.step = "connectors" + if spec.connector is not None: + self._ensure_connector(team, spec.connector, result) + self._ensure_connector(mgmt, spec.connector, result) + else: + self._read_connector(team) + self._read_connector(mgmt) + + run.step = "groups" + self._ensure_groups(team, result) + self._ensure_groups(mgmt, result) + + run.step = "rules" + settings = self._settings_from(spec.alerts) + self._ensure_rules(team, settings, result) + + run.step = "insights_hub" + self._ensure_insights_hub(team) + self._monitor_all_off(mgmt.location_id) + result.pending = self._pending(result) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def _find_company(self, reseller_id: str, spec: CustomerSpec) -> Optional[Dict[str, Any]]: + """``spec.company_id``, or the one company with this exact name whose primary contact email is + ``spec.admin.email``. Raises ConflictError, before any write, when the name is taken by another.""" + c = self._c + if spec.company_id: + return unwrap(c.companies.get_company(spec.company_id)) + same_name = c.companies.find_companies(reseller_id, spec.company_name) + if not same_name: + return None + want = (spec.admin.email or "").strip().lower() + matches = [] + for row in same_name: + detail = unwrap(c.companies.get_company(row["id"])) or {} + if (detail.get("primary_admin_contact_email") or "").strip().lower() == want: + matches.append(detail) + if len(matches) == 1: + return matches[0] + text = (f"A company named {spec.company_name!r} already exists with a different primary contact. " + "Pass company_id to use an existing company, or choose a different company name.") + raise ConflictError(409, COMPANY_NAME_CONFLICT, text, public_message=text) + + def _ensure_domain(self, company_id: str, domain: str, result: Customer) -> None: + want = domain.strip().lower() + dom = next((d for d in unwrap(self._c.sso.list_company_domains(company_id)) or [] + if (d.get("domain") or "").strip().lower() == want), None) + if dom is None: + dom = unwrap(self._c.sso.claim_company_domain(company_id, {"domain": domain})) or {} + result.created.append("sso_domain") + else: + result.existing.append("sso_domain") + result.sso_domain_id = dom.get("id") + ver = dom.get("verification") or {} + result.sso_txt_record = {"name": ver.get("name"), "value": ver.get("value")} + + def _ensure_location(self, company_id: str, name: str, spec: TeamSpec, kind: str, reactivate: bool, + result: Customer) -> Team: + c = self._c + loc = c.locations.find_location(company_id, name) + if loc is None: + loc = unwrap(c.locations.create_location(company_id, { + "location_name": name, "street": spec.street, "city": spec.city, "state": spec.state, + "country": spec.country, "zipcode": spec.zipcode, "vertical_id": self._vertical_id(spec.vertical), + "enabled_products": list(PRODUCT_KEYS), + })) + result.created.append(f"location:{name}") + else: + result.existing.append(f"location:{name}") + if not loc.get("is_active", True): + if not reactivate: + raise InvalidRequestError(f"Location {name!r} exists but is inactive " + "(set reactivate=True to reactivate it)") + c.locations.reactivate_location(company_id, loc["id"]) + if not set(PRODUCT_KEYS) <= set(loc.get("enabled_products") or []): + c.locations.add_products(company_id, loc["id"], PRODUCT_KEYS) + return Team(location_id=loc["id"], name=name, kind=kind) + + def _ensure_groups(self, team: Team, result: Customer) -> None: + fields = list(TEAM_GROUPS) if team.kind == "team" else ["weekly_reports"] + existing = {g.get("group_name"): g["id"] for g in self._c.groups.iter_user_groups(team.location_id)} + for f in fields: + gname = TEAM_GROUPS[f] + gid = existing.get(gname) + if gid is None: + gid = unwrap(self._c.groups.create_user_group(team.location_id, {"group_name": gname}))["id"] + result.created.append(f"group:{team.name}:{gname}") + else: + result.existing.append(f"group:{team.name}:{gname}") + setattr(team.groups, f, gid) + + @staticmethod + def _settings_from(alerts: Optional[AlertSettings]) -> Dict[str, Tuple[Optional[List[str]], Optional[int]]]: + out: Dict[str, Tuple[Optional[List[str]], Optional[int]]] = {} + for key in RULES: + s = getattr(alerts, key, None) if alerts is not None else None + out[key] = (_clean_phrases(s.phrases), s.sentiment_below) if s is not None else (None, None) + return out + + def _ensure_rules(self, team: Team, settings: Mapping[str, Tuple[Optional[List[str]], Optional[int]]], + result: Optional[Customer]) -> List[str]: + """Create missing rules (switched off) and apply the given phrases and levels to existing ones. + Returns the ids of the rules created or changed.""" + fa = self._c.first_alert + changed: List[str] = [] + found = {r.get("name"): r for r in fa.iter_alert_rules(team.location_id)} + for key, d in RULES.items(): + phrases, level = settings.get(key, (None, None)) + group_id = getattr(team.groups, d.group) + row = found.get(d.name) + if row is None: + if d.has_phrases and not phrases: + setattr(team.rules, key, None) + continue # pending until its phrases arrive + if not group_id: + raise InvalidRequestError(f"{team.name}: group {TEAM_GROUPS[d.group]} is missing") + rule = unwrap(fa.create_alert_rule(team.location_id, rule_body(key, group_id, phrases, level))) + setattr(team.rules, key, rule["id"]) + changed.append(rule["id"]) + if result is not None: + result.created.append(f"rule:{team.name}:{d.name}") + continue + if result is not None: + result.existing.append(f"rule:{team.name}:{d.name}") + rule = unwrap(fa.get_alert_rule(team.location_id, row["id"])) or {} + setattr(team.rules, key, rule.get("id", row["id"])) + have_groups = {g.get("id") for g in rule.get("groups") or []} + if group_id and group_id not in have_groups: + fa.add_rule_groups(team.location_id, row["id"], [group_id]) + cur_phrases, cur_level = _rule_settings(rule) + new_phrases = phrases if phrases is not None else cur_phrases + new_level = level if level is not None else (cur_level if cur_level is not None else d.default_level) + if d.has_phrases and not new_phrases: + continue # a phrase rule read back without phrases: leave it for a person to check + want = _triggers(key, new_phrases, new_level) + if _norm_triggers(rule) != want: + fa.update_alert_rule(team.location_id, row["id"], {"triggers": want}) + if row["id"] not in changed: + changed.append(row["id"]) + return changed + + def _ensure_insights_hub(self, team: Team) -> None: + ih = self._c.insights_hub + setup = unwrap(ih.get_insights_hub_setup(team.location_id)) or {} + access = setup.get("group_access") or [] + gid = team.groups.insights_hub_access + if gid and gid not in access: + if not access and not setup.get("connector_mappings"): + ih.save_insights_hub_setup(team.location_id, {"connector_mappings": [], "group_access": [gid]}) + else: + ih.add_groups(team.location_id, [gid]) + self._monitor_all_off(team.location_id) + + def _monitor_all_off(self, location_id: str) -> None: + cfg = unwrap(self._c.insights_hub.get_insights_hub_config(location_id)) or {} + if cfg.get("monitor_all_numbers"): + self._c.insights_hub.update_insights_hub_config(location_id, {"monitor_all_numbers": False}) + + # ------------------------------------------------------------------ connectors + + def _find_connector(self, location_id: str, cs: ConnectorSpec, name: str) -> Optional[Dict[str, Any]]: + """The location's connector of this type for the same phone-system domain (best status first), + else one of this type with this name.""" + conns = self._c.connectors + rows = sorted(conns.iter_location_connectors(location_id), key=lambda x: _RANK.get(x.get("status"), 5)) + want_domain = str(cs.config.get("domain") or "").strip().lower() + by_name = None + for row in rows: + if row.get("type") and row.get("type") != cs.type: + continue + detail = unwrap(conns.get_connector(location_id, row["id"])) or {} + have_domain = str((detail.get("config") or {}).get("domain") or "").strip().lower() + if want_domain and have_domain == want_domain: + return detail + if by_name is None and detail.get("name") == name: + by_name = detail + return by_name + + def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Customer]) -> None: + name = cs.name or f"{team.name} phone system" + conns = self._c.connectors + config = dict(cs.config) + found = self._find_connector(team.location_id, cs, name) + label = f"connector:{team.name}" + if found is not None: + have = found.get("config") or {} + unchanged = found.get("name") == name and all( + have.get(k) == v for k, v in config.items() if k in have and not _is_secret(k)) + if found.get("status") in ("active", "connecting") and unchanged: + if result is not None: + result.existing.append(label) + self._set_conn(team, found) + return + try: + if found is not None: + # In error, stopped or changed: apply the settings (and key) given now, then restart. + if result is not None: + result.existing.append(label) + result.existing.append(label + ":updated") + conns.update_connector(team.location_id, found["id"], {"name": name, "config": config}) + if found.get("status") == "inactive": + conn = unwrap(conns.reactivate_connector(team.location_id, found["id"], timeout=cs.timeout)) + else: + conn = conns.wait_for_status(team.location_id, found["id"], ("active", "error"), cs.timeout, + raise_on_error=False) + if conn.get("status") == "error": + conns.deactivate_connector(team.location_id, found["id"], timeout=cs.timeout) + conn = unwrap(conns.reactivate_connector(team.location_id, found["id"], timeout=cs.timeout)) + else: + if result is not None: + result.created.append(label) + conn = unwrap(conns.create_connector(team.location_id, {"name": name, "type": cs.type, + "config": config}, timeout=cs.timeout)) + except (ConnectorError, ConnectorTimeoutError) as exc: + conn = exc.connector # recorded on the team; user lines need it active + self._set_conn(team, conn) + + @staticmethod + def _set_conn(team: Team, conn: Mapping[str, Any]) -> None: + team.connector_id = conn.get("id") + team.connector_status = conn.get("status") + team.connector_state_reason = conn.get("state_reason") + + # ------------------------------------------------------------------ teams and alerts + + def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSpec, *, + alerts: Optional[AlertSettings] = None, reactivate: bool = False) -> Team: + """Add a further team: its location, connector (required; give the key in full each time), + groups, rules (copying the phrases and levels of the first team's rules, except where + ``alerts`` sets them) and Insights Hub setup. The rules are created switched off.""" + self._require_admin() + if not isinstance(team, TeamSpec): + raise InvalidRequestError("team must be a TeamSpec") + self._check_connector(connector, required=True) + _check_alerts(alerts) + cust = self._resolve(customer) + if cust.management is not None and team.name == cust.management.name: + raise InvalidRequestError("That name is the Management location; name the team differently") + self._vertical_id(team.vertical) + settings = self._settings_from(alerts) + first = next((t for t in cust.teams if t.name != team.name), None) + new = Team(location_id="", name=team.name) + run = self._run(new) + try: + run.step = "copy_alerts" + if first is not None: + for key, d in RULES.items(): + rid = getattr(first.rules, key) + if rid is None: + continue + phr, lvl = _rule_settings(unwrap(self._c.first_alert.get_alert_rule(first.location_id, rid)) or {}) + given_phr, given_lvl = settings[key] + settings[key] = (given_phr if given_phr is not None else (phr if d.has_phrases else None), + given_lvl if given_lvl is not None else lvl) + run.step = "location" + made = self._ensure_location(cust.company_id, team.name, team, "team", reactivate, cust) + new.location_id = made.location_id + run.step = "connector" + self._ensure_connector(new, connector, cust) + run.step = "groups" + self._ensure_groups(new, cust) + run.step = "rules" + self._ensure_rules(new, settings, cust) + run.step = "insights_hub" + self._ensure_insights_hub(new) + existing = next((i for i, t in enumerate(cust.teams) if t.location_id == new.location_id), None) + if existing is None: + cust.teams.append(new) + else: + cust.teams[existing] = new + cust.pending = self._pending(cust) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return new + + def set_alerts(self, customer: CustomerRef, alerts: AlertSettings, *, team: Optional[TeamRef] = None) -> List[str]: + """Create or update the three rules' phrases and sentiment levels on one team or on every team. + Anything left as None is kept. Existing rules keep their on or off state; a rule created here + (one that was pending its phrases) starts switched off: ``activate_alerts`` switches it on. + Returns the ids of the rules created or changed.""" + self._require_admin() + _check_alerts(alerts) + if alerts is None: + raise InvalidRequestError("alerts is required") + cust = self._resolve(customer) + teams = self._teams(cust, team) + settings = self._settings_from(alerts) + changed: List[str] = [] + run = self._run(changed) + try: + for t in teams: + run.step = f"rules:{t.name}" + changed.extend(self._ensure_rules(t, settings, None)) + cust.pending = self._pending(cust) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return changed + + def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, + team: Optional[TeamRef] = None) -> List[Team]: + """Attach a phone system to a customer created without one: the named team, or the first team + and Management. Refuses (InvalidRequestError, before any write) where an active connector + exists. Returns the teams it attached.""" + self._require_admin() + self._check_connector(connector, required=True) + cust = self._resolve(customer) + if team is not None: + targets = [self._team(cust, team)] + else: + if not cust.teams: + raise InvalidRequestError("This customer has no team") + targets = [cust.teams[0]] + ([cust.management] if cust.management else []) + todo: List[Team] = [] + for t in targets: + name = connector.name or f"{t.name} phone system" + found = self._find_connector(t.location_id, connector, name) + active = [x for x in self._c.connectors.iter_location_connectors(t.location_id) + if x.get("status") == "active"] + same = found is not None and found.get("status") == "active" and all( + (found.get("config") or {}).get(k) == v for k, v in connector.config.items() + if k in (found.get("config") or {}) and not _is_secret(k)) + if active and not same: + raise InvalidRequestError(f"{t.name} already has an active connector") + if same: + self._set_conn(t, found) # type: ignore[arg-type] + continue # already attached: nothing to do + todo.append(t) + run = self._run(targets) + try: + for t in todo: + run.step = f"connector:{t.name}" + self._ensure_connector(t, connector, cust) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return targets + + def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = None) -> Dict[str, Any]: + """Switch the rules on for teams that have at least one Base Manager in each alert group. + Teams that do not are skipped and reported. + + Returns ``{"switched_on": [rule ids], "skipped": [{"location_id", "team", "missing"}]}``.""" + self._require_admin() + cust = self._resolve(customer) + out: Dict[str, Any] = {"switched_on": [], "skipped": []} + people = self._index(cust) + managers = {p.id for p in people.values() if p.license == "base_manager"} + run = self._run(out) + try: + for t in self._teams(cust, team): + run.step = f"activate:{t.name}" + missing = [] + for f in ALERT_GROUPS: + gid = getattr(t.groups, f) + members = set() + if gid: + grp = unwrap(self._c.groups.get_user_group(t.location_id, gid)) or {} + members = {m.get("id") for m in grp.get("members") or []} + if not members & managers: + missing.append(TEAM_GROUPS[f]) + if missing: + out["skipped"].append({"location_id": t.location_id, "team": t.name, "missing": missing}) + continue + for key in RULES: + rid = getattr(t.rules, key) + if not rid: + continue + rule = unwrap(self._c.first_alert.get_alert_rule(t.location_id, rid)) or {} + if not rule.get("enabled"): + self._c.first_alert.update_alert_rule(t.location_id, rid, {"enabled": True}) + out["switched_on"].append(rid) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return out + + # ------------------------------------------------------------------ people: reading + + def _index(self, cust: Customer, include_inactive: bool = False) -> Dict[str, _Person]: + """Everyone at the customer's locations, with products and groups per location, lines and license.""" + c = self._c + people: Dict[str, _Person] = {} + for t in self._locations(cust): + for r in c.users.iter_location_users(t.location_id): + p = people.get(r["id"]) + if p is None: + p = people[r["id"]] = _Person(id=r["id"], email=r.get("email") or "", status=r.get("status")) + p.locs[t.location_id] = {"products": set(r.get("enabled_products") or []), + "groups": set(r.get("groups") or [])} + for u in c.users.iter_company_users(cust.company_id): + p = people.get(u.get("id")) + if p is not None: + p.department = u.get("department") + p.status = u.get("status") or p.status + p.invited_at = u.get("invited_at") + p.invite_expires_at = u.get("invite_expires_at") + if not include_inactive: + people = {k: v for k, v in people.items() if v.active} + for p in people.values(): + if p.active: + p.mappings = unwrap(c.users.get_user_number_mappings(cust.company_id, p.id)) or [] + self._classify(cust, p) + return people + + @staticmethod + def _classify(cust: Customer, p: _Person) -> None: + team_ids = [t.location_id for t in cust.teams] + mgmt = cust.management.location_id if cust.management else None + alert_names = {TEAM_GROUPS[f] for f in ALERT_GROUPS} + p.teams = [lid for lid in team_ids if lid in p.locs] + if _is_integration({"department": p.department}): + p.license = "integration" + return + all_three = any(set(PRODUCT_KEYS) <= v["products"] for v in p.locs.values()) + in_alert_groups = any(p.locs[lid]["groups"] & alert_names for lid in p.teams) + if all_three and mgmt in p.locs and in_alert_groups: + p.license = "base_manager" + return + conn = {t.location_id: t.connector_id for t in cust.teams} + own_line = any(conn.get(lid) and p.numbers(conn[lid]) for lid in p.teams) + only_after_call = p.teams and all(p.locs[lid]["products"] == {AFTER_CALL} for lid in p.teams) + if only_after_call and own_line and mgmt not in p.locs: + p.license = "base_user" + return + p.license = "other" + + @staticmethod + def _member(p: _Person, **kw: Any) -> Member: + return Member(user_id=p.id, email=p.email, license=p.license, teams=list(p.teams), lines=p.numbers(), **kw) + + def _person(self, cust: Customer, user_id: str, include_inactive: bool = False) -> Tuple[_Person, Dict[str, _Person]]: + people = self._index(cust, include_inactive=include_inactive) + p = people.get(user_id) + if p is None: + raise InvalidRequestError(f"User {user_id} is not at any of this customer's locations") + return p, people + + @staticmethod + def _holders(team: Team, people: Mapping[str, _Person], exclude: Iterable[str] = ()) -> List[_Person]: + """People who hold a team's lines: its Base Managers and integration users.""" + skip = set(exclude) + return [p for p in people.values() if p.active and p.id not in skip and team.location_id in p.teams + and p.license in ("base_manager", "integration")] + + @staticmethod + def _team_lines(team: Team, people: Mapping[str, _Person], exclude: Iterable[str] = ()) -> List[str]: + """A team's lines: the number of every Base User there who holds exactly one on its connector.""" + skip = set(exclude) + out: List[str] = [] + if not team.connector_id: + return out + for p in people.values(): + if p.active and p.license == "base_user" and p.id not in skip and team.location_id in p.teams: + nums = p.numbers(team.connector_id) + if len(nums) == 1: + out = _uniq(out + nums) + return out + + def list_members(self, customer: CustomerRef, *, license: Optional[str] = None, + team: Optional[TeamRef] = None) -> List[Member]: + """Everyone active at the customer's locations, with license, teams and lines. + + ``license``: "base_user", "base_manager", "integration" or "other". A Base User has After Call + on and their own line mapped; a Base Manager has all three products, is on Management and is in + the alert groups of at least one team; an integration user is tagged as one; anyone else is + "other", listed so it can be corrected.""" + self._require_admin() + if license is not None and license not in LICENSES: + raise InvalidRequestError(f"license: one of {list(LICENSES)}") + cust = self._resolve(customer) + lid = self._team(cust, team).location_id if team is not None else None + out = [] + for p in self._index(cust).values(): + if license is not None and p.license != license: + continue + if lid is not None and lid not in p.teams: + continue + out.append(self._member(p)) + return out + + def license_report(self, customer: CustomerRef) -> Dict[str, Any]: + """People by license and the number of teams (Management not counted).""" + cust = self._resolve(customer) + members = self.list_members(cust) + by: Dict[str, List[Member]] = {k: [] for k in LICENSES} + for m in members: + by[m.license].append(m) + return {"base_user": len(by["base_user"]), "base_manager": len(by["base_manager"]), + "integration": len(by["integration"]), "other": len(by["other"]), + "teams": len(cust.teams), "members": by} + + # ------------------------------------------------------------------ people: low-level steps + + def _ensure_user(self, cust: Customer, person: PersonSpec, location_ids: Sequence[str]) -> Tuple[str, bool, Dict[str, Any]]: + """Find or create the person (never emailing an invitation here) and make sure they are on + ``location_ids``. Returns (id, created, company user).""" + users = self._c.users + found = users.find_user_by_email(cust.company_id, person.email) + if found is None: + body: Dict[str, Any] = { + "email": person.email, "first_name": person.first_name, "last_name": person.last_name, + "role": "frontline_user", "location_ids": list(location_ids), + "send_invitation": False, "auth_method": person.auth_method, + } + if person.phone_number: + body["phone_number"] = person.phone_number + row = unwrap(users.create_company_user(cust.company_id, body)) or {} + row.setdefault("status", "invited") + return row["id"], True, row + uid = found["id"] + if found.get("status") == "deactivated": + users.reactivate_company_user(cust.company_id, uid) + detail = unwrap(users.get_company_user(cust.company_id, uid)) or {} + if detail.get("role") != "frontline_user": + raise InvalidRequestError(f"{person.email} has role {detail.get('role')}; licensed people are frontline users") + self._add_locations(cust, uid, location_ids, detail) + return uid, False, detail + + def _add_locations(self, cust: Customer, uid: str, location_ids: Sequence[str], + detail: Optional[Dict[str, Any]] = None) -> None: + detail = detail if detail is not None else unwrap(self._c.users.get_company_user(cust.company_id, uid)) or {} + have = [x.get("location_id") for x in detail.get("locations") or []] + if any(lid not in have for lid in location_ids): + self._c.users.update_company_user(cust.company_id, uid, {"location_ids": _uniq(have + list(location_ids))}) + + def _remove_locations(self, cust: Customer, uid: str, location_ids: Sequence[str]) -> None: + detail = unwrap(self._c.users.get_company_user(cust.company_id, uid)) or {} + have = [x.get("location_id") for x in detail.get("locations") or []] + keep = [x for x in have if x not in set(location_ids)] + if keep != have: + self._c.users.update_company_user(cust.company_id, uid, {"location_ids": keep}) + + def _products_on(self, location_id: str, uid: str, keys: Iterable[str]) -> None: + row = unwrap(self._c.users.get_location_user(location_id, uid)) or {} + have = set(row.get("enabled_products") or []) + for key in keys: + if key not in have: + self._c.products.enable_user_product(location_id, uid, key) + + def _products_off(self, location_id: str, uid: str, keys: Iterable[str]) -> None: + row = unwrap(self._c.users.get_location_user(location_id, uid)) or {} + have = set(row.get("enabled_products") or []) + for key in keys: + if key in have: + self._c.products.disable_user_product(location_id, uid, key) + + def _join_groups(self, location_id: str, uid: str, group_ids: Iterable[str]) -> None: + want = [g for g in group_ids if g] + current = self._c.groups.user_group_ids(location_id, uid) + if any(g not in current for g in want): + self._c.groups.set_user_group_membership(location_id, uid, {"group_ids": _uniq(current + want)}) + + def _leave_groups(self, location_id: str, uid: str, group_ids: Optional[Iterable[str]] = None) -> None: + current = self._c.groups.user_group_ids(location_id, uid) + keep = [] if group_ids is None else [g for g in current if g not in set(group_ids)] + if keep != current: + self._c.groups.set_user_group_membership(location_id, uid, {"group_ids": keep}) + + def _email_off(self, location_id: str, uid: str, created: bool, status: Optional[str]) -> None: + """Alert email off for a person the helpers create. Someone who has signed in keeps their own + choice.""" + if not (created or status == "invited"): + return + prefs = self._c.first_alert.get_alert_notification_preferences(location_id, uid) or {} + if ((prefs.get("emailNotifications") or {}).get("masterEnabled")) is not False: + self._c.first_alert.set_alert_email_preferences(location_id, uid, {"masterEnabled": False, "alerts": []}) + + def _set_mappings(self, cust: Customer, uid: str, mappings: List[Dict[str, Any]]) -> None: + try: + self._c.users.set_user_number_mappings(cust.company_id, uid, {"mappings": mappings}) + except (ValidationError, ConflictError) as exc: + raise ExtensionMappingError(uid, exc) from exc + + def _map(self, cust: Customer, uid: str, connector_id: str, numbers: Sequence[str], + current: Optional[List[Dict[str, Any]]] = None, replace: bool = True) -> None: + """Set (``replace``) or add to the person's numbers on one connector; other connectors are kept.""" + current = current if current is not None else unwrap(self._c.users.get_user_number_mappings(cust.company_id, uid)) or [] + have = numbers_for(current, connector_id) + target = list(numbers) if replace else _uniq(have + list(numbers)) + if target == have: + return + others = [m for m in current if m.get("connector_id") != connector_id] + self._set_mappings(cust, uid, merge_mappings(others, connector_id, add=target)) + + def _invite(self, cust: Customer, uid: str, invite: bool) -> bool: + """The last step: email the invitation to a person who has none yet.""" + if not invite: + return False + detail = unwrap(self._c.users.get_company_user(cust.company_id, uid)) or {} + if detail.get("status") != "invited" or detail.get("invited_at"): + return False + self._c.users.resend_invitation(cust.company_id, uid) + return True + + def _fa_numbers(self, team: Team) -> List[str]: + cfg = unwrap(self._c.first_alert.get_first_alert_config(team.location_id)) or {} + return numbers_for(cfg.get("connector_mappings") or [], team.connector_id) + + def _ih_numbers(self, team: Team) -> List[str]: + setup = unwrap(self._c.insights_hub.get_insights_hub_setup(team.location_id)) or {} + return numbers_for(setup.get("connector_mappings") or [], team.connector_id) + + def _attach_line(self, cust: Customer, team: Team, line: str, people: Mapping[str, _Person], + exclude: Iterable[str] = ()) -> None: + """A team line onto First Alert, Insights Hub and every holder of the team's lines.""" + assert team.connector_id + if line not in self._fa_numbers(team): + self._c.first_alert.add_monitored_numbers(team.location_id, team.connector_id, [line]) + if line not in self._ih_numbers(team): + self._c.insights_hub.add_numbers(team.location_id, team.connector_id, [line]) + for h in self._holders(team, people, exclude): + if line not in h.numbers(team.connector_id): + self._map(cust, h.id, team.connector_id, [line], current=h.mappings, replace=False) + + def _release_line(self, cust: Customer, team: Team, line: str, people: Mapping[str, _Person], + leaving: str) -> bool: + """Take a team line off its holders, First Alert and Insights Hub, unless another Base User at + the team still holds it. Returns True when it was released.""" + if not team.connector_id: + return False + for p in people.values(): + if (p.id != leaving and p.active and p.license == "base_user" and team.location_id in p.teams + and line in p.numbers(team.connector_id)): + return False + for h in self._holders(team, people, exclude=[leaving]): + have = h.numbers(team.connector_id) + if line in have: + self._map(cust, h.id, team.connector_id, [n for n in have if n != line], current=h.mappings) + if line in self._fa_numbers(team): + self._c.first_alert.remove_monitored_numbers(team.location_id, team.connector_id, [line]) + if line in self._ih_numbers(team): + self._c.insights_hub.remove_numbers(team.location_id, team.connector_id, [line]) + return True + + def _need_connector(self, team: Team) -> str: + if not team.connector_id: + raise InvalidRequestError(f"{team.name} has no connector: attach one with set_connector") + return team.connector_id + + def _manager_setup(self, cust: Customer, uid: str, teams: List[Team], line: Optional[str], + company_reports: bool, created: bool, status: Optional[str], run: _Run) -> List[str]: + """Management and each team: products, groups, alert email off, lines. Returns the lines held.""" + mgmt = cust.management + assert mgmt is not None + run.step = "products" + for t in teams + [mgmt]: + self._products_on(t.location_id, uid, PRODUCT_KEYS) + run.step = "groups" + for t in teams: + self._join_groups(t.location_id, uid, [getattr(t.groups, f) for f in TEAM_GROUPS]) + if company_reports: + self._join_groups(mgmt.location_id, uid, [mgmt.groups.weekly_reports]) + run.step = "alert_email" + for t in teams: + self._email_off(t.location_id, uid, created, status) + run.step = "lines" + people = self._index(cust) + current = unwrap(self._c.users.get_user_number_mappings(cust.company_id, uid)) or [] + mappings = [dict(m) for m in current] + if line: + mappings = merge_mappings([m for m in mappings if m.get("connector_id") != mgmt.connector_id], + self._need_connector(mgmt), add=_uniq(numbers_for(current, mgmt.connector_id) + [line])) + for t in teams: + if t.connector_id: + lines = self._team_lines(t, people, exclude=[uid]) + mappings = merge_mappings(mappings, t.connector_id, add=lines) + if not _same_mappings(mappings, current): + self._set_mappings(cust, uid, mappings) + return numbers_for(mappings) + + # ------------------------------------------------------------------ people: helpers + + def add_base_user(self, customer: CustomerRef, person: PersonSpec, *, team: TeamRef, line: str, + invite: bool = True) -> Member: + """Add a Base User: created without an invitation, After Call on, their line mapped on the + team's connector and added to the team's First Alert and Insights Hub lines and to every Base + Manager and integration user of the team, then the invitation (if ``invite``). If the line + cannot be mapped, AccountError (cause ExtensionMappingError) is raised and no invitation is sent.""" + self._require_admin() + cust = self._resolve(customer) + t = self._team(cust, team) + line = _line(line) + self._need_connector(t) + result = Member(user_id="", email=person.email, license="base_user", teams=[t.location_id], lines=[line]) + run = self._run(result) + try: + run.step = "user" + uid, created, detail = self._ensure_user(cust, person, [t.location_id]) + result.user_id, result.created = uid, created + run.step = "products" + self._products_on(t.location_id, uid, [AFTER_CALL]) + run.step = "alert_email" + self._email_off(t.location_id, uid, created, detail.get("status")) + run.step = "line" + self._map(cust, uid, t.connector_id, [line]) # type: ignore[arg-type] + run.step = "team_lines" + self._attach_line(cust, t, line, self._index(cust), exclude=[uid]) + run.step = "invitation" + result.invited = self._invite(cust, uid, invite) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def add_base_manager(self, customer: CustomerRef, person: PersonSpec, *, teams: Sequence[TeamRef], + line: Optional[str] = None, company_reports: bool = False, invite: bool = True) -> Member: + """Add a Base Manager on each team and on Management: all three products; their own line at + Management (if ``line``); every Base User line of each team; the three alert groups, Insights + Hub Access and Insights Hub Weekly Reports of each team (and the company-wide weekly reports + group with ``company_reports=True``); alert email off. The invitation is sent last.""" + self._require_admin() + cust = self._resolve(customer) + if isinstance(teams, (str, Team)) or not teams: + raise InvalidRequestError("teams: a list of one or more teams") + ts = _dedupe_teams([self._team(cust, x) for x in teams]) + if cust.management is None: + raise InvalidRequestError("This customer has no Management location: run create_customer again") + own = _line(line) if line is not None else None + if own: + self._need_connector(cust.management) + result = Member(user_id="", email=person.email, license="base_manager", teams=[t.location_id for t in ts]) + run = self._run(result) + try: + run.step = "user" + uid, created, detail = self._ensure_user(cust, person, [t.location_id for t in ts] + [cust.management.location_id]) + result.user_id, result.created = uid, created + result.lines = self._manager_setup(cust, uid, ts, own, company_reports, created, detail.get("status"), run) + run.step = "invitation" + result.invited = self._invite(cust, uid, invite) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, invite: bool = True) -> Member: + """Add the customer's integration (data-reading) user across every team: password sign-in, + tagged ``department: "integration"``, all three products, the alert groups and Insights Hub + Access, alert email off, every team's lines. Later Base Users' lines are added to it. The + company needs MFA off (``CustomerSpec.mfa_off``) for it to sign in.""" + self._require_admin() + if person.auth_method != "password": + raise InvalidRequestError("An integration user signs in with a password: set auth_method='password'") + cust = self._resolve(customer) + if not cust.teams: + raise InvalidRequestError("This customer has no team") + result = Member(user_id="", email=person.email, license="integration", + teams=[t.location_id for t in cust.teams]) + run = self._run(result) + try: + run.step = "user" + uid, created, detail = self._ensure_user(cust, person, [t.location_id for t in cust.teams]) + result.user_id, result.created = uid, created + run.step = "tag" + detail = unwrap(self._c.users.get_company_user(cust.company_id, uid)) or {} + if not _is_integration(detail): + self._c.users.update_company_user(cust.company_id, uid, {"department": INTEGRATION_DEPARTMENT}) + run.step = "products" + for t in cust.teams: + self._products_on(t.location_id, uid, PRODUCT_KEYS) + run.step = "groups" + for t in cust.teams: + self._join_groups(t.location_id, uid, [getattr(t.groups, f) for f in ALERT_GROUPS + ("insights_hub_access",)]) + run.step = "alert_email" + for t in cust.teams: + self._email_off(t.location_id, uid, created, detail.get("status")) + run.step = "lines" + people = self._index(cust) + current = people[uid].mappings if uid in people else [] + mappings = [dict(m) for m in current] + for t in cust.teams: + if t.connector_id: + mappings = merge_mappings(mappings, t.connector_id, add=self._team_lines(t, people, exclude=[uid])) + if not _same_mappings(mappings, current): + self._set_mappings(cust, uid, mappings) + result.lines = numbers_for(mappings) + run.step = "invitation" + result.invited = self._invite(cust, uid, invite) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def change_license(self, customer: CustomerRef, user_id: str, to: str, *, + teams: Optional[Sequence[TeamRef]] = None, line: Optional[str] = None) -> Member: + """Base User to Base Manager (``to="base_manager"``): their own line moves to Management and they + get the products, team lines and groups of ``teams`` (default: their team). + Base Manager to Base User (``to="base_user"``): groups, team lines, the extra products and + Management are removed; they keep one team (``teams[0]``, default their first) and their own + line (``line``, default their Management line), which is added to that team's lists.""" + self._require_admin() + if to not in ("base_user", "base_manager"): + raise InvalidRequestError('to: "base_user" or "base_manager"') + cust = self._resolve(customer) + p, people = self._person(cust, user_id) + ts = _dedupe_teams([self._team(cust, x) for x in teams]) if teams else [t for t in cust.teams if t.location_id in p.teams] + mgmt = cust.management + if mgmt is None: + raise InvalidRequestError("This customer has no Management location: run create_customer again") + if p.license == to: + return self._member(p) + if p.license not in ("base_user", "base_manager"): + raise InvalidRequestError(f"User {user_id} is {p.license!r}; only Base Users and Base Managers change license") + if not ts: + raise InvalidRequestError("teams: the person is on no team; pass teams") + result = self._member(p) + run = self._run(result) + try: + if to == "base_manager": + old = [(t, n) for t in cust.teams if t.location_id in p.teams for n in p.numbers(t.connector_id)] + own = _line(line) if line is not None else (old[0][1] if old else None) + if own: + self._need_connector(mgmt) + run.step = "release_line" + current = list(p.mappings) + for t, n in old: + self._release_line(cust, t, n, people, leaving=p.id) + current = merge_mappings(current, t.connector_id, remove=[n]) # type: ignore[arg-type] + if [n for _, n in old]: + self._set_mappings(cust, p.id, current) + run.step = "locations" + self._add_locations(cust, p.id, [t.location_id for t in ts] + [mgmt.location_id]) + detail = unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {} + result.lines = self._manager_setup(cust, p.id, ts, own, False, False, detail.get("status"), run) + result.license, result.teams = "base_manager", [t.location_id for t in ts] + else: + keep = ts[0] + self._need_connector(keep) + own = _line(line) if line is not None else next(iter(p.numbers(mgmt.connector_id)), None) + if not own: + raise InvalidRequestError("line: this manager has no own line at Management; pass line") + run.step = "groups" + for t in self._locations(cust): + if t.location_id in p.locs: + self._leave_groups(t.location_id, p.id) + run.step = "products" + self._products_off(keep.location_id, p.id, [FIRST_ALERT, INSIGHTS_HUB]) + self._products_on(keep.location_id, p.id, [AFTER_CALL]) + run.step = "lines" + self._set_mappings(cust, p.id, merge_mappings([], keep.connector_id, add=[own])) # type: ignore[arg-type] + run.step = "locations" + self._add_locations(cust, p.id, [keep.location_id]) + self._remove_locations(cust, p.id, [t.location_id for t in self._locations(cust) if t is not keep]) + run.step = "team_lines" + self._attach_line(cust, keep, own, self._index(cust), exclude=[p.id]) + result.license, result.teams, result.lines = "base_user", [keep.location_id], [own] + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def move_user(self, customer: CustomerRef, user_id: str, *, from_team: TeamRef, to_team: TeamRef) -> Member: + """Move a Base User (membership and line) to another team, or swap one of a Base Manager's teams + for another. Calls captured before the move stay with the old team (``Member.notes`` says so).""" + self._require_admin() + cust = self._resolve(customer) + src, dst = self._team(cust, from_team), self._team(cust, to_team) + if src.location_id == dst.location_id: + raise InvalidRequestError("from_team and to_team are the same team") + p, people = self._person(cust, user_id) + note = f"Call history stays with {src.name}: calls captured before the move remain there." + result = self._member(p, notes=[note]) + if src.location_id not in p.teams and dst.location_id in p.teams: + return result # already moved + if src.location_id not in p.teams: + raise InvalidRequestError(f"User {user_id} is not on {src.name}") + run = self._run(result) + try: + if p.license == "base_user": + self._need_connector(dst) + nums = p.numbers(src.connector_id) if src.connector_id else [] + if len(nums) != 1: + raise InvalidRequestError("A Base User holds exactly one line; fix it with change_line first") + line = nums[0] + run.step = "release_line" + self._release_line(cust, src, line, people, leaving=p.id) + run.step = "locations" + self._add_locations(cust, p.id, [dst.location_id]) + run.step = "products" + self._products_on(dst.location_id, p.id, [AFTER_CALL]) + run.step = "line" + current = merge_mappings(p.mappings, src.connector_id, remove=[line]) # type: ignore[arg-type] + self._set_mappings(cust, p.id, merge_mappings(current, dst.connector_id, add=[line])) # type: ignore[arg-type] + run.step = "team_lines" + self._remove_locations(cust, p.id, [src.location_id]) + self._attach_line(cust, dst, line, self._index(cust), exclude=[p.id]) + result.teams, result.lines = [dst.location_id], [line] + elif p.license == "base_manager": + run.step = "leave_team" + if src.location_id in p.locs: + self._leave_groups(src.location_id, p.id) + if src.connector_id and p.numbers(src.connector_id): + self._set_mappings(cust, p.id, [m for m in p.mappings if m.get("connector_id") != src.connector_id]) + run.step = "locations" + self._add_locations(cust, p.id, [dst.location_id]) + self._remove_locations(cust, p.id, [src.location_id]) + detail = unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {} + result.lines = self._manager_setup(cust, p.id, [dst], None, False, False, detail.get("status"), run) + result.teams = _uniq([x for x in p.teams if x != src.location_id] + [dst.location_id]) + else: + raise InvalidRequestError(f"User {user_id} is {p.license!r}; only Base Users and Base Managers move") + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def change_line(self, customer: CustomerRef, user_id: str, old: str, new: str) -> Member: + """Release ``old`` everywhere it is listed for this person (their mapping, the team's holders, + First Alert and Insights Hub) and map ``new`` in its place.""" + self._require_admin() + old, new = _line(old, "old"), _line(new, "new") + cust = self._resolve(customer) + p, people = self._person(cust, user_id) + by_conn = {t.connector_id: t for t in self._locations(cust) if t.connector_id} + result = self._member(p) + run = self._run(result) + try: + current = [dict(m) for m in p.mappings] + touched = [cid for cid in by_conn if old in numbers_for(current, cid)] + run.step = "line" + if touched: + mappings = current + for cid in touched: + nums = numbers_for(current, cid) + target = _uniq([new if n == old else n for n in nums]) + mappings = merge_mappings([m for m in mappings if m.get("connector_id") != cid], cid, add=target) + self._set_mappings(cust, p.id, mappings) + result.lines = numbers_for(mappings) + run.step = "team_lines" + teams = [by_conn[cid] for cid in touched if by_conn[cid].kind == "team"] + if not touched and p.license == "base_user": + teams = [t for t in cust.teams if t.location_id in p.teams and new in p.numbers(t.connector_id)] + for t in teams: + cid = t.connector_id + for h in self._holders(t, people, exclude=[p.id]): + have = h.numbers(cid) + target = _uniq([new if n == old else n for n in have]) + if p.license == "base_user" and new not in target: + target.append(new) + if target != have: + self._map(cust, h.id, cid, target, current=h.mappings) # type: ignore[arg-type] + for getter, setter in ((self._fa_numbers, self._c.first_alert.set_monitored_numbers), + (self._ih_numbers, self._c.insights_hub.set_numbers)): + have = getter(t) + target = _uniq([new if n == old else n for n in have]) + if p.license == "base_user" and new not in target: + target.append(new) + if target != have: + setter(t.location_id, cid, target) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + + def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = False) -> Dict[str, Any]: + """Take the person out of every group, release a Base User's line (unless ``keep_lines``, and only + when no other Base User of the team holds it), clear their lines, then deactivate them. Removing + a Base Manager or an integration user never takes a line off anyone else.""" + self._require_admin() + cust = self._resolve(customer) + p, people = self._person(cust, user_id, include_inactive=True) + if not p.active: + p.mappings = unwrap(self._c.users.get_user_number_mappings(cust.company_id, p.id)) or [] + self._classify(cust, p) + out: Dict[str, Any] = {"user_id": user_id, "license": p.license, "released_lines": [], "deactivated": False} + run = self._run(out) + try: + run.step = "groups" + for t in self._locations(cust): + if t.location_id in p.locs: + self._leave_groups(t.location_id, p.id) + run.step = "release_lines" + if p.license == "base_user" and not keep_lines: + for t in cust.teams: + if t.location_id in p.teams and t.connector_id: + for n in p.numbers(t.connector_id): + if self._release_line(cust, t, n, people, leaving=p.id): + out["released_lines"].append(n) + run.step = "lines" + if p.mappings: + self._set_mappings(cust, p.id, []) + run.step = "deactivate" + if p.active: + try: + self._c.users.deactivate_company_user(cust.company_id, p.id) + out["deactivated"] = True + except ConflictError: + pass # already deactivated + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return out + + def send_invitations(self, customer: CustomerRef, *, user_ids: Optional[Sequence[str]] = None) -> List[str]: + """Email invitations to people who have not signed in. Without ``user_ids``: everyone who was + never sent one, or whose invitation has expired. With ``user_ids``: re-send to those of them who + have not signed in. Returns the ids invited.""" + self._require_admin() + cust = self._resolve(customer) + now = datetime.now(timezone.utc) + wanted = set(user_ids) if user_ids is not None else None + sent: List[str] = [] + run = self._run(sent) + try: + for p in self._index(cust).values(): + if p.status != "invited": + continue + if wanted is not None: + if p.id not in wanted: + continue + elif p.invited_at and not _expired(p.invite_expires_at, now): + continue + run.step = f"invite:{p.id}" + self._c.users.resend_invitation(cust.company_id, p.id) + sent.append(p.id) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return sent + + # ------------------------------------------------------------------ lines + + def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[str, Any]: + """Make the line lists match the people: every Base User's line is on their team's First Alert + and Insights Hub lists and on its holders; Base Managers and integration users hold exactly + their teams' lines on each team's connector; nothing else is listed. ``dry_run=True`` returns the + changes without making them. + + Returns ``{"teams": {location_id: {"lines", "first_alert", "insights_hub", "holders"}}, "applied"}``.""" + self._require_admin() + cust = self._resolve(customer) + people = self._index(cust) + diff: Dict[str, Any] = {"teams": {}, "applied": False} + plans = [] + for t in cust.teams: + if not t.connector_id: + continue + lines = self._team_lines(t, people) + fa, ih = self._fa_numbers(t), self._ih_numbers(t) + d: Dict[str, Any] = { + "team": t.name, "lines": lines, + "first_alert": {"add": [n for n in lines if n not in fa], "remove": [n for n in fa if n not in lines]}, + "insights_hub": {"add": [n for n in lines if n not in ih], "remove": [n for n in ih if n not in lines]}, + "holders": {}, + } + for h in self._holders(t, people): + have = h.numbers(t.connector_id) + add, remove = [n for n in lines if n not in have], [n for n in have if n not in lines] + if add or remove: + d["holders"][h.id] = {"add": add, "remove": remove} + diff["teams"][t.location_id] = d + plans.append((t, lines, d)) + if dry_run: + return diff + run = self._run(diff) + try: + for t, lines, d in plans: + run.step = f"sync:{t.name}" + for uid in d["holders"]: + self._map(cust, uid, t.connector_id, lines, current=people[uid].mappings) # type: ignore[arg-type] + if d["first_alert"]["add"] or d["first_alert"]["remove"]: + self._c.first_alert.set_monitored_numbers(t.location_id, t.connector_id, lines) + if d["insights_hub"]["add"] or d["insights_hub"]["remove"]: + self._c.insights_hub.set_numbers(t.location_id, t.connector_id, lines) + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + diff["applied"] = True + return diff + + # ------------------------------------------------------------------ offboarding + + def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = True) -> Dict[str, Any]: + """Stop everything for a customer who leaves, at every team and at Management, in this order: + pause each After Call webhook (its address is kept; it can't be deleted), clear each First Alert + webhook, stop each connector (ends the phone-system subscription), deactivate the integration + users, then deactivate the company. Ask your Tresic contact about retention of the customer's data.""" + self._require_admin() + cust = self._resolve(customer) + c = self._c + out: Dict[str, Any] = {"webhooks_paused": [], "first_alert_webhooks_cleared": [], + "connectors_deactivated": [], "integration_users_deactivated": [], + "company_deactivated": False} + run = self._run(out) + try: + locs = self._locations(cust) + run.step = "webhooks" + for t in locs: + hook = c.intelligence.get_after_call_webhook(t.location_id) or {} + if hook.get("webhook_url") and hook.get("enabled"): + c.intelligence.set_after_call_webhook(t.location_id, hook["webhook_url"], enabled=False) + out["webhooks_paused"].append(t.location_id) + if c.intelligence.get_first_alert_webhook(t.location_id): + c.intelligence.set_first_alert_webhook(t.location_id, None) + out["first_alert_webhooks_cleared"].append(t.location_id) + run.step = "connectors" + for t in locs: + for row in c.connectors.iter_location_connectors(t.location_id): + if row.get("status") in ("inactive", "deactivating"): + continue + try: + c.connectors.deactivate_connector(t.location_id, row["id"]) + except ConflictError: + continue # already inactive + out["connectors_deactivated"].append(row["id"]) + run.step = "integration_users" + for p in self._index(cust).values(): + if p.license != "integration": + continue + try: + c.users.deactivate_company_user(cust.company_id, p.id) + except ConflictError: + continue + out["integration_users_deactivated"].append(p.id) + run.step = "company" + if deactivate_company: + company = unwrap(c.companies.get_company(cust.company_id)) or {} + if company.get("is_active", True): + try: + c.companies.deactivate_company(cust.company_id) + out["company_deactivated"] = True + except ConflictError: + pass # already inactive + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return out + + +def _same_mappings(a: Sequence[Mapping[str, Any]], b: Sequence[Mapping[str, Any]]) -> bool: + def norm(ms: Sequence[Mapping[str, Any]]) -> Dict[str, List[str]]: + out: Dict[str, List[str]] = {} + for m in ms: + nums = list(m.get("monitored_numbers") or []) + if nums: + out.setdefault(m.get("connector_id") or "", []).extend(nums) + return out + return norm(a) == norm(b) + + +def _dedupe_teams(teams: List[Team]) -> List[Team]: + seen, out = set(), [] + for t in teams: + if t.location_id not in seen: + seen.add(t.location_id) + out.append(t) + return out + + +def _expired(when: Optional[str], now: datetime) -> bool: + if not when: + return False + try: + return datetime.fromisoformat(when.replace("Z", "+00:00")) < now + except ValueError: + return False diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index 7670271..ef00bc5 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -58,7 +58,9 @@ class Client: """Signs in with an integration user's email and password and calls the API. One client per credential. Admin (reseller admin) and frontline logins see different data: - use one client for each. + use one client for each. ``client.accounts`` needs an administrator login and + ``client.conversations`` a user login. ``mask_numbers=False`` shows caller numbers in full in + ``client.conversations`` (by default only their last four digits are shown). >>> client = Client(email="integration@example.com", password="...") >>> client.intelligence.whoami()["role"] @@ -78,6 +80,7 @@ def __init__( sleep: Callable[[float], None] = time.sleep, login_rate_limit_wait: float = LOGIN_RATE_LIMIT_WAIT, keep_unknown_fields: bool = False, + mask_numbers: bool = True, ): self.base_url = check_base_url(base_url).rstrip("/") self._email = email @@ -88,6 +91,9 @@ def __init__( self._sleep = sleep self._login_wait = max(0.0, float(login_rate_limit_wait)) self.keep_unknown_fields = keep_unknown_fields + # client.conversations shows caller numbers as their last four digits unless this is False. + self.mask_numbers = mask_numbers + self._writes = 0 # write requests attempted; account helpers use it to tell a clean stop from a partial one ua = f"intelligence-cloud-python/{__version__}" if user_agent: ua = f"{user_agent} {ua}" @@ -99,8 +105,9 @@ def __init__( FirstAlertAPI, GroupsAPI, InsightsAPI, InsightsHubAPI, LocationsAPI, ProductsAPI, ResellersAPI, SsoAPI, TasksAPI, UsersAPI, WebhooksAPI, ) + from .accounts import Accounts + from .conversations import Conversations from .intelligence import Intelligence - from .workflows import Workflows self.resellers = ResellersAPI(self) self.companies = CompaniesAPI(self) @@ -120,7 +127,8 @@ def __init__( self.insights = InsightsAPI(self) self.webhooks = WebhooksAPI(self) self.intelligence = Intelligence(self) - self.workflows = Workflows(self) + self.accounts = Accounts(self) + self.conversations = Conversations(self) def __repr__(self) -> str: return f"Client(base_url={self.base_url!r}, email={self._email!r})" @@ -400,6 +408,8 @@ def _build(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any], def _request(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any], body: Any, headers: Optional[Dict[str, str]] = None) -> httpx.Response: op, url_path, params = self._build(op_id, path, query, body) + if op["method"] != "GET": + self._writes += 1 resp = self._send_with_retries(op["method"], url_path, op_id=op_id, params=params, json_body=dict(body) if body is not None else None, headers=headers) if resp.status_code >= 400: diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py new file mode 100644 index 0000000..e16a6a8 --- /dev/null +++ b/src/intelligence_cloud/conversations.py @@ -0,0 +1,491 @@ +"""The conversation layer: what a signed-in person does with their own calls, tasks and alerts. + +Sign in as the person (a user login). The platform decides what each call returns: a Base User gets +their own calls, a Base Manager their teams'. An administrator login raises :class:`WrongLoginError`. + +Careful defaults: caller numbers are shown as their last four digits unless the client was created +with ``mask_numbers=False``; windows are at most 31 days; lists are capped (``limit``); the printed +form of a brief shows only its id and time; nothing here writes call content to logs. There is no +helper that walks every call: for a bounded daily job use ``client.intelligence.iter_calls``. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date, datetime, time, timedelta, timezone +from typing import Any, Dict, List, Mapping, Optional, Sequence, Union + +from ._base import Namespace, Page, unwrap +from ._spec import is_uuid +from .errors import InvalidRequestError, WrongLoginError +from .intelligence import RecordingLink, _search_term +from .receiver import FirstAlertEvent, parse_first_alert_event + +MAX_WINDOW_DAYS = 31 +MAX_LIMIT = 200 +MAX_HISTORY = 50 +_PAGE = 100 # the API's largest page + +When = Union[datetime, str] + + +def mask_number(number: Optional[str]) -> Optional[str]: + """``***`` and the last four digits. Extensions (four digits or fewer) are shown as they are.""" + if not number: + return number + digits = "".join(ch for ch in str(number) if ch.isdigit()) + if len(digits) <= 4: + return number + return "***" + digits[-4:] + + +def _parse_time(value: Any) -> Optional[datetime]: + if not isinstance(value, str) or not value: + return None + try: + dt = datetime.fromisoformat(value.replace("Z", "+00:00").replace("z", "+00:00")) + except ValueError: + try: + dt = datetime.combine(date.fromisoformat(value[:10]), time(), tzinfo=timezone.utc) + except ValueError: + return None + return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc) + + +@dataclass +class TeamRef: + """A team (location) this person can see.""" + + location_id: str + name: str + kind: str = "team" # "team" or "management" + + +@dataclass +class Me: + user_id: str + email: Optional[str] + name: Optional[str] + role: Optional[str] + company_id: Optional[str] + teams: List[TeamRef] = field(default_factory=list) + # The person's own lines. The API gives a user login no way to read them yet: None. + lines: Optional[List[str]] = None + + +@dataclass(repr=False) +class TaskBrief: + id: str + title: Optional[str] = None + status: Optional[str] = None + due_date: Optional[str] = None + call_id: Optional[str] = None + description: Optional[str] = None + + def __repr__(self) -> str: + return f"TaskBrief(id={self.id!r}, status={self.status!r}, due_date={self.due_date!r})" + + +@dataclass(repr=False) +class CallBrief: + """One call, without transcript or recording. Printing it shows only the id and time.""" + + id: str + when: Optional[datetime] = None + direction: Optional[str] = None # inbound, outbound, internal, missed, forwarded or unknown + status: Optional[str] = None + duration_seconds: Optional[int] = None + caller_name: Optional[str] = None + caller_number: Optional[str] = None # last four digits unless the client has mask_numbers=False + callee_name: Optional[str] = None + callee_number: Optional[str] = None + summary: Optional[str] = None + key_points: List[str] = field(default_factory=list) # from brief(); empty in list results + tasks: List[TaskBrief] = field(default_factory=list) # from brief(); see task_count in list results + task_count: Optional[int] = None + sentiment: Optional[str] = None + sentiment_score: Optional[int] = None + topics: List[str] = field(default_factory=list) + alerts: List[str] = field(default_factory=list) # names of the alerts the call raised (brief() only) + location_id: Optional[str] = None + + def __repr__(self) -> str: + return f"CallBrief(id={self.id!r}, when={self.when.isoformat() if self.when else None!r})" + + __str__ = __repr__ + + +@dataclass(repr=False) +class AlertBrief: + """One First Alert hit. Printing it shows only the id and time.""" + + id: str + call_id: Optional[str] = None + when: Optional[datetime] = None + alerts: List[str] = field(default_factory=list) # the alert (rule) names that fired + caller_name: Optional[str] = None + caller_number: Optional[str] = None + callee_name: Optional[str] = None + callee_number: Optional[str] = None + summary: Optional[str] = None + sentiment: Optional[str] = None + sentiment_score: Optional[int] = None + topics: List[str] = field(default_factory=list) + holder: Optional[str] = None # who holds the alert; the API does not publish it yet + call: Optional[CallBrief] = None # set by alert() + + def __repr__(self) -> str: + return f"AlertBrief(id={self.id!r}, when={self.when.isoformat() if self.when else None!r})" + + __str__ = __repr__ + + +@dataclass +class TeamView: + team: str # location id + since: datetime + until: datetime + counts: Dict[str, int] = field(default_factory=dict) + alerts: List[AlertBrief] = field(default_factory=list) + open_tasks: List[TaskBrief] = field(default_factory=list) + briefs: List[CallBrief] = field(default_factory=list) + + +@dataclass +class TopicsView: + since: datetime + until: datetime + calls: Dict[str, int] = field(default_factory=dict) # total, answered, unanswered + topics: List[Dict[str, Any]] = field(default_factory=list) # name, slug, call_count + rising: List[Dict[str, Any]] = field(default_factory=list) # name, slug, call_count, percentage_change + + +@dataclass +class Reference: + """An id to pass to another system in place of content.""" + + kind: str # "call" or "alert" + id: str + link: Optional[str] = None # the app link; the API does not publish app links yet + + +class Conversations(Namespace): + """A signed-in person's calls, tasks and alerts (user login).""" + + def __init__(self, client: Any): + super().__init__(client) + self._me: Optional[Dict[str, Any]] = None + + # ------------------------------------------------------------------ plumbing + + def _require_user(self) -> Dict[str, Any]: + if self._me is None: + self._me = unwrap(self._c.account.get_me()) or {} + if self._me.get("role") != "frontline_user": + raise WrongLoginError(self._me.get("role"), "user") + return self._me + + def _mask(self, number: Optional[str]) -> Optional[str]: + return mask_number(number) if self._c.mask_numbers else number + + @staticmethod + def _limit(limit: int, top: int) -> int: + if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= top: + raise InvalidRequestError(f"limit: 1 to {top}") + return limit + + @staticmethod + def _when(value: When, name: str) -> datetime: + if isinstance(value, str): + try: + parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00").replace("z", "+00:00")) + except ValueError: + parsed = None + if parsed is None or parsed.tzinfo is None: + raise InvalidRequestError(f"{name}: an RFC 3339 date-time with a time zone") + return parsed + if not isinstance(value, datetime): + raise InvalidRequestError(f"{name}: a datetime") + if value.tzinfo is None: + raise InvalidRequestError(f"{name}: a datetime with a time zone") + return value + + def _window(self, day: Optional[Union[date, datetime]], since: Optional[When], until: Optional[When], + default_days: Optional[int] = None) -> tuple: + """(start, end). Default: today (local time), or the last ``default_days`` days. At most 31 days.""" + if day is not None and (since is not None or until is not None): + raise InvalidRequestError("Pass day, or since/until, not both") + local = datetime.now().astimezone().tzinfo + if day is not None: + if isinstance(day, datetime): + d = self._when(day, "day") + start = d.replace(hour=0, minute=0, second=0, microsecond=0) + elif isinstance(day, date): + start = datetime.combine(day, time(), tzinfo=local) + else: + raise InvalidRequestError("day: a date") + return start, start + timedelta(days=1) - timedelta(seconds=1) + end = self._when(until, "until") if until is not None else datetime.now(timezone.utc).astimezone(local) + if since is not None: + start = self._when(since, "since") + elif default_days: + start = end - timedelta(days=default_days) + else: + start = datetime.combine(end.astimezone(local).date(), time(), tzinfo=local) + if end <= start: + raise InvalidRequestError("until must be after since") + if end - start > timedelta(days=MAX_WINDOW_DAYS): + raise InvalidRequestError(f"The window is at most {MAX_WINDOW_DAYS} days") + return start, end + + def _team_id(self, team: Optional[Union[str, TeamRef]]) -> Optional[str]: + if team is None: + return None + if isinstance(team, TeamRef): + return team.location_id + if hasattr(team, "location_id"): + return getattr(team, "location_id") + if isinstance(team, str) and is_uuid(team.strip()): + return team.strip().lower() + if isinstance(team, str): + for t in self.teams(): + if t.name == team: + return t.location_id + raise InvalidRequestError(f"Unknown team {team!r}: use a TeamRef, its location id or its name") + + def _pages(self, fetch, limit: int) -> List[Any]: + out: List[Any] = [] + cursor = None + while len(out) < limit: + page: Page = fetch(min(_PAGE, limit - len(out)), cursor) + out.extend(page.items) + if not page.has_more or not page.next_cursor: + break + cursor = page.next_cursor + return out[:limit] + + def _brief_from_row(self, row: Mapping[str, Any]) -> CallBrief: + return CallBrief( + id=row.get("id") or "", + when=_parse_time(row.get("call_date")), + direction=row.get("call_type"), + status=row.get("status"), + duration_seconds=row.get("duration"), + caller_name=row.get("caller_name"), + caller_number=self._mask(row.get("caller_number")), + callee_name=row.get("callee_name"), + callee_number=self._mask(row.get("callee_number")), + summary=row.get("summary"), + task_count=row.get("task_count"), + sentiment=row.get("sentiment") or row.get("sentiment_label"), + sentiment_score=row.get("sentiment_score"), + location_id=row.get("location_id"), + ) + + def _alert_from_row(self, row: Mapping[str, Any]) -> AlertBrief: + return AlertBrief( + id=row.get("id") or "", + call_id=row.get("call_id"), + when=_parse_time(row.get("call_date")), + alerts=list(row.get("keywords") or []), + caller_name=row.get("caller_name"), + caller_number=self._mask(row.get("caller_number")), + callee_name=row.get("callee_name"), + callee_number=self._mask(row.get("callee_number")), + summary=row.get("summary"), + sentiment=row.get("sentiment") or row.get("sentiment_label"), + sentiment_score=row.get("sentiment_score"), + topics=list(row.get("topics") or []), + ) + + @staticmethod + def _task_from_row(row: Mapping[str, Any]) -> TaskBrief: + return TaskBrief(id=row.get("id") or "", title=row.get("title"), status=row.get("status"), + due_date=row.get("due_date"), call_id=row.get("call_id"), description=row.get("description")) + + # ------------------------------------------------------------------ who + + def me(self) -> Me: + """Who is signed in, and their teams. (Their own lines are not readable with a user login yet.)""" + me = self._require_user() + name = me.get("display_name") or " ".join(x for x in (me.get("first_name"), me.get("last_name")) if x) or None + return Me(user_id=me.get("id") or "", email=me.get("email"), name=name, role=me.get("role"), + company_id=me.get("company_id"), teams=self.teams()) + + def teams(self) -> List[TeamRef]: + """The teams (locations) this person can see. Management is listed with ``kind="management"``.""" + self._require_user() + out = [] + for loc in self._c.account.iter_visible_locations(): + name = loc.get("location_name") or "" + out.append(TeamRef(location_id=loc.get("id") or "", name=name, + kind="management" if name.endswith(" - Management") else "team")) + return out + + # ------------------------------------------------------------------ calls + + def calls(self, *, day: Optional[Union[date, datetime]] = None, since: Optional[When] = None, + until: Optional[When] = None, team: Optional[Union[str, TeamRef]] = None, + number: Optional[str] = None, search: Optional[str] = None, limit: int = 50) -> List[CallBrief]: + """Calls, newest first, as briefs. Default: today. The window is at most 31 days and ``limit`` at + most 200. ``number`` and ``search`` share the API's one search field: pass one or the other.""" + self._require_user() + limit = self._limit(limit, MAX_LIMIT) + start, end = self._window(day, since, until) + term = _search_term(number, search) + lid = self._team_id(team) + rows = self._pages(lambda n, cur: self._c.calls.list_calls( + date_from=start, date_to=end, search=term, location_id=lid, limit=n, cursor=cur), limit) + return [self._brief_from_row(r) for r in rows] + + def brief(self, call_id: str) -> CallBrief: + """One call: when, direction, parties, summary, key points, tasks, sentiment, topics and the alerts + it raised. No transcript and no recording.""" + self._require_user() + data = unwrap(self._c.calls.get_call(call_id)) or {} + b = self._brief_from_row(data) + analysis = data.get("analysis") or {} + summ = analysis.get("summary") or {} + b.summary = b.summary or summ.get("text") + b.key_points = list(summ.get("key_points") or []) + b.sentiment = b.sentiment or (analysis.get("sentiment") or {}).get("overall") + b.topics = [t.get("name") for t in analysis.get("topics") or [] if isinstance(t, dict) and t.get("name")] + b.tasks = [self._task_from_row(dict(t, call_id=b.id)) for t in data.get("tasks") or []] + b.task_count = data.get("task_count", len(b.tasks)) + if b.when is not None: + day0 = b.when.astimezone(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0) + page = self._c.alerts.list_alerts(date_from=day0, date_to=day0 + timedelta(days=1) - timedelta(seconds=1), + limit=_PAGE) + names: List[str] = [] + for a in page.items: + if a.get("call_id") == b.id: + names.extend(k for k in a.get("keywords") or [] if k not in names) + b.alerts = names + return b + + def transcript(self, call_id: str) -> List[Dict[str, Any]]: + """The transcript of one call: segments with ``time``, ``speaker``, ``name`` and ``text``.""" + self._require_user() + data = unwrap(self._c.calls.get_call_transcript(call_id)) or {} + return data.get("transcript") or [] + + def recording_link(self, call_id: str) -> Optional[RecordingLink]: + """A link to the call's audio that expires, or None when the call has no recording. The SDK + never downloads the audio. Treat the link as a secret: never log or store it.""" + self._require_user() + return self._c.intelligence.get_recording_url(call_id) + + def caller_history(self, number: str, *, limit: int = 10) -> List[CallBrief]: + """Recent briefs for one caller (the last 31 days), for use before a callback. ``limit`` at most 50.""" + self._require_user() + limit = self._limit(limit, MAX_HISTORY) + term = _search_term(number, None) + start, end = self._window(None, None, None, default_days=MAX_WINDOW_DAYS) + rows = self._pages(lambda n, cur: self._c.calls.list_calls( + date_from=start, date_to=end, search=term, limit=n, cursor=cur), limit) + return [self._brief_from_row(r) for r in rows] + + # ------------------------------------------------------------------ tasks and alerts + + def open_tasks(self, *, due: Optional[Union[date, str]] = None, + team: Optional[Union[str, TeamRef]] = None) -> List[TaskBrief]: + """Open tasks (up to 200), each with the id of the call it came from. ``due``: only tasks due that day.""" + self._require_user() + lid = self._team_id(team) + rows = self._pages(lambda n, cur: self._c.tasks.list_tasks( + status="open", due_on=due, location_id=lid, limit=n, cursor=cur), MAX_LIMIT) + return [self._task_from_row(r) for r in rows] + + def alerts(self, *, since: Optional[When] = None, until: Optional[When] = None, + team: Optional[Union[str, TeamRef]] = None, status: Optional[str] = None, + limit: int = 50) -> List[AlertBrief]: + """Alerts on this person's teams, newest first. Default: today; at most 31 days and 200 alerts. + ``status`` is refused: the API has no alert status filter yet.""" + self._require_user() + if status is not None: + raise InvalidRequestError("status: the API has no alert status filter yet") + limit = self._limit(limit, MAX_LIMIT) + start, end = self._window(None, since, until) + lid = self._team_id(team) + rows = self._pages(lambda n, cur: self._c.alerts.list_alerts( + date_from=start, date_to=end, location_id=lid, limit=n, cursor=cur), limit) + return [self._alert_from_row(r) for r in rows] + + def alert(self, alert_id: str) -> Optional[AlertBrief]: + """One alert with its call brief, or None when this login cannot see it.""" + self._require_user() + aid = str(alert_id).strip().lower() + page = self._c.alerts.list_alerts(search=aid, limit=10) + row = next((a for a in page.items if a.get("id") == aid), None) + if row is None: + return None + out = self._alert_from_row(row) + if out.call_id: + out.call = self.brief(out.call_id) + return out + + def team_view(self, team: Union[str, TeamRef], *, day: Optional[Union[date, datetime]] = None, + since: Optional[When] = None, until: Optional[When] = None) -> TeamView: + """For a manager: one team's counts, alerts, open tasks and briefs (up to 200) for a day or a + window of at most 31 days. Default: today.""" + self._require_user() + lid = self._team_id(team) + if lid is None: + raise InvalidRequestError("team is required") + start, end = self._window(day, since, until) + first = self._c.calls.list_calls(date_from=start, date_to=end, location_id=lid, limit=_PAGE) + rows = list(first.items) + if first.has_more and first.next_cursor: + rows += self._c.calls.list_calls(date_from=start, date_to=end, location_id=lid, limit=_PAGE, + cursor=first.next_cursor).items + data = first.raw.get("data") if isinstance(first.raw, dict) else None + summary = (data or {}).get("summary") if isinstance(data, dict) else None + counts = {k: v for k, v in (summary or {}).items() if isinstance(v, int)} + alerts = self._pages(lambda n, cur: self._c.alerts.list_alerts( + date_from=start, date_to=end, location_id=lid, limit=n, cursor=cur), MAX_LIMIT) + tasks = self._pages(lambda n, cur: self._c.tasks.list_tasks( + status="open", location_id=lid, limit=n, cursor=cur), MAX_LIMIT) + return TeamView(team=lid, since=start, until=end, counts=counts, + alerts=[self._alert_from_row(a) for a in alerts], + open_tasks=[self._task_from_row(t) for t in tasks], + briefs=[self._brief_from_row(r) for r in rows[:MAX_LIMIT]]) + + def topics(self, *, since: Optional[When] = None, until: Optional[When] = None, + team: Optional[Union[str, TeamRef]] = None) -> TopicsView: + """What customers are raising and which topics are rising. Default: the last 7 days; at most 31. + Needs Insights Hub access.""" + self._require_user() + start, end = self._window(None, since, until, default_days=7) + lid = self._team_id(team) + data = unwrap(self._c.insights.get_insights_dashboard(start=start, end=end, location_id=lid)) or {} + stats = data.get("stats") or {} + rising = [dict(t) for t in data.get("trending_topics") or [] if (t.get("percentage_change") or 0) > 0] + rising.sort(key=lambda t: t.get("percentage_change") or 0, reverse=True) + for t in rising: + t.pop("trend_data", None) + return TopicsView( + since=start, until=end, + calls={"total": stats.get("total_calls", 0), "answered": stats.get("answered_calls", 0), + "unanswered": stats.get("unanswered_calls", 0)}, + topics=[dict(t) for t in data.get("topic_call_volumes") or []], + rising=rising) + + # ------------------------------------------------------------------ passing on + + @staticmethod + def reference(call_or_alert: Union[CallBrief, AlertBrief, FirstAlertEvent, str]) -> Reference: + """The id only, for passing to another system in place of content. A string is taken as a call id.""" + if isinstance(call_or_alert, CallBrief): + return Reference(kind="call", id=call_or_alert.id) + if isinstance(call_or_alert, AlertBrief): + return Reference(kind="alert", id=call_or_alert.id) + if isinstance(call_or_alert, FirstAlertEvent): + return Reference(kind="alert", id=call_or_alert.alert_id) + if isinstance(call_or_alert, str) and call_or_alert.strip(): + return Reference(kind="call", id=call_or_alert.strip()) + raise InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") + + @staticmethod + def parse_first_alert_event(payload: Any) -> FirstAlertEvent: + """A typed First Alert event, beside ``parse_after_call_event``. See + :func:`intelligence_cloud.parse_first_alert_event`.""" + return parse_first_alert_event(payload) diff --git a/src/intelligence_cloud/errors.py b/src/intelligence_cloud/errors.py index ffea36c..a7b8a06 100644 --- a/src/intelligence_cloud/errors.py +++ b/src/intelligence_cloud/errors.py @@ -129,10 +129,10 @@ def __init__(self, connector: Any, waited: float): class ExtensionMappingError(IntelligenceCloudError): - """A workflow created or updated the user, but could not map the user's numbers. + """A helper created or updated the user, but could not map the user's numbers. - The usual cause is a connector that is not ``active`` yet. Fix the connector, then run the workflow - again (it finds the user and carries on) or call ``sync_numbers``. + The usual cause is a connector that is not ``active`` yet. Fix the connector, then run the helper + again (it finds the user and carries on) or call ``accounts.sync_lines``. """ def __init__(self, user_id: Optional[str], cause: ApiError): @@ -142,8 +142,42 @@ def __init__(self, user_id: Optional[str], cause: ApiError): "connector and extensions no other location monitors.") +class AccountError(IntelligenceCloudError): + """An account helper stopped part-way. + + ``step`` names the step it reached, ``result`` is the result so far (the same type the helper + returns) and ``cause`` is the error that stopped it. Run the helper again with the same input: it + finds what exists and carries on. + """ + + def __init__(self, step: str, result: Any, cause: BaseException): + self.step = step + self.result = result + self.cause = cause + super().__init__(f"Stopped at step {step!r}: {cause}. Run the helper again to continue.") + + +class WrongLoginError(IntelligenceCloudError): + """The helper needs the other kind of login. + + Account helpers (``client.accounts``) need an administrator login. Conversation helpers + (``client.conversations``) need the person's own user login. + """ + + def __init__(self, role: Optional[str], needed: str): + self.role = role + self.needed = needed + if needed == "admin": + text = (f"This login has role {role!r}. Account helpers need an administrator login: " + "create the client with an administrator's email and password.") + else: + text = (f"This login has role {role!r}. Conversation helpers need a user login: " + "sign in as the person whose calls, tasks and alerts you want.") + super().__init__(text) + + class WebhookPayloadError(IntelligenceCloudError, ValueError): - """The webhook body is not JSON, or is a malformed After Call event. Answer 400.""" + """The webhook body is not JSON, or is a malformed After Call or First Alert event. Answer 400.""" class PayloadTooLargeError(WebhookPayloadError): diff --git a/src/intelligence_cloud/receiver.py b/src/intelligence_cloud/receiver.py index 985e868..c5218db 100644 --- a/src/intelligence_cloud/receiver.py +++ b/src/intelligence_cloud/receiver.py @@ -1,4 +1,4 @@ -"""Receive the After Call webhook: parse the event and drop duplicates. +"""Receive the After Call and First Alert webhooks: parse the event and drop duplicates. The webhook sends every call at the location, unsigned. Use an unguessable HTTPS URL, answer 2xx within 2 seconds and do the work afterwards. Treat an event as a notification: read the call with @@ -153,6 +153,90 @@ def parse_after_call_event(body: Union[bytes, str, Mapping[str, Any]], ) +@dataclass(repr=False) +class FirstAlertEvent: + """A First Alert delivery. Take the alert id, answer 2xx, then read the alert with + ``client.conversations.alert(event.alert_id)``. Printing it shows only the alert id and time. + + The published event schema is an open object (alert id, rule, location, call, time), so only the + alert id is required; the other fields are None when the delivery does not carry them.""" + + alert_id: str + rule: Optional[str] = None + location_id: Optional[str] = None + call_id: Optional[str] = None + timestamp: Optional[datetime] = None + is_test: bool = False + raw: Dict[str, Any] = field(default_factory=dict, repr=False) + + def __repr__(self) -> str: + when = self.timestamp.isoformat() if self.timestamp else None + return f"FirstAlertEvent(alert_id={self.alert_id!r}, timestamp={when!r})" + + __str__ = __repr__ + + +def _first_str(*values: Any) -> Optional[str]: + for v in values: + if isinstance(v, str) and v.strip(): + return v.strip() + return None + + +def _uuid(value: Optional[str]) -> Optional[str]: + if value is None: + return None + return value.lower() if _spec.is_uuid(value) else None + + +def _load(body: Union[bytes, str, Mapping[str, Any]], max_bytes: int) -> Mapping[str, Any]: + if isinstance(body, str): + body = body.encode("utf-8") + if isinstance(body, (bytes, bytearray)): + if max_bytes and len(body) > max_bytes: + raise PayloadTooLargeError(f"body is larger than {max_bytes} bytes") + try: + body = json.loads(bytes(body).decode("utf-8")) + except (ValueError, UnicodeDecodeError): + raise WebhookPayloadError("body is not JSON") from None + if not isinstance(body, Mapping): + raise WebhookPayloadError("body is not a JSON object") + return body + + +def parse_first_alert_event(body: Union[bytes, str, Mapping[str, Any]], + max_bytes: int = MAX_EVENT_BYTES) -> FirstAlertEvent: + """Parse a First Alert webhook body into a :class:`FirstAlertEvent`. + + Raises :class:`PayloadTooLargeError` (answer 413) above ``max_bytes`` and + :class:`WebhookPayloadError` (answer 400) for a body that is not JSON or carries no alert id.""" + data = _load(body, max_bytes) + + def sub(key: str) -> Mapping[str, Any]: + v = data.get(key) + return v if isinstance(v, Mapping) else {} + + alert, rule, call, loc = sub("alert"), sub("rule"), sub("call"), sub("location") + alert_id = _uuid(_first_str(data.get("alert_id"), alert.get("id"), data.get("id"))) + if alert_id is None: + raise WebhookPayloadError("event has no alert id") + stamp = _first_str(data.get("timestamp"), data.get("fired_at"), data.get("created_at"), alert.get("created_at")) + try: + when = _ts(stamp, "timestamp") if stamp else None + except WebhookPayloadError: + when = None + return FirstAlertEvent( + alert_id=alert_id, + rule=_first_str(data.get("rule_name"), rule.get("name"), data.get("rule") if isinstance(data.get("rule"), str) else None, + data.get("alert_name"), alert.get("rule_name"), alert.get("name")), + location_id=_uuid(_first_str(data.get("location_id"), loc.get("id"), alert.get("location_id"))), + call_id=_uuid(_first_str(data.get("call_id"), call.get("id"), alert.get("call_id"))), + timestamp=when, + is_test=data.get("is_test") is True, + raw=dict(data), + ) + + class DedupStore(Protocol): """Remembers which keys were seen. ``add`` returns True when the key is new.""" diff --git a/src/intelligence_cloud/workflows.py b/src/intelligence_cloud/workflows.py deleted file mode 100644 index 2a5dcf3..0000000 --- a/src/intelligence_cloud/workflows.py +++ /dev/null @@ -1,791 +0,0 @@ -"""Base Intelligence Seat lifecycle: provision a customer, add and remove users, keep numbers in sync. - -A Seat customer is one company with one location, two alert rules ("Upset Customer", "Customer -Threat") routed to a "Manager Alerts" group, and an "Insights Hub Access" group. - -- **End users** (frontline) have After Call on their own line. -- **Managers** have After Call on all lines, First Alert and Insights Hub. A manager's own phone - line is never captured on the Seat: their mapping is exactly the end users' lines. -- **Integration users** (``add_integration_user``) read data for another system. They hold every - line like a manager but are tagged ``department: "integration"``, are never counted as seats or - managers, and removing one never takes a line off anyone else. - -Every workflow is safe to run again. Store the returned ``company_id`` and pass it in -``SeatCustomerSpec.company_id`` on re-runs: a company is never adopted by its name alone. -""" -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any, Dict, Iterable, List, Optional, Tuple - -from ._base import Namespace, unwrap -from ._spec import is_uuid -from .errors import ( - ApiError, - ConflictError, - ConnectorError, - ConnectorTimeoutError, - ExtensionMappingError, - InvalidRequestError, - ValidationError, -) -from .resources import PRODUCT_KEYS, numbers_for - -AFTER_CALL = "after-call-copilot" -FIRST_ALERT = "first-alert-copilot" -INSIGHTS_HUB = "insights-hub" -INTEGRATION_DEPARTMENT = "integration" -COMPANY_NAME_CONFLICT = "company_name_conflict" -MANAGER_ALERTS_GROUP = "Manager Alerts" -INSIGHTS_HUB_GROUP = "Insights Hub Access" -UPSET_CUSTOMER_RULE = "Upset Customer" -CUSTOMER_THREAT_RULE = "Customer Threat" -UPSET_CUSTOMER_THRESHOLD = -40 -THREAT_PHRASES_MISSING = "Customer Threat phrases are provided by your Tresic contact." -CUSTOMER_THREAT_THRESHOLD = -20 - - -def upset_customer_rule(group_ids: List[str], enabled: bool = False) -> Dict[str, Any]: - return { - "name": UPSET_CUSTOMER_RULE, "priority": "high", "match_logic": "any", "enabled": enabled, - "triggers": [{"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": UPSET_CUSTOMER_THRESHOLD}}], - "group_ids": group_ids, - } - - -def customer_threat_rule(group_ids: List[str], phrases: List[str], enabled: bool = False) -> Dict[str, Any]: - """The Customer Threat alert: sentiment below -20 and any of the phrases. Phrases come from your - Tresic contact.""" - if not phrases: - raise InvalidRequestError(THREAT_PHRASES_MISSING) - return { - "name": CUSTOMER_THREAT_RULE, "priority": "critical", "match_logic": "all", "enabled": enabled, - "triggers": [ - {"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": CUSTOMER_THREAT_THRESHOLD}}, - {"trigger_type": "keyword_match", "config": {"keywords": phrases, "match_logic": "any"}}, - ], - "group_ids": group_ids, - } - - -@dataclass -class LocationSpec: - name: str - street: str - city: str - state: str - country: str - zipcode: str - vertical: str # vertical id, or its key from list_verticals (e.g. the key for service providers) - - -@dataclass -class ConnectorSpec: - api_url: str # full API root ending in /ns-api/v2 - domain: str - api_key: str = field(repr=False) # read/write key - name: Optional[str] = None # default " - NetSapiens" - timeout: float = 600.0 # seconds to wait for the connector to settle - - -@dataclass -class SeatCustomerSpec: - company_name: str - admin_name: str # primary contact; invited as customer admin by email - admin_email: str - admin_phone: str - location: LocationSpec - reseller_id: Optional[str] = None # default: the signed-in reseller - company_code: Optional[str] = None - mfa_off: bool = False # True for a company whose users include an integration user - threat_phrases: Optional[List[str]] = None # required to create the Customer Threat alert (from your Tresic contact) - connector: Optional[ConnectorSpec] = None - sso_domain: Optional[str] = None - reactivate: bool = False # reactivate a company or location found inactive - # The company to use, from an earlier run. Without it, a company with the same name is reused only - # when its primary contact email is admin_email; otherwise ConflictError is raised. - company_id: Optional[str] = None - - -@dataclass -class SeatCustomer: - company_id: str - location_id: str - manager_alerts_group_id: Optional[str] = None - insights_hub_group_id: Optional[str] = None - upset_customer_rule_id: Optional[str] = None - customer_threat_rule_id: Optional[str] = None - connector_id: Optional[str] = None - connector_status: Optional[str] = None - connector_state_reason: Optional[str] = None - sso_domain_id: Optional[str] = None - sso_txt_record: Optional[Dict[str, str]] = None # {"name": ..., "value": ...} for the customer's DNS - created: List[str] = field(default_factory=list) - existing: List[str] = field(default_factory=list) - # Users every workflow ignores (not seats, managers or integration users; their lines don't count). - exclude_user_ids: List[str] = field(default_factory=list) - exclude_emails: List[str] = field(default_factory=list) - - -@dataclass -class UserSpec: - email: str - first_name: str - last_name: str - phone_number: Optional[str] = None - # Email the invitation once the user is fully set up (lines mapped, groups and products on). - # False: create the user without an invitation; send one later with users.resend_invitation. - send_invitation: bool = True - auth_method: str = "password" - - -@dataclass -class SeatUser: - user_id: str - email: str - kind: str # "frontline", "manager" or "integration" - numbers: List[str] = field(default_factory=list) - created: bool = False - invited: bool = False # an invitation was emailed by this call - alerts_activated: List[str] = field(default_factory=list) # rule ids switched on by this call - - -def _products(row: Dict[str, Any]) -> set: - return set(row.get("enabled_products") or []) - - -def is_integration(row: Dict[str, Any]) -> bool: - """An integration (data-reading) user: tagged ``department: "integration"``.""" - return (row.get("department") or "").strip().lower() == INTEGRATION_DEPARTMENT - - -def _active_frontline(row: Dict[str, Any]) -> bool: - return row.get("status") != "deactivated" and row.get("role") == "frontline_user" - - -def is_manager(row: Dict[str, Any]) -> bool: - """A manager: all three products (After Call, First Alert, Insights Hub), not an integration user.""" - return _active_frontline(row) and not is_integration(row) and set(PRODUCT_KEYS) <= _products(row) - - -def is_frontline(row: Dict[str, Any]) -> bool: - """An end user (a seat): After Call only, not an integration user.""" - return _active_frontline(row) and not is_integration(row) and _products(row) == {AFTER_CALL} - - -def _uniq(values: Iterable[str]) -> List[str]: - out: List[str] = [] - for v in values: - if v not in out: - out.append(v) - return out - - -class Workflows(Namespace): - """Base Intelligence Seat lifecycle (admin credentials).""" - - # ------------------------------------------------------------------ provisioning - - def provision_seat_customer(self, spec: SeatCustomerSpec) -> SeatCustomer: - c = self._c - phrases = [p.strip() for p in (spec.threat_phrases or []) if p and p.strip()] - created: List[str] = [] - existing: List[str] = [] - reseller_id = spec.reseller_id or unwrap(c.account.get_me()).get("reseller_id") - if not reseller_id: - raise InvalidRequestError("reseller_id is required (this login has none)") - - # 1. company: by id, or by name AND primary contact email; never by name alone - company = self._find_seat_company(reseller_id, spec) - if company is None and not phrases: - raise InvalidRequestError(THREAT_PHRASES_MISSING) - if company is None: - body: Dict[str, Any] = { - "company_name": spec.company_name, - "primary_admin_contact_name": spec.admin_name, - "primary_admin_contact_email": spec.admin_email, - "primary_admin_contact_phone": spec.admin_phone, - "enabled_products": list(PRODUCT_KEYS), - } - if spec.company_code: - body["company_code"] = spec.company_code - company = unwrap(c.companies.create_company(reseller_id, body)) - created.append("company") - else: - existing.append("company") - if not company.get("is_active"): - if not spec.reactivate: - raise InvalidRequestError(f"Company {spec.company_name!r} exists but is inactive " - "(set reactivate=True to reactivate it)") - c.companies.reactivate_company(company["id"]) - if not set(PRODUCT_KEYS) <= set(company.get("enabled_products") or []): - c.companies.add_products(company["id"], PRODUCT_KEYS) - company_id = company["id"] - - # 2. MFA off for an integration-user company, then verify - if spec.mfa_off: - current = unwrap(c.companies.get_company(company_id)) - if current.get("mfa_enforced"): - c.companies.update_company(company_id, {"mfa_enforced": False}) - if unwrap(c.companies.get_company(company_id)).get("mfa_enforced"): - text = "MFA is still on for the company after the update" - raise ApiError(200, None, text, public_message=text) - - # 3. location - loc = c.locations.find_location(company_id, spec.location.name) - if loc is None: - loc = unwrap(c.locations.create_location(company_id, { - "location_name": spec.location.name, "street": spec.location.street, "city": spec.location.city, - "state": spec.location.state, "country": spec.location.country, "zipcode": spec.location.zipcode, - "vertical_id": self._vertical_id(spec.location.vertical), - "enabled_products": list(PRODUCT_KEYS), - })) - created.append("location") - else: - existing.append("location") - if not loc.get("is_active"): - if not spec.reactivate: - raise InvalidRequestError(f"Location {spec.location.name!r} exists but is inactive " - "(set reactivate=True to reactivate it)") - c.locations.reactivate_location(company_id, loc["id"]) - if not set(PRODUCT_KEYS) <= set(loc.get("enabled_products") or []): - c.locations.add_products(company_id, loc["id"], PRODUCT_KEYS) - location_id = loc["id"] - result = SeatCustomer(company_id=company_id, location_id=location_id, created=created, existing=existing) - - # 4. groups - result.manager_alerts_group_id = self._ensure_group(location_id, MANAGER_ALERTS_GROUP, result) - result.insights_hub_group_id = self._ensure_group(location_id, INSIGHTS_HUB_GROUP, result) - - # 5. rules, created disabled and routed to Manager Alerts - groups = [result.manager_alerts_group_id] - result.upset_customer_rule_id = self._ensure_rule(location_id, upset_customer_rule(groups), result) - if phrases: - threat = customer_threat_rule(groups, phrases) - elif c.first_alert.find_rule(location_id, CUSTOMER_THREAT_RULE) is not None: - threat = {"name": CUSTOMER_THREAT_RULE, "group_ids": groups} # keep its configured phrases - else: - raise InvalidRequestError(THREAT_PHRASES_MISSING) - result.customer_threat_rule_id = self._ensure_rule(location_id, threat, result) - - # 6. connector (optional) - if spec.connector is not None: - self._ensure_connector(location_id, spec, result) - - # 7. Insights Hub: group access; only the listed lines are covered ("monitor all numbers" stays off) - setup = unwrap(c.insights_hub.get_insights_hub_setup(location_id)) or {} - access = setup.get("group_access") or [] - if result.insights_hub_group_id not in access: - if not access and not setup.get("connector_mappings"): - c.insights_hub.save_insights_hub_setup( - location_id, {"connector_mappings": [], "group_access": [result.insights_hub_group_id]}) - else: - c.insights_hub.add_groups(location_id, [result.insights_hub_group_id]) - cfg = unwrap(c.insights_hub.get_insights_hub_config(location_id)) or {} - if cfg.get("monitor_all_numbers"): - c.insights_hub.update_insights_hub_config(location_id, {"monitor_all_numbers": False}) - - # 8. SSO domain claim (optional): the customer publishes the TXT record, then verify - if spec.sso_domain: - dom = unwrap(c.sso.claim_company_domain(company_id, {"domain": spec.sso_domain})) or {} - result.sso_domain_id = dom.get("id") - ver = dom.get("verification") or {} - result.sso_txt_record = {"name": ver.get("name"), "value": ver.get("value")} - - # The two rules stay off until a manager is in place: add_manager switches them on - # (activate_alerts=True), or call activate_seat_alerts yourself. - return result - - def _find_seat_company(self, reseller_id: str, spec: SeatCustomerSpec) -> Optional[Dict[str, Any]]: - """The company to provision into: ``spec.company_id``, or the one company with this exact name - whose primary contact email is ``spec.admin_email``. Raises ConflictError when the name is taken - by any other company. Nothing has been written when it raises.""" - c = self._c - if spec.company_id: - return unwrap(c.companies.get_company(spec.company_id)) - same_name = c.companies.find_companies(reseller_id, spec.company_name) - if not same_name: - return None - want = (spec.admin_email or "").strip().lower() - matches = [] - for row in same_name: - detail = unwrap(c.companies.get_company(row["id"])) or {} - if (detail.get("primary_admin_contact_email") or "").strip().lower() == want: - matches.append(detail) - if len(matches) == 1: - return matches[0] - text = (f"A company named {spec.company_name!r} already exists with a different primary contact. " - "Pass company_id to use an existing company, or choose a different company name.") - raise ConflictError(409, COMPANY_NAME_CONFLICT, text, public_message=text) - - def activate_seat_alerts(self, customer: SeatCustomer) -> List[str]: - """Switch on the customer's two alert rules (Upset Customer, Customer Threat). Rules already on - are left as they are. Returns the ids of the rules this call switched on.""" - fa = self._c.first_alert - switched: List[str] = [] - for rule_id in (customer.upset_customer_rule_id, customer.customer_threat_rule_id): - if not rule_id: - continue - rule = unwrap(fa.get_alert_rule(customer.location_id, rule_id)) - if not rule.get("enabled"): - fa.update_alert_rule(customer.location_id, rule_id, {"enabled": True}) - switched.append(rule_id) - return switched - - def _vertical_id(self, vertical: str) -> str: - if is_uuid(vertical): - return vertical - for v in unwrap(self._c.locations.list_verticals()) or []: - if vertical in (v.get("key"), v.get("name")): - return v["id"] - raise InvalidRequestError(f"Unknown vertical {vertical!r}: use an id or key from list_verticals()") - - def _ensure_group(self, location_id: str, name: str, result: SeatCustomer) -> str: - grp = self._c.groups.find_group(location_id, name) - if grp is None: - grp = unwrap(self._c.groups.create_user_group(location_id, {"group_name": name})) - result.created.append(f"group:{name}") - else: - result.existing.append(f"group:{name}") - return grp["id"] - - def _ensure_rule(self, location_id: str, body: Dict[str, Any], result: SeatCustomer) -> str: - fa = self._c.first_alert - found = fa.find_rule(location_id, body["name"]) - if found is None: - rule = unwrap(fa.create_alert_rule(location_id, body)) - result.created.append(f"rule:{body['name']}") - return rule["id"] - result.existing.append(f"rule:{body['name']}") - rule = unwrap(fa.get_alert_rule(location_id, found["id"])) - have = {g["id"] for g in rule.get("groups") or []} - if not set(body["group_ids"]) <= have: - fa.add_rule_groups(location_id, rule["id"], body["group_ids"]) - if "triggers" in body: - current = [{"trigger_type": t.get("trigger_type"), "config": t.get("config")} for t in rule.get("triggers") or []] - if current != body["triggers"]: - fa.update_alert_rule(location_id, rule["id"], {"triggers": body["triggers"]}) # e.g. a new phrase list - return rule["id"] - - def _find_seat_connector(self, location_id: str, domain: str, name: str) -> Optional[Dict[str, Any]]: - """The location's connector for this NetSapiens domain (best status first), else one with this - name.""" - conns = self._c.connectors - rank = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4} - rows = sorted(conns.iter_location_connectors(location_id), key=lambda x: rank.get(x.get("status"), 5)) - by_name = None - for row in rows: - detail = unwrap(conns.get_connector(location_id, row["id"])) or {} - cfg = detail.get("config") or {} - if (cfg.get("domain") or "").strip().lower() == domain.strip().lower(): - return detail - if by_name is None and detail.get("name") == name: - by_name = detail - return by_name - - def _ensure_connector(self, location_id: str, spec: SeatCustomerSpec, result: SeatCustomer) -> None: - cs = spec.connector - assert cs is not None - name = cs.name or f"{spec.location.name} - NetSapiens" - conns = self._c.connectors - found = self._find_seat_connector(location_id, cs.domain, name) - if found is not None: - cfg = found.get("config") or {} - unchanged = (cfg.get("api_url") == cs.api_url and cfg.get("domain") == cs.domain - and found.get("name") == name) - if found.get("status") in ("active", "connecting") and unchanged: - result.existing.append("connector") - result.connector_id = found["id"] - result.connector_status = found.get("status") - result.connector_state_reason = found.get("state_reason") - return - try: - if found is not None: - # In error, stopped or changed: apply the settings (and key) given now, then restart. - result.existing.append("connector") - result.existing.append("connector:updated") - conns.update_connector(location_id, found["id"], { - "name": name, "config": {"api_url": cs.api_url, "domain": cs.domain, "api_key": cs.api_key}}) - if found.get("status") == "inactive": - conn = unwrap(conns.reactivate_connector(location_id, found["id"], timeout=cs.timeout)) - else: - conn = conns.wait_for_status(location_id, found["id"], ("active", "error"), cs.timeout, - raise_on_error=False) - if conn.get("status") == "error": - conns.deactivate_connector(location_id, found["id"], timeout=cs.timeout) - conn = unwrap(conns.reactivate_connector(location_id, found["id"], timeout=cs.timeout)) - else: - conn = unwrap(conns.create_connector(location_id, { - "name": name, "type": "netsapiens", - "config": {"api_url": cs.api_url, "domain": cs.domain, "api_key": cs.api_key}, - }, timeout=cs.timeout)) - result.created.append("connector") - except ConnectorError as exc: - conn = exc.connector - if found is None: - result.created.append("connector") - except ConnectorTimeoutError as exc: - conn = exc.connector - if found is None: - result.created.append("connector") - result.connector_id = conn.get("id") - result.connector_status = conn.get("status") - result.connector_state_reason = conn.get("state_reason") - - def get_seat_customer(self, company_id: str) -> SeatCustomer: - """Rebuild the customer object (location, groups, rules, connector) from what is configured.""" - c = self._c - locations = list(c.locations.iter_company_locations(company_id)) - if not locations: - raise InvalidRequestError(f"Company {company_id} has no location") - loc = next((x for x in locations if x.get("is_active")), locations[0]) - lid = loc["id"] - result = SeatCustomer(company_id=company_id, location_id=lid) - ma = c.groups.find_group(lid, MANAGER_ALERTS_GROUP) - ih = c.groups.find_group(lid, INSIGHTS_HUB_GROUP) - result.manager_alerts_group_id = ma and ma["id"] - result.insights_hub_group_id = ih and ih["id"] - for r in c.first_alert.iter_alert_rules(lid): - if r.get("name") == UPSET_CUSTOMER_RULE: - result.upset_customer_rule_id = r["id"] - elif r.get("name") == CUSTOMER_THREAT_RULE: - result.customer_threat_rule_id = r["id"] - rank = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4} - conns = sorted(c.connectors.iter_location_connectors(lid), key=lambda x: rank.get(x.get("status"), 5)) - if conns and conns[0].get("status") != "inactive": - result.connector_id = conns[0]["id"] - result.connector_status = conns[0].get("status") - result.connector_state_reason = conns[0].get("state_reason") - return result - - # ------------------------------------------------------------------ users - - def _ensure_user(self, customer: SeatCustomer, user: UserSpec) -> Tuple[str, bool, Optional[str]]: - """Find or create the user, never emailing an invitation here. Returns (id, created, status).""" - users = self._c.users - found = users.find_user_by_email(customer.company_id, user.email) - if found is None: - body: Dict[str, Any] = { - "email": user.email, "first_name": user.first_name, "last_name": user.last_name, - "role": "frontline_user", "location_ids": [customer.location_id], - "send_invitation": False, "auth_method": user.auth_method, - } - if user.phone_number: - body["phone_number"] = user.phone_number - row = unwrap(users.create_company_user(customer.company_id, body)) - return row["id"], True, row.get("status") or "invited" - uid = found["id"] - if found.get("status") == "deactivated": - users.reactivate_company_user(customer.company_id, uid) - detail = unwrap(users.get_company_user(customer.company_id, uid)) - if detail.get("role") != "frontline_user": - raise InvalidRequestError(f"{user.email} is a {detail.get('role')}; Seat users are frontline users") - if customer.location_id not in [x["location_id"] for x in detail.get("locations") or []]: - users.add_locations(customer.company_id, uid, [customer.location_id]) - return uid, False, detail.get("status") - - def _invite(self, customer: SeatCustomer, user: UserSpec, user_id: str, status: Optional[str]) -> bool: - """The last step: email the invitation to a user who has not accepted one yet.""" - if not user.send_invitation or status != "invited": - return False - self._c.users.resend_invitation(customer.company_id, user_id) - return True - - def _map(self, customer: SeatCustomer, user_id: str, numbers: List[str]) -> None: - if not customer.connector_id: - raise InvalidRequestError("This customer has no connector; numbers cannot be mapped yet") - try: - self._c.users.set_numbers(customer.company_id, user_id, customer.connector_id, numbers) - except (ValidationError, ConflictError) as exc: - raise ExtensionMappingError(user_id, exc) from exc - - def add_frontline_user(self, customer: SeatCustomer, user: UserSpec, extension: str) -> SeatUser: - """Create an end user with After Call on their own line, and add the line to every manager, - First Alert and Insights Hub. The invitation is emailed last, once all of that has worked - (unless ``user.send_invitation`` is False). If the line cannot be mapped, - ExtensionMappingError is raised and no invitation has been sent.""" - c = self._c - ext = str(extension).strip() - if not ext: - raise InvalidRequestError("extension is required") - if not customer.connector_id: - raise InvalidRequestError("This customer has no connector; add one before adding end users") - uid, created, status = self._ensure_user(customer, user) - c.products.enable_user_product(customer.location_id, uid, AFTER_CALL) - c.first_alert.set_alert_email_preferences(customer.location_id, uid, {"masterEnabled": False, "alerts": []}) - self._map(customer, uid, [ext]) - for m in self._line_holders(customer): - if ext not in c.users.user_numbers(customer.company_id, m["id"], customer.connector_id): - try: - c.users.add_numbers(customer.company_id, m["id"], customer.connector_id, [ext]) - except (ValidationError, ConflictError) as exc: - raise ExtensionMappingError(m["id"], exc) from exc - c.first_alert.add_monitored_numbers(customer.location_id, customer.connector_id, [ext]) - c.insights_hub.add_numbers(customer.location_id, customer.connector_id, [ext]) - invited = self._invite(customer, user, uid, status) - return SeatUser(user_id=uid, email=user.email, kind="frontline", numbers=[ext], created=created, - invited=invited) - - def add_manager(self, customer: SeatCustomer, user: UserSpec, *, activate_alerts: bool = True) -> SeatUser: - """Create a manager: After Call on all lines, First Alert, Insights Hub, both groups, alert email on. - - The manager reads every end-user line at the location. Their own phone line is not captured - on the Seat: it is never mapped, nor added to First Alert or Insights Hub, and a third - positional argument raises TypeError (``activate_alerts`` is keyword-only). - - Then, with ``activate_alerts=True`` (the default), switch the customer's two alert rules on - (see activate_seat_alerts), and last email the invitation (unless ``user.send_invitation`` is - False). If the lines cannot be mapped, ExtensionMappingError is raised, the rules stay as they - were and no invitation has been sent.""" - c = self._c - uid, created, status = self._ensure_user(customer, user) - for key in PRODUCT_KEYS: - c.products.enable_user_product(customer.location_id, uid, key) - groups = [g for g in (customer.manager_alerts_group_id, customer.insights_hub_group_id) if g] - if groups: - c.groups.add_user_to_groups(customer.location_id, uid, groups) - prefs = c.first_alert.get_alert_notification_preferences(customer.location_id, uid) or {} - alerts = ((prefs.get("emailNotifications") or {}).get("alerts")) or [] - c.first_alert.set_alert_email_preferences(customer.location_id, uid, { - "masterEnabled": True, "alerts": [{"alertId": a["alertId"], "emailEnabled": True} for a in alerts]}) - numbers = self._lines(customer) - if numbers: - self._map(customer, uid, numbers) - activated = self.activate_seat_alerts(customer) if activate_alerts else [] - invited = self._invite(customer, user, uid, status) - return SeatUser(user_id=uid, email=user.email, kind="manager", numbers=numbers, created=created, - invited=invited, alerts_activated=activated) - - def add_integration_user(self, customer: SeatCustomer, user: UserSpec) -> SeatUser: - """Create the customer's integration (data-reading) user: password sign-in, tagged - ``department: "integration"``, all three products, both groups, alert email off, every line. - - It is never counted as a seat or a manager, later end users' lines are added to it, and - ``remove_user`` on it never takes a line off anyone else. It never switches alerts on. The - invitation (to set its password) is emailed last unless ``user.send_invitation`` is False. - The company needs MFA off (``SeatCustomerSpec.mfa_off``) for it to sign in.""" - c = self._c - if user.auth_method != "password": - raise InvalidRequestError("An integration user signs in with a password: set auth_method='password'") - uid, created, status = self._ensure_user(customer, user) - detail = unwrap(c.users.get_company_user(customer.company_id, uid)) or {} - if not is_integration(detail): - c.users.update_company_user(customer.company_id, uid, {"department": INTEGRATION_DEPARTMENT}) - for key in PRODUCT_KEYS: - c.products.enable_user_product(customer.location_id, uid, key) - groups = [g for g in (customer.manager_alerts_group_id, customer.insights_hub_group_id) if g] - if groups: - c.groups.add_user_to_groups(customer.location_id, uid, groups) - c.first_alert.set_alert_email_preferences(customer.location_id, uid, {"masterEnabled": False, "alerts": []}) - numbers = self._lines(customer) - if numbers: - self._map(customer, uid, numbers) - invited = self._invite(customer, user, uid, status) - return SeatUser(user_id=uid, email=user.email, kind="integration", numbers=numbers, created=created, - invited=invited) - - def change_user_extension(self, customer: SeatCustomer, user_id: str, old: str, new: str) -> Dict[str, Any]: - """Move an end user from ``old`` to ``new``: their mapping, every manager, First Alert, Insights Hub.""" - c = self._c - old, new = str(old).strip(), str(new).strip() - if not customer.connector_id: - raise InvalidRequestError("This customer has no connector") - conn = customer.connector_id - mine = c.users.user_numbers(customer.company_id, user_id, conn) - self._map(customer, user_id, _uniq([new if n == old else n for n in mine] + [new])) - for m in self._line_holders(customer): - if m["id"] == user_id: - continue - cur = c.users.user_numbers(customer.company_id, m["id"], conn) - target = _uniq([n for n in cur if n != old] + [new]) - if target != cur: - self._map(customer, m["id"], target) - fa = self._fa_numbers(customer) - c.first_alert.set_monitored_numbers(customer.location_id, conn, _uniq([n for n in fa if n != old] + [new])) - ih = self._ih_numbers(customer) - c.insights_hub.set_numbers(customer.location_id, conn, _uniq([n for n in ih if n != old] + [new])) - return {"user_id": user_id, "old": old, "new": new} - - def remove_user(self, customer: SeatCustomer, user_id: str, keep_extensions: bool = False) -> Dict[str, Any]: - """Deactivate a user: they leave every group and their number mapping is cleared. - - Only an end user's line is released, and only when no other end user at the location holds - it: it comes off managers, integration users, First Alert and Insights Hub (unless - ``keep_extensions``). Removing a manager, an integration user, or any user holding several - lines never takes a line off anyone else.""" - c = self._c - conn = customer.connector_id - rows = self._location_rows(customer, include_excluded=True) - row = next((r for r in rows if r.get("id") == user_id), None) - if row is None: - row = dict(unwrap(c.users.get_location_user(customer.location_id, user_id)) or {}) - row["department"] = (unwrap(c.users.get_company_user(customer.company_id, user_id)) or {}).get("department") - mine = c.users.user_numbers(customer.company_id, user_id, conn) if conn else [] - if is_integration(row): - kind = "integration" - elif set(PRODUCT_KEYS) <= _products(row): - kind = "manager" - elif len(mine) > 1: - kind = "integration" # holds several lines and is not a manager: not a seat - else: - kind = "frontline" - released: List[str] = [] - if conn and kind == "frontline" and not self._excluded(customer, row): - held_by_others = set() - for u in self.list_frontline_users(customer): - if u["id"] != user_id: - held_by_others.update(c.users.user_numbers(customer.company_id, u["id"], conn)) - released = [n for n in mine if n not in held_by_others] - c.groups.remove_user_from_groups(customer.location_id, user_id) - if unwrap(c.users.get_user_number_mappings(customer.company_id, user_id)): - c.users.set_user_number_mappings(customer.company_id, user_id, {"mappings": []}) - if released and not keep_extensions: - for m in self._line_holders(customer): - if m["id"] == user_id: - continue - cur = c.users.user_numbers(customer.company_id, m["id"], conn) - if set(released) & set(cur): - self._map(customer, m["id"], [n for n in cur if n not in released]) - c.first_alert.remove_monitored_numbers(customer.location_id, conn, released) - c.insights_hub.remove_numbers(customer.location_id, conn, released) - try: - c.users.deactivate_company_user(customer.company_id, user_id) - except ConflictError: - pass # already deactivated - return {"user_id": user_id, "released_numbers": [] if keep_extensions else released, "kind": kind} - - @staticmethod - def _excluded(customer: SeatCustomer, row: Dict[str, Any]) -> bool: - emails = {e.strip().lower() for e in customer.exclude_emails} - return row.get("id") in customer.exclude_user_ids or (row.get("email") or "").strip().lower() in emails - - def _location_rows(self, customer: SeatCustomer, include_excluded: bool = False) -> List[Dict[str, Any]]: - """Users at the location, each with its company-level ``department`` joined in.""" - c = self._c - departments = {u["id"]: u.get("department") - for u in c.users.iter_company_users(customer.company_id, location_id=customer.location_id)} - rows = [] - for r in c.users.iter_location_users(customer.location_id): - row = dict(r, department=departments.get(r.get("id"))) - if include_excluded or not self._excluded(customer, row): - rows.append(row) - return rows - - def list_frontline_users(self, customer: SeatCustomer) -> List[Dict[str, Any]]: - """Active end users (After Call only, not integration users) at the customer's location.""" - return [r for r in self._location_rows(customer) if is_frontline(r)] - - def list_managers(self, customer: SeatCustomer) -> List[Dict[str, Any]]: - """Active managers (all three products, not integration users) at the customer's location.""" - return [r for r in self._location_rows(customer) if is_manager(r)] - - def list_integration_users(self, customer: SeatCustomer) -> List[Dict[str, Any]]: - """Active integration users (tagged ``department: "integration"``) at the customer's location.""" - return [r for r in self._location_rows(customer) if _active_frontline(r) and is_integration(r)] - - def _line_holders(self, customer: SeatCustomer) -> List[Dict[str, Any]]: - """Users who hold every line: managers and integration users.""" - return [r for r in self._location_rows(customer) - if is_manager(r) or (_active_frontline(r) and is_integration(r))] - - # ------------------------------------------------------------------ numbers - - def _lines(self, customer: SeatCustomer) -> List[str]: - """The location's lines: the number of every end user who holds exactly one.""" - if not customer.connector_id: - return [] - out: List[str] = [] - for u in self.list_frontline_users(customer): - nums = self._c.users.user_numbers(customer.company_id, u["id"], customer.connector_id) - if len(nums) == 1: - out = _uniq(out + nums) - return out - - def _fa_numbers(self, customer: SeatCustomer) -> List[str]: - cfg = unwrap(self._c.first_alert.get_first_alert_config(customer.location_id)) or {} - return numbers_for(cfg.get("connector_mappings") or [], customer.connector_id) - - def _ih_numbers(self, customer: SeatCustomer) -> List[str]: - setup = unwrap(self._c.insights_hub.get_insights_hub_setup(customer.location_id)) or {} - return numbers_for(setup.get("connector_mappings") or [], customer.connector_id) - - def sync_numbers(self, customer: SeatCustomer, dry_run: bool = False) -> Dict[str, Any]: - """Recompute the location's lines (every end user's extension) and push them to managers, - integration users, First Alert and Insights Hub. Managers and integration users hold exactly - the lines: any other number on their mapping is removed. - ``dry_run=True`` returns the changes without making them.""" - c = self._c - diff: Dict[str, Any] = {"lines": [], "managers": {}, "first_alert": {"add": [], "remove": []}, - "insights_hub": {"add": [], "remove": []}, "applied": False} - if not customer.connector_id: - return diff - conn = customer.connector_id - lines = self._lines(customer) - diff["lines"] = lines - fa = self._fa_numbers(customer) - ih = self._ih_numbers(customer) - 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]} - 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]} - targets: Dict[str, List[str]] = {} - for m in self._line_holders(customer): - cur = c.users.user_numbers(customer.company_id, m["id"], conn) - target = list(lines) - add = [n for n in target if n not in cur] - remove = [n for n in cur if n not in target] - if add or remove: - diff["managers"][m["id"]] = {"add": add, "remove": remove} - targets[m["id"]] = target - if dry_run: - return diff - for uid, target in targets.items(): - self._map(customer, uid, target) - if diff["first_alert"]["add"] or diff["first_alert"]["remove"]: - c.first_alert.set_monitored_numbers(customer.location_id, conn, lines) - if diff["insights_hub"]["add"] or diff["insights_hub"]["remove"]: - c.insights_hub.set_numbers(customer.location_id, conn, lines) - diff["applied"] = True - return diff - - # ------------------------------------------------------------------ offboarding - - def offboard_customer(self, customer: SeatCustomer, deactivate_company: bool = True) -> Dict[str, Any]: - """Stop everything for a customer who leaves, in this order: pause the After Call webhook (its - URL is kept; it can't be deleted), clear the First Alert webhook, stop the connector (ends the - phone-system subscription), deactivate the integration users, then deactivate the company. - - Safe to run again. Ask your Tresic contact about retention of the customer's data.""" - c = self._c - lid = customer.location_id - out: Dict[str, Any] = {"webhook_paused": False, "first_alert_webhook_cleared": False, - "connector_deactivated": False, "integration_users_deactivated": [], - "company_deactivated": False} - hook = c.intelligence.get_after_call_webhook(lid) or {} - if hook.get("webhook_url") and hook.get("enabled"): - c.intelligence.set_after_call_webhook(lid, hook["webhook_url"], enabled=False) - out["webhook_paused"] = True - if c.intelligence.get_first_alert_webhook(lid): - c.intelligence.set_first_alert_webhook(lid, None) - out["first_alert_webhook_cleared"] = True - if customer.connector_id: - conn = unwrap(c.connectors.get_connector(lid, customer.connector_id)) or {} - if conn.get("status") not in ("inactive", "deactivating"): - try: - c.connectors.deactivate_connector(lid, customer.connector_id) - except ConflictError: - pass # already inactive - out["connector_deactivated"] = True - for u in self.list_integration_users(customer): - try: - c.users.deactivate_company_user(customer.company_id, u["id"]) - except ConflictError: - continue # already deactivated - out["integration_users_deactivated"].append(u["id"]) - if deactivate_company: - company = unwrap(c.companies.get_company(customer.company_id)) or {} - if company.get("is_active", True): - try: - c.companies.deactivate_company(customer.company_id) - except ConflictError: - pass # already inactive - out["company_deactivated"] = True - return out diff --git a/tests/live/test_live.py b/tests/live/test_live.py index e376424..ce5a0bd 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -6,13 +6,15 @@ SBX_NS_API_URL / SBX_NS_DOMAIN / SBX_NA_API_KEY phone-system connector settings for the test company IC_LIVE_COMPANY_NAME the test company this suite creates (or finds) and deactivates at the end IC_LIVE_COMPANY_CODE its company code (optional) - IC_LIVE_LOCATION_NAME its location (default "SDK Test - Main") + IC_LIVE_LOCATION_NAME its first team (default "SDK Test - Main"); Management is " - Management" IC_LIVE_COMPANY_SEARCH a company-name prefix with at least one match, for the paging check (default: IC_LIVE_COMPANY_NAME) IC_LIVE_EMAIL_PREFIX / IC_LIVE_EMAIL_DOMAIN test users are -@ (n = 0 is the company's primary contact, who is always emailed an invitation) IC_LIVE_SSO_DOMAIN a domain to claim and release (optional; the SSO step is skipped without it) - IC_LIVE_THREAT_PHRASES_FILE Customer Threat phrases, one per line + IC_LIVE_THREAT_PHRASES_FILE Customer Threat phrases, one per line (optional: the alert is left pending) + IC_LIVE_UPSET_PHRASES_FILE Upset Customer phrases, one per line (optional: the alert is left pending) + IC_LIVE_MANAGER_EXTENSION the manager's own extension, captured at Management (optional) IC_LIVE_EXPECT_CONNECTOR the connector status the test key reaches: "active" or "error" (default "error") IC_LIVE_FREE_EXTENSION an extension no other location monitors IC_LIVE_CONFLICT_EXTENSION an extension another location monitors (optional; the 409 check is skipped) @@ -150,33 +152,44 @@ def test_admin_errors(admin): admin.users.list_company_users(str(uuid.uuid4()), product="insights-hub") # type: ignore[call-arg] -# ====================================================================== admin: Seat lifecycle +# ====================================================================== admin: account layer -def _threat_phrases(admin): - if "phrases" not in STATE: - with open(env("IC_LIVE_THREAT_PHRASES_FILE")) as fh: - STATE["phrases"] = [line.strip() for line in fh if line.strip()] - return STATE["phrases"] +def _phrases(name): + path = os.environ.get(name) + if not path: + return None + with open(path) as fh: + return [line.strip() for line in fh if line.strip()] or None -def _spec_for(admin): - return ic.SeatCustomerSpec( - company_name=COMPANY, admin_name="SDK Test Admin", admin_email=email(0), - admin_phone="+15555550100", company_code=os.environ.get("IC_LIVE_COMPANY_CODE") or None, - mfa_off=True, reactivate=True, - threat_phrases=_threat_phrases(admin), - location=ic.LocationSpec(name=LOCATION, street="1 Example Way", city="Springfield", state="IL", - country="US", zipcode="62701", vertical=STATE["vertical"]), - connector=ic.ConnectorSpec(api_url=env("SBX_NS_API_URL"), domain=env("SBX_NS_DOMAIN"), - api_key=env("SBX_NA_API_KEY"), name=f"{LOCATION} - NetSapiens", timeout=90), - sso_domain=SSO_DOMAIN or None, +def _alerts(): + threat, upset = _phrases("IC_LIVE_THREAT_PHRASES_FILE"), _phrases("IC_LIVE_UPSET_PHRASES_FILE") + return ic.AlertSettings(customer_threat=ic.AlertSetting(phrases=threat) if threat else None, + upset_customer=ic.AlertSetting(phrases=upset) if upset else None) + + +def _connector(): + return ic.ConnectorSpec.netsapiens(env("SBX_NS_API_URL"), env("SBX_NS_DOMAIN"), env("SBX_NA_API_KEY"), timeout=90) + + +def _spec_for(admin, **kw): + base = dict( + company_name=COMPANY, company_code=os.environ.get("IC_LIVE_COMPANY_CODE") or None, + admin=ic.PersonSpec(email(0), "SDK Test", "Admin", phone_number="+15555550100"), + team=ic.TeamSpec(name=LOCATION, street="1 Example Way", city="Springfield", state="IL", + country="US", zipcode="62701", vertical=STATE["vertical"]), + connector=_connector(), alerts=_alerts(), mfa_off=True, reactivate=True, + sso_domain=SSO_DOMAIN or None, company_id=STATE.get("company_id"), ) + base.update(kw) + return ic.CustomerSpec(**base) @pytest.fixture(scope="module") def customer(admin): - cust = admin.workflows.provision_seat_customer(_spec_for(admin)) + cust = admin.accounts.create_customer(_spec_for(admin)) STATE["customer"] = cust + STATE["company_id"] = cust.company_id yield cust _cleanup(admin, cust) @@ -194,143 +207,158 @@ def attempt(fn, *a, **kw): errors.append(f"{fn.__name__}: {type(exc).__name__}") for uid in STATE.get("users", []): attempt(admin.users.deactivate_company_user, cust.company_id, uid) - if cust.connector_id: - attempt(admin.connectors.deactivate_connector, cust.location_id, cust.connector_id, timeout=60) + for t in [cust.management] + cust.teams: + if t is None: + continue + if t.connector_id: + attempt(admin.connectors.deactivate_connector, t.location_id, t.connector_id, timeout=60) + attempt(admin.intelligence.set_first_alert_webhook, t.location_id, None) + attempt(admin.locations.deactivate_location, cust.company_id, t.location_id) if cust.sso_domain_id: attempt(admin.sso.remove_company_domain, cust.company_id, cust.sso_domain_id) - attempt(admin.intelligence.set_first_alert_webhook, cust.location_id, None) - attempt(admin.locations.deactivate_location, cust.company_id, cust.location_id) attempt(admin.companies.deactivate_company, cust.company_id) assert not errors, errors -def test_provision_seat_customer(admin, customer): - assert customer.company_id and customer.location_id - assert customer.manager_alerts_group_id and customer.insights_hub_group_id - assert customer.upset_customer_rule_id and customer.customer_threat_rule_id +def _no_monitor_all_no_rules_at_management(admin, cust): + for t in [cust.management] + cust.teams: + assert unwrap(admin.insights_hub.get_insights_hub_config(t.location_id))["monitor_all_numbers"] is False + assert list(admin.first_alert.iter_alert_rules(cust.management.location_id)) == [] + + +def test_create_customer(admin, customer): + team, mgmt = customer.teams[0], customer.management + assert customer.company_id and team.location_id and mgmt.location_id and mgmt.kind == "management" + assert all(getattr(team.groups, f) for f in ("customer_threats", "upset_customers", "low_sentiment_calls", + "insights_hub_access", "weekly_reports")) + assert mgmt.groups.weekly_reports and team.rules.low_sentiment company = unwrap(admin.companies.get_company(customer.company_id)) assert company["mfa_enforced"] is False and company["is_active"] - assert customer.connector_status == EXPECT_CONNECTOR + assert team.connector_status == EXPECT_CONNECTOR if EXPECT_CONNECTOR == "error": - assert customer.connector_state_reason == "invalid_permissions" + assert team.connector_state_reason == "invalid_permissions" if SSO_DOMAIN: assert customer.sso_txt_record and customer.sso_txt_record["name"] == "_ic-verify." + SSO_DOMAIN - threat = unwrap(admin.first_alert.get_alert_rule(customer.location_id, customer.customer_threat_rule_id)) - kw = next(t for t in threat["triggers"] if t["trigger_type"] == "keyword_match")["config"] - assert sorted(kw["keywords"]) == sorted(_threat_phrases(admin)) - assert [g["id"] for g in threat["groups"]] == [customer.manager_alerts_group_id] - setup = unwrap(admin.insights_hub.get_insights_hub_setup(customer.location_id)) - assert customer.insights_hub_group_id in setup["group_access"] - assert unwrap(admin.insights_hub.get_insights_hub_config(customer.location_id))["monitor_all_numbers"] is False - raw_keys(admin, "getConnector", {"locationId": customer.location_id, "connectorId": customer.connector_id}) + low = unwrap(admin.first_alert.get_alert_rule(team.location_id, team.rules.low_sentiment)) + assert low["enabled"] is False and [g["id"] for g in low["groups"]] == [team.groups.low_sentiment_calls] + setup = unwrap(admin.insights_hub.get_insights_hub_setup(team.location_id)) + assert team.groups.insights_hub_access in setup["group_access"] + _no_monitor_all_no_rules_at_management(admin, customer) + raw_keys(admin, "getConnector", {"locationId": team.location_id, "connectorId": team.connector_id}) raw_keys(admin, "getCompany", {"companyId": customer.company_id}) -def test_provision_is_idempotent(admin, customer): - again = admin.workflows.provision_seat_customer(_spec_for(admin)) - assert not [x for x in again.created if x != "connector"] - assert again.location_id == customer.location_id - assert again.customer_threat_rule_id == customer.customer_threat_rule_id - got = admin.workflows.get_seat_customer(customer.company_id) - assert got.manager_alerts_group_id == customer.manager_alerts_group_id - assert got.connector_id == customer.connector_id +def test_create_customer_is_idempotent(admin, customer): + start = admin._writes + again = admin.accounts.create_customer(_spec_for(admin)) + if EXPECT_CONNECTOR == "active": + assert admin._writes == start # a re-run writes nothing + assert again.teams[0].location_id == customer.teams[0].location_id + assert again.teams[0].rules == customer.teams[0].rules + got = admin.accounts.get_customer(customer.company_id) + assert got.management.location_id == customer.management.location_id + assert got.teams[0].groups == customer.teams[0].groups + + +def test_alert_levels_change_without_touching_phrases(admin, customer): + team = customer.teams[0] + admin.accounts.set_alerts(customer, ic.AlertSettings(low_sentiment=ic.AlertSetting(sentiment_below=-45))) + low = unwrap(admin.first_alert.get_alert_rule(team.location_id, team.rules.low_sentiment)) + assert low["triggers"][0]["config"]["threshold"] == -45 + admin.accounts.set_alerts(customer, ic.AlertSettings(low_sentiment=ic.AlertSetting(sentiment_below=-40))) def test_connector_polling_to_error(admin, customer): if EXPECT_CONNECTOR != "error": pytest.skip("the test key connects") - out = unwrap(admin.connectors.deactivate_connector(customer.location_id, customer.connector_id, timeout=60)) + team = customer.teams[0] + out = unwrap(admin.connectors.deactivate_connector(team.location_id, team.connector_id, timeout=60)) assert out["status"] == "inactive" with pytest.raises(ic.ConnectorError) as e: - admin.connectors.reactivate_connector(customer.location_id, customer.connector_id, timeout=90) + admin.connectors.reactivate_connector(team.location_id, team.connector_id, timeout=90) assert e.value.state_reason == "invalid_permissions" - ok = unwrap(admin.connectors.test_connector(customer.location_id, {"type": "netsapiens", "config": { + ok = unwrap(admin.connectors.test_connector(team.location_id, {"type": "netsapiens", "config": { "api_url": env("SBX_NS_API_URL"), "domain": env("SBX_NS_DOMAIN"), "api_key": env("SBX_NA_API_KEY")}})) assert set(ok) == {"success"} -def test_add_manager(admin, customer): - mgr = admin.workflows.add_manager(customer, ic.UserSpec(email(2), "SDK", "Manager", - send_invitation=False)) - assert not mgr.invited - for rid in (customer.upset_customer_rule_id, customer.customer_threat_rule_id): - assert unwrap(admin.first_alert.get_alert_rule(customer.location_id, rid))["enabled"] # switched on +def test_add_base_manager(admin, customer): + team, mgmt = customer.teams[0], customer.management + own = os.environ.get("IC_LIVE_MANAGER_EXTENSION") if EXPECT_CONNECTOR == "active" else None + mgr = admin.accounts.add_base_manager(customer, ic.PersonSpec(email(2), "SDK", "Manager"), + teams=[team], line=own, invite=False) + assert not mgr.invited and mgr.license == "base_manager" STATE.setdefault("users", []).append(mgr.user_id) STATE["manager"] = mgr.user_id - row = unwrap(admin.users.get_location_user(customer.location_id, mgr.user_id)) - assert set(row["enabled_products"]) == {"after-call-copilot", "first-alert-copilot", "insights-hub"} - access = unwrap(admin.insights_hub.get_user_insights_hub_access(customer.location_id, mgr.user_id)) - assert access["enabled"] is True - prefs = admin.first_alert.get_alert_notification_preferences(customer.location_id, mgr.user_id) - assert prefs["emailNotifications"]["masterEnabled"] is True - assert {a["alertId"] for a in prefs["emailNotifications"]["alerts"]} == { - customer.upset_customer_rule_id, customer.customer_threat_rule_id} - raw_keys(admin, "getAlertNotificationPreferences", {"locationId": customer.location_id, "userId": mgr.user_id}) - - -def test_add_frontline_user_mapping_422(admin, customer): - # the connector is not active: the user is created (not invited), the mapping is refused + for lid in (team.location_id, mgmt.location_id): + row = unwrap(admin.users.get_location_user(lid, mgr.user_id)) + assert set(row["enabled_products"]) == {"after-call-copilot", "first-alert-copilot", "insights-hub"} + prefs = admin.first_alert.get_alert_notification_preferences(team.location_id, mgr.user_id) + assert prefs["emailNotifications"]["masterEnabled"] is False # alert email off for managers too + raw_keys(admin, "getAlertNotificationPreferences", {"locationId": team.location_id, "userId": mgr.user_id}) + + +def test_add_base_user_mapping_422(admin, customer): + # the connector is not active: the person is created (not invited), the mapping is refused if EXPECT_CONNECTOR != "error": pytest.skip("the test key connects") - with pytest.raises(ic.ExtensionMappingError) as e: - admin.workflows.add_frontline_user(customer, ic.UserSpec(email(1), "SDK", "Agent", - send_invitation=False), FREE_EXT) - assert e.value.cause.status == 422 - uid = e.value.user_id + with pytest.raises(ic.AccountError) as e: + admin.accounts.add_base_user(customer, ic.PersonSpec(email(1), "SDK", "Agent"), + team=customer.teams[0], line=FREE_EXT, invite=False) + assert isinstance(e.value.cause, ic.ExtensionMappingError) and e.value.cause.cause.status == 422 + uid = e.value.result.user_id STATE.setdefault("users", []).append(uid) - STATE["frontline"] = uid - row = unwrap(admin.users.get_location_user(customer.location_id, uid)) + STATE["base_user"] = uid + row = unwrap(admin.users.get_location_user(customer.teams[0].location_id, uid)) assert row["enabled_products"] == ["after-call-copilot"] raw_keys(admin, "getCompanyUser", {"companyId": customer.company_id, "userId": uid}) -def test_add_frontline_user_mapping_success(admin, customer): - """With an active connector: the end user's line maps, and reaches managers, First Alert and Insights Hub.""" +def test_add_base_user_mapping_success(admin, customer): + """With an active connector: the line maps, and reaches the manager, First Alert and Insights Hub.""" if EXPECT_CONNECTOR != "active": pytest.skip("needs a read/write phone-system key (IC_LIVE_EXPECT_CONNECTOR=active)") - user = admin.workflows.add_frontline_user(customer, ic.UserSpec(email(1), "SDK", "Agent", - send_invitation=False), FREE_EXT) + team = customer.teams[0] + user = admin.accounts.add_base_user(customer, ic.PersonSpec(email(1), "SDK", "Agent"), + team=team, line=FREE_EXT, invite=False) STATE.setdefault("users", []).append(user.user_id) - STATE["frontline"] = user.user_id - assert admin.users.user_numbers(customer.company_id, user.user_id, customer.connector_id) == [FREE_EXT] - assert FREE_EXT in admin.users.user_numbers(customer.company_id, STATE["manager"], customer.connector_id) - assert FREE_EXT in admin.workflows._fa_numbers(customer) and FREE_EXT in admin.workflows._ih_numbers(customer) - - -def test_classification(admin, customer): - assert [u["id"] for u in admin.workflows.list_frontline_users(customer)] == [STATE["frontline"]] - assert [u["id"] for u in admin.workflows.list_managers(customer)] == [STATE["manager"]] + STATE["base_user"] = user.user_id + assert admin.users.user_numbers(customer.company_id, user.user_id, team.connector_id) == [FREE_EXT] + assert FREE_EXT in admin.users.user_numbers(customer.company_id, STATE["manager"], team.connector_id) + assert FREE_EXT in admin.accounts._fa_numbers(team) and FREE_EXT in admin.accounts._ih_numbers(team) + out = admin.accounts.activate_alerts(customer) + assert out["skipped"] == [] -def test_change_user_extension_422(admin, customer): - if EXPECT_CONNECTOR != "error": - pytest.skip("the test key connects") - with pytest.raises(ic.ExtensionMappingError) as e: - admin.workflows.change_user_extension(customer, STATE["frontline"], FREE_EXT, FREE_EXT + "0") - assert e.value.cause.status == 422 +def test_license_report(admin, customer): + rep = admin.accounts.license_report(customer) + assert rep["base_manager"] == 1 and rep["teams"] == 1 + if EXPECT_CONNECTOR == "active": + assert rep["base_user"] == 1 def test_extension_conflict_409_is_sanitised(admin, customer): if not CONFLICT_EXT: pytest.skip("IC_LIVE_CONFLICT_EXTENSION not set") + team = customer.teams[0] with pytest.raises((ic.ConflictError, ic.ValidationError)) as e: admin.after_call_settings.update_user_after_call_settings( - customer.location_id, STATE["manager"], - {"connector_mappings": [{"connector_id": customer.connector_id, "monitored_numbers": [CONFLICT_EXT]}]}) + team.location_id, STATE["manager"], + {"connector_mappings": [{"connector_id": team.connector_id, "monitored_numbers": [CONFLICT_EXT]}]}) STATE["conflict_status"] = e.value.status if isinstance(e.value, ic.ConflictError): assert e.value.message == "Extension is already monitored at another location." assert e.value.extensions == [CONFLICT_EXT] -def test_sync_numbers(admin, customer): - diff = admin.workflows.sync_numbers(customer, dry_run=True) +def test_sync_lines(admin, customer): + diff = admin.accounts.sync_lines(customer, dry_run=True) assert not diff["applied"] - assert admin.workflows.sync_numbers(customer)["applied"] + assert admin.accounts.sync_lines(customer)["applied"] def test_webhook_configuration(admin, customer): - lid = customer.location_id + lid = customer.teams[0].location_id token = uuid.uuid4().hex out = admin.intelligence.set_after_call_webhook(lid, f"https://example.com/ic-sdk/{token}", enabled=False) assert out["enabled"] is False @@ -350,17 +378,14 @@ def test_webhook_configuration(admin, customer): def test_remove_users(admin, customer): - again = admin.workflows.provision_seat_customer( - ic.SeatCustomerSpec(**{**vars(_spec_for(admin)), "threat_phrases": None, "connector": None, "sso_domain": None})) - assert again.customer_threat_rule_id == customer.customer_threat_rule_id # re-run without phrases keeps the rule - out = admin.workflows.remove_user(customer, STATE["frontline"]) - assert out["kind"] == "frontline" - out = admin.workflows.remove_user(customer, STATE["manager"]) - assert out["kind"] == "manager" - for uid in (STATE["frontline"], STATE["manager"]): + out = admin.accounts.remove_user(customer, STATE["manager"]) + assert out["license"] == "base_manager" + admin.accounts.remove_user(customer, STATE["base_user"]) + for uid in (STATE["base_user"], STATE["manager"]): assert unwrap(admin.users.get_company_user(customer.company_id, uid))["status"] == "deactivated" - assert not admin.groups.user_group_ids(customer.location_id, uid) - assert admin.workflows.list_managers(customer) == [] + assert not admin.groups.user_group_ids(customer.teams[0].location_id, uid) + assert admin.accounts.list_members(customer, license="base_manager") == [] + _no_monitor_all_no_rules_at_management(admin, customer) # ====================================================================== frontline: read only @@ -369,6 +394,17 @@ def test_frontline_identity(frontline): me = frontline.intelligence.require_frontline() assert me["role"] == "frontline_user" raw_keys(frontline, "getMe", {}) + assert frontline.conversations.me().user_id == me["id"] + + +def test_conversation_layer(frontline, admin): + with pytest.raises(ic.WrongLoginError): + admin.conversations.calls() + briefs = frontline.conversations.calls(since=NOW - timedelta(days=2), limit=5) + assert len(briefs) <= 5 + for b in briefs: + assert b.caller_number is None or len(b.caller_number) <= 7 # masked to the last four digits + assert repr(b).startswith("CallBrief(id=") def test_frontline_calls(frontline): diff --git a/tests/unit/fake_api.py b/tests/unit/fake_api.py index df6aba1..efff3f0 100644 --- a/tests/unit/fake_api.py +++ b/tests/unit/fake_api.py @@ -12,6 +12,8 @@ RESELLER = "00000000-0000-4000-8000-0000000000aa" VERTICAL = "00000000-0000-4000-8000-0000000000bb" +CONNECTOR_TYPES = [{"key": "netsapiens", "name": "NetSapiens"}, {"key": "examplepbx", "name": "Example PBX"}] +SECRET_WORDS = ("key", "secret", "token", "password") def new_id() -> str: @@ -28,7 +30,11 @@ def page(rows: List[Dict[str, Any]], type_: Optional[str] = None) -> Dict[str, A class FakeAPI: - """Stateful fake. ``calls`` logs (METHOD, path) for every request after sign-in.""" + """Stateful fake. ``calls`` logs (METHOD, path) for every request after sign-in. + + Products, groups and alert email preferences are per location. A user's number mappings are + company-wide, one entry per connector; mapping a number that a user at another location already + holds returns 409, as the API does. New users start with alert email on, as on the platform.""" def __init__(self, connector_outcome: str = "active", role: str = "reseller_admin"): self.calls: List[Tuple[str, str]] = [] @@ -48,6 +54,17 @@ def __init__(self, connector_outcome: str = "active", role: str = "reseller_admi self.email_prefs: Dict[str, Dict[str, Any]] = {} self.invitations: List[str] = [] # user ids emailed an invitation, in order self.after_call_hooks: Dict[str, Dict[str, Any]] = {} + self.domains: Dict[str, List[Dict[str, Any]]] = {} + self.secrets_sent: List[Dict[str, Any]] = [] # connector configs as sent (keys included), for assertions + self.me_extra: Dict[str, Any] = {} + # conversation data (frontline reads) + self.visible_locations: List[Dict[str, Any]] = [] + self.call_rows: List[Dict[str, Any]] = [] + self.call_details: Dict[str, Dict[str, Any]] = {} + self.alert_rows: List[Dict[str, Any]] = [] + self.task_rows: List[Dict[str, Any]] = [] + self.insights: Dict[str, Any] = {} + self._clock = 0 self.routes: List[Tuple[str, re.Pattern, Callable]] = [] self._register() @@ -87,14 +104,41 @@ def count(self, method: str, pattern: str) -> int: def location_users(self, lid: str) -> List[Dict[str, Any]]: return [u for u in self.users.values() if lid in u["_locations"]] + def tick(self) -> str: + self._clock += 1 + return f"2026-11-01T00:00:{self._clock:02d}Z" + + def writes(self, start: int = 0) -> List[Tuple[str, str]]: + return [(m, p.split("/api/v1")[-1]) for m, p in self.calls[start:] if m != "GET"] + + def products(self, uid: str, lid: str) -> set: + return self.users[uid]["_products"].setdefault(lid, set()) + + def numbers(self, uid: str, connector_id: Optional[str] = None) -> List[str]: + return [n for m in self.mappings.get(uid, []) if connector_id in (None, m["connector_id"]) + for n in m["monitored_numbers"]] + + def fa_numbers(self, lid: str) -> List[str]: + return [n for m in self.fa_config.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] + + def ih_numbers(self, lid: str) -> List[str]: + return [n for m in self.ih_setup.get(lid, {}).get("connector_mappings", []) for n in m["monitored_numbers"]] + + def group_members(self, lid: str, name: str) -> List[str]: + return next((g["members"] for g in self.groups.values() if g["location_id"] == lid and g["group_name"] == name), []) + # ------------------------------------------------------------------ routes def _register(self) -> None: # noqa: C901 - a fake server is a long switch api = self @self.route("GET", r"/me") def me(req, body): - return 200, {"data": {"id": new_id(), "role": api.role, "reseller_id": RESELLER, - "user_type": "reseller_user", "unexpected_field": "redacted"}} + return 200, {"data": dict({"id": new_id(), "role": api.role, "reseller_id": RESELLER, + "user_type": "reseller_user", "unexpected_field": "redacted"}, **api.me_extra)} + + @self.route("GET", r"/connector-types") + def connector_types(req, body): + return 200, {"data": CONNECTOR_TYPES} @self.route("GET", r"/verticals") def verticals(req, body): @@ -148,8 +192,14 @@ def react_company(req, body, cid): @self.route("POST", r"/companies/([^/]+)/domains") def claim(req, body, cid): - return 201, {"data": {"id": "dom-1", "domain": body["domain"], "status": "pending", - "verification": {"type": "TXT", "name": "_ic-verify." + body["domain"], "value": "abc"}}} + d = {"id": "dom-1", "domain": body["domain"], "status": "pending", + "verification": {"type": "TXT", "name": "_ic-verify." + body["domain"], "value": "abc"}} + api.domains.setdefault(cid, []).append(d) + return 201, {"data": d} + + @self.route("GET", r"/companies/([^/]+)/domains") + def list_domains(req, body, cid): + return 200, {"data": api.domains.get(cid, [])} # locations @self.route("GET", r"/companies/([^/]+)/locations") @@ -161,7 +211,7 @@ def list_locations(req, body, cid): @self.route("POST", r"/companies/([^/]+)/locations") def create_location(req, body, cid): lid = new_id() - api.locations[lid] = dict(body, id=lid, company_id=cid, is_active=True) + api.locations[lid] = dict(body, id=lid, company_id=cid, is_active=True, created_at=api.tick()) return 201, res("location", api.locations[lid]) @self.route("GET", r"/companies/([^/]+)/locations/([^/]+)") @@ -242,11 +292,14 @@ def list_conns(req, body, lid): @self.route("POST", r"/locations/([^/]+)/connectors") def create_conn(req, body, lid): + if body["type"] not in [t["key"] for t in CONNECTOR_TYPES]: + return 422, {"error": {"code": "VALIDATION_ERROR", "message": "unknown connector type"}} cid = new_id() + api.secrets_sent.append(dict(body["config"])) + public = {k: v for k, v in body["config"].items() if not any(w in k.lower() for w in SECRET_WORDS)} api.connectors[cid] = {"id": cid, "location_id": lid, "name": body["name"], "type": body["type"], "status": "connecting", "_polls": 0, - "config": {"api_url": body["config"]["api_url"], "domain": body["config"]["domain"], - "unexpected_field": "redacted"}} + "config": dict(public, unexpected_field="redacted")} return 202, {"data": api.connectors[cid]} @self.route("GET", r"/locations/([^/]+)/connectors/([^/]+)") @@ -268,8 +321,10 @@ def patch_conn(req, body, lid, cid): if "name" in body: c["name"] = body["name"] if "config" in body: - c["config"].update(api_url=body["config"]["api_url"], domain=body["config"]["domain"]) - c["_key"] = body["config"]["api_key"] + api.secrets_sent.append(dict(body["config"])) + c["config"].update({k: v for k, v in body["config"].items() + if not any(w in k.lower() for w in SECRET_WORDS)}) + c["_key"] = body["config"].get("api_key") return 200, {"data": c} @self.route("POST", r"/locations/([^/]+)/connectors/([^/]+)/deactivate") @@ -334,9 +389,11 @@ def create_user(req, body, cid): assert req.headers.get("Idempotency-Key") uid = new_id() api.users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], - "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": set()} + "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": {}, + "invited_at": None} if body.get("send_invitation"): api.invitations.append(uid) + api.users[uid]["invited_at"] = api.tick() return 201, {"data": {"type": "company_user", "attributes": api._user_attrs(api.users[uid])}, "meta": {"invitation_link": "https://app.example.com/accept?token=SECRET"}} @@ -364,6 +421,7 @@ def resend(req, body, cid, uid): if api.users[uid]["status"] != "invited": return 409, {"error": {"code": "CONFLICT", "message": "User does not have a pending invitation"}} api.invitations.append(uid) + api.users[uid]["invited_at"] = api.tick() return 202, {"data": {"type": "invitation_resend", "attributes": {"user_id": uid, "email": api.users[uid]["email"]}}} @@ -381,6 +439,17 @@ def put_maps(req, body, cid, uid): for m in body["mappings"]: if api.connectors.get(m["connector_id"], {}).get("status") != "active": return 422, {"error": {"code": "VALIDATION_ERROR", "message": "connector not found or inactive"}} + for m in body["mappings"]: # one extension, one location + lid = api.connectors[m["connector_id"]]["location_id"] + for other, maps in api.mappings.items(): + if other == uid: + continue + for om in maps: + olid = api.connectors.get(om["connector_id"], {}).get("location_id") + clash = set(om["monitored_numbers"]) & set(m["monitored_numbers"]) + if olid != lid and clash: + return 409, {"error": {"code": "CONFLICT", + "message": f"Extension {sorted(clash)[0]} is monitored at Other Co"}} api.mappings[uid] = body["mappings"] return 200, {"data": body["mappings"]} @@ -394,27 +463,82 @@ def get_loc_user(req, body, lid, uid): @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/enable") def enable(req, body, lid, uid, key): - api.users[uid]["_products"].add(key) + api.products(uid, lid).add(key) return 200, {"data": {"product_key": key, "enabled": True}} + @self.route("POST", r"/locations/([^/]+)/users/([^/]+)/products/([^/]+)/disable") + def disable(req, body, lid, uid, key): + api.products(uid, lid).discard(key) + return 200, {"data": {"product_key": key, "enabled": False}} + @self.route("PUT", r"/locations/([^/]+)/users/([^/]+)/first-alert/email-preferences") def email_prefs(req, body, lid, uid): - api.email_prefs[uid] = body + api.email_prefs[(lid, uid)] = body return 200, {"emailNotifications": {"masterEnabled": body["masterEnabled"], "alerts": []}} @self.route("GET", r"/locations/([^/]+)/users/([^/]+)/first-alert/notification-preferences") def get_prefs(req, body, lid, uid): - alerts = [{"alertId": r["id"], "alertName": r["name"], "emailEnabled": False} + master = api.email_prefs.get((lid, uid), {"masterEnabled": True})["masterEnabled"] + alerts = [{"alertId": r["id"], "alertName": r["name"], "emailEnabled": master} for r in api.rules.values() if r["location_id"] == lid] - return 200, {"emailNotifications": {"masterEnabled": False, "alerts": alerts}, + return 200, {"emailNotifications": {"masterEnabled": master, "alerts": alerts}, "digest": {"enabled": False}, "webhook": {"url": None}} + # conversation data (frontline) + @self.route("GET", r"/locations") + def visible_locations(req, body): + return 200, page(api.visible_locations, "location") + + @self.route("GET", r"/calls") + def list_calls(req, body): + lid = req.url.params.get("location_id") + q = req.url.params.get("search") + rows = [r for r in api.call_rows if (not lid or r.get("location_id") in lid.split(",")) + and (not q or q in (r.get("caller_number") or "") + (r.get("summary") or ""))] + return api._paged(req, rows, "calls", {"total_calls": len(rows), "missed_calls": 0}) + + @self.route("GET", r"/calls/([^/]+)") + def get_call(req, body, cid): + if cid not in api.call_details: + return 404, {"error": {"code": "NOT_FOUND", "message": "not found"}} + return 200, {"data": api.call_details[cid]} + + @self.route("GET", r"/calls/([^/]+)/transcript") + def get_transcript(req, body, cid): + return 200, {"data": {"transcript": [{"time": 0.0, "speaker": "Speaker 1", "name": "Sam", "text": "Hello"}]}} + + @self.route("GET", r"/alerts") + def list_alerts(req, body): + q = req.url.params.get("search") + rows = [a for a in api.alert_rows if not q or a["id"] == q] + return api._paged(req, rows, "alerts", {"total": len(rows)}) + + @self.route("GET", r"/tasks") + def list_tasks(req, body): + st = req.url.params.get("status") + rows = [t for t in api.task_rows if st != "open" or t["status"] in ("pending", "in_progress", "overdue")] + return 200, {"data": rows, "meta": {"has_more": False, "next_cursor": None}} + + @self.route("GET", r"/insights/dashboard") + def insights(req, body): + return 200, {"data": api.insights} + + def _paged(self, req: httpx.Request, rows: List[Dict[str, Any]], key: str, summary: Dict[str, Any]): + limit = int(req.url.params.get("limit") or 50) + start = int(req.url.params.get("cursor") or 0) + chunk = rows[start:start + limit] + more = start + limit < len(rows) + return 200, {"data": {key: chunk, "summary": summary}, + "meta": {"has_more": more, "next_cursor": str(start + limit) if more else None, "limit": limit}} + def _user_attrs(self, u: Dict[str, Any]) -> Dict[str, Any]: return {"id": u["id"], "company_id": u["company_id"], "email": u["email"], "role": u["role"], "status": u["status"], "locations": [{"location_id": x} for x in u["_locations"]], + "invited_at": u.get("invited_at"), **({"department": u["department"]} if u.get("department") else {})} def _loc_user(self, u: Dict[str, Any], lid: str) -> Dict[str, Any]: return {"id": u["id"], "email": u["email"], "role": u["role"], "status": u["status"], "location_id": lid, - "enabled_products": sorted(u["_products"]), - "groups": [g["group_name"] for g in self.groups.values() if u["id"] in g["members"]]} + "enabled_products": sorted(u["_products"].get(lid, set())), + "groups": [g["group_name"] for g in self.groups.values() + if g["location_id"] == lid and u["id"] in g["members"]]} diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py new file mode 100644 index 0000000..e65552c --- /dev/null +++ b/tests/unit/test_accounts.py @@ -0,0 +1,618 @@ +"""The account layer against the in-memory fake API.""" +from __future__ import annotations + +import logging +import re + +import pytest + +import intelligence_cloud as ic +from intelligence_cloud.accounts import TEAM_GROUPS + +from .fake_api import RESELLER, FakeAPI, new_id + +COMPANY = "Riverbend Auto Group" +MGMT = COMPANY + " - Management" +TEAM = ic.TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", + country="US", zipcode="62701", vertical="service-providers") +EAST = ic.TeamSpec(name="Riverbend - East", street="9 Lake St", city="Springfield", state="IL", + country="US", zipcode="62702", vertical="service-providers") +CONN = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend.example.com", "KEY-123") +EAST_CONN = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend-east.example.com", "KEY-456") +THREAT = ["example threat one", "example threat two"] +UPSET = ["example upset one"] +ALERTS = ic.AlertSettings(customer_threat=ic.AlertSetting(phrases=THREAT), + upset_customer=ic.AlertSetting(phrases=UPSET)) +ALERT_GROUPS = ("Customer Threats", "Upset Customers", "Low Sentiment Calls") + + +def spec(**kw): + base = dict(company_name=COMPANY, + admin=ic.PersonSpec("pat@example.com", "Pat", "Lee", phone_number="+15555550100"), + team=TEAM, connector=CONN, alerts=ALERTS, mfa_off=True, sso_domain="riverbend.example.com") + base.update(kw) + return ic.CustomerSpec(**base) + + +def person(n): + return ic.PersonSpec(email=f"user{n}@example.com", first_name="U", last_name=str(n)) + + +def rule(api, lid, name): + return next(r for r in api.rules.values() if r["location_id"] == lid and r["name"] == name) + + +def invariants(api): + """Monitor-all off everywhere, no alert email on for anyone, no rules at Management.""" + assert not any(api.ih_config.values()) + assert all(p["masterEnabled"] is False for p in api.email_prefs.values()) + mgmt = [lid for lid, loc in api.locations.items() if loc["location_name"].endswith(" - Management")] + assert not [r for r in api.rules.values() if r["location_id"] in mgmt] + + +@pytest.fixture +def api(): + return FakeAPI() + + +@pytest.fixture +def client(api): + return api.client() + + +@pytest.fixture +def customer(client): + return client.accounts.create_customer(spec()) + + +# ---------------------------------------------------------------------- create + + +def test_create_follows_the_setup_flow(api, client): + cust = client.accounts.create_customer(spec()) + order = [("POST", r"/resellers/[^/]+/companies"), ("PATCH", r"/companies/[^/]+"), + ("POST", r"/companies/[^/]+/domains"), ("POST", r"/companies/[^/]+/locations"), + ("POST", r"/locations/[^/]+/connectors"), ("POST", r"/locations/[^/]+/user-groups"), + ("POST", r"/locations/[^/]+/first-alert/rules"), ("POST", r"/locations/[^/]+/insights-hub/setup")] + seq = api.writes() + pos = -1 + for m, pat in order: + pos = next(i for i, (mm, pp) in enumerate(seq) if mm == m and re.match("^" + pat + "$", pp) and i > pos) + company = api.companies[cust.company_id] + assert company["mfa_enforced"] is False + assert company["enabled_products"] == ["after-call-copilot", "first-alert-copilot", "insights-hub"] + team, mgmt = cust.teams[0], cust.management + assert (team.name, team.kind, mgmt.name, mgmt.kind) == ("Riverbend - Main", "team", MGMT, "management") + assert api.count("POST", r"/companies/[^/]+/locations") == 2 + # five groups on the team, the weekly reports group at Management + assert sorted(g["group_name"] for g in api.groups.values() if g["location_id"] == team.location_id) == \ + sorted(TEAM_GROUPS.values()) + assert [g["group_name"] for g in api.groups.values() if g["location_id"] == mgmt.location_id] == \ + ["Insights Hub Weekly Reports"] + # three rules, switched off, each routed to its group, at the documented levels and priorities + ct, uc, ls = (rule(api, team.location_id, n) for n in ("Customer Threat", "Upset Customer", "Low Sentiment")) + assert (ct["priority"], uc["priority"], ls["priority"]) == ("high", "medium", "low") + assert ct["triggers"] == [{"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": -20}}, + {"trigger_type": "keyword_match", "config": {"keywords": THREAT, "match_logic": "any"}}] + assert uc["triggers"][0]["config"]["threshold"] == -20 and uc["triggers"][1]["config"]["keywords"] == UPSET + assert ls["triggers"] == [{"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": -40}}] + assert ct["match_logic"] == uc["match_logic"] == "all" and ls["match_logic"] == "any" + assert ct["groups"] == [{"id": team.groups.customer_threats}] + assert uc["groups"] == [{"id": team.groups.upset_customers}] + assert ls["groups"] == [{"id": team.groups.low_sentiment_calls}] + assert not any(r["enabled"] for r in api.rules.values()) + assert (team.rules.customer_threat, team.rules.upset_customer, team.rules.low_sentiment) == (ct["id"], uc["id"], ls["id"]) + assert mgmt.rules == ic.TeamRules() + # connector on each location, named " phone system" + names = sorted(c["name"] for c in api.connectors.values()) + assert names == sorted([f"{MGMT} phone system", "Riverbend - Main phone system"]) + assert team.connector_status == mgmt.connector_status == "active" and team.connector_id != mgmt.connector_id + assert api.ih_setup[team.location_id]["group_access"] == [team.groups.insights_hub_access] + assert cust.sso_txt_record == {"name": "_ic-verify.riverbend.example.com", "value": "abc"} + assert cust.pending == [] and "company" in cust.created + loc_body = next(b for m, p, b in api.bodies if m == "POST" and p.endswith("/locations")) + assert set(loc_body) == {"location_name", "street", "city", "state", "country", "zipcode", "vertical_id", + "enabled_products"} + invariants(api) + + +def test_rerun_writes_nothing(api, client, customer): + start = len(api.calls) + again = client.accounts.create_customer(spec(company_id=customer.company_id)) + assert api.writes(start) == [] + assert again.company_id == customer.company_id and again.teams[0].location_id == customer.teams[0].location_id + assert again.teams[0].rules == customer.teams[0].rules and again.management.groups == customer.management.groups + assert not again.created and again.existing + + +def test_rerun_switches_monitor_all_off(api, client, customer): + api.ih_config[customer.teams[0].location_id] = True + api.ih_config[customer.management.location_id] = True + client.accounts.create_customer(spec()) + assert not any(api.ih_config.values()) + + +def test_create_without_phrases_leaves_them_pending(api, client): + cust = client.accounts.create_customer(spec(alerts=None)) + team = cust.teams[0] + assert cust.pending == ["customer_threat", "upset_customer"] + assert [r["name"] for r in api.rules.values()] == ["Low Sentiment"] + assert len([g for g in api.groups.values() if g["location_id"] == team.location_id]) == 5 + changed = client.accounts.set_alerts(cust, ALERTS) + assert len(changed) == 2 and cust.pending == [] + assert rule(api, team.location_id, "Customer Threat")["triggers"][1]["config"]["keywords"] == THREAT + assert client.accounts.get_customer(cust.company_id).pending == [] + start = len(api.calls) + assert client.accounts.set_alerts(cust, ALERTS) == [] and api.writes(start) == [] + + +def test_alert_levels_and_phrases_change_independently(api, client, customer): + lid = customer.teams[0].location_id + client.accounts.set_alerts(customer, ic.AlertSettings(customer_threat=ic.AlertSetting(sentiment_below=-30), + low_sentiment=ic.AlertSetting(sentiment_below=-55))) + ct = rule(api, lid, "Customer Threat") + assert ct["triggers"][0]["config"]["threshold"] == -30 and ct["triggers"][1]["config"]["keywords"] == THREAT + assert rule(api, lid, "Low Sentiment")["triggers"][0]["config"]["threshold"] == -55 + client.accounts.set_alerts(customer, ic.AlertSettings(customer_threat=ic.AlertSetting(phrases=["example new"]))) + ct = rule(api, lid, "Customer Threat") + assert ct["triggers"][0]["config"]["threshold"] == -30 and ct["triggers"][1]["config"]["keywords"] == ["example new"] + assert rule(api, lid, "Upset Customer")["triggers"][1]["config"]["keywords"] == UPSET + + +@pytest.mark.parametrize("bad", [ic.AlertSetting(sentiment_below=0), ic.AlertSetting(sentiment_below=-101), + ic.AlertSetting(phrases=[]), ic.AlertSetting(phrases="one phrase")]) +def test_bad_alert_settings_are_refused_before_any_write(api, client, bad): + with pytest.raises(ic.InvalidRequestError): + client.accounts.create_customer(spec(alerts=ic.AlertSettings(customer_threat=bad))) + with pytest.raises(ic.InvalidRequestError): + client.accounts.create_customer(spec(alerts=ic.AlertSettings( + low_sentiment=ic.AlertSetting(phrases=["x"])))) + assert api.writes() == [] + + +def test_set_alerts_keeps_on_off_state(api, client, customer): + lid = customer.teams[0].location_id + rule(api, lid, "Customer Threat")["enabled"] = True + client.accounts.set_alerts(customer, ic.AlertSettings(customer_threat=ic.AlertSetting(sentiment_below=-25))) + assert rule(api, lid, "Customer Threat")["enabled"] is True + assert rule(api, lid, "Upset Customer")["enabled"] is False + + +def test_inactive_company_needs_reactivate(api, client, customer): + api.companies[customer.company_id]["is_active"] = False + with pytest.raises(ic.InvalidRequestError): + client.accounts.create_customer(spec()) + client.accounts.create_customer(spec(reactivate=True)) + assert api.companies[customer.company_id]["is_active"] + + +def test_management_name_is_reserved(api, client): + with pytest.raises(ic.InvalidRequestError): + client.accounts.create_customer(spec(team=ic.TeamSpec(**{**vars(TEAM), "name": MGMT}))) + assert api.writes() == [] + + +def test_user_login_is_refused(api): + api.role = "frontline_user" + with pytest.raises(ic.WrongLoginError) as e: + api.client().accounts.create_customer(spec()) + assert "administrator" in str(e.value) and api.writes() == [] + + +# ---------------------------------------------------------------------- company matching + + +def add_company(api, name, email): + cid = new_id() + api.companies[cid] = {"id": cid, "company_name": name, "primary_admin_contact_email": email, + "reseller_id": RESELLER, "is_active": True, "mfa_enforced": True, + "enabled_products": ["after-call-copilot"]} + return cid + + +def test_same_name_other_contact_is_refused_before_any_write(api, client): + add_company(api, COMPANY, "someone.else@example.com") + with pytest.raises(ic.ConflictError) as e: + client.accounts.create_customer(spec()) + assert e.value.code == "company_name_conflict" and "company_id" in str(e.value) + assert api.writes() == [] + + +def test_same_name_and_contact_is_reused(api, client): + cid = add_company(api, COMPANY, "PAT@example.com ") + cust = client.accounts.create_customer(spec()) + assert cust.company_id == cid and "company" in cust.existing + assert api.count("POST", r"/resellers/[^/]+/companies") == 0 + assert api.companies[cid]["enabled_products"] == ["after-call-copilot", "first-alert-copilot", "insights-hub"] + + +def test_explicit_company_id_wins(api, client): + add_company(api, COMPANY, "other@example.com") + mine = add_company(api, COMPANY + " (East)", "pat@example.com") + assert client.accounts.create_customer(spec(company_id=mine)).company_id == mine + + +# ---------------------------------------------------------------------- connectors + + +def test_connector_spec_hides_secrets(): + cs = ic.ConnectorSpec(type="examplepbx", config={"host": "pbx.example.com", "client_secret": "S3CRET", + "API_TOKEN": "T0KEN", "password": "PW"}) + text = repr(cs) + str(cs.config) + repr(CONN) + for secret in ("S3CRET", "T0KEN", "PW", "KEY-123"): + assert secret not in text + assert "pbx.example.com" in text and cs.config["client_secret"] == "S3CRET" + + +def test_connector_of_another_type_from_type_and_config(api, caplog): + caplog.set_level(logging.DEBUG) + other = ic.ConnectorSpec(type="examplepbx", config={"host": "pbx.example.com", "domain": "rb.example", + "api_token": "T0KEN-SECRET"}) + c = api.client() + cust = c.accounts.create_customer(spec(connector=other)) + assert {x["type"] for x in api.connectors.values()} == {"examplepbx"} + assert all(x["config"]["host"] == "pbx.example.com" for x in api.connectors.values()) + assert api.secrets_sent[0] == {"host": "pbx.example.com", "domain": "rb.example", "api_token": "T0KEN-SECRET"} + assert "T0KEN-SECRET" not in repr(cust) + caplog.text + start = len(api.calls) + c.accounts.create_customer(spec(connector=other, company_id=cust.company_id)) + assert api.writes(start) == [] + + +def test_unknown_connector_type_is_refused_before_any_write(api, client): + bad = ic.ConnectorSpec(type="nosuchpbx", config={"api_key": "K-SECRET"}) + with pytest.raises(ic.InvalidRequestError) as e: + client.accounts.create_customer(spec(connector=bad)) + assert "K-SECRET" not in str(e.value) and api.writes() == [] + + +def test_connector_error_is_recorded_and_a_fixed_key_repairs_it(api): + api.connector_outcome = "error" + c = api.client() + first = c.accounts.create_customer(spec(sso_domain=None)) + assert first.teams[0].connector_status == "error" + assert first.teams[0].connector_state_reason == "invalid_permissions" + assert first.teams[0].rules.low_sentiment # the rest is still built + api.connector_outcome = "active" + fixed = ic.ConnectorSpec.netsapiens(CONN.config["api_url"], CONN.config["domain"], "NEW-KEY") + again = c.accounts.create_customer(spec(connector=fixed, company_id=first.company_id, sso_domain=None)) + assert again.teams[0].connector_id == first.teams[0].connector_id + assert again.teams[0].connector_status == "active" + assert api.connectors[first.teams[0].connector_id]["_key"] == "NEW-KEY" + assert api.count("POST", r"/locations/[^/]+/connectors") == 2 # never a second one per location + + +def test_same_domain_under_another_name_is_reused(api, client, customer): + renamed = ic.ConnectorSpec.netsapiens(CONN.config["api_url"], CONN.config["domain"].upper(), "KEY", name="Phones") + again = client.accounts.create_customer(spec(connector=renamed, company_id=customer.company_id)) + assert again.teams[0].connector_id == customer.teams[0].connector_id + assert api.count("POST", r"/locations/[^/]+/connectors") == 2 + assert api.connectors[customer.teams[0].connector_id]["name"] == "Phones" + + +def test_set_connector_attaches_one_later_and_refuses_an_active_one(api, client): + cust = client.accounts.create_customer(spec(connector=None, sso_domain=None)) + assert cust.teams[0].connector_id is None and api.connectors == {} + teams = client.accounts.set_connector(cust, CONN) + assert [t.kind for t in teams] == ["team", "management"] and all(t.connector_status == "active" for t in teams) + start = len(api.calls) + client.accounts.set_connector(cust, CONN) + assert api.writes(start) == [] + with pytest.raises(ic.InvalidRequestError): + client.accounts.set_connector(cust, EAST_CONN) + assert api.writes(start) == [] + + +# ---------------------------------------------------------------------- teams + + +def test_add_team_copies_the_first_teams_alerts(api, client, customer): + client.accounts.set_alerts(customer, ic.AlertSettings(upset_customer=ic.AlertSetting(sentiment_below=-35))) + east = client.accounts.add_team(customer, EAST, EAST_CONN) + assert east.kind == "team" and east.connector_status == "active" and len(customer.teams) == 2 + assert rule(api, east.location_id, "Customer Threat")["triggers"][1]["config"]["keywords"] == THREAT + assert rule(api, east.location_id, "Upset Customer")["triggers"][0]["config"]["threshold"] == -35 + assert not any(r["enabled"] for r in api.rules.values() if r["location_id"] == east.location_id) + assert len([g for g in api.groups.values() if g["location_id"] == east.location_id]) == 5 + start = len(api.calls) + again = client.accounts.add_team(customer.company_id, EAST, EAST_CONN) + assert again.location_id == east.location_id and api.writes(start) == [] + with pytest.raises(ic.InvalidRequestError): + client.accounts.add_team(customer, EAST, None) # type: ignore[arg-type] + other = client.accounts.add_team(customer, ic.TeamSpec(**{**vars(EAST), "name": "Riverbend - West"}), + EAST_CONN, alerts=ic.AlertSettings(low_sentiment=ic.AlertSetting(sentiment_below=-60))) + assert rule(api, other.location_id, "Low Sentiment")["triggers"][0]["config"]["threshold"] == -60 + invariants(api) + + +def test_get_customer_reads_the_layout(api, client, customer): + client.accounts.add_team(customer, EAST, EAST_CONN) + got = client.accounts.get_customer(customer.company_id) + assert got.management == customer.management + assert [t.location_id for t in got.teams] == [t.location_id for t in customer.teams] + assert got.teams[0].groups == customer.teams[0].groups and got.teams[0].rules == customer.teams[0].rules + assert got.pending == [] and got.sso_domain_id == "dom-1" + + +def test_an_old_layout_is_reported_with_what_is_missing(api, client): + cid = add_company(api, COMPANY, "pat@example.com") + lid = new_id() + api.locations[lid] = {"id": lid, "company_id": cid, "location_name": "Riverbend - Main", "is_active": True, + "created_at": api.tick()} + gid = new_id() + api.groups[gid] = {"id": gid, "location_id": lid, "group_name": "Manager Alerts", "members": []} + got = client.accounts.get_customer(cid) + assert "management location" in got.pending and "customer_threat" in got.pending + assert "Riverbend - Main: group Customer Threats" in got.pending + assert "Riverbend - Main: rule Low Sentiment" in got.pending + + +# ---------------------------------------------------------------------- people + + +def test_add_base_user(api, client, customer): + team = customer.teams[0] + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) + start = len(api.calls) + bu = client.accounts.add_base_user(customer, person(1), team=team, line="2101") + writes = api.writes(start) + assert writes[0][1].endswith("/users") and writes[-1][1].endswith(f"/{bu.user_id}/resend-invitation") + create = next(b for m, p, b in api.bodies if m == "POST" and p.endswith("/users") and b["email"] == "user1@example.com") + assert create["send_invitation"] is False and create["location_ids"] == [team.location_id] + assert api.products(bu.user_id, team.location_id) == {"after-call-copilot"} + assert api.mappings[bu.user_id] == [{"connector_id": team.connector_id, "monitored_numbers": ["2101"]}] + assert api.fa_numbers(team.location_id) == ["2101"] and api.ih_numbers(team.location_id) == ["2101"] + assert api.numbers(mgr.user_id, team.connector_id) == ["2101"] + assert api.email_prefs[(team.location_id, bu.user_id)]["masterEnabled"] is False + assert bu.created and bu.invited and bu.license == "base_user" and api.invitations == [bu.user_id] + start = len(api.calls) + again = client.accounts.add_base_user(customer, person(1), team=team, line="2101") + assert again.user_id == bu.user_id and not again.created and not again.invited + assert api.writes(start) == [] + invariants(api) + + +def test_add_base_manager(api, client, customer): + team, mgmt = customer.teams[0], customer.management + client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + client.accounts.add_base_user(customer, person(3), team=team, line="2103", invite=False) + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", company_reports=True) + assert sorted(mgr.lines) == ["2001", "2101", "2103"] and mgr.license == "base_manager" and mgr.invited + assert api.numbers(mgr.user_id, mgmt.connector_id) == ["2001"] + assert sorted(api.numbers(mgr.user_id, team.connector_id)) == ["2101", "2103"] + for lid in (team.location_id, mgmt.location_id): + assert api.products(mgr.user_id, lid) == {"after-call-copilot", "first-alert-copilot", "insights-hub"} + for name in TEAM_GROUPS.values(): + assert mgr.user_id in api.group_members(team.location_id, name) + assert mgr.user_id in api.group_members(mgmt.location_id, "Insights Hub Weekly Reports") + assert "2001" not in api.fa_numbers(team.location_id) + api.ih_numbers(team.location_id) + assert api.email_prefs[(team.location_id, mgr.user_id)]["masterEnabled"] is False + other = client.accounts.add_base_manager(customer, person(4), teams=[team]) + assert other.user_id not in api.group_members(mgmt.location_id, "Insights Hub Weekly Reports") + with pytest.raises(TypeError): + client.accounts.add_base_manager(customer, person(5), [team]) # type: ignore[misc] + invariants(api) + + +def test_activate_alerts_needs_a_manager_in_each_group(api, client, customer): + team = customer.teams[0] + out = client.accounts.activate_alerts(customer) + assert out["switched_on"] == [] and out["skipped"][0]["missing"] == list(ALERT_GROUPS) + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], invite=False) + api.groups[team.groups.upset_customers]["members"].remove(mgr.user_id) + out = client.accounts.activate_alerts(customer) + assert out["skipped"][0]["missing"] == ["Upset Customers"] + api.groups[team.groups.upset_customers]["members"].append(mgr.user_id) + out = client.accounts.activate_alerts(customer) + assert len(out["switched_on"]) == 3 and out["skipped"] == [] + assert all(r["enabled"] for r in api.rules.values()) + start = len(api.calls) + assert client.accounts.activate_alerts(customer)["switched_on"] == [] and api.writes(start) == [] + + +def test_mapping_failure_raises_account_error_and_rerun_continues(api): + api.connector_outcome = "error" + c = api.client() + cust = c.accounts.create_customer(spec(sso_domain=None)) + with pytest.raises(ic.AccountError) as e: + c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="2101") + err = e.value + assert err.step == "line" and isinstance(err.cause, ic.ExtensionMappingError) + assert err.result.user_id in api.users and api.invitations == [] + assert not api.fa_config.get(cust.teams[0].location_id) + api.connectors[cust.teams[0].connector_id]["status"] = "active" # the connector is fixed + again = c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="2101") + assert again.user_id == err.result.user_id and not again.created and again.invited + + +def test_integration_user(api, client, customer): + team = customer.teams[0] + a = client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], invite=False) + integ = client.accounts.add_integration_user(customer, person(9), invite=False) + assert api.users[integ.user_id]["department"] == "integration" and integ.lines == ["2101"] + assert api.email_prefs[(team.location_id, integ.user_id)]["masterEnabled"] is False + client.accounts.add_base_user(customer, person(3), team=team, line="2103", invite=False) + assert sorted(api.numbers(integ.user_id)) == ["2101", "2103"] + by = client.accounts.license_report(customer) + assert (by["base_user"], by["base_manager"], by["integration"], by["other"], by["teams"]) == (2, 1, 1, 0, 1) + out = client.accounts.remove_user(customer, integ.user_id) + assert out["license"] == "integration" and out["released_lines"] == [] + assert sorted(api.numbers(mgr.user_id, team.connector_id)) == ["2101", "2103"] + assert a.user_id + u = person(8) + u.auth_method = "sso" + with pytest.raises(ic.InvalidRequestError): + client.accounts.add_integration_user(customer, u) + + +def test_remove_user_releases_only_a_line_no_one_else_holds(api, client, customer): + team = customer.teams[0] + a = client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + client.accounts.add_base_user(customer, person(3), team=team, line="2103", invite=False) + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) + out = client.accounts.remove_user(customer, a.user_id) + assert out["released_lines"] == ["2101"] and out["deactivated"] + assert api.users[a.user_id]["status"] == "deactivated" and api.mappings[a.user_id] == [] + assert api.numbers(mgr.user_id, team.connector_id) == ["2103"] + assert api.fa_numbers(team.location_id) == ["2103"] and api.ih_numbers(team.location_id) == ["2103"] + start = len(api.calls) + client.accounts.remove_user(customer, a.user_id) + assert api.writes(start) == [] + out = client.accounts.remove_user(customer, mgr.user_id) + assert out["license"] == "base_manager" and out["released_lines"] == [] + assert api.fa_numbers(team.location_id) == ["2103"] + assert all(mgr.user_id not in g["members"] for g in api.groups.values()) + + +def test_remove_user_keep_lines(api, client, customer): + team = customer.teams[0] + a = client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + client.accounts.remove_user(customer, a.user_id, keep_lines=True) + assert api.fa_numbers(team.location_id) == ["2101"] + + +def test_sync_lines(api, client, customer): + team = customer.teams[0] + client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], line="2001", invite=False) + client.first_alert.set_monitored_numbers(team.location_id, team.connector_id, ["2199"]) + client.users.set_numbers(customer.company_id, mgr.user_id, team.connector_id, ["2199"]) + start = len(api.calls) + diff = client.accounts.sync_lines(customer, dry_run=True) + assert api.writes(start) == [] and not diff["applied"] + d = diff["teams"][team.location_id] + assert d["first_alert"] == {"add": ["2101"], "remove": ["2199"]} and d["insights_hub"] == {"add": [], "remove": []} + assert d["holders"][mgr.user_id] == {"add": ["2101"], "remove": ["2199"]} + assert client.accounts.sync_lines(customer)["applied"] + assert api.fa_numbers(team.location_id) == ["2101"] + assert api.numbers(mgr.user_id, team.connector_id) == ["2101"] + assert api.numbers(mgr.user_id, customer.management.connector_id) == ["2001"] # own line kept + start = len(api.calls) + client.accounts.sync_lines(customer) + assert api.writes(start) == [] + + +def test_send_invitations(api, client, customer): + team = customer.teams[0] + a = client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + b = client.accounts.add_base_user(customer, person(3), team=team, line="2103") + assert api.invitations == [b.user_id] + assert client.accounts.send_invitations(customer) == [a.user_id] + assert client.accounts.send_invitations(customer) == [] + assert client.accounts.send_invitations(customer, user_ids=[b.user_id]) == [b.user_id] + + +def test_offboard_customer(api, client, customer): + team = customer.teams[0] + client.accounts.add_base_user(customer, person(1), team=team, line="2101", invite=False) + mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], invite=False) + integ = client.accounts.add_integration_user(customer, person(9), invite=False) + client.intelligence.set_after_call_webhook(team.location_id, "https://hooks.example.com/ic/" + "x" * 32) + client.intelligence.set_first_alert_webhook(team.location_id, "https://hooks.example.com/fa/" + "y" * 32) + start = len(api.calls) + out = client.accounts.offboard_customer(customer) + kinds = [("automation" in p and "hook") or ("first-alert/config" in p and "fa") or + ("/connectors/" in p and "conn") or ("/users/" in p and "user") or ("/deactivate" in p and "company") + for _, p in api.writes(start)] + assert kinds == ["hook", "fa", "conn", "conn", "user", "company"] + assert api.after_call_hooks[team.location_id]["enabled"] is False + assert api.fa_config[team.location_id]["webhook_url"] is None and api.fa_numbers(team.location_id) == ["2101"] + assert all(c["status"] == "inactive" for c in api.connectors.values()) + assert out["integration_users_deactivated"] == [integ.user_id] + assert api.users[mgr.user_id]["status"] != "deactivated" and not api.companies[customer.company_id]["is_active"] + start = len(api.calls) + again = client.accounts.offboard_customer(customer) + assert not again["company_deactivated"] and again["connectors_deactivated"] == [] and api.writes(start) == [] + + +# ---------------------------------------------------------------------- the acceptance scenario + + +def test_acceptance_scenario(api, client): + """create, re-run (no writes), add team, add people, change license both ways, move, change line, + remove, activate, report, offboard.""" + acc = client.accounts + # create + cust = acc.create_customer(spec()) + main, mgmt = cust.teams[0], cust.management + invariants(api) + # re-run: no writes + start = len(api.calls) + acc.create_customer(spec(company_id=cust.company_id)) + assert api.writes(start) == [] + # add team + east = acc.add_team(cust, EAST, EAST_CONN) + assert [t.name for t in cust.teams] == ["Riverbend - Main", "Riverbend - East"] + invariants(api) + # add people + ana = acc.add_base_user(cust, person(1), team=main, line="2101") + ben = acc.add_base_user(cust, person(3), team=main, line="2103") + cy = acc.add_base_user(cust, person(5), team=east, line="3101") + dee = acc.add_base_manager(cust, person(2), teams=[main, east], line="2001", company_reports=True) + assert sorted(api.numbers(dee.user_id)) == ["2001", "2101", "2103", "3101"] + invariants(api) + # change license: Base User -> Base Manager (own line moves to Management) + up = acc.change_license(cust, ben.user_id, "base_manager", teams=[main]) + assert up.license == "base_manager" + assert api.numbers(ben.user_id, mgmt.connector_id) == ["2103"] + assert api.numbers(ben.user_id, main.connector_id) == ["2101"] + assert "2103" not in api.fa_numbers(main.location_id) + api.ih_numbers(main.location_id) + assert api.numbers(dee.user_id, main.connector_id) == ["2101"] + assert ben.user_id in api.group_members(main.location_id, "Customer Threats") + start = len(api.calls) + acc.change_license(cust, ben.user_id, "base_manager", teams=[main]) + assert api.writes(start) == [] + # change license: Base Manager -> Base User (keeps one team and their own line) + down = acc.change_license(cust, ben.user_id, "base_user", teams=[main]) + assert down.license == "base_user" and down.lines == ["2103"] + assert api.mappings[ben.user_id] == [{"connector_id": main.connector_id, "monitored_numbers": ["2103"]}] + assert api.products(ben.user_id, main.location_id) == {"after-call-copilot"} + assert mgmt.location_id not in api.users[ben.user_id]["_locations"] + assert all(ben.user_id not in g["members"] for g in api.groups.values()) + assert sorted(api.fa_numbers(main.location_id)) == ["2101", "2103"] + assert sorted(api.numbers(dee.user_id, main.connector_id)) == ["2101", "2103"] + invariants(api) + # move a Base User to another team + moved = acc.move_user(cust, ana.user_id, from_team=main, to_team=east) + assert moved.teams == [east.location_id] and "Call history stays with Riverbend - Main" in moved.notes[0] + assert api.mappings[ana.user_id] == [{"connector_id": east.connector_id, "monitored_numbers": ["2101"]}] + assert api.fa_numbers(main.location_id) == ["2103"] and sorted(api.fa_numbers(east.location_id)) == ["2101", "3101"] + assert sorted(api.numbers(dee.user_id, east.connector_id)) == ["2101", "3101"] + start = len(api.calls) + acc.move_user(cust, ana.user_id, from_team=main, to_team=east) + assert api.writes(start) == [] + # move: swap one of a Base Manager's teams + eve = acc.add_base_manager(cust, person(6), teams=[main], invite=False) + acc.move_user(cust, eve.user_id, from_team=main, to_team=east) + assert eve.user_id in api.group_members(east.location_id, "Upset Customers") + assert eve.user_id not in api.group_members(main.location_id, "Upset Customers") + assert api.numbers(eve.user_id, main.connector_id) == [] and sorted(api.numbers(eve.user_id, east.connector_id)) == ["2101", "3101"] + # change line + acc.change_line(cust, cy.user_id, "3101", "3109") + assert api.numbers(cy.user_id) == ["3109"] and "3101" not in api.fa_numbers(east.location_id) + assert "3109" in api.fa_numbers(east.location_id) and "3109" in api.ih_numbers(east.location_id) + assert "3109" in api.numbers(dee.user_id, east.connector_id) and "3101" not in api.numbers(dee.user_id) + start = len(api.calls) + acc.change_line(cust, cy.user_id, "3101", "3109") + assert api.writes(start) == [] + # remove + out = acc.remove_user(cust, cy.user_id) + assert out["released_lines"] == ["3109"] and "3109" not in api.numbers(dee.user_id) + # activate + act = acc.activate_alerts(cust) + assert len(act["switched_on"]) == 6 and act["skipped"] == [] + assert all(r["enabled"] for r in api.rules.values()) + # report + rep = acc.license_report(cust) + assert (rep["base_user"], rep["base_manager"], rep["integration"], rep["other"], rep["teams"]) == (2, 2, 0, 0, 2) + assert {m.user_id for m in acc.list_members(cust, license="base_manager")} == {dee.user_id, eve.user_id} + assert {m.user_id for m in acc.list_members(cust, team=east)} == {ana.user_id, dee.user_id, eve.user_id} + # nothing drifted along the way + assert all(not d["holders"] and not d["first_alert"]["add"] and not d["first_alert"]["remove"] + for d in acc.sync_lines(cust, dry_run=True)["teams"].values()) + invariants(api) + # offboard + off = acc.offboard_customer(cust.company_id) + assert off["company_deactivated"] and len(off["connectors_deactivated"]) == 3 + invariants(api) diff --git a/tests/unit/test_conversations.py b/tests/unit/test_conversations.py new file mode 100644 index 0000000..54cbcd2 --- /dev/null +++ b/tests/unit/test_conversations.py @@ -0,0 +1,202 @@ +"""The conversation layer against the in-memory fake API.""" +from __future__ import annotations + +import json +import logging +from datetime import date, datetime, timedelta, timezone + +import pytest + +import intelligence_cloud as ic + +from .fake_api import FakeAPI, new_id + +LOC = "0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02" +MGMT = "0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a03" +CALL = "0193b6d0-1e2f-7a3b-8c4d-5e6f7a8b9c01" +ALERT = "0193b6e1-1e2f-7a3b-8c4d-5e6f7a8b9c02" +SUMMARY = "Caller asked about a billing question." + + +def call_row(i=0, **kw): + row = {"id": CALL if i == 0 else new_id(), "call_date": "2026-11-02T16:41:07Z", "call_type": "inbound", + "status": "completed", "duration": 284, "caller_name": "Morgan Diaz", "caller_number": "+15555550142", + "callee_name": "Jordan Reyes", "callee_number": "2102", "location_id": LOC, "summary": SUMMARY, + "sentiment": "negative", "sentiment_score": -46, "task_count": 1} + row.update(kw) + return row + + +@pytest.fixture +def api(): + a = FakeAPI(role="frontline_user") + a.me_extra = {"email": "jordan.reyes@example.com", "first_name": "Jordan", "last_name": "Reyes", + "company_id": new_id(), "location_ids": [LOC]} + a.visible_locations = [{"id": LOC, "location_name": "Riverbend - Main"}, + {"id": MGMT, "location_name": "Riverbend Auto Group - Management"}] + a.call_rows = [call_row()] + a.call_details[CALL] = dict(call_row(), analysis={ + "summary": {"text": SUMMARY, "key_points": ["Billed twice"], "action_items": ["Refund"]}, + "sentiment": {"overall": "negative"}, "topics": [{"name": "Billing"}]}, + tasks=[{"id": new_id(), "title": "Call back", "status": "pending", "due_date": "2026-11-03"}], + vcon={"recording_url": "https://media.example.com/rec?sig=SECRET", "recording_url_expires_at": "2026-11-02T18:41:07Z"}) + a.alert_rows = [{"id": ALERT, "call_id": CALL, "call_date": "2026-11-02T16:41:07Z", "caller_name": "Morgan Diaz", + "caller_number": "+15555550142", "callee_name": "Jordan Reyes", "callee_number": "2102", + "summary": SUMMARY, "sentiment": "negative", "sentiment_score": -46, + "keywords": ["Upset Customer"], "topics": []}] + a.task_rows = [{"id": new_id(), "title": "Call back", "status": "pending", "due_date": "2026-11-03", + "call_id": CALL}, {"id": new_id(), "title": "Done", "status": "done", "call_id": CALL}] + a.insights = {"stats": {"total_calls": 10, "answered_calls": 8, "unanswered_calls": 2}, + "topic_call_volumes": [{"name": "Billing", "slug": "billing", "call_count": 4}], + "trending_topics": [{"name": "Billing", "slug": "billing", "call_count": 4, "percentage_change": 50, + "previous_call_count": 2, "trend_data": []}, + {"name": "Hours", "slug": "hours", "call_count": 1, "percentage_change": -20}]} + return a + + +def data_requests(api): + return [p for _, p in api.calls if not p.endswith("/me")] + + +def test_caller_numbers_are_masked_by_default(api): + b = api.client().conversations.calls()[0] + assert b.caller_number == "***0142" and b.callee_number == "2102" + full = api.client(mask_numbers=False).conversations.calls()[0] + assert full.caller_number == "+15555550142" + assert ic.mask_number("+1 (555) 555-0199") == "***0199" and ic.mask_number(None) is None + + +def test_brief_prints_only_id_and_time(api, caplog): + caplog.set_level(logging.DEBUG) + c = api.client() + b = c.conversations.brief(CALL) + assert repr(b) == str(b) == f"CallBrief(id='{CALL}', when='2026-11-02T16:41:07+00:00')" + a = c.conversations.alert(ALERT) + assert repr(a) == f"AlertBrief(id='{ALERT}', when='2026-11-02T16:41:07+00:00')" + for text in (repr(b), repr(a), repr(c.conversations.calls()), caplog.text): + assert SUMMARY not in text and "5555550142" not in text and "Morgan" not in text + + +def test_brief_fields(api): + b = api.client().conversations.brief(CALL) + assert b.when == datetime(2026, 11, 2, 16, 41, 7, tzinfo=timezone.utc) + assert (b.direction, b.duration_seconds, b.caller_name, b.callee_number) == ("inbound", 284, "Morgan Diaz", "2102") + assert b.summary == SUMMARY and b.key_points == ["Billed twice"] and b.topics == ["Billing"] + assert [t.title for t in b.tasks] == ["Call back"] and b.tasks[0].call_id == CALL + assert b.sentiment == "negative" and b.sentiment_score == -46 and b.alerts == ["Upset Customer"] + + +def test_limits_are_enforced_before_any_request(api): + conv = api.client().conversations + now = datetime.now(timezone.utc) + cases = [ + lambda: conv.calls(limit=201), lambda: conv.calls(limit=0), + lambda: conv.calls(since=now - timedelta(days=32)), + lambda: conv.calls(since=now - timedelta(days=1), until=now - timedelta(days=2)), + lambda: conv.calls(day=date(2026, 11, 2), since=now), + lambda: conv.calls(since=datetime(2026, 11, 1)), # no time zone + lambda: conv.calls(since="2026-11-01"), # date only + lambda: conv.calls(number="5555550142", search="billing"), + lambda: conv.alerts(limit=500), lambda: conv.alerts(since=now - timedelta(days=40)), + lambda: conv.alerts(status="open"), + lambda: conv.caller_history("5555550142", limit=51), + lambda: conv.team_view(LOC, since=now - timedelta(days=31, seconds=1)), + lambda: conv.topics(since=now - timedelta(days=60)), + ] + for case in cases: + with pytest.raises(ic.InvalidRequestError): + case() + assert data_requests(api) == [] + assert conv.calls(since=now - timedelta(days=31), until=now) # 31 days is allowed + + +def test_calls_follow_pages_up_to_the_limit(api): + api.call_rows = [call_row(i) for i in range(260)] + conv = api.client().conversations + assert len(conv.calls(limit=150)) == 150 + assert api.count("GET", r"/calls") == 2 + assert len(conv.calls(limit=200)) == 200 + + +def test_day_window(api): + api.client().conversations.calls(day=date(2026, 11, 2), team=LOC) + _, path, _ = api.bodies[-1] + assert path.endswith("/calls") + + +def test_administrator_login_gets_wrong_login_error(api): + api.role = "reseller_admin" + conv = api.client().conversations + for fn in (conv.calls, conv.me, conv.teams, conv.open_tasks, conv.alerts, lambda: conv.brief(CALL), + lambda: conv.transcript(CALL), lambda: conv.caller_history("5555550142"), + lambda: conv.team_view(LOC), conv.topics, lambda: conv.recording_link(CALL)): + with pytest.raises(ic.WrongLoginError) as e: + fn() + assert "user login" in str(e.value) + assert data_requests(api) == [] + + +def test_me_and_teams(api): + me = api.client().conversations.me() + assert me.email == "jordan.reyes@example.com" and me.name == "Jordan Reyes" and me.lines is None + assert [(t.name, t.kind) for t in me.teams] == [("Riverbend - Main", "team"), + ("Riverbend Auto Group - Management", "management")] + + +def test_transcript_recording_history_tasks_alerts(api): + conv = api.client().conversations + assert conv.transcript(CALL)[0]["speaker"] == "Speaker 1" + link = conv.recording_link(CALL) + assert link.url.startswith("https://media.example.com/") and "SECRET" not in repr(link) + assert [b.id for b in conv.caller_history("5555550142")] == [CALL] + tasks = conv.open_tasks(team="Riverbend - Main") + assert [t.title for t in tasks] == ["Call back"] and tasks[0].call_id == CALL + alerts = conv.alerts(since=datetime(2026, 11, 1, tzinfo=timezone.utc), until=datetime(2026, 11, 20, tzinfo=timezone.utc)) + assert alerts[0].alerts == ["Upset Customer"] and alerts[0].caller_number == "***0142" and alerts[0].holder is None + one = conv.alert(ALERT) + assert one.call.id == CALL and one.call.key_points == ["Billed twice"] + assert conv.alert(new_id()) is None + + +def test_team_view_and_topics(api): + conv = api.client().conversations + view = conv.team_view(LOC, day=date(2026, 11, 2)) + assert view.counts["total_calls"] == 1 and [b.id for b in view.briefs] == [CALL] + assert len(view.alerts) == 1 and [t.title for t in view.open_tasks] == ["Call back"] + topics = conv.topics() + assert topics.calls == {"total": 10, "answered": 8, "unanswered": 2} + assert [t["slug"] for t in topics.rising] == ["billing"] and "trend_data" not in topics.rising[0] + + +def test_reference_carries_only_the_id(api): + conv = api.client().conversations + ref = conv.reference(conv.brief(CALL)) + assert (ref.kind, ref.id, ref.link) == ("call", CALL, None) + assert conv.reference(conv.alert(ALERT)).kind == "alert" + assert conv.reference(CALL).id == CALL + + +# ---------------------------------------------------------------------- First Alert event + + +def test_parse_first_alert_event_shapes(): + flat = {"alert_id": ALERT.upper(), "rule_name": "Customer Threat", "location_id": LOC, "call_id": CALL, + "timestamp": "2026-11-02T16:46:12Z"} + ev = ic.parse_first_alert_event(json.dumps(flat)) + assert (ev.alert_id, ev.rule, ev.location_id, ev.call_id) == (ALERT, "Customer Threat", LOC, CALL) + assert ev.timestamp == datetime(2026, 11, 2, 16, 46, 12, tzinfo=timezone.utc) + assert repr(ev) == f"FirstAlertEvent(alert_id='{ALERT}', timestamp='2026-11-02T16:46:12+00:00')" + nested = {"alert": {"id": ALERT}, "rule": {"name": "Upset Customer"}, "location": {"id": LOC}, + "call": {"id": CALL, "caller_number": "+15555550142"}, "fired_at": "2026-11-02T16:46:12Z"} + ev2 = ic.Client(email="x@example.com", password="pw").conversations.parse_first_alert_event(json.dumps(nested).encode()) + assert (ev2.alert_id, ev2.rule, ev2.call_id) == (ALERT, "Upset Customer", CALL) + assert "5555550142" not in repr(ev2) + assert ic.parse_first_alert_event({"id": ALERT}).rule is None + + +def test_parse_first_alert_event_refuses_bad_bodies(): + for bad in (b"not json", b"[1]", b'{"alert_id": "not-a-uuid"}', b"{}"): + with pytest.raises(ic.WebhookPayloadError): + ic.parse_first_alert_event(bad) + with pytest.raises(ic.PayloadTooLargeError): + ic.parse_first_alert_event(b'{"alert_id": "' + ALERT.encode() + b'", "pad": "' + b"x" * ic.MAX_EVENT_BYTES + b'"}') diff --git a/tests/unit/test_review2.py b/tests/unit/test_review2.py index 3b7f858..7fb976b 100644 --- a/tests/unit/test_review2.py +++ b/tests/unit/test_review2.py @@ -1,4 +1,4 @@ -"""Company matching, integration users, connector re-runs, offboarding, receivers, tokens and errors.""" +"""Receivers, tokens and errors.""" from __future__ import annotations import json @@ -12,222 +12,11 @@ import intelligence_cloud as ic from intelligence_cloud import _spec -from .fake_api import RESELLER, FakeAPI, new_id from .test_client import UID, login_ok, make, token_body -from .test_workflows import CONN, spec, user SAMPLE = Path(__file__).resolve().parents[2] / "examples" / "after-call-sample.json" -@pytest.fixture -def api(): - return FakeAPI() - - -@pytest.fixture -def customer(api): - return api.client().workflows.provision_seat_customer(spec()) - - -def add_company(api, name, email): - cid = new_id() - api.companies[cid] = {"id": cid, "company_name": name, "primary_admin_contact_email": email, - "reseller_id": RESELLER, "is_active": True, "mfa_enforced": True, - "enabled_products": ["after-call-copilot"]} - return cid - - -def writes(api, start=0): - return [(m, p) for m, p in api.calls[start:] if m != "GET"] - - -# ------------------------------------------------------------------ company matching (never by name alone) - -def test_same_name_other_contact_is_refused_before_any_write(api): - add_company(api, "Riverbend Auto Group", "someone.else@example.com") - with pytest.raises(ic.ConflictError) as e: - api.client().workflows.provision_seat_customer(spec()) - assert e.value.code == "company_name_conflict" - assert "company_id" in str(e.value) - assert writes(api) == [] - - -def test_same_name_and_contact_is_reused(api): - cid = add_company(api, "Riverbend Auto Group", "PAT@example.com ") - cust = api.client().workflows.provision_seat_customer(spec()) - assert cust.company_id == cid and "company" in cust.existing - assert api.count("POST", r"/resellers/[^/]+/companies") == 0 - - -def test_only_the_contact_match_is_used_among_same_names(api): - add_company(api, "Riverbend Auto Group", "other@example.com") - mine = add_company(api, "Riverbend Auto Group", "pat@example.com") - cust = api.client().workflows.provision_seat_customer(spec()) - assert cust.company_id == mine - - -def test_explicit_company_id_wins(api): - add_company(api, "Riverbend Auto Group", "other@example.com") - mine = add_company(api, "Riverbend Auto Group (East)", "pat@example.com") - cust = api.client().workflows.provision_seat_customer(spec(company_id=mine)) - assert cust.company_id == mine - assert api.count("POST", r"/resellers/[^/]+/companies") == 0 - - -# ------------------------------------------------------------------ integration users - -def seat_with_people(api, customer): - c = api.client() - a = c.workflows.add_frontline_user(customer, user(1), "2101") - b = c.workflows.add_frontline_user(customer, user(3), "2103") - mgr = c.workflows.add_manager(customer, user(2)) - return c, a, b, mgr - - -def lines_everywhere(api, customer, mgr_id): - fa_nums = [n for m in api.fa_config[customer.location_id]["connector_mappings"] for n in m["monitored_numbers"]] - ih_nums = [n for m in api.ih_setup[customer.location_id]["connector_mappings"] for n in m["monitored_numbers"]] - mgr_nums = [n for m in api.mappings[mgr_id] for n in m["monitored_numbers"]] - return sorted(fa_nums), sorted(ih_nums), sorted(mgr_nums) - - -def test_integration_user_is_tagged_and_holds_every_line(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - integ = c.workflows.add_integration_user(customer, user(9)) - assert integ.kind == "integration" - assert api.users[integ.user_id]["department"] == "integration" - assert sorted(integ.numbers) == ["2101", "2103"] - assert api.email_prefs[integ.user_id]["masterEnabled"] is False - assert {m["id"] for m in c.workflows.list_managers(customer)} == {mgr.user_id} - assert {u["id"] for u in c.workflows.list_frontline_users(customer)} == {a.user_id, b.user_id} - assert [u["id"] for u in c.workflows.list_integration_users(customer)] == [integ.user_id] - # a later end user's line reaches the integration user, like a manager - c.workflows.add_frontline_user(customer, user(4), "2104") - assert sorted(n for m in api.mappings[integ.user_id] for n in m["monitored_numbers"]) == ["2101", "2103", "2104"] - - -def test_integration_user_needs_password_sign_in(api, customer): - u = user(9) - u.auth_method = "sso" - with pytest.raises(ic.InvalidRequestError): - api.client().workflows.add_integration_user(customer, u) - - -def test_removing_an_integration_user_keeps_every_line(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - integ = c.workflows.add_integration_user(customer, user(9)) - before = lines_everywhere(api, customer, mgr.user_id) - out = c.workflows.remove_user(customer, integ.user_id) - assert out["kind"] == "integration" and out["released_numbers"] == [] - assert lines_everywhere(api, customer, mgr.user_id) == before == (["2101", "2103"],) * 3 - assert api.users[integ.user_id]["status"] == "deactivated" and api.mappings[integ.user_id] == [] - - -def test_removing_an_untagged_all_lines_user_keeps_every_line(api, customer): - """A data user set up by hand (After Call only, every line, no tag) is not a seat.""" - c, a, b, mgr = seat_with_people(api, customer) - raw = c.workflows._ensure_user(customer, user(8))[0] - c.products.enable_user_product(customer.location_id, raw, "after-call-copilot") - c.users.set_numbers(customer.company_id, raw, customer.connector_id, ["2101", "2103"]) - assert sorted(c.workflows._lines(customer)) == ["2101", "2103"] # multi-line users add no lines - out = c.workflows.remove_user(customer, raw) - assert out["kind"] == "integration" and out["released_numbers"] == [] - assert lines_everywhere(api, customer, mgr.user_id) == (["2101", "2103"],) * 3 - - -def test_a_line_another_end_user_holds_is_not_released(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - shared = c.workflows.add_frontline_user(customer, user(5), "2101") # same line as user 1 - out = c.workflows.remove_user(customer, shared.user_id) - assert out["kind"] == "frontline" and out["released_numbers"] == [] - assert lines_everywhere(api, customer, mgr.user_id) == (["2101", "2103"],) * 3 - out = c.workflows.remove_user(customer, a.user_id) # now the last holder of 2101 - assert out["released_numbers"] == ["2101"] - assert lines_everywhere(api, customer, mgr.user_id) == (["2103"],) * 3 - - -def test_sync_numbers_gives_integration_users_exactly_the_lines(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - integ = c.workflows.add_integration_user(customer, user(9)) - c.users.set_numbers(customer.company_id, integ.user_id, customer.connector_id, ["2101", "2199"]) - diff = c.workflows.sync_numbers(customer) - assert diff["managers"][integ.user_id] == {"add": ["2103"], "remove": ["2199"]} - assert sorted(n for m in api.mappings[integ.user_id] for n in m["monitored_numbers"]) == ["2101", "2103"] - - -def test_excluded_users_are_invisible(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - customer.exclude_user_ids = [a.user_id] - customer.exclude_emails = ["USER2@example.com"] - assert {u["id"] for u in c.workflows.list_frontline_users(customer)} == {b.user_id} - assert c.workflows.list_managers(customer) == [] - assert c.workflows._lines(customer) == ["2103"] - - -def test_manager_needs_all_three_products(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - api.users[mgr.user_id]["_products"].discard("after-call-copilot") - assert c.workflows.list_managers(customer) == [] - - -# ------------------------------------------------------------------ connector re-runs - -def test_rerun_applies_a_fixed_key_to_a_connector_in_error(api): - api.connector_outcome = "error" - c = api.client() - first = c.workflows.provision_seat_customer(spec()) - assert first.connector_status == "error" - api.connector_outcome = "active" - fixed = ic.ConnectorSpec(api_url=CONN.api_url, domain=CONN.domain, api_key="NEW-KEY") - again = c.workflows.provision_seat_customer(spec(connector=fixed, company_id=first.company_id)) - conn = api.connectors[first.connector_id] - assert again.connector_id == first.connector_id and again.connector_status == "active" - assert conn["_key"] == "NEW-KEY" and "connector:updated" in again.existing - assert api.count("PATCH", r"/locations/[^/]+/connectors/[^/]+") == 1 - assert api.count("POST", r"/locations/[^/]+/connectors/[^/]+/reactivate") == 1 - assert api.count("POST", r"/locations/[^/]+/connectors") == 1 # never a second connector - - -def test_same_domain_under_another_name_is_reused(api, customer): - renamed = ic.ConnectorSpec(api_url=CONN.api_url, domain=CONN.domain.upper(), api_key="KEY", name="Phones") - again = api.client().workflows.provision_seat_customer(spec(connector=renamed, company_id=customer.company_id)) - assert again.connector_id == customer.connector_id - assert api.count("POST", r"/locations/[^/]+/connectors") == 1 - assert api.connectors[customer.connector_id]["name"] == "Phones" - - -def test_unchanged_active_connector_is_left_alone(api, customer): - start = len(api.calls) - api.client().workflows.provision_seat_customer(spec(company_id=customer.company_id)) - assert not [p for m, p in writes(api, start) if "/connectors" in p] - - -# ------------------------------------------------------------------ offboarding - -def test_offboard_customer_order(api, customer): - c, a, b, mgr = seat_with_people(api, customer) - integ = c.workflows.add_integration_user(customer, user(9)) - c.intelligence.set_after_call_webhook(customer.location_id, "https://hooks.example.com/ic/" + "x" * 32) - c.intelligence.set_first_alert_webhook(customer.location_id, "https://hooks.example.com/fa/" + "y" * 32) - start = len(api.calls) - out = c.workflows.offboard_customer(customer) - seq = [p.split("/api/v1")[-1] for m, p in writes(api, start)] - kinds = [("automation" in p and "hook") or ("first-alert/config" in p and "fa") or - ("deactivate" in p and "/connectors/" in p and "conn") or - ("/users/" in p and "user") or ("/deactivate" in p and "company") for p in seq] - assert kinds == ["hook", "fa", "conn", "user", "company"] - assert api.after_call_hooks[customer.location_id]["enabled"] is False - assert api.after_call_hooks[customer.location_id]["webhook_url"].startswith("https://hooks.example.com/") - assert api.fa_config[customer.location_id]["webhook_url"] is None - assert api.fa_config[customer.location_id]["connector_mappings"] # numbers kept - assert api.connectors[customer.connector_id]["status"] == "inactive" - assert out["integration_users_deactivated"] == [integ.user_id] - assert api.users[mgr.user_id]["status"] != "deactivated" - assert api.companies[customer.company_id]["is_active"] is False - again = c.workflows.offboard_customer(customer) # safe to run again - assert again["company_deactivated"] is False and again["connector_deactivated"] is False - - # ------------------------------------------------------------------ receiver def test_sample_event_parses(): diff --git a/tests/unit/test_workflows.py b/tests/unit/test_workflows.py deleted file mode 100644 index d27aef5..0000000 --- a/tests/unit/test_workflows.py +++ /dev/null @@ -1,369 +0,0 @@ -"""Seat lifecycle workflows against the in-memory fake API.""" -from __future__ import annotations - -import pytest - -import intelligence_cloud as ic -from intelligence_cloud.workflows import CUSTOMER_THREAT_RULE, UPSET_CUSTOMER_RULE - -from .fake_api import FakeAPI - -LOC = ic.LocationSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", - country="US", zipcode="62701", vertical="service-providers") -PHRASES = ["example phrase one", "example phrase two"] -CONN = ic.ConnectorSpec(api_url="https://pbx.example.com/ns-api/v2", domain="riverbend.example.com", api_key="KEY") - - -def spec(**kw): - base = dict(company_name="Riverbend Auto Group", admin_name="Pat Lee", admin_email="pat@example.com", - admin_phone="+15555550100", location=LOC, mfa_off=True, connector=CONN, threat_phrases=PHRASES, - sso_domain="riverbend.example.com") - base.update(kw) - return ic.SeatCustomerSpec(**base) - - -def user(n, invite=False): - return ic.UserSpec(email=f"user{n}@example.com", first_name="U", last_name=str(n), send_invitation=invite) - - -def write_paths(api, start): - return [(m, p.split("/api/v1")[-1]) for m, p in api.calls[start:] if m != "GET"] - - -@pytest.fixture -def api(): - return FakeAPI() - - -@pytest.fixture -def customer(api): - return api.client().workflows.provision_seat_customer(spec()) - - -def test_provision_call_sequence(api): - c = api.client() - cust = c.workflows.provision_seat_customer(spec()) - seq = [(m, p.split("/api/v1")[-1]) for m, p in api.calls] - order = [ - ("POST", r"/resellers/[^/]+/companies"), ("PATCH", r"/companies/[^/]+"), - ("POST", r"/companies/[^/]+/locations"), ("POST", r"/locations/[^/]+/user-groups"), - ("POST", r"/locations/[^/]+/first-alert/rules"), ("POST", r"/locations/[^/]+/connectors"), - ("POST", r"/locations/[^/]+/insights-hub/setup"), - ("POST", r"/companies/[^/]+/domains"), - ] - import re - pos = -1 - for m, pat in order: - idx = next(i for i, (mm, pp) in enumerate(seq) if mm == m and re.match("^" + pat + "$", pp) and i > pos) - pos = idx - company = api.companies[cust.company_id] - assert company["mfa_enforced"] is False - assert company["enabled_products"] == ["after-call-copilot", "first-alert-copilot", "insights-hub"] - assert api.count("POST", r"/locations/[^/]+/user-groups") == 2 - assert api.count("POST", r"/locations/[^/]+/first-alert/rules") == 2 - rules = {r["name"]: r for r in api.rules.values()} - upset, threat = rules[UPSET_CUSTOMER_RULE], rules[CUSTOMER_THREAT_RULE] - assert upset["triggers"] == [{"trigger_type": "sentiment", "config": {"operator": "lt", "threshold": -40}}] - assert upset["priority"] == "high" and threat["priority"] == "critical" and threat["match_logic"] == "all" - kw = threat["triggers"][1]["config"] - assert threat["triggers"][0]["config"] == {"operator": "lt", "threshold": -20} - assert kw["match_logic"] == "any" and kw["keywords"] == PHRASES - assert not any(r["enabled"] for r in rules.values()) # switched on by add_manager / activate_seat_alerts - assert api.count("PATCH", r"/locations/[^/]+/first-alert/rules/[^/]+") == 0 - assert all(r["groups"] == [{"id": cust.manager_alerts_group_id}] for r in rules.values()) - assert api.ih_setup[cust.location_id]["group_access"] == [cust.insights_hub_group_id] - assert api.ih_config.get(cust.location_id, False) is False # "monitor all numbers" stays off - assert api.count("PATCH", r"/locations/[^/]+/insights-hub/config") == 0 - assert cust.connector_status == "active" and cust.connector_id - assert cust.sso_txt_record == {"name": "_ic-verify.riverbend.example.com", "value": "abc"} - assert "company" in cust.created and not cust.existing - # only the documented location fields: no default rule pack, no support contact - loc_body = next(b for m, p, b in api.bodies if m == "POST" and p.endswith("/locations")) - assert set(loc_body) == {"location_name", "street", "city", "state", "country", "zipcode", "vertical_id", - "enabled_products"} - - -def test_rerun_switches_monitor_all_off(api, customer): - api.ih_config[customer.location_id] = True # as a 0.1.0 run left it - api.client().workflows.provision_seat_customer(spec()) - assert api.ih_config[customer.location_id] is False - - -def test_provision_is_idempotent(api, customer): - before = len(api.calls) - again = api.client().workflows.provision_seat_customer(spec()) - new_calls = api.calls[before:] - assert not [x for x in new_calls if x[0] == "POST" and not x[1].endswith("/domains")] - assert again.company_id == customer.company_id and again.location_id == customer.location_id - assert again.upset_customer_rule_id == customer.upset_customer_rule_id - assert not again.created - - -def test_provision_records_connector_error(api): - api.connector_outcome = "error" - cust = api.client().workflows.provision_seat_customer(spec(sso_domain=None)) - assert cust.connector_status == "error" and cust.connector_state_reason == "invalid_permissions" - assert cust.upset_customer_rule_id # the rest of the seat is still built - - -def test_inactive_company_needs_reactivate(api, customer): - api.companies[customer.company_id]["is_active"] = False - with pytest.raises(ic.InvalidRequestError): - api.client().workflows.provision_seat_customer(spec()) - api.client().workflows.provision_seat_customer(spec(reactivate=True)) - assert api.companies[customer.company_id]["is_active"] - - -def test_add_frontline_user_sequence(api, customer): - c = api.client() - mgr = c.workflows.add_manager(customer, user(2)) - before = len(api.calls) - fl = c.workflows.add_frontline_user(customer, user(1), "2101") - seq = [(m, p.split("/api/v1")[-1]) for m, p in api.calls[before:]] - writes = [(m, p) for m, p in seq if m != "GET"] - assert [m for m, _ in writes] == ["POST", "POST", "PUT", "PUT", "PUT", "PUT", "PATCH"] - assert writes[0][1].endswith("/users") and writes[1][1].endswith("/after-call-copilot/enable") - assert writes[2][1].endswith("/email-preferences") and writes[3][1].endswith(f"/{fl.user_id}/connector-mappings") - assert writes[4][1].endswith(f"/{mgr.user_id}/connector-mappings") - assert writes[5][1].endswith("/first-alert/config") and writes[6][1].endswith("/insights-hub/setup") - assert api.email_prefs[fl.user_id] == {"masterEnabled": False, "alerts": []} - assert api.mappings[fl.user_id] == [{"connector_id": customer.connector_id, "monitored_numbers": ["2101"]}] - assert api.mappings[mgr.user_id][0]["monitored_numbers"] == ["2101"] - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2101"] - assert api.ih_setup[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2101"] - assert api.users[fl.user_id]["_products"] == {"after-call-copilot"} - - -def test_add_manager_gets_all_lines(api, customer): - c = api.client() - c.workflows.add_frontline_user(customer, user(1), "2101") - c.workflows.add_frontline_user(customer, user(3), "2103") - mgr = c.workflows.add_manager(customer, user(2)) - assert mgr.numbers == ["2101", "2103"] - assert api.users[mgr.user_id]["_products"] == {"after-call-copilot", "first-alert-copilot", "insights-hub"} - groups = {g["group_name"]: g["members"] for g in api.groups.values()} - assert mgr.user_id in groups["Manager Alerts"] and mgr.user_id in groups["Insights Hub Access"] - prefs = api.email_prefs[mgr.user_id] - assert prefs["masterEnabled"] and len(prefs["alerts"]) == 2 and all(a["emailEnabled"] for a in prefs["alerts"]) - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2101", "2103"] - assert [r["id"] for r in c.workflows.list_managers(customer)] == [mgr.user_id] - assert len(c.workflows.list_frontline_users(customer)) == 2 - - -def test_manager_mapping_is_exactly_the_end_user_lines(api, customer): - # Base Intelligence Seat: a manager's own phone line is never captured - c = api.client() - c.workflows.add_frontline_user(customer, user(1), "2101") - c.workflows.add_frontline_user(customer, user(3), "2103") - with pytest.raises(TypeError): - c.workflows.add_manager(customer, user(2), "2190") # type: ignore[misc] - mgr = c.workflows.add_manager(customer, user(2)) - lines = ["2101", "2103"] - assert mgr.numbers == lines - assert api.mappings[mgr.user_id] == [{"connector_id": customer.connector_id, "monitored_numbers": lines}] - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == lines - assert api.ih_setup[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == lines - - -def test_add_frontline_user_is_rerunnable(api, customer): - c = api.client() - first = c.workflows.add_frontline_user(customer, user(1), "2101") - again = c.workflows.add_frontline_user(customer, user(1), "2101") - assert first.user_id == again.user_id and first.created and not again.created - assert api.count("POST", r"/companies/[^/]+/users") == 1 - - -def test_mapping_failure_raises_extension_mapping_error(api): - api.connector_outcome = "error" - c = api.client() - cust = c.workflows.provision_seat_customer(spec(sso_domain=None)) - with pytest.raises(ic.ExtensionMappingError) as e: - c.workflows.add_frontline_user(cust, user(1), "2101") - assert e.value.user_id in api.users # the user exists; re-run once the connector is active - assert e.value.cause.status == 422 - assert not api.fa_config.get(cust.location_id) # nothing half-synced - - -def test_change_user_extension(api, customer): - c = api.client() - fl = c.workflows.add_frontline_user(customer, user(1), "2101") - mgr = c.workflows.add_manager(customer, user(2)) - c.workflows.change_user_extension(customer, fl.user_id, "2101", "2106") - assert api.mappings[fl.user_id][0]["monitored_numbers"] == ["2106"] - assert api.mappings[mgr.user_id][0]["monitored_numbers"] == ["2106"] - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2106"] - assert api.ih_setup[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2106"] - - -def test_remove_user(api, customer): - c = api.client() - fl = c.workflows.add_frontline_user(customer, user(1), "2101") - c.workflows.add_frontline_user(customer, user(3), "2103") - mgr = c.workflows.add_manager(customer, user(2)) - c.groups.add_user_to_groups(customer.location_id, fl.user_id, [customer.insights_hub_group_id]) - out = c.workflows.remove_user(customer, fl.user_id) - assert out["released_numbers"] == ["2101"] - assert api.users[fl.user_id]["status"] == "deactivated" - assert all(fl.user_id not in g["members"] for g in api.groups.values()) - assert api.mappings[fl.user_id] == [] - assert api.mappings[mgr.user_id][0]["monitored_numbers"] == ["2103"] - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2103"] - # deactivate is last, and a second run tolerates "already deactivated" - assert api.calls[-1][0] == "POST" and api.calls[-1][1].endswith("/deactivate") - c.workflows.remove_user(customer, fl.user_id) - - -def test_remove_user_keep_extensions(api, customer): - c = api.client() - fl = c.workflows.add_frontline_user(customer, user(1), "2101") - c.workflows.remove_user(customer, fl.user_id, keep_extensions=True) - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2101"] - - -def test_sync_numbers_dry_run_and_apply(api, customer): - c = api.client() - c.workflows.add_frontline_user(customer, user(1), "2101") - mgr = c.workflows.add_manager(customer, user(2)) - # drift: First Alert lost 2101 and carries a stale 2199; the manager lost 2101 and carries - # 2190 (their own phone, which the Seat never captures) and 2199 - c.first_alert.set_monitored_numbers(customer.location_id, customer.connector_id, ["2199"]) - c.users.set_numbers(customer.company_id, mgr.user_id, customer.connector_id, ["2190", "2199"]) - before = len(api.calls) - diff = c.workflows.sync_numbers(customer, dry_run=True) - assert all(m == "GET" for m, _ in api.calls[before:]) - assert diff["first_alert"] == {"add": ["2101"], "remove": ["2199"]} - assert diff["managers"][mgr.user_id] == {"add": ["2101"], "remove": ["2190", "2199"]} - assert diff["insights_hub"] == {"add": [], "remove": []} and not diff["applied"] - applied = c.workflows.sync_numbers(customer) - assert applied["applied"] - assert api.fa_config[customer.location_id]["connector_mappings"][0]["monitored_numbers"] == ["2101"] - assert api.mappings[mgr.user_id][0]["monitored_numbers"] == ["2101"] - assert c.workflows.sync_numbers(customer, dry_run=True)["managers"] == {} - - -def test_get_seat_customer(api, customer): - got = api.client().workflows.get_seat_customer(customer.company_id) - for f in ("location_id", "manager_alerts_group_id", "insights_hub_group_id", "upset_customer_rule_id", - "customer_threat_rule_id", "connector_id"): - assert getattr(got, f) == getattr(customer, f) - - -def test_threat_phrases_required_for_a_new_customer(api): - with pytest.raises(ic.InvalidRequestError) as e: - api.client().workflows.provision_seat_customer(spec(threat_phrases=None)) - assert str(e.value) == "Customer Threat phrases are provided by your Tresic contact." - assert not [x for x in api.calls if x[0] != "GET"] # nothing created - - -def test_rerun_without_phrases_keeps_the_rule(api, customer): - again = api.client().workflows.provision_seat_customer(spec(threat_phrases=None)) - assert again.customer_threat_rule_id == customer.customer_threat_rule_id - kw = api.rules[customer.customer_threat_rule_id]["triggers"][1]["config"]["keywords"] - assert kw == PHRASES - - -def test_rerun_with_new_phrases_updates_the_rule(api, customer): - api.client().workflows.provision_seat_customer(spec(threat_phrases=["example phrase three"])) - kw = api.rules[customer.customer_threat_rule_id]["triggers"][1]["config"]["keywords"] - assert kw == ["example phrase three"] - - -def test_phrases_missing_when_rule_absent(api, customer): - del api.rules[customer.customer_threat_rule_id] - with pytest.raises(ic.InvalidRequestError): - api.client().workflows.provision_seat_customer(spec(threat_phrases=[])) - - -# ---------------------------------------------------------------------- invitation and alert order - - -def test_users_are_created_without_an_invitation(api, customer): - c = api.client() - c.workflows.add_frontline_user(customer, user(1, invite=True), "2101") - c.workflows.add_manager(customer, user(2, invite=True)) - creates = [b for m, p, b in api.bodies if m == "POST" and p.endswith("/users")] - assert len(creates) == 2 and all(b["send_invitation"] is False for b in creates) - - -def test_frontline_invitation_is_the_last_write(api, customer): - c = api.client() - mgr = c.workflows.add_manager(customer, user(2)) - before = len(api.calls) - fl = c.workflows.add_frontline_user(customer, user(1, invite=True), "2101") - writes = write_paths(api, before) - assert writes[-1] == ("POST", f"/companies/{customer.company_id}/users/{fl.user_id}/resend-invitation") - mapping = writes.index(("PUT", f"/companies/{customer.company_id}/users/{fl.user_id}/connector-mappings")) - assert mapping < len(writes) - 1 - assert ("PUT", f"/companies/{customer.company_id}/users/{mgr.user_id}/connector-mappings") in writes[:-1] - assert fl.invited and api.invitations == [fl.user_id] - - -def test_manager_activates_alerts_then_invites(api, customer): - c = api.client() - c.workflows.add_frontline_user(customer, user(1), "2101") - before = len(api.calls) - mgr = c.workflows.add_manager(customer, user(2, invite=True)) - writes = write_paths(api, before) - rule_patches = [i for i, (m, p) in enumerate(writes) if m == "PATCH" and "/first-alert/rules/" in p] - mapping = writes.index(("PUT", f"/companies/{customer.company_id}/users/{mgr.user_id}/connector-mappings")) - assert len(rule_patches) == 2 and mapping < rule_patches[0] - assert writes[-1] == ("POST", f"/companies/{customer.company_id}/users/{mgr.user_id}/resend-invitation") - assert all(r["enabled"] for r in api.rules.values()) - assert sorted(mgr.alerts_activated) == sorted([customer.upset_customer_rule_id, customer.customer_threat_rule_id]) - assert mgr.invited - # a second manager finds the alerts on already - second = c.workflows.add_manager(customer, user(3)) - assert second.alerts_activated == [] and not second.invited - - -def test_manager_without_alert_activation(api, customer): - c = api.client() - mgr = c.workflows.add_manager(customer, user(2), activate_alerts=False) - assert mgr.alerts_activated == [] and not any(r["enabled"] for r in api.rules.values()) - switched = c.workflows.activate_seat_alerts(customer) - assert len(switched) == 2 and all(r["enabled"] for r in api.rules.values()) - assert c.workflows.activate_seat_alerts(customer) == [] - - -def test_send_invitation_false_never_invites(api, customer): - c = api.client() - c.workflows.add_frontline_user(customer, user(1), "2101") - c.workflows.add_manager(customer, user(2)) - assert api.invitations == [] and api.count("POST", r"/companies/[^/]+/users/[^/]+/resend-invitation") == 0 - - -def test_no_invitation_when_mapping_fails(api): - api.connector_outcome = "error" - c = api.client() - cust = c.workflows.provision_seat_customer(spec(sso_domain=None)) - with pytest.raises(ic.ExtensionMappingError): - c.workflows.add_frontline_user(cust, user(1, invite=True), "2101") - with pytest.raises(ic.ExtensionMappingError): - c.workflows.add_frontline_user(cust, user(3, invite=True), "2103") - assert api.invitations == [] - # a manager whose lines cannot be mapped is not invited and does not switch the alerts on - for u in list(api.users.values()): - api.mappings[u["id"]] = [{"connector_id": cust.connector_id, "monitored_numbers": ["2101"]}] - u["_products"] = {"after-call-copilot"} - with pytest.raises(ic.ExtensionMappingError): - c.workflows.add_manager(cust, user(2, invite=True)) - assert api.invitations == [] and not any(r["enabled"] for r in api.rules.values()) - - -def test_rerun_after_mapping_failure_invites(api): - api.connector_outcome = "error" - c = api.client() - cust = c.workflows.provision_seat_customer(spec(sso_domain=None)) - with pytest.raises(ic.ExtensionMappingError) as e: - c.workflows.add_frontline_user(cust, user(1, invite=True), "2101") - api.connectors[cust.connector_id]["status"] = "active" # the connector is fixed - again = c.workflows.add_frontline_user(cust, user(1, invite=True), "2101") - assert again.user_id == e.value.user_id and not again.created and again.invited - assert api.invitations == [again.user_id] - - -def test_rerun_keeps_rules_on(api, customer): - c = api.client() - c.workflows.add_manager(customer, user(2)) - c.workflows.provision_seat_customer(spec()) - assert all(r["enabled"] for r in api.rules.values()) From a6c9ae2baf1ce2eb377d474c6a0d340b7f05dfca Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:00:43 -0700 Subject: [PATCH 02/12] Examples: create_customer.py replaces the provisioning example; add my_day.py create_customer.py builds a customer with the account layer (dry run unless --apply; phrase lists optional). my_day.py shows a person's day through the conversation layer with masked numbers and no content in logs. Co-Authored-By: Claude Opus 5.5 --- examples/_common.py | 2 +- examples/alert_webhook_receiver.py | 2 +- examples/create_customer.py | 68 ++++++++++++++++++++++++++++++ examples/my_day.py | 33 +++++++++++++++ examples/provision_seat.py | 48 --------------------- 5 files changed, 103 insertions(+), 50 deletions(-) create mode 100644 examples/create_customer.py create mode 100644 examples/my_day.py delete mode 100644 examples/provision_seat.py diff --git a/examples/_common.py b/examples/_common.py index 65c88e2..0fe01bb 100644 --- a/examples/_common.py +++ b/examples/_common.py @@ -18,6 +18,6 @@ def client_from_env(kind: str = "data") -> Client: e, p = PAIRS[k] email, password = os.environ.get(e), os.environ.get(p) if email and password: - return Client(email=email, password=password, user_agent="ic-examples/0.1") + return Client(email=email, password=password, user_agent="ic-examples/0.2") names = " or ".join(f"{PAIRS[k][0]} and {PAIRS[k][1]}" for k in kinds) sys.exit(f"Set {names} (a dedicated integration user).") diff --git a/examples/alert_webhook_receiver.py b/examples/alert_webhook_receiver.py index 5e114eb..8e41602 100644 --- a/examples/alert_webhook_receiver.py +++ b/examples/alert_webhook_receiver.py @@ -9,7 +9,7 @@ for example with admin.intelligence.set_first_alert_webhook(location_id, url). The receiver checks the path token in constant time, reads only the alert id from the request, answers 204 at once and drops repeat deliveries of the same alert. A worker thread then fetches the -alert and its call with the frontline integration user (a member of Manager Alerts). +alert and its call with the frontline integration user (a member of every alert group). Pass --self-test to post a sample delivery to itself, without fetching, and exit. """ import hmac diff --git a/examples/create_customer.py b/examples/create_customer.py new file mode 100644 index 0000000..09aa917 --- /dev/null +++ b/examples/create_customer.py @@ -0,0 +1,68 @@ +"""Create a customer, add a Base User and a Base Manager, then switch the alerts on. Admin login. + +Dry run by default: prints what it would do. Pass --apply to make the changes. +Phrase lists come from you (ask your Tresic contact): put each list one phrase per line in the files +named by IC_THREAT_PHRASES_FILE and IC_UPSET_PHRASES_FILE. Without them the customer is still +created, and the two phrase alerts are listed in customer.pending until set_alerts adds them. +Running it again with the same input changes nothing. +""" +import os +import sys + +from _common import client_from_env +from intelligence_cloud import (AccountError, AlertSetting, AlertSettings, ConnectorSpec, CustomerSpec, + PersonSpec, TeamSpec) + + +def phrases(env_name): + path = os.environ.get(env_name) + if not path: + return None + with open(path) as fh: + return [line.strip() for line in fh if line.strip()] or None + + +threat, upset = phrases("IC_THREAT_PHRASES_FILE"), phrases("IC_UPSET_PHRASES_FILE") +spec = CustomerSpec( + company_id=os.environ.get("IC_COMPANY_ID") or None, # store customer.company_id after the first run + company_name="Riverbend Dental", + admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"), + team=TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", + country="US", zipcode="62701", vertical=os.environ.get("IC_VERTICAL", "")), + connector=ConnectorSpec.netsapiens(os.environ.get("IC_PBX_API_URL", "https://pbx.example.com/ns-api/v2"), + os.environ.get("IC_PBX_DOMAIN", "riverbend.example.com"), + os.environ.get("IC_PBX_API_KEY", "")), + alerts=AlertSettings(customer_threat=AlertSetting(phrases=threat) if threat else None, + upset_customer=AlertSetting(phrases=upset) if upset else None), + mfa_off=True, +) +user = PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz") +manager = PersonSpec("dana.cho@example.com", "Dana", "Cho") + +if "--apply" not in sys.argv: + print(f"Would create {spec.company_name!r} with team {spec.team.name!r} and " + f"{spec.company_name + ' - Management'!r}, a connector on each,") + print("five groups on the team, the weekly reports group at Management, and the alerts switched off;") + print(f"then add Base User {user.email} on line 2101 and Base Manager {manager.email} (own line 2001),") + print("and switch the alerts on. Phrase lists:", + "loaded" if threat and upset else "missing (those alerts stay pending)") + print("Run with --apply to make the changes.") + sys.exit(0) + +with client_from_env("admin") as admin: + try: + customer = admin.accounts.create_customer(spec) + team = customer.teams[0] + print("company", customer.company_id, "team", team.location_id, "connector", team.connector_status, + team.connector_state_reason or "") + if customer.pending: + print("pending:", ", ".join(customer.pending)) + # Invitations are emailed last, once each person's lines are mapped. invite=False holds them back. + admin.accounts.add_base_user(customer, user, team=team, line="2101", invite=False) + admin.accounts.add_base_manager(customer, manager, teams=[team], line="2001", invite=False) + result = admin.accounts.activate_alerts(customer) + print("alerts switched on:", len(result["switched_on"]), "teams skipped:", len(result["skipped"])) + print("invitations sent:", len(admin.accounts.send_invitations(customer))) + except AccountError as exc: + # Log the step and the error code, not the content. Run the script again to continue. + sys.exit(f"stopped at {exc.step}: {exc.cause}") diff --git a/examples/my_day.py b/examples/my_day.py new file mode 100644 index 0000000..d6f95a0 --- /dev/null +++ b/examples/my_day.py @@ -0,0 +1,33 @@ +"""A person's day: today's calls, open tasks and alerts. The person's own login. + + IC_DATA_EMAIL=... IC_DATA_PASSWORD=... python my_day.py + +Caller numbers are shown as their last four digits. Printing a brief shows only its id and time, +so this script prints the fields it means to show and writes nothing to logs. +""" +from _common import client_from_env +from intelligence_cloud import WrongLoginError + +with client_from_env("data") as client: + conv = client.conversations + try: + me = conv.me() + except WrongLoginError as exc: + raise SystemExit(str(exc)) + print(f"Signed in as {me.name}; teams: {', '.join(t.name for t in me.teams if t.kind == 'team')}") + + calls = conv.calls(limit=20) # today, newest first + print(f"\nCalls today: {len(calls)}") + for b in calls: + when = b.when.astimezone().strftime("%H:%M") if b.when else "--:--" + print(f" {when} {b.direction or '':<9} {b.caller_number or '':<8} {b.sentiment or ''}") + + tasks = conv.open_tasks() + print(f"\nOpen tasks: {len(tasks)}") + for t in tasks[:10]: + print(f" {t.due_date or 'no date':<10} {t.title}") + + alerts = conv.alerts(limit=20) + print(f"\nAlerts today: {len(alerts)}") + for a in alerts: + print(f" {', '.join(a.alerts)} call {conv.reference(a).id}") diff --git a/examples/provision_seat.py b/examples/provision_seat.py deleted file mode 100644 index f67f68b..0000000 --- a/examples/provision_seat.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Provision a Base Intelligence Seat customer, then add an end user and a manager. Admin login. - -Dry run by default: prints what it would create. Pass --apply to make the changes. -Customer Threat phrases are provided by your Tresic contact: put them one per line in the file -named by IC_THREAT_PHRASES_FILE. -""" -import os -import sys - -from _common import client_from_env -from intelligence_cloud import ConnectorSpec, LocationSpec, SeatCustomerSpec, UserSpec - -phrases_file = os.environ.get("IC_THREAT_PHRASES_FILE") -phrases = [l.strip() for l in open(phrases_file) if l.strip()] if phrases_file else None - -spec = SeatCustomerSpec( - company_id=os.environ.get("IC_COMPANY_ID") or None, # store customer.company_id after the first run - company_name="Riverbend Auto Group", - admin_name="Pat Lee", admin_email="pat.lee@example.com", admin_phone="+15555550100", - location=LocationSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", - country="US", zipcode="62701", vertical=os.environ.get("IC_VERTICAL", "csps-msps")), - threat_phrases=phrases, - mfa_off=True, - connector=ConnectorSpec(api_url=os.environ.get("IC_PBX_API_URL", "https://pbx.example.com/ns-api/v2"), - domain=os.environ.get("IC_PBX_DOMAIN", "riverbend.example.com"), - api_key=os.environ.get("IC_PBX_API_KEY", "")), -) -# Invitations are emailed only after each user's lines are mapped. send_invitation=False holds them back. -manager = UserSpec("dana.cho@example.com", "Dana", "Cho", send_invitation=False) -agent = UserSpec("sam.ortiz@example.com", "Sam", "Ortiz", send_invitation=False) - -if "--apply" not in sys.argv: - print(f"Would provision {spec.company_name!r} with location {spec.location.name!r},") - print("groups 'Manager Alerts' and 'Insights Hub Access', alerts 'Upset Customer' and 'Customer Threat',") - print(f"then add end user {agent.email} on extension 2101 and manager {manager.email},") - print("which switches both alerts on.") - print("Customer Threat phrases:", f"{len(phrases)} loaded" if phrases else "missing (set IC_THREAT_PHRASES_FILE)") - print("Run with --apply to make the changes.") - sys.exit(0) - -with client_from_env("admin") as admin: - customer = admin.workflows.provision_seat_customer(spec) - print("company", customer.company_id, "location", customer.location_id, - "connector", customer.connector_status, customer.connector_state_reason or "") - admin.workflows.add_frontline_user(customer, agent, "2101") - mgr = admin.workflows.add_manager(customer, manager) # switches both alerts on - print("alerts switched on:", len(mgr.alerts_activated)) - print("done") From ee6edbf7c87fadb4ca311d7d7d87823354d6bd8c Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:00:43 -0700 Subject: [PATCH 03/12] README and CHANGELOG for 0.2.0 The README replaces the workflow sections with the account and conversation layers and keeps the sections on reading data. The CHANGELOG entry carries the removal table. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 34 ++++++++++ README.md | 174 +++++++++++++++++++++++++++++++++------------------ 2 files changed, 148 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b715f..d42b6d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## 0.2.0 (2026-11-29) + +Two new layers. `client.accounts` replaces `client.workflows`; `client.conversations` is new. Every generated resource method and every `client.intelligence` helper keeps its name and behaviour. + +- **Account layer, `client.accounts`** (administrator login): create and maintain a customer on Base User and Base Manager licenses. A customer is a company with teams and a ` - Management` location. Each team gets its own connector, five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub Access, Insights Hub Weekly Reports) and three alerts (Customer Threat, Upset Customer, Low Sentiment), each routed to its group. Management gets its own connector, which captures the managers' own lines, and the weekly reports group; it has no alerts. Helpers: `create_customer`, `get_customer`, `add_team`, `set_alerts`, `set_connector`, `add_base_user`, `add_base_manager`, `add_integration_user`, `change_license`, `move_user`, `change_line`, `remove_user`, `activate_alerts`, `send_invitations`, `list_members`, `license_report`, `sync_lines`, `offboard_customer`. +- Every account helper finds what exists before it writes: a second run with the same input writes nothing. A helper that stops part-way raises `AccountError` with the step, the result so far and the cause. +- A customer can be created without the phrase lists: Low Sentiment and every group are created, `Customer.pending` lists the two phrase alerts, and `set_alerts` creates them when the lists arrive. `AlertSettings` sets the phrases and the sentiment level of each alert; `None` keeps what is there. Alerts are created switched off; `activate_alerts` switches them on for teams with a Base Manager in each alert group. +- Alert email is off for every person the helpers create, managers included (0.1.x switched it on for managers). Insights Hub "monitor all numbers" stays off. +- `ConnectorSpec(type, config, name=None, timeout=600)` takes any connector type the API accepts with that type's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Values whose names contain key, secret, token or password are hidden when the spec is printed. `add_team` requires a connector; `set_connector` attaches one to a customer created without it. +- **Conversation layer, `client.conversations`** (the person's own login): `me`, `teams`, `calls`, `brief`, `transcript`, `recording_link`, `caller_history`, `open_tasks`, `alerts`, `alert`, `team_view`, `topics`, `reference`, `parse_first_alert_event`. Caller numbers are masked to their last four digits unless the client is created with `mask_numbers=False`. Windows are at most 31 days and lists at most 200 (`caller_history` 50), checked before any request. Printing a `CallBrief` or `AlertBrief` shows only its id and time. +- `parse_first_alert_event` and `FirstAlertEvent` parse the First Alert webhook, beside `parse_after_call_event`. +- New errors: `AccountError` and `WrongLoginError` (an account helper with a user login, or a conversation helper with an administrator login). +- Examples: `examples/create_customer.py` replaces the provisioning example; `examples/my_day.py` shows the conversation layer. + +Removed in 0.2.0, with no aliases: + +| 0.1.x | 0.2.0 | +|---|---| +| `client.workflows` | `client.accounts` | +| the 0.1.x provisioning helper and its spec and result types | `create_customer`, `CustomerSpec`, `Customer` | +| `ConnectorSpec(api_url, domain, api_key)` | `ConnectorSpec.netsapiens(api_url, domain, api_key)`, or `ConnectorSpec(type, config)` | +| `threat_phrases` | `alerts` (`AlertSettings`: phrases and sentiment level per alert) | +| the 0.1.x customer read-back helper | `get_customer` | +| `add_frontline_user` | `add_base_user` | +| `add_manager` | `add_base_manager` (own line now captured at Management; alert email now off) | +| the 0.1.x alert activation helper | `activate_alerts` | +| `change_user_extension` | `change_line` | +| `list_frontline_users`, `list_managers`, `list_integration_users` | `list_members(license=...)` | +| `sync_numbers` | `sync_lines` | +| the 0.1.x user result type, `UserSpec`, `LocationSpec` | `Member`, `PersonSpec`, `TeamSpec` | +| "Manager Alerts" group, two rules | Three groups and three rules per team | + +A customer built with 0.1.x is not converted automatically: `get_customer` lists what its layout is missing in `Customer.pending`. + ## 0.1.1 (2026-11-29) - Insights Hub "monitor all numbers" is never switched on. `provision_seat_customer` used to set `monitor_all_numbers` to true; it now leaves it off and switches it off where an earlier run switched it on. Insights Hub covers the lines listed for the location, which `add_frontline_user` already adds. Re-run `provision_seat_customer` for customers set up with 0.1.0. diff --git a/README.md b/README.md index 15da0f1..e7366ee 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ Python client for the Intelligence Cloud partner API. It covers both jobs: -- **Customer lifecycle** with admin credentials (a reseller admin login): companies, locations, users, products, connectors, First Alert, Insights Hub, and the Base Intelligence Seat workflows. -- **Conversation intelligence** with frontline credentials (a frontline user login): calls, transcripts, recordings, alerts, tasks, insights, and the After Call webhook. +- **Customers** with an administrator login: the account layer (`client.accounts`) creates and maintains a customer on Base User and Base Manager licenses, beside one method per API operation (companies, locations, users, products, connectors, First Alert, Insights Hub). +- **Conversations** with a user login: the conversation layer (`client.conversations`) gives a signed-in person their own calls, tasks and alerts; `client.intelligence` reads calls, transcripts, recordings, alerts, tasks and insights; and the After Call and First Alert webhooks. -Version 0.1.1. Python 3.10 or later. One dependency: `httpx` (0.27 or later). +Version 0.2.0. Python 3.10 or later. One dependency: `httpx` (0.27 or later). The API reference is at https://docs.intelligence.cloud/reference.html, built from https://docs.intelligence.cloud/openapi.yaml. @@ -28,16 +28,16 @@ To run the examples without installing: `uv run --with httpx --with-editable . p ## Credentials -Today every integration signs in with the email and password of a **dedicated integration user**. Turn MFA off for that user's company (`mfa_off=True` in `provision_seat_customer`, or `PATCH /companies/{id}` with `mfa_enforced: false`). **API keys arrive in December 2026.** +Today every integration signs in with the email and password of a **dedicated integration user**. Turn MFA off for that user's company (`mfa_off=True` in `create_customer`, or `PATCH /companies/{id}` with `mfa_enforced: false`). **API keys arrive in December 2026.** Use one client per credential: | Credential | Role | Use it for | |---|---|---| -| Admin | `reseller_admin` | `client.companies`, `client.users`, ... and `client.workflows` | -| Frontline | `frontline_user` | `client.intelligence` (calls, alerts, tasks, insights) | +| Admin | `reseller_admin` | `client.accounts`, `client.companies`, `client.users`, ... | +| Frontline | `frontline_user` | `client.conversations` and `client.intelligence` (calls, alerts, tasks, insights) | -Admin logins get empty lists from the conversation-data endpoints by design. `client.intelligence` checks the role once and raises `FrontlineRequiredError` instead of returning empty data. +Admin logins get empty lists from the conversation-data endpoints by design. `client.intelligence` checks the role once and raises `FrontlineRequiredError` instead of returning empty data. `client.conversations` raises `WrongLoginError` for an administrator login, and `client.accounts` raises it for a user login. Keep credentials out of source code. Read them from your secret store or environment. Send secrets to Tresic only through **security@tresic.cloud**, and report security issues there too. @@ -49,7 +49,7 @@ admin = Client(email=os.environ["IC_ADMIN_EMAIL"], password=os.environ["IC_ADMIN data = Client(email=os.environ["IC_DATA_EMAIL"], password=os.environ["IC_DATA_PASSWORD"]) ``` -`Client(base_url="https://app.intelligence.cloud/api/v1", email, password, token_store=None, timeout=30)`; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. +`Client(base_url="https://app.intelligence.cloud/api/v1", email, password, token_store=None, timeout=30)`; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you") and `mask_numbers=True` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. ### Sign-in, tokens and sign-out @@ -62,61 +62,108 @@ data = Client(email=os.environ["IC_DATA_EMAIL"], password=os.environ["IC_DATA_PA - `client.logout()` signs out and **ends every session of that user, including the web app**. The SDK never calls it by itself. - Sign-in returning `mfa_required` raises `MfaRequiredError`: "Integration users need MFA off for their company. API keys arrive in December 2026." -## Quick start: customer lifecycle (admin) +## Account layer: `client.accounts` (admin) -Provision a Base Intelligence Seat customer: one location, After Call for end users, First Alert and Insights Hub for managers, the "Upset Customer" and "Customer Threat" alerts routed to "Manager Alerts", and an "Insights Hub Access" group. +A customer is one company with one or more **teams** (each a location in the API) and a **Management** location named ` - Management`. + +- Each team has a connector to the phone system, five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub Access, Insights Hub Weekly Reports) and three alerts, each routed to its group: Customer Threat (priority high, sentiment below -20 and its phrases), Upset Customer (medium, below -20 and its phrases) and Low Sentiment (low, below -40). +- Management has its own connector, which captures the managers' own lines, and the Insights Hub Weekly Reports group for the company-wide reports. It has no alerts. +- A **Base User** has After Call on their own line at one team. A **Base Manager** has all three products, their own line at Management, every Base User line of the teams they run, and those teams' groups. ```python -from intelligence_cloud import Client, SeatCustomerSpec, LocationSpec, ConnectorSpec, UserSpec +from intelligence_cloud import (AlertSetting, AlertSettings, Client, ConnectorSpec, CustomerSpec, + PersonSpec, TeamSpec) admin = Client(email=..., password=...) +phone_system = ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend.example.com", + api_key=phone_system_key) -customer = admin.workflows.provision_seat_customer(SeatCustomerSpec( +customer = admin.accounts.create_customer(CustomerSpec( company_id=saved_company_id, # None the first time; store customer.company_id and pass it on re-runs - company_name="Riverbend Auto Group", - admin_name="Pat Lee", admin_email="pat.lee@example.com", admin_phone="+15555550100", - location=LocationSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", - state="IL", country="US", zipcode="62701", vertical=""), - threat_phrases=customer_threat_phrases, # from your Tresic contact + company_name="Riverbend Dental", + admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"), + team=TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL", + country="US", zipcode="62701", vertical=""), + connector=phone_system, # used for the team and for Management + alerts=AlertSettings(customer_threat=AlertSetting(phrases=threat_phrases), + upset_customer=AlertSetting(phrases=upset_phrases)), mfa_off=True, # the company has an integration user - connector=ConnectorSpec(api_url="https://pbx.example.com/ns-api/v2", - domain="riverbend.example.com", api_key=phone_system_key), - sso_domain="riverbend.example.com", # optional: returns the DNS TXT record to publish )) +team = customer.teams[0] -# End users first: each line is mapped, then the invitation is emailed. -admin.workflows.add_frontline_user(customer, UserSpec("sam.ortiz@example.com", "Sam", "Ortiz"), "2101") -# The first manager switches the two alerts on, then gets the invitation. -admin.workflows.add_manager(customer, UserSpec("dana.cho@example.com", "Dana", "Cho")) +admin.accounts.add_base_user(customer, PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), team=team, line="2101") +admin.accounts.add_base_manager(customer, PersonSpec("dana.cho@example.com", "Dana", "Cho"), + teams=[team], line="2001") +admin.accounts.activate_alerts(customer) # once each team has a manager in its alert groups ``` -- **Customer Threat phrases are provided by your Tresic contact.** Pass them as `threat_phrases`. Creating the Customer Threat alert without them raises `InvalidRequestError`. -- The primary contact (`admin_email`) is always invited as customer admin by email. -- Every workflow can be run again. **Store `customer.company_id` and pass it as `company_id` on every re-run.** Without it, a company with the same name is used only when its primary contact email is `admin_email`; any other company with that name raises `ConflictError` (code `company_name_conflict`) before anything is written. The location, groups and rules are found by name, users by email, and the connector by its phone-system domain. A company or location found inactive raises unless `reactivate=True`. -- Both alert rules are created **switched off**. `add_manager` switches them on once the manager is set up (`activate_alerts=True`, the default). To switch them on yourself, pass `activate_alerts=False` and call `activate_seat_alerts(customer)` when you are ready. Re-running `provision_seat_customer` never switches a rule off. -- Users are created **without** an invitation. The workflow maps their lines and sets their products and groups, and only then emails the invitation. If a mapping is refused, `ExtensionMappingError` is raised and no invitation has been sent. Pass `UserSpec(..., send_invitation=False)` to invite later with `admin.users.resend_invitation(company_id, user_id)`. -- The connector connects in the background. The workflow checks it every 10 seconds, for up to 10 minutes (`ConnectorSpec(timeout=...)`), until it is `active` or `error`, and records `connector_status` and `connector_state_reason` on the result. A key that cannot create call subscriptions ends in `error` / `invalid_permissions`: use a read/write key. Re-run the workflow with the corrected key: a connector found in `error`, stopped, or with changed settings is updated with the settings you pass and restarted, never duplicated. -- Get the customer object back later with `admin.workflows.get_seat_customer(company_id)`. +- **Phrase lists come from you.** The SDK holds none; ask your Tresic contact for them. A customer can be created without them: Low Sentiment and every group are created, `customer.pending` lists `"customer_threat"` and `"upset_customer"`, and `set_alerts` creates those alerts when the lists arrive. +- **Safe to re-run.** Every helper finds what exists before it writes; a second run with the same input writes nothing. A company is never adopted by its name alone: pass `company_id` from the first run. Without it, a same-named company is used only when its primary contact email is `admin.email`; otherwise `ConflictError` (code `company_name_conflict`) is raised before anything is written. +- **Stops are reported.** A helper that fails part-way raises `AccountError` with `.step`, `.result` (so far) and `.cause`. Run it again with the same input to continue. +- **Alerts start switched off.** `activate_alerts` switches them on only for teams with at least one Base Manager in each alert group, and reports the teams it skipped. +- **Alert email is off** for every person the helpers create, managers included. People switch it on in their own settings. +- **Insights Hub "monitor all numbers" stays off.** The helpers never switch it on and switch it off where they find it on. +- **Invitations go last.** People are created without one; it is emailed once their products, groups and lines are in place (`invite=False` holds it back; `send_invitations` sends it later). +- **Connectors.** `ConnectorSpec(type, config, name=None, timeout=600)` takes the phone platform as the API names it and that platform's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Give the key in full each time: it is sent when a connector is created or repaired and is never kept, logged or shown when the object is printed. A new connector is checked every 10 seconds until it settles; its status is recorded on the team (`connector_status`, `connector_state_reason`). A re-run with a corrected key repairs a connector in `error`; it never creates a second one. -### Seat workflows +| Helper | Does | Returns | +|---|---|---| +| `create_customer(spec)` | Company with all three products, SSO domain claim (optional), first team and Management, connector on each (if given), groups, alerts (switched off), Insights Hub | `Customer` | +| `get_customer(company_id)` | Reads the layout back; a layout it does not recognise is listed in `pending` | `Customer` | +| `add_team(customer, team, connector, *, alerts=None)` | A further team with its connector, groups, alerts (copying the first team's phrases and levels unless `alerts` sets them) and Insights Hub | `Team` | +| `set_alerts(customer, alerts, *, team=None)` | Phrases and sentiment levels on one team or all; `None` keeps what is there; alerts keep their on or off state | rule ids changed | +| `set_connector(customer, connector, *, team=None)` | Attaches a phone system to the named team, or the first team and Management; refuses where an active one exists | `list[Team]` | +| `add_base_user(customer, person, *, team, line, invite=True)` | After Call, their line on the team's connector, First Alert and Insights Hub lists and the team's managers | `Member` | +| `add_base_manager(customer, person, *, teams, line=None, company_reports=False, invite=True)` | All three products on each team and Management, own line at Management, the teams' lines and groups; `company_reports=True` adds the company-wide reports group | `Member` | +| `add_integration_user(customer, person)` | A data-reading user across every team: password sign-in, tagged `department: "integration"`, every line | `Member` | +| `change_license(customer, user_id, to, *, teams=None, line=None)` | `"base_manager"` or `"base_user"`, moving their own line between the team and Management | `Member` | +| `move_user(customer, user_id, *, from_team, to_team)` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` | +| `change_line(customer, user_id, old, new)` | Releases the old line everywhere it is listed and maps the new one | `Member` | +| `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates | summary | +| `activate_alerts(customer, *, team=None)` | Switches alerts on where each alert group has a manager | `{"switched_on", "skipped"}` | +| `send_invitations(customer, *, user_ids=None)` | Sends invitations not yet sent or expired; re-sends to `user_ids` | user ids | +| `list_members(customer, *, license=None, team=None)` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `list[Member]` | +| `license_report(customer)` | People by license and the number of teams (Management not counted) | counts and members | +| `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people | changes | +| `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary | + +Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only: a clash raises `ConflictError` with the message "Extension is already monitored at another location." + +## Conversation layer: `client.conversations` (user login) + +Sign in as the person. The platform decides what each call returns: a Base User gets their own calls, a Base Manager their teams'. -| Method | Does | -|---|---| -| `provision_seat_customer(spec)` | Company, MFA off (optional), products, location, groups, both rules (switched off), connector (optional), Insights Hub access, SSO domain claim (optional). Returns `SeatCustomer` with every id. | -| `get_seat_customer(company_id)` | Rebuilds `SeatCustomer` from what is configured. | -| `add_frontline_user(customer, user, extension)` | Creates an end user (no invitation yet) with After Call on their own line and alert email off, maps the line, adds it to every manager, First Alert and Insights Hub, then emails the invitation. | -| `add_manager(customer, user, *, activate_alerts=True)` | Creates a manager (no invitation yet) with all three products, both groups and alert email on, maps all end-user lines at the location, switches both alerts on, then emails the invitation. The manager's own phone line is not captured on the Seat: it is never mapped, nor added to First Alert or Insights Hub. | -| `activate_seat_alerts(customer)` | Switches on the Upset Customer and Customer Threat rules. Returns the ids it switched on. | -| `change_user_extension(customer, user_id, old, new)` | Moves an end user's line: their mapping, every manager, First Alert, Insights Hub. | -| `add_integration_user(customer, user)` | Creates the customer's integration (data-reading) user: password sign-in, tagged `department: "integration"`, all three products, both groups, alert email off, every line. Never counted as a seat or manager; later end users' lines are added to it. Invitation last. | -| `remove_user(customer, user_id, keep_extensions=False)` | Removes the user from groups, clears their numbers, then deactivates. Only an end user's line is released, and only when no other end user holds it: it comes off managers, integration users, First Alert and Insights Hub (unless kept). Removing a manager, an integration user or anyone holding several lines never takes a line off anyone else. | -| `list_frontline_users(customer)` / `list_managers(customer)` / `list_integration_users(customer)` | The location's users, classified: end users have After Call only; managers have all three products; integration users are tagged `department: "integration"`. | -| `sync_numbers(customer, dry_run=False)` | Recomputes the location's lines (each end user's single extension) and pushes them to managers, integration users, First Alert and Insights Hub. Managers and integration users end up with exactly the lines; any other number on their mapping is removed. `dry_run=True` returns the changes only. | -| `offboard_customer(customer, deactivate_company=True)` | A customer leaves: pauses the After Call webhook, clears the First Alert webhook, stops the connector, deactivates the integration users, then deactivates the company. Safe to run again. | - -To keep a user out of every workflow (for example a person you manage by hand), list them in `customer.exclude_user_ids` or `customer.exclude_emails`. - -Number mappings need an **active** connector. When a mapping is refused, the workflow raises `ExtensionMappingError` with `user_id` set: the user exists but has not been invited, and you run the workflow again once the connector is active. The re-run finds the user, finishes the setup and emails the invitation. A re-run also re-sends the invitation to any user who has not accepted one yet. An extension can belong to one location only: a conflict raises `ConflictError` with the message "Extension is already monitored at another location." and the clashing numbers in `.extensions`. +```python +me = Client(email=..., password=...) + +for brief in me.conversations.calls(): # today, newest first + print(brief) # CallBrief(id=..., when=...): no content +history = me.conversations.caller_history("5555550142", limit=5) +detail = me.conversations.brief(call_id) # summary, key points, tasks, sentiment, topics, alerts +tasks = me.conversations.open_tasks() +board = me.conversations.team_view(team_id) # for a manager: counts, alerts, open tasks, briefs +``` + +| Helper | Returns | Limits | +|---|---|---| +| `me()`, `teams()` | Who is signed in and the teams they can see | | +| `calls(*, day=None, since=None, until=None, team=None, number=None, search=None, limit=50)` | `list[CallBrief]`, newest first; default today | window at most 31 days, `limit` at most 200 | +| `brief(call_id)` | One `CallBrief` with key points, tasks, topics and the alerts it raised | no transcript, no recording | +| `transcript(call_id)` | The transcript of one call | one call per request | +| `recording_link(call_id)` | A `RecordingLink` that expires; the SDK never downloads the audio | | +| `caller_history(number, *, limit=10)` | Recent briefs for one caller (last 31 days) | `limit` at most 50 | +| `open_tasks(*, due=None, team=None)` | Open tasks with the id of the call each came from | up to 200 | +| `alerts(*, since=None, until=None, team=None, limit=50)` | `list[AlertBrief]` on this person's teams | as `calls` | +| `alert(alert_id)` | One alert with its call brief | | +| `team_view(team, *, day=None, since=None, until=None)` | Counts, alerts, open tasks and briefs for one team | as `calls` | +| `topics(*, since=None, until=None, team=None)` | Topic volumes and rising topics (default last 7 days) | needs Insights Hub access | +| `reference(call_or_alert)` | The id only, to pass to another system in place of content | | +| `parse_first_alert_event(payload)` | A `FirstAlertEvent` | | + +- **Caller numbers are masked** to their last four digits (`***0142`) unless the client was created with `mask_numbers=False`. Extensions are shown as they are. +- **Limits are checked before any request**: a longer window, a larger limit, `number` with `search`, or a date without a time zone raises `InvalidRequestError`. +- **Nothing is logged.** Printing a brief shows its id and time only. Keep summaries, names and numbers out of your own logs too. +- An administrator login raises `WrongLoginError`. There is no helper that walks every call; for a bounded daily job use `client.intelligence.iter_calls`. ## Quick start: conversation intelligence (frontline) @@ -179,10 +226,11 @@ Every API operation is a method named after its `operationId` in snake case, gro | `client.insights` | `get_insights_dashboard`, `list_topic_calls` / `iter_topic_calls` | | `client.webhooks` | `get_after_call_webhook`, `save_after_call_webhook`, `test_after_call_webhook` | | `client.intelligence` | `whoami`, `require_frontline`, `search_calls` / `iter_calls`, `get_call`, `get_transcript`, `get_recording_url`, `search_alerts` / `iter_alerts`, `get_alert(alert_id, with_call=False)`, `get_alerts_dashboard`, `list_tasks` / `iter_tasks`, `get_insights_dashboard`, `list_topic_calls` / `iter_topic_calls`, `get_after_call_webhook`, `set_after_call_webhook`, `test_after_call_webhook`, `get_first_alert_webhook`, `set_first_alert_webhook`, `test_first_alert_webhook` | -| `client.workflows` | see "Seat workflows" | +| `client.accounts` | see "Account layer" | +| `client.conversations` | see "Conversation layer" | | `client` | `login`, `logout`, `close` | -Module level: `parse_after_call_event`, `UnknownEvent`, `MAX_EVENT_BYTES`, `Deduplicator`, `FileTokenStore`, `unwrap`, `Page`, the error classes and the spec dataclasses. +Module level: `parse_after_call_event`, `parse_first_alert_event`, `UnknownEvent`, `MAX_EVENT_BYTES`, `mask_number`, `Deduplicator`, `FileTokenStore`, `unwrap`, `Page`, the error classes and the spec dataclasses. ### Rules the SDK applies for you @@ -217,12 +265,14 @@ Log `status`, `code` and `request_id`, not exception text or response bodies. `s | `ConflictError` (409) | Duplicate name or email, already active or inactive, extension already monitored (`.extensions`) | | `ValidationError` (400, 422) | Malformed request or refused value | | `RateLimitError` (429) | Still rate limited after retries (`.retry_after`) | -| `InvalidRequestError` | Refused by the SDK before sending | +| `InvalidRequestError` | Bad input, refused by the SDK before sending | | `MfaRequiredError` | The integration user's company has MFA on | -| `FrontlineRequiredError` | Conversation data asked for with an admin login | -| `ConnectorError`, `ConnectorTimeoutError` | A connector ended in `error`, or did not finish in time | -| `ExtensionMappingError` | A workflow could not map numbers (`.user_id`, `.cause`) | -| `WebhookPayloadError` | A webhook body is not JSON, or is a malformed After Call event (answer 400) | +| `FrontlineRequiredError` | `client.intelligence` conversation data asked for with an admin login | +| `WrongLoginError` | An account helper with a user login, or a conversation helper with an administrator login; the message says which login to use | +| `AccountError` | An account helper stopped part-way (`.step`, `.result`, `.cause`); run it again to continue | +| `ConnectorError`, `ConnectorTimeoutError` | A connector ended in `error`, or a new connector did not settle in time | +| `ExtensionMappingError` | A helper could not map numbers (`.user_id`, `.cause`); the `.cause` of an `AccountError` | +| `WebhookPayloadError` | A webhook body is not JSON, or is a malformed After Call or First Alert event (answer 400) | | `PayloadTooLargeError` | A webhook body is over `max_bytes` (256 KB; answer 413) | All derive from `IntelligenceCloudError`. @@ -314,15 +364,18 @@ def after_call(token): ### Receive First Alert -The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. Read only the alert id, answer 2xx at once, then fetch the alert and its call with a frontline integration user in Manager Alerts: +The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. `parse_first_alert_event` returns a `FirstAlertEvent` (`alert_id`, and `rule`, `location_id`, `call_id`, `timestamp` when the delivery carries them). Take the alert id, answer 2xx at once, then fetch the alert and its call with a frontline integration user in every alert group: ```python @app.post("/ic/alerts/{token}") async def first_alert(token: str, request: Request, background: BackgroundTasks): if not hmac.compare_digest(token.encode(), ALERT_TOKEN.encode()): # IC_ALERT_WEBHOOK_TOKEN, 32+ characters raise HTTPException(status_code=404) - alert_id = alert_id_from(await request.body()) # see examples/alert_webhook_receiver.py - if alert_id is None: + try: + alert_id = parse_first_alert_event(await request.body()).alert_id + except PayloadTooLargeError: + raise HTTPException(status_code=413) + except WebhookPayloadError: raise HTTPException(status_code=400) if not alert_dedup.is_duplicate(alert_id): # a second Deduplicator, keyed on the alert id background.add_task(handle_alert, alert_id) @@ -350,7 +403,8 @@ Alerts are dated by their call, so start the window 30 minutes before the receiv |---|---|---| | `examples/whoami.py` | Sign in and print the role | any | | `examples/export_calls.py` | Export yesterday's calls to CSV (ids, dates, sentiment, duration) | frontline | -| `examples/provision_seat.py` | Provision a Seat customer and add an end user and a manager (dry run unless `--apply`; phrases from the file in `IC_THREAT_PHRASES_FILE`) | admin | +| `examples/create_customer.py` | Create a customer, add a Base User and a Base Manager, switch the alerts on (dry run unless `--apply`; phrase lists from the files in `IC_THREAT_PHRASES_FILE` and `IC_UPSET_PHRASES_FILE`, optional) | admin | +| `examples/my_day.py` | A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs | frontline (the person's own login) | | `examples/webhook_receiver.py` | A dependency-free After Call webhook receiver: 256 KB cap, a persistent queue keyed on `call.id`, a worker that reads each call (`--self-test` to try it offline) | frontline (worker) | | `examples/after-call-sample.json` | A sample After Call event for local tests | none | | `examples/alert_webhook_receiver.py` | A dependency-free First Alert webhook receiver that fetches each alert and its call (`--self-test` to try it offline) | frontline | From 28f3a566062e737adc5872479671b3bbbc734e2f Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:15:51 -0700 Subject: [PATCH 04/12] Fix review findings in the account and conversation layers - add_* helpers refuse a person already set up with another license - change_line changes only the person's own line; shared lines stay listed - change_license and move_user continue after a stop; old lines and teams stay on the result until the change completes; former teams are left - a line owned by someone read back as "other" is never released - connector failures stop create_customer, add_team and set_connector at the end with AccountError(step="connectors") - nested connector secrets hidden; config wraps on assignment - numbers inside names masked; day windows use each date's own offset - notes when a team's alert groups lose their last manager; people helpers switch monitor-all off on teams they touch - CallBrief.link, AlertBrief.link and reference() give app page links; Client(app_url=...) - fake API: duplicate email 409, alert search as published Co-Authored-By: Claude Opus 5.5 --- src/intelligence_cloud/accounts.py | 476 ++++++++++++++++------- src/intelligence_cloud/client.py | 15 +- src/intelligence_cloud/conversations.py | 80 +++- tests/unit/fake_api.py | 9 +- tests/unit/test_accounts.py | 15 +- tests/unit/test_conversations.py | 5 +- tests/unit/test_review_fixes.py | 487 ++++++++++++++++++++++++ 7 files changed, 930 insertions(+), 157 deletions(-) create mode 100644 tests/unit/test_review_fixes.py diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index ad74093..ccbb316 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -77,7 +77,7 @@ class _RuleDef: } PHRASE_ALERTS = ("customer_threat", "upset_customer") LICENSES = ("base_user", "base_manager", "integration", "other") -_SECRET_WORDS = ("key", "secret", "token", "password") +_SECRET_WORDS = ("key", "secret", "token", "password", "passwd", "pwd", "credential", "auth") _RANK = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4} @@ -102,9 +102,26 @@ def _is_secret(name: Any) -> bool: return any(w in low for w in _SECRET_WORDS) +def _wrap(value: Any) -> Any: + """Nested mappings become _Config (so they print masked too); lists are wrapped item by item.""" + if isinstance(value, Mapping) and not isinstance(value, _Config): + return _Config(value) + if isinstance(value, (list, tuple)): + return [_wrap(v) for v in value] + return value + + class _Config(dict): - """A connector's settings. Values whose names contain key, secret, token or password are hidden - when printed.""" + """A connector's settings. Values whose names contain key, secret, token, password, pwd, + credential or auth are hidden when printed, at any depth.""" + + def __init__(self, *args: Any, **kw: Any): + super().__init__(*args, **kw) + for k in list(self): + dict.__setitem__(self, k, _wrap(dict.__getitem__(self, k))) + + def __setitem__(self, key: Any, value: Any) -> None: + super().__setitem__(key, _wrap(value)) def __repr__(self) -> str: return "{" + ", ".join(f"{k!r}: {'***' if _is_secret(k) else repr(v)}" for k, v in self.items()) + "}" @@ -124,10 +141,12 @@ class ConnectorSpec: name: Optional[str] = None # default " phone system" timeout: float = 600.0 # seconds to wait for a new connector to settle - def __post_init__(self) -> None: - if not isinstance(self.config, Mapping): - raise InvalidRequestError("ConnectorSpec.config must be a mapping") - self.config = _Config(self.config) + def __setattr__(self, name: str, value: Any) -> None: + if name == "config": + if not isinstance(value, Mapping): + raise InvalidRequestError("ConnectorSpec.config must be a mapping") + value = value if isinstance(value, _Config) else _Config(value) + object.__setattr__(self, name, value) def __repr__(self) -> str: return (f"ConnectorSpec(type={self.type!r}, config={self.config!r}, name={self.name!r}, " @@ -545,6 +564,7 @@ def create_customer(self, spec: CustomerSpec) -> Customer: self._vertical_id(spec.team.vertical) # unknown verticals are refused before any write result = Customer(company_id="") + failures: List[BaseException] = [] run = self._run(result) try: run.step = "company" @@ -596,8 +616,8 @@ def create_customer(self, spec: CustomerSpec) -> Customer: run.step = "connectors" if spec.connector is not None: - self._ensure_connector(team, spec.connector, result) - self._ensure_connector(mgmt, spec.connector, result) + failures += [e for e in (self._ensure_connector(team, spec.connector, result), + self._ensure_connector(mgmt, spec.connector, result)) if e] else: self._read_connector(team) self._read_connector(mgmt) @@ -616,6 +636,7 @@ def create_customer(self, spec: CustomerSpec) -> Customer: result.pending = self._pending(result) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) + _raise_connector_failure(failures, result) return result def _find_company(self, reseller_id: str, spec: CustomerSpec) -> Optional[Dict[str, Any]]: @@ -774,7 +795,10 @@ def _find_connector(self, location_id: str, cs: ConnectorSpec, name: str) -> Opt by_name = detail return by_name - def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Customer]) -> None: + def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Customer]) -> Optional[BaseException]: + """Find, repair or create the team's connector and record its status on the team. Returns the + ConnectorError or ConnectorTimeoutError when it did not become active (the caller raises it at + the end, once everything else is built), else None.""" name = cs.name or f"{team.name} phone system" conns = self._c.connectors config = dict(cs.config) @@ -788,7 +812,7 @@ def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Cust if result is not None: result.existing.append(label) self._set_conn(team, found) - return + return None try: if found is not None: # In error, stopped or changed: apply the settings (and key) given now, then restart. @@ -810,8 +834,12 @@ def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Cust conn = unwrap(conns.create_connector(team.location_id, {"name": name, "type": cs.type, "config": config}, timeout=cs.timeout)) except (ConnectorError, ConnectorTimeoutError) as exc: - conn = exc.connector # recorded on the team; user lines need it active + self._set_conn(team, exc.connector) # recorded on the team; user lines need it active + return exc self._set_conn(team, conn) + if conn.get("status") == "error": + return ConnectorError(conn) + return None @staticmethod def _set_conn(team: Team, conn: Mapping[str, Any]) -> None: @@ -838,6 +866,7 @@ def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSp settings = self._settings_from(alerts) first = next((t for t in cust.teams if t.name != team.name), None) new = Team(location_id="", name=team.name) + failure: Optional[BaseException] = None run = self._run(new) try: run.step = "copy_alerts" @@ -854,7 +883,7 @@ def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSp made = self._ensure_location(cust.company_id, team.name, team, "team", reactivate, cust) new.location_id = made.location_id run.step = "connector" - self._ensure_connector(new, connector, cust) + failure = self._ensure_connector(new, connector, cust) run.step = "groups" self._ensure_groups(new, cust) run.step = "rules" @@ -869,6 +898,7 @@ def add_team(self, customer: CustomerRef, team: TeamSpec, connector: ConnectorSp cust.pending = self._pending(cust) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) + _raise_connector_failure([failure] if failure else [], new) return new def set_alerts(self, customer: CustomerRef, alerts: AlertSettings, *, team: Optional[TeamRef] = None) -> List[str]: @@ -924,12 +954,16 @@ def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, continue # already attached: nothing to do todo.append(t) run = self._run(targets) + failures: List[BaseException] = [] try: for t in todo: run.step = f"connector:{t.name}" - self._ensure_connector(t, connector, cust) + failure = self._ensure_connector(t, connector, cust) + if failure: + failures.append(failure) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) + _raise_connector_failure(failures, targets) return targets def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = None) -> Dict[str, Any]: @@ -1039,19 +1073,80 @@ def _holders(team: Team, people: Mapping[str, _Person], exclude: Iterable[str] = and p.license in ("base_manager", "integration")] @staticmethod - def _team_lines(team: Team, people: Mapping[str, _Person], exclude: Iterable[str] = ()) -> List[str]: - """A team's lines: the number of every Base User there who holds exactly one on its connector.""" + def _owned_line(p: _Person, team: Team) -> Optional[str]: + """The team line this person owns: anyone active on the team, not a Base Manager or integration + user, with After Call on there and exactly one number on its connector. A Base User normally; + also someone read back as "other" (for example with First Alert switched on in the app), whose + line is never taken away.""" + if (not p.active or p.license in ("base_manager", "integration") or not team.connector_id + or team.location_id not in p.teams or AFTER_CALL not in p.locs[team.location_id]["products"]): + return None + nums = p.numbers(team.connector_id) + return nums[0] if len(nums) == 1 else None + + @classmethod + def _owners(cls, team: Team, people: Mapping[str, _Person], exclude: Iterable[str] = ()) -> Dict[str, str]: + """user id -> the team line they own.""" skip = set(exclude) - out: List[str] = [] - if not team.connector_id: - return out + out: Dict[str, str] = {} for p in people.values(): - if p.active and p.license == "base_user" and p.id not in skip and team.location_id in p.teams: - nums = p.numbers(team.connector_id) - if len(nums) == 1: - out = _uniq(out + nums) + if p.id in skip: + continue + line = cls._owned_line(p, team) + if line is not None: + out[p.id] = line return out + @classmethod + def _team_lines(cls, team: Team, people: Mapping[str, _Person], exclude: Iterable[str] = ()) -> List[str]: + """A team's lines: the line of every person who owns one there (see _owned_line).""" + return _uniq(cls._owners(team, people, exclude).values()) + + def _check_existing(self, cust: Customer, email: str, target: str) -> None: + """Refuse, before any write, to give an existing person a different license through an add_* + helper: that would take away lines they hold. change_license converts Base Users and Base + Managers. A person read back as "other" (for example one an earlier run of this helper left + part-way) is accepted when the helper cannot take anything away from them.""" + found = self._c.users.find_user_by_email(cust.company_id, email) + if found is None: + return + p = self._index(cust, include_inactive=True).get(found["id"]) + if p is None or not p.active or p.license == target: + return + mgmt = cust.management.location_id if cust.management else None + if p.license == "other": + nums = _uniq(p.numbers()) + if target == "base_user" and len(nums) <= 1 and mgmt not in p.locs: + return + if target == "base_manager" and (not nums or mgmt in p.locs): + return + if target == "integration" and not nums: + return + hint = ("use change_license" if target in ("base_user", "base_manager") + and p.license in ("base_user", "base_manager") else "remove them first, or use another person") + raise InvalidRequestError(f"{email} is already set up as {p.license!r}, not {target!r}: {hint}") + + def _emptied_groups(self, cust: Customer, people: Mapping[str, _Person], uid: str, + team_ids: Iterable[str]) -> List[str]: + """Notes for the teams whose alert groups this person leaves with no Base Manager in them.""" + notes: List[str] = [] + p = people.get(uid) + wanted = set(team_ids) + for t in cust.teams: + if p is None or t.location_id not in wanted or t.location_id not in p.locs: + continue + empty = [] + for f in ALERT_GROUPS: + name = TEAM_GROUPS[f] + if name not in p.locs[t.location_id]["groups"]: + continue + if not any(q.id != uid and q.active and q.license == "base_manager" and t.location_id in q.locs + and name in q.locs[t.location_id]["groups"] for q in people.values()): + empty.append(name) + if empty: + notes.append(f"{t.name} has no Base Manager left in {', '.join(empty)}; its alerts were not changed.") + return notes + def list_members(self, customer: CustomerRef, *, license: Optional[str] = None, team: Optional[TeamRef] = None) -> List[Member]: """Everyone active at the customer's locations, with license, teams and lines. @@ -1214,10 +1309,8 @@ def _release_line(self, cust: Customer, team: Team, line: str, people: Mapping[s the team still holds it. Returns True when it was released.""" if not team.connector_id: return False - for p in people.values(): - if (p.id != leaving and p.active and p.license == "base_user" and team.location_id in p.teams - and line in p.numbers(team.connector_id)): - return False + if line in self._owners(team, people, exclude=[leaving]).values(): + return False for h in self._holders(team, people, exclude=[leaving]): have = h.numbers(team.connector_id) if line in have: @@ -1277,9 +1370,12 @@ def add_base_user(self, customer: CustomerRef, person: PersonSpec, *, team: Team t = self._team(cust, team) line = _line(line) self._need_connector(t) + self._check_existing(cust, person.email, "base_user") result = Member(user_id="", email=person.email, license="base_user", teams=[t.location_id], lines=[line]) run = self._run(result) try: + run.step = "monitor_all" + self._monitor_all_off(t.location_id) run.step = "user" uid, created, detail = self._ensure_user(cust, person, [t.location_id]) result.user_id, result.created = uid, created @@ -1313,9 +1409,13 @@ def add_base_manager(self, customer: CustomerRef, person: PersonSpec, *, teams: own = _line(line) if line is not None else None if own: self._need_connector(cust.management) + self._check_existing(cust, person.email, "base_manager") result = Member(user_id="", email=person.email, license="base_manager", teams=[t.location_id for t in ts]) run = self._run(result) try: + run.step = "monitor_all" + for t in ts: + self._monitor_all_off(t.location_id) run.step = "user" uid, created, detail = self._ensure_user(cust, person, [t.location_id for t in ts] + [cust.management.location_id]) result.user_id, result.created = uid, created @@ -1337,6 +1437,7 @@ def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, inv cust = self._resolve(customer) if not cust.teams: raise InvalidRequestError("This customer has no team") + self._check_existing(cust, person.email, "integration") result = Member(user_id="", email=person.email, license="integration", teams=[t.location_id for t in cust.teams]) run = self._run(result) @@ -1376,73 +1477,128 @@ def add_integration_user(self, customer: CustomerRef, person: PersonSpec, *, inv def change_license(self, customer: CustomerRef, user_id: str, to: str, *, teams: Optional[Sequence[TeamRef]] = None, line: Optional[str] = None) -> Member: """Base User to Base Manager (``to="base_manager"``): their own line moves to Management and they - get the products, team lines and groups of ``teams`` (default: their team). + get the products, team lines and groups of ``teams`` (default: their teams); teams they were on + and that are not in ``teams`` are left. Base Manager to Base User (``to="base_user"``): groups, team lines, the extra products and Management are removed; they keep one team (``teams[0]``, default their first) and their own - line (``line``, default their Management line), which is added to that team's lists.""" + line (``line``, default their Management line), which is added to that team's lists. + + Safe to run again, also after an AccountError: a person part-way through the change is + recognised and the change continues. Until it completes, ``result.lines`` and ``result.teams`` + hold what the person had before.""" self._require_admin() if to not in ("base_user", "base_manager"): raise InvalidRequestError('to: "base_user" or "base_manager"') cust = self._resolve(customer) - p, people = self._person(cust, user_id) - ts = _dedupe_teams([self._team(cust, x) for x in teams]) if teams else [t for t in cust.teams if t.location_id in p.teams] - mgmt = cust.management - if mgmt is None: + if cust.management is None: raise InvalidRequestError("This customer has no Management location: run create_customer again") - if p.license == to: - return self._member(p) - if p.license not in ("base_user", "base_manager"): + p, people = self._person(cust, user_id) + if p.license not in ("base_user", "base_manager", "other"): raise InvalidRequestError(f"User {user_id} is {p.license!r}; only Base Users and Base Managers change license") + ts = _dedupe_teams([self._team(cust, x) for x in teams]) if teams else \ + [t for t in cust.teams if t.location_id in p.teams] if not ts: raise InvalidRequestError("teams: the person is on no team; pass teams") result = self._member(p) run = self._run(result) try: if to == "base_manager": - old = [(t, n) for t in cust.teams if t.location_id in p.teams for n in p.numbers(t.connector_id)] - own = _line(line) if line is not None else (old[0][1] if old else None) - if own: - self._need_connector(mgmt) - run.step = "release_line" - current = list(p.mappings) - for t, n in old: - self._release_line(cust, t, n, people, leaving=p.id) - current = merge_mappings(current, t.connector_id, remove=[n]) # type: ignore[arg-type] - if [n for _, n in old]: - self._set_mappings(cust, p.id, current) - run.step = "locations" - self._add_locations(cust, p.id, [t.location_id for t in ts] + [mgmt.location_id]) - detail = unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {} - result.lines = self._manager_setup(cust, p.id, ts, own, False, False, detail.get("status"), run) - result.license, result.teams = "base_manager", [t.location_id for t in ts] + self._to_manager(cust, p, people, ts, line, run, result) else: - keep = ts[0] - self._need_connector(keep) - own = _line(line) if line is not None else next(iter(p.numbers(mgmt.connector_id)), None) - if not own: - raise InvalidRequestError("line: this manager has no own line at Management; pass line") - run.step = "groups" - for t in self._locations(cust): - if t.location_id in p.locs: - self._leave_groups(t.location_id, p.id) - run.step = "products" - self._products_off(keep.location_id, p.id, [FIRST_ALERT, INSIGHTS_HUB]) - self._products_on(keep.location_id, p.id, [AFTER_CALL]) - run.step = "lines" - self._set_mappings(cust, p.id, merge_mappings([], keep.connector_id, add=[own])) # type: ignore[arg-type] - run.step = "locations" - self._add_locations(cust, p.id, [keep.location_id]) - self._remove_locations(cust, p.id, [t.location_id for t in self._locations(cust) if t is not keep]) - run.step = "team_lines" - self._attach_line(cust, keep, own, self._index(cust), exclude=[p.id]) - result.license, result.teams, result.lines = "base_user", [keep.location_id], [own] + self._to_user(cust, p, people, ts[0], line, run, result) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) return result + def _to_manager(self, cust: Customer, p: _Person, people: Mapping[str, _Person], ts: List[Team], + line: Optional[str], run: _Run, result: Member) -> None: + mgmt = cust.management + assert mgmt is not None + # The person's own line: on Management already, or a number on a team connector that no one else + # owns there (their Base User line). + stray: List[Tuple[Team, str]] = [] + for t in cust.teams: + if t.connector_id: + lines = self._team_lines(t, people, exclude=[p.id]) + stray += [(t, n) for n in p.numbers(t.connector_id) if n not in lines] + mg_nums = p.numbers(mgmt.connector_id) if mgmt.connector_id else [] + own = _line(line) if line is not None else (mg_nums[0] if mg_nums else (stray[0][1] if stray else None)) + if own: + self._need_connector(mgmt) + keep_ids = {t.location_id for t in ts} + former = [t for t in cust.teams if t.location_id in p.locs and t.location_id not in keep_ids] + notes = self._emptied_groups(cust, people, p.id, [t.location_id for t in former]) + # Products and groups first: from here on the person reads back as a Base Manager. + run.step = "locations" + self._add_locations(cust, p.id, [t.location_id for t in ts] + [mgmt.location_id]) + run.step = "products" + for t in ts + [mgmt]: + self._products_on(t.location_id, p.id, PRODUCT_KEYS) + run.step = "groups" + for t in ts: + self._join_groups(t.location_id, p.id, [getattr(t.groups, f) for f in TEAM_GROUPS]) + run.step = "alert_email" + status = (unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {}).get("status") + for t in ts: + self._email_off(t.location_id, p.id, False, status) + run.step = "monitor_all" + for t in ts: + self._monitor_all_off(t.location_id) + run.step = "release_line" + for t, n in stray: + self._release_line(cust, t, n, people, leaving=p.id) + run.step = "lines" # one write: the own line moves to Management, the teams' lines are set + mappings = merge_mappings([], mgmt.connector_id, add=[own]) if own else [] # type: ignore[arg-type] + for t in ts: + if t.connector_id: + mappings = merge_mappings(mappings, t.connector_id, add=self._team_lines(t, people, exclude=[p.id])) + if not _same_mappings(mappings, p.mappings): + self._set_mappings(cust, p.id, mappings) + run.step = "former_teams" + for t in former: + self._leave_groups(t.location_id, p.id) + self._remove_locations(cust, p.id, [t.location_id for t in former]) + result.license, result.teams, result.lines = "base_manager", [t.location_id for t in ts], numbers_for(mappings) + result.notes.extend(notes) + + def _to_user(self, cust: Customer, p: _Person, people: Mapping[str, _Person], keep: Team, + line: Optional[str], run: _Run, result: Member) -> None: + mgmt = cust.management + assert mgmt is not None + self._need_connector(keep) + mg_nums = p.numbers(mgmt.connector_id) if mgmt.connector_id else [] + lines = self._team_lines(keep, people, exclude=[p.id]) + mine = [n for n in p.numbers(keep.connector_id) if n not in lines] + own = _line(line) if line is not None else (mg_nums[0] if mg_nums else (mine[0] if mine else None)) + if not own: + raise InvalidRequestError("line: this manager has no own line at Management; pass line") + notes = self._emptied_groups(cust, people, p.id, p.teams) + others = [t.location_id for t in self._locations(cust) if t.location_id != keep.location_id and t.location_id in p.locs] + run.step = "groups" + for t in self._locations(cust): + if t.location_id in p.locs: + self._leave_groups(t.location_id, p.id) + run.step = "products" + self._products_off(keep.location_id, p.id, [FIRST_ALERT, INSIGHTS_HUB]) + self._products_on(keep.location_id, p.id, [AFTER_CALL]) + run.step = "monitor_all" + self._monitor_all_off(keep.location_id) + run.step = "lines" # one write: only their own line, on the team's connector + target = merge_mappings([], keep.connector_id, add=[own]) # type: ignore[arg-type] + if not _same_mappings(target, p.mappings): + self._set_mappings(cust, p.id, target) + run.step = "team_lines" + self._attach_line(cust, keep, own, people, exclude=[p.id]) + run.step = "locations" + self._add_locations(cust, p.id, [keep.location_id]) + self._remove_locations(cust, p.id, others) + result.license, result.teams, result.lines = "base_user", [keep.location_id], [own] + result.notes.extend(notes) + def move_user(self, customer: CustomerRef, user_id: str, *, from_team: TeamRef, to_team: TeamRef) -> Member: """Move a Base User (membership and line) to another team, or swap one of a Base Manager's teams - for another. Calls captured before the move stay with the old team (``Member.notes`` says so).""" + for another. Calls captured before the move stay with the old team (``Member.notes`` says so). + Safe to run again, also after an AccountError: the move continues.""" self._require_admin() cust = self._resolve(customer) src, dst = self._team(cust, from_team), self._team(cust, to_team) @@ -1455,88 +1611,133 @@ def move_user(self, customer: CustomerRef, user_id: str, *, from_team: TeamRef, return result # already moved if src.location_id not in p.teams: raise InvalidRequestError(f"User {user_id} is not on {src.name}") + if p.license == "integration": + raise InvalidRequestError(f"User {user_id} is an integration user; it is on every team already") run = self._run(result) try: - if p.license == "base_user": + if p.license == "base_manager": + self._move_manager(cust, p, people, src, dst, run, result) + else: # a Base User, or one an earlier run left part-way ("other") self._need_connector(dst) - nums = p.numbers(src.connector_id) if src.connector_id else [] + nums = _uniq((p.numbers(src.connector_id) if src.connector_id else []) + p.numbers(dst.connector_id)) if len(nums) != 1: raise InvalidRequestError("A Base User holds exactly one line; fix it with change_line first") line = nums[0] + run.step = "monitor_all" + for t in (src, dst): + self._monitor_all_off(t.location_id) run.step = "release_line" self._release_line(cust, src, line, people, leaving=p.id) run.step = "locations" self._add_locations(cust, p.id, [dst.location_id]) run.step = "products" self._products_on(dst.location_id, p.id, [AFTER_CALL]) + run.step = "alert_email" + status = (unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {}).get("status") + self._email_off(dst.location_id, p.id, False, status) run.step = "line" - current = merge_mappings(p.mappings, src.connector_id, remove=[line]) # type: ignore[arg-type] - self._set_mappings(cust, p.id, merge_mappings(current, dst.connector_id, add=[line])) # type: ignore[arg-type] - run.step = "team_lines" - self._remove_locations(cust, p.id, [src.location_id]) + target = merge_mappings([m for m in p.mappings if m.get("connector_id") != src.connector_id], + dst.connector_id, add=[line]) # type: ignore[arg-type] + if not _same_mappings(target, p.mappings): + self._set_mappings(cust, p.id, target) + run.step = "team_lines" # read again: the release above changed the holders' lines self._attach_line(cust, dst, line, self._index(cust), exclude=[p.id]) - result.teams, result.lines = [dst.location_id], [line] - elif p.license == "base_manager": run.step = "leave_team" - if src.location_id in p.locs: - self._leave_groups(src.location_id, p.id) - if src.connector_id and p.numbers(src.connector_id): - self._set_mappings(cust, p.id, [m for m in p.mappings if m.get("connector_id") != src.connector_id]) - run.step = "locations" - self._add_locations(cust, p.id, [dst.location_id]) self._remove_locations(cust, p.id, [src.location_id]) - detail = unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {} - result.lines = self._manager_setup(cust, p.id, [dst], None, False, False, detail.get("status"), run) - result.teams = _uniq([x for x in p.teams if x != src.location_id] + [dst.location_id]) - else: - raise InvalidRequestError(f"User {user_id} is {p.license!r}; only Base Users and Base Managers move") + result.teams, result.lines = [dst.location_id], [line] except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) return result + def _move_manager(self, cust: Customer, p: _Person, people: Mapping[str, _Person], src: Team, dst: Team, + run: _Run, result: Member) -> None: + notes = self._emptied_groups(cust, people, p.id, [src.location_id]) + # Join the new team first, so the person always reads back as a Base Manager. + run.step = "locations" + self._add_locations(cust, p.id, [dst.location_id]) + run.step = "products" + self._products_on(dst.location_id, p.id, PRODUCT_KEYS) + run.step = "groups" + self._join_groups(dst.location_id, p.id, [getattr(dst.groups, f) for f in TEAM_GROUPS]) + run.step = "alert_email" + status = (unwrap(self._c.users.get_company_user(cust.company_id, p.id)) or {}).get("status") + self._email_off(dst.location_id, p.id, False, status) + run.step = "monitor_all" + for t in (src, dst): + self._monitor_all_off(t.location_id) + run.step = "lines" + mappings = [dict(m) for m in p.mappings if m.get("connector_id") != src.connector_id] + if dst.connector_id: + mappings = merge_mappings(mappings, dst.connector_id, add=self._team_lines(dst, people, exclude=[p.id])) + if not _same_mappings(mappings, p.mappings): + self._set_mappings(cust, p.id, mappings) + run.step = "leave_team" + if src.location_id in p.locs: + self._leave_groups(src.location_id, p.id) + self._remove_locations(cust, p.id, [src.location_id]) + result.teams = _uniq([x for x in p.teams if x != src.location_id] + [dst.location_id]) + result.lines = numbers_for(mappings) + result.notes.extend(notes) + def change_line(self, customer: CustomerRef, user_id: str, old: str, new: str) -> Member: - """Release ``old`` everywhere it is listed for this person (their mapping, the team's holders, - First Alert and Insights Hub) and map ``new`` in its place.""" + """Change a person's own line from ``old`` to ``new``. + + A Base User: their mapping, and the team's First Alert and Insights Hub lists and holders, where + ``old`` is released only when no other Base User of the team still holds it. A Base Manager: + their own line at Management only; a team line belongs to the Base User who holds it, so + ``old`` must be the manager's own line.""" self._require_admin() old, new = _line(old, "old"), _line(new, "new") cust = self._resolve(customer) p, people = self._person(cust, user_id) - by_conn = {t.connector_id: t for t in self._locations(cust) if t.connector_id} result = self._member(p) + mgmt = cust.management + if p.license == "integration": + raise InvalidRequestError("An integration user holds every line; it has no line of its own") + if p.license == "base_manager": + mine = p.numbers(mgmt.connector_id) if mgmt and mgmt.connector_id else [] + if old not in mine and new not in mine: + raise InvalidRequestError(f"{old} is not this manager's own line; a team line changes with " + "the Base User who holds it") + run = self._run(result) + try: + run.step = "line" + if old in mine: + self._map(cust, p.id, mgmt.connector_id, _uniq([new if n == old else n for n in mine]), # type: ignore[union-attr,arg-type] + current=p.mappings) + result.lines = [new if n == old else n for n in result.lines] + except (IntelligenceCloudError, httpx.HTTPError) as exc: + self._stop(run, exc) + return result + team = next((t for t in cust.teams if t.connector_id and t.location_id in p.teams + and (old in p.numbers(t.connector_id) or new in p.numbers(t.connector_id))), None) + if team is None: + raise InvalidRequestError(f"{old} is not one of this person's lines") + cid = team.connector_id + shared = old in self._owners(team, people, exclude=[p.id]).values() run = self._run(result) try: - current = [dict(m) for m in p.mappings] - touched = [cid for cid in by_conn if old in numbers_for(current, cid)] + run.step = "monitor_all" + self._monitor_all_off(team.location_id) run.step = "line" - if touched: - mappings = current - for cid in touched: - nums = numbers_for(current, cid) - target = _uniq([new if n == old else n for n in nums]) - mappings = merge_mappings([m for m in mappings if m.get("connector_id") != cid], cid, add=target) - self._set_mappings(cust, p.id, mappings) - result.lines = numbers_for(mappings) + nums = p.numbers(cid) + if old in nums: + self._map(cust, p.id, cid, _uniq([new if n == old else n for n in nums]), current=p.mappings) # type: ignore[arg-type] + result.lines = _uniq([new if n == old else n for n in result.lines]) + + def swap(have: List[str]) -> List[str]: + out = list(have) if shared else [n for n in have if n != old] + return out if new in out else out + [new] run.step = "team_lines" - teams = [by_conn[cid] for cid in touched if by_conn[cid].kind == "team"] - if not touched and p.license == "base_user": - teams = [t for t in cust.teams if t.location_id in p.teams and new in p.numbers(t.connector_id)] - for t in teams: - cid = t.connector_id - for h in self._holders(t, people, exclude=[p.id]): - have = h.numbers(cid) - target = _uniq([new if n == old else n for n in have]) - if p.license == "base_user" and new not in target: - target.append(new) - if target != have: - self._map(cust, h.id, cid, target, current=h.mappings) # type: ignore[arg-type] - for getter, setter in ((self._fa_numbers, self._c.first_alert.set_monitored_numbers), - (self._ih_numbers, self._c.insights_hub.set_numbers)): - have = getter(t) - target = _uniq([new if n == old else n for n in have]) - if p.license == "base_user" and new not in target: - target.append(new) - if target != have: - setter(t.location_id, cid, target) + for h in self._holders(team, people, exclude=[p.id]): + have = h.numbers(cid) + if swap(have) != have: + self._map(cust, h.id, cid, swap(have), current=h.mappings) # type: ignore[arg-type] + for getter, setter in ((self._fa_numbers, self._c.first_alert.set_monitored_numbers), + (self._ih_numbers, self._c.insights_hub.set_numbers)): + have = getter(team) + if swap(have) != have: + setter(team.location_id, cid, swap(have)) except (IntelligenceCloudError, httpx.HTTPError) as exc: self._stop(run, exc) return result @@ -1544,14 +1745,16 @@ def change_line(self, customer: CustomerRef, user_id: str, old: str, new: str) - def remove_user(self, customer: CustomerRef, user_id: str, *, keep_lines: bool = False) -> Dict[str, Any]: """Take the person out of every group, release a Base User's line (unless ``keep_lines``, and only when no other Base User of the team holds it), clear their lines, then deactivate them. Removing - a Base Manager or an integration user never takes a line off anyone else.""" + a Base Manager or an integration user never takes a line off anyone else. ``notes`` names any + team whose alert groups are left with no Base Manager (its alerts are not changed).""" self._require_admin() cust = self._resolve(customer) p, people = self._person(cust, user_id, include_inactive=True) if not p.active: p.mappings = unwrap(self._c.users.get_user_number_mappings(cust.company_id, p.id)) or [] self._classify(cust, p) - out: Dict[str, Any] = {"user_id": user_id, "license": p.license, "released_lines": [], "deactivated": False} + out: Dict[str, Any] = {"user_id": user_id, "license": p.license, "released_lines": [], "deactivated": False, + "notes": self._emptied_groups(cust, people, p.id, p.teams) if p.active else []} run = self._run(out) try: run.step = "groups" @@ -1613,7 +1816,11 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st their teams' lines on each team's connector; nothing else is listed. ``dry_run=True`` returns the changes without making them. - Returns ``{"teams": {location_id: {"lines", "first_alert", "insights_hub", "holders"}}, "applied"}``.""" + Anyone with After Call on and exactly one line on a team's connector owns that line, also when + they read back as "other" (listed under ``"other"``): their line is never released. + + Returns ``{"teams": {location_id: {"team", "lines", "other", "first_alert", "insights_hub", + "holders"}}, "applied"}``.""" self._require_admin() cust = self._resolve(customer) people = self._index(cust) @@ -1622,10 +1829,13 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st for t in cust.teams: if not t.connector_id: continue - lines = self._team_lines(t, people) + owners = self._owners(t, people) + lines = _uniq(owners.values()) fa, ih = self._fa_numbers(t), self._ih_numbers(t) d: Dict[str, Any] = { "team": t.name, "lines": lines, + # people who own a line here but read back as "other" (their line is kept; correct them) + "other": [uid for uid in owners if people[uid].license == "other"], "first_alert": {"add": [n for n in lines if n not in fa], "remove": [n for n in fa if n not in lines]}, "insights_hub": {"add": [n for n in lines if n not in ih], "remove": [n for n in ih if n not in lines]}, "holders": {}, @@ -1643,6 +1853,7 @@ def sync_lines(self, customer: CustomerRef, *, dry_run: bool = False) -> Dict[st try: for t, lines, d in plans: run.step = f"sync:{t.name}" + self._monitor_all_off(t.location_id) for uid in d["holders"]: self._map(cust, uid, t.connector_id, lines, current=people[uid].mappings) # type: ignore[arg-type] if d["first_alert"]["add"] or d["first_alert"]["remove"]: @@ -1712,6 +1923,13 @@ def offboard_customer(self, customer: CustomerRef, *, deactivate_company: bool = return out +def _raise_connector_failure(failures: Sequence[BaseException], result: Any) -> None: + """Everything else is built; a connector that did not become active stops the helper here. Run it + again (with a corrected key if the cause is an error) once the phone system is reachable.""" + if failures: + raise AccountError("connectors", result, failures[0]) from failures[0] + + def _same_mappings(a: Sequence[Mapping[str, Any]], b: Sequence[Mapping[str, Any]]) -> bool: def norm(ms: Sequence[Mapping[str, Any]]) -> Dict[str, List[str]]: out: Dict[str, List[str]] = {} diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index ef00bc5..348f7c9 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -32,6 +32,7 @@ ) DEFAULT_BASE_URL = "https://app.intelligence.cloud/api/v1" +DEFAULT_APP_URL = "https://app.intelligence.cloud" # the app's own address; providers often use their own # Test endpoints whose error text is never surfaced (only success and the HTTP status). SANITIZED_ERRORS = {"testConnector", "testFirstAlertWebhook", "testAfterCallWebhook"} @@ -54,13 +55,22 @@ def check_base_url(base_url: str) -> str: raise InvalidRequestError("base_url must be an https:// URL (http:// only for localhost)") +def check_app_url(app_url: str) -> str: + """The app address for page links: https only, trailing slash removed.""" + parts = urlsplit(app_url or "") + if parts.scheme != "https" or not parts.hostname: + raise InvalidRequestError("app_url must be an https:// URL") + return app_url.rstrip("/") + + class Client: """Signs in with an integration user's email and password and calls the API. One client per credential. Admin (reseller admin) and frontline logins see different data: use one client for each. ``client.accounts`` needs an administrator login and ``client.conversations`` a user login. ``mask_numbers=False`` shows caller numbers in full in - ``client.conversations`` (by default only their last four digits are shown). + ``client.conversations`` (by default only their last four digits are shown). ``app_url`` is the + app's address for call and alert page links (default https://app.intelligence.cloud). >>> client = Client(email="integration@example.com", password="...") >>> client.intelligence.whoami()["role"] @@ -81,6 +91,7 @@ def __init__( login_rate_limit_wait: float = LOGIN_RATE_LIMIT_WAIT, keep_unknown_fields: bool = False, mask_numbers: bool = True, + app_url: str = DEFAULT_APP_URL, ): self.base_url = check_base_url(base_url).rstrip("/") self._email = email @@ -93,6 +104,8 @@ def __init__( self.keep_unknown_fields = keep_unknown_fields # client.conversations shows caller numbers as their last four digits unless this is False. self.mask_numbers = mask_numbers + # The app's address for links to call and alert pages (client.conversations.reference). + self.app_url = check_app_url(app_url) self._writes = 0 # write requests attempted; account helpers use it to tell a clean stop from a partial one ua = f"intelligence-cloud-python/{__version__}" if user_agent: diff --git a/src/intelligence_cloud/conversations.py b/src/intelligence_cloud/conversations.py index e16a6a8..cf6df1f 100644 --- a/src/intelligence_cloud/conversations.py +++ b/src/intelligence_cloud/conversations.py @@ -10,10 +10,13 @@ """ from __future__ import annotations +import re from dataclasses import dataclass, field from datetime import date, datetime, time, timedelta, timezone from typing import Any, Dict, List, Mapping, Optional, Sequence, Union +from urllib.parse import quote + from ._base import Namespace, Page, unwrap from ._spec import is_uuid from .errors import InvalidRequestError, WrongLoginError @@ -38,6 +41,25 @@ def mask_number(number: Optional[str]) -> Optional[str]: return "***" + digits[-4:] +def _local_midnight(day: date) -> datetime: + """00:00 on ``day`` in this machine's time zone, with that date's own offset (daylight saving).""" + return datetime.combine(day, time()).astimezone() + + +_NUMBER_RUN = re.compile(r"\+?\d[\d\s().-]*\d") + + +def mask_name(name: Optional[str]) -> Optional[str]: + """A name with any phone number in it (five or more digits) shown as ``***`` and its last four.""" + if not name: + return name + + def sub(m: "re.Match[str]") -> str: + digits = "".join(ch for ch in m.group(0) if ch.isdigit()) + return "***" + digits[-4:] if len(digits) >= 5 else m.group(0) + return _NUMBER_RUN.sub(sub, name) + + def _parse_time(value: Any) -> Optional[datetime]: if not isinstance(value, str) or not value: return None @@ -107,6 +129,7 @@ class CallBrief: topics: List[str] = field(default_factory=list) alerts: List[str] = field(default_factory=list) # names of the alerts the call raised (brief() only) location_id: Optional[str] = None + link: Optional[str] = None # the call's page in the app (an id-only address) def __repr__(self) -> str: return f"CallBrief(id={self.id!r}, when={self.when.isoformat() if self.when else None!r})" @@ -132,6 +155,7 @@ class AlertBrief: topics: List[str] = field(default_factory=list) holder: Optional[str] = None # who holds the alert; the API does not publish it yet call: Optional[CallBrief] = None # set by alert() + link: Optional[str] = None # the alert's page in the app (an id-only address) def __repr__(self) -> str: return f"AlertBrief(id={self.id!r}, when={self.when.isoformat() if self.when else None!r})" @@ -165,7 +189,7 @@ class Reference: kind: str # "call" or "alert" id: str - link: Optional[str] = None # the app link; the API does not publish app links yet + link: Optional[str] = None # the page in the app: /after-call-copilot/calls/ or .../first-alert-copilot/alerts/ class Conversations(Namespace): @@ -187,6 +211,15 @@ def _require_user(self) -> Dict[str, Any]: def _mask(self, number: Optional[str]) -> Optional[str]: return mask_number(number) if self._c.mask_numbers else number + def _mask_name(self, name: Optional[str]) -> Optional[str]: + return mask_name(name) if self._c.mask_numbers else name + + def _link(self, kind: str, item_id: str) -> Optional[str]: + if not item_id: + return None + page = "after-call-copilot/calls" if kind == "call" else "first-alert-copilot/alerts" + return f"{self._c.app_url}/{page}/{quote(item_id, safe='')}" + @staticmethod def _limit(limit: int, top: int) -> int: if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= top: @@ -214,23 +247,24 @@ def _window(self, day: Optional[Union[date, datetime]], since: Optional[When], u """(start, end). Default: today (local time), or the last ``default_days`` days. At most 31 days.""" if day is not None and (since is not None or until is not None): raise InvalidRequestError("Pass day, or since/until, not both") - local = datetime.now().astimezone().tzinfo if day is not None: if isinstance(day, datetime): d = self._when(day, "day") start = d.replace(hour=0, minute=0, second=0, microsecond=0) elif isinstance(day, date): - start = datetime.combine(day, time(), tzinfo=local) + start = _local_midnight(day) else: raise InvalidRequestError("day: a date") - return start, start + timedelta(days=1) - timedelta(seconds=1) - end = self._when(until, "until") if until is not None else datetime.now(timezone.utc).astimezone(local) + if isinstance(day, datetime): + return start, start + timedelta(days=1) - timedelta(seconds=1) + return start, _local_midnight(day + timedelta(days=1)) - timedelta(seconds=1) + end = self._when(until, "until") if until is not None else datetime.now().astimezone() if since is not None: start = self._when(since, "since") elif default_days: start = end - timedelta(days=default_days) else: - start = datetime.combine(end.astimezone(local).date(), time(), tzinfo=local) + start = _local_midnight(end.astimezone().date()) if end <= start: raise InvalidRequestError("until must be after since") if end - start > timedelta(days=MAX_WINDOW_DAYS): @@ -270,15 +304,16 @@ def _brief_from_row(self, row: Mapping[str, Any]) -> CallBrief: direction=row.get("call_type"), status=row.get("status"), duration_seconds=row.get("duration"), - caller_name=row.get("caller_name"), + caller_name=self._mask_name(row.get("caller_name")), caller_number=self._mask(row.get("caller_number")), - callee_name=row.get("callee_name"), + callee_name=self._mask_name(row.get("callee_name")), callee_number=self._mask(row.get("callee_number")), summary=row.get("summary"), task_count=row.get("task_count"), sentiment=row.get("sentiment") or row.get("sentiment_label"), sentiment_score=row.get("sentiment_score"), location_id=row.get("location_id"), + link=self._link("call", row.get("id") or ""), ) def _alert_from_row(self, row: Mapping[str, Any]) -> AlertBrief: @@ -287,14 +322,15 @@ def _alert_from_row(self, row: Mapping[str, Any]) -> AlertBrief: call_id=row.get("call_id"), when=_parse_time(row.get("call_date")), alerts=list(row.get("keywords") or []), - caller_name=row.get("caller_name"), + caller_name=self._mask_name(row.get("caller_name")), caller_number=self._mask(row.get("caller_number")), - callee_name=row.get("callee_name"), + callee_name=self._mask_name(row.get("callee_name")), callee_number=self._mask(row.get("callee_number")), summary=row.get("summary"), sentiment=row.get("sentiment") or row.get("sentiment_label"), sentiment_score=row.get("sentiment_score"), topics=list(row.get("topics") or []), + link=self._link("alert", row.get("id") or ""), ) @staticmethod @@ -471,18 +507,20 @@ def topics(self, *, since: Optional[When] = None, until: Optional[When] = None, # ------------------------------------------------------------------ passing on - @staticmethod - def reference(call_or_alert: Union[CallBrief, AlertBrief, FirstAlertEvent, str]) -> Reference: - """The id only, for passing to another system in place of content. A string is taken as a call id.""" + def reference(self, call_or_alert: Union[CallBrief, AlertBrief, FirstAlertEvent, str]) -> Reference: + """The id and its page in the app, for passing to another system in place of content. A string is + taken as a call id. The link uses the client's ``app_url`` (default https://app.intelligence.cloud).""" if isinstance(call_or_alert, CallBrief): - return Reference(kind="call", id=call_or_alert.id) - if isinstance(call_or_alert, AlertBrief): - return Reference(kind="alert", id=call_or_alert.id) - if isinstance(call_or_alert, FirstAlertEvent): - return Reference(kind="alert", id=call_or_alert.alert_id) - if isinstance(call_or_alert, str) and call_or_alert.strip(): - return Reference(kind="call", id=call_or_alert.strip()) - raise InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") + kind, item = "call", call_or_alert.id + elif isinstance(call_or_alert, AlertBrief): + kind, item = "alert", call_or_alert.id + elif isinstance(call_or_alert, FirstAlertEvent): + kind, item = "alert", call_or_alert.alert_id + elif isinstance(call_or_alert, str) and call_or_alert.strip(): + kind, item = "call", call_or_alert.strip() + else: + raise InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id") + return Reference(kind=kind, id=item, link=self._link(kind, item)) @staticmethod def parse_first_alert_event(payload: Any) -> FirstAlertEvent: diff --git a/tests/unit/fake_api.py b/tests/unit/fake_api.py index efff3f0..4a3a3fe 100644 --- a/tests/unit/fake_api.py +++ b/tests/unit/fake_api.py @@ -387,6 +387,8 @@ def list_users(req, body, cid): @self.route("POST", r"/companies/([^/]+)/users") def create_user(req, body, cid): assert req.headers.get("Idempotency-Key") + if any(u["email"].lower() == body["email"].lower() for u in api.users.values()): + return 409, {"error": {"code": "CONFLICT", "message": "A user with this email already exists"}} uid = new_id() api.users[uid] = {"id": uid, "company_id": cid, "email": body["email"], "role": body["role"], "status": "invited", "_locations": list(body.get("location_ids", [])), "_products": {}, @@ -509,8 +511,11 @@ def get_transcript(req, body, cid): @self.route("GET", r"/alerts") def list_alerts(req, body): - q = req.url.params.get("search") - rows = [a for a in api.alert_rows if not q or a["id"] == q] + # as published: caller or callee name or number, summary text, or an exact lowercase alert id + q = (req.url.params.get("search") or "").lower() + fields = ("caller_name", "caller_number", "callee_name", "callee_number", "summary") + rows = [a for a in api.alert_rows if not q or a["id"] == q + or any(q in str(a.get(f) or "").lower() for f in fields)] return api._paged(req, rows, "alerts", {"total": len(rows)}) @self.route("GET", r"/tasks") diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index e65552c..2615f2b 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -266,10 +266,21 @@ def test_unknown_connector_type_is_refused_before_any_write(api, client): assert "K-SECRET" not in str(e.value) and api.writes() == [] +def create_with_connector_stop(c, s): + """create_customer builds everything, then stops at "connectors" when a connector is not active.""" + with pytest.raises(ic.AccountError) as e: + c.accounts.create_customer(s) + assert e.value.step == "connectors" and isinstance(e.value.result, ic.Customer) + return e.value + + def test_connector_error_is_recorded_and_a_fixed_key_repairs_it(api): api.connector_outcome = "error" c = api.client() - first = c.accounts.create_customer(spec(sso_domain=None)) + err = create_with_connector_stop(c, spec(sso_domain=None)) + assert isinstance(err.cause, ic.ConnectorError) and err.cause.state_reason == "invalid_permissions" + assert "KEY-123" not in str(err) + first = err.result assert first.teams[0].connector_status == "error" assert first.teams[0].connector_state_reason == "invalid_permissions" assert first.teams[0].rules.low_sentiment # the rest is still built @@ -413,7 +424,7 @@ def test_activate_alerts_needs_a_manager_in_each_group(api, client, customer): def test_mapping_failure_raises_account_error_and_rerun_continues(api): api.connector_outcome = "error" c = api.client() - cust = c.accounts.create_customer(spec(sso_domain=None)) + cust = create_with_connector_stop(c, spec(sso_domain=None)).result with pytest.raises(ic.AccountError) as e: c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="2101") err = e.value diff --git a/tests/unit/test_conversations.py b/tests/unit/test_conversations.py index 54cbcd2..06c2c0a 100644 --- a/tests/unit/test_conversations.py +++ b/tests/unit/test_conversations.py @@ -168,10 +168,11 @@ def test_team_view_and_topics(api): assert [t["slug"] for t in topics.rising] == ["billing"] and "trend_data" not in topics.rising[0] -def test_reference_carries_only_the_id(api): +def test_reference_carries_the_id_and_its_page(api): conv = api.client().conversations ref = conv.reference(conv.brief(CALL)) - assert (ref.kind, ref.id, ref.link) == ("call", CALL, None) + assert (ref.kind, ref.id) == ("call", CALL) + assert ref.link == f"https://app.intelligence.cloud/after-call-copilot/calls/{CALL}" assert conv.reference(conv.alert(ALERT)).kind == "alert" assert conv.reference(CALL).id == CALL diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py new file mode 100644 index 0000000..93b9841 --- /dev/null +++ b/tests/unit/test_review_fixes.py @@ -0,0 +1,487 @@ +"""Regression tests for the 0.2.0 review findings: existing people, shared lines, resuming after a stop, +secrets, masking, connector stops, time zones, notes, monitor-all and app links.""" +from __future__ import annotations + +import time +from datetime import date, datetime, timedelta, timezone + +import httpx +import pytest + +import intelligence_cloud as ic + +from .fake_api import FakeAPI, new_id +from .test_accounts import CONN, EAST, EAST_CONN, TEAM, person, spec + + +class Flaky: + """Fails the write numbered ``fail_at`` (0-based, counted from arming) with a 400, once.""" + + def __init__(self, api: FakeAPI): + self.api = api + self.fail_at = None + self.n = 0 + + def arm(self, k): + self.fail_at, self.n = k, 0 + + def __call__(self, req): + if self.fail_at is not None and req.method != "GET" and not req.url.path.endswith("/auth/login"): + hit = self.n == self.fail_at + self.n += 1 + if hit: + self.fail_at = None + return httpx.Response(400, json={"error": {"code": "X", "message": "boom"}}) + return self.api(req) + + +def flaky(): + api = FakeAPI() + f = Flaky(api) + c = ic.Client(email="a@example.com", password="pw", transport=httpx.MockTransport(f), sleep=lambda s: None) + return api, f, c + + +def base(): + api = FakeAPI() + c = api.client() + return api, c, c.accounts.create_customer(spec()) + + +# ---------------------------------------------------------------------- B1: existing people + + +def test_add_base_user_refuses_an_existing_manager_before_any_write(): + api, c, cust = base() + t = cust.teams[0] + c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + c.accounts.add_base_user(cust, person(2), team=t, line="202", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) + start = len(api.calls) + with pytest.raises(ic.InvalidRequestError) as e: + c.accounts.add_base_user(cust, person(9), team=t, line="299") + assert "change_license" in str(e.value) and api.writes(start) == [] + assert sorted(api.numbers(m.user_id)) == ["201", "202", "900"] + + +def test_add_base_manager_refuses_an_existing_base_user_and_integration_refuses_both(): + api, c, cust = base() + t = cust.teams[0] + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + start = len(api.calls) + with pytest.raises(ic.InvalidRequestError): + c.accounts.add_base_manager(cust, person(1), teams=[t], line="901") + with pytest.raises(ic.InvalidRequestError): + c.accounts.add_integration_user(cust, person(1)) + assert api.writes(start) == [] and api.numbers(u.user_id) == ["201"] + assert api.fa_numbers(t.location_id) == ["201"] + + +def test_add_base_user_resumes_a_person_it_left_part_way(): + api, f, c = flaky() + cust = c.accounts.create_customer(spec()) + f.arm(3) # create, After Call, alert email, then the line mapping fails + with pytest.raises(ic.AccountError): + c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="201", invite=False) + again = c.accounts.add_base_user(cust, person(1), team=cust.teams[0], line="201", invite=False) + assert api.numbers(again.user_id) == ["201"] and api.fa_numbers(cust.teams[0].location_id) == ["201"] + + +# ---------------------------------------------------------------------- B2: change_line + + +def test_change_line_keeps_a_line_another_base_user_still_holds(): + api, c, cust = base() + t = cust.teams[0] + u1 = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + u2 = c.accounts.add_base_user(cust, person(2), team=t, line="201", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) + c.accounts.change_line(cust, u1.user_id, "201", "211") + assert api.numbers(u1.user_id) == ["211"] and api.numbers(u2.user_id) == ["201"] + assert sorted(api.fa_numbers(t.location_id)) == sorted(api.ih_numbers(t.location_id)) == ["201", "211"] + assert sorted(api.numbers(m.user_id, t.connector_id)) == ["201", "211"] + start = len(api.calls) + c.accounts.change_line(cust, u1.user_id, "201", "211") + assert api.writes(start) == [] + c.accounts.change_line(cust, u2.user_id, "201", "212") # the last holder: 201 is released now + assert sorted(api.fa_numbers(t.location_id)) == ["211", "212"] + assert sorted(api.numbers(m.user_id, t.connector_id)) == ["211", "212"] + + +def test_change_line_for_a_manager_touches_only_their_own_line(): + api, c, cust = base() + t = cust.teams[0] + u1 = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) + m2 = c.accounts.add_base_manager(cust, person(8), teams=[t], line="800", invite=False) + start = len(api.calls) + with pytest.raises(ic.InvalidRequestError): + c.accounts.change_line(cust, m.user_id, "201", "777") + assert api.writes(start) == [] + c.accounts.change_line(cust, m.user_id, "900", "901") + assert api.numbers(m.user_id, cust.management.connector_id) == ["901"] + assert api.numbers(m.user_id, t.connector_id) == ["201"] and api.numbers(m2.user_id, t.connector_id) == ["201"] + assert api.fa_numbers(t.location_id) == ["201"] and api.numbers(u1.user_id) == ["201"] + + +# ---------------------------------------------------------------------- B3: resume after a stop + + +def _writes_of(setup, action): + api, f, c = flaky() + ctx = setup(c) + start = len(api.calls) + action(c, ctx) + return len(api.writes(start)) + + +def _resume_every_step(setup, action, check): + """Fail each write of ``action`` in turn; the re-run must finish the job, and a third run writes nothing.""" + total = _writes_of(setup, action) + assert total > 0 + for k in range(total): + api, f, c = flaky() + ctx = setup(c) + f.arm(k) + with pytest.raises(ic.AccountError) as e: + action(c, ctx) + ctx["error"] = e.value + action(c, ctx) + check(api, ctx) + start = len(api.calls) + action(c, ctx) + assert api.writes(start) == [], f"write {k}: the third run wrote" + + +def test_change_license_to_base_user_resumes_after_any_step(): + def setup(c): + cust = c.accounts.create_customer(spec()) + t = cust.teams[0] + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) + return {"cust": cust, "t": t, "u": u, "m": m} + + def action(c, x): + return c.accounts.change_license(x["cust"], x["m"].user_id, "base_user") + + def check(api, x): + t, m = x["t"], x["m"] + assert x["error"].result.lines == ["201", "900"] or sorted(x["error"].result.lines) == ["201", "900"] + assert api.mappings[m.user_id] == [{"connector_id": t.connector_id, "monitored_numbers": ["900"]}] + assert sorted(api.fa_numbers(t.location_id)) == ["201", "900"] + assert api.products(m.user_id, t.location_id) == {"after-call-copilot"} + assert api.users[m.user_id]["_locations"] == [t.location_id] + assert all(m.user_id not in g["members"] for g in api.groups.values()) + assert api.numbers(x["u"].user_id) == ["201"] + _resume_every_step(setup, action, check) + + +def test_change_license_to_base_manager_resumes_after_any_step(): + def setup(c): + cust = c.accounts.create_customer(spec()) + t = cust.teams[0] + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + u2 = c.accounts.add_base_user(cust, person(2), team=t, line="202", invite=False) + return {"cust": cust, "t": t, "u": u, "u2": u2} + + def action(c, x): + return c.accounts.change_license(x["cust"], x["u"].user_id, "base_manager") + + def check(api, x): + t, u, mg = x["t"], x["u"], x["cust"].management + assert x["error"].result.lines == ["201"] and x["error"].result.teams == [t.location_id] + assert api.numbers(u.user_id, mg.connector_id) == ["201"] + assert api.numbers(u.user_id, t.connector_id) == ["202"] + assert api.fa_numbers(t.location_id) == ["202"] and api.ih_numbers(t.location_id) == ["202"] + assert u.user_id in api.group_members(t.location_id, "Customer Threats") + assert api.products(u.user_id, mg.location_id) == {"after-call-copilot", "first-alert-copilot", "insights-hub"} + _resume_every_step(setup, action, check) + + +def test_move_base_user_resumes_after_any_step(): + def setup(c): + cust = c.accounts.create_customer(spec()) + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t, east], line="900", invite=False) + return {"cust": cust, "t": t, "east": east, "u": u, "m": m} + + def action(c, x): + return c.accounts.move_user(x["cust"], x["u"].user_id, from_team=x["t"], to_team=x["east"]) + + def check(api, x): + t, east, u, m = x["t"], x["east"], x["u"], x["m"] + assert api.mappings[u.user_id] == [{"connector_id": east.connector_id, "monitored_numbers": ["201"]}] + assert api.fa_numbers(t.location_id) == [] and api.fa_numbers(east.location_id) == ["201"] + assert api.numbers(m.user_id, t.connector_id) == [] and api.numbers(m.user_id, east.connector_id) == ["201"] + assert api.users[u.user_id]["_locations"] == [east.location_id] + _resume_every_step(setup, action, check) + + +def test_move_manager_resumes_after_any_step(): + def setup(c): + cust = c.accounts.create_customer(spec()) + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + c.accounts.add_base_user(cust, person(3), team=east, line="301", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) + return {"cust": cust, "t": t, "east": east, "m": m} + + def action(c, x): + return c.accounts.move_user(x["cust"], x["m"].user_id, from_team=x["t"], to_team=x["east"]) + + def check(api, x): + t, east, m, mg = x["t"], x["east"], x["m"], x["cust"].management + assert api.numbers(m.user_id, mg.connector_id) == ["900"] and api.numbers(m.user_id, t.connector_id) == [] + assert api.numbers(m.user_id, east.connector_id) == ["301"] + assert m.user_id in api.group_members(east.location_id, "Upset Customers") + assert m.user_id not in api.group_members(t.location_id, "Upset Customers") + assert sorted(api.users[m.user_id]["_locations"]) == sorted([east.location_id, mg.location_id]) + _resume_every_step(setup, action, check) + + +# ---------------------------------------------------------------------- N4: focused people cases + + +def test_promoting_onto_another_team_leaves_the_old_one(): + api, c, cust = base() + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + c.accounts.add_base_user(cust, person(2), team=t, line="202", invite=False) + r = c.accounts.change_license(cust, u.user_id, "base_manager", teams=[east]) + assert r.teams == [east.location_id] + assert t.location_id not in api.users[u.user_id]["_locations"] + assert api.numbers(u.user_id) == ["201"] and api.fa_numbers(t.location_id) == ["202"] + c.accounts.add_base_user(cust, person(3), team=t, line="203", invite=False) + assert api.numbers(u.user_id) == ["201"] # not a holder of the old team's lines + + +def test_demoting_a_manager_of_several_teams_keeps_one_and_notes_empty_groups(): + api, c, cust = base() + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + c.accounts.add_base_user(cust, person(3), team=east, line="301", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t, east], line="900", invite=False) + other = c.accounts.add_base_manager(cust, person(8), teams=[t], invite=False) + r = c.accounts.change_license(cust, m.user_id, "base_user", teams=[east]) + assert r.license == "base_user" and r.lines == ["900"] and r.teams == [east.location_id] + assert sorted(api.fa_numbers(east.location_id)) == ["301", "900"] and api.fa_numbers(t.location_id) == ["201"] + assert api.users[m.user_id]["_locations"] == [east.location_id] + assert len(r.notes) == 1 and "Riverbend - East" in r.notes[0] and "Customer Threats" in r.notes[0] + out = c.accounts.remove_user(cust, other.user_id) + assert "Riverbend - Main has no Base Manager left in Customer Threats, Upset Customers, Low Sentiment Calls" \ + in out["notes"][0] + + +def test_moving_the_last_manager_off_a_team_is_noted(): + api, c, cust = base() + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], invite=False) + r = c.accounts.move_user(cust, m.user_id, from_team=t, to_team=east) + assert any("Riverbend - Main has no Base Manager left" in n for n in r.notes) + + +def test_the_last_base_user_leaving_a_team_empties_its_lists(): + api, c, cust = base() + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t, east], line="900", invite=False) + c.accounts.move_user(cust, u.user_id, from_team=t, to_team=east) + c.accounts.remove_user(cust, u.user_id) + assert api.fa_numbers(t.location_id) == api.fa_numbers(east.location_id) == [] + assert api.numbers(m.user_id) == ["900"] + + +def test_re_running_every_people_helper_writes_nothing(): + api, c, cust = base() + t = cust.teams[0] + east = c.accounts.add_team(cust, EAST, EAST_CONN) + + def everyone(): + c.accounts.add_base_user(cust, person(1), team=t, line="201") + c.accounts.add_base_user(cust, person(2), team=east, line="301") + c.accounts.add_base_manager(cust, person(9), teams=[t, east], line="900", company_reports=True) + c.accounts.add_integration_user(cust, person(7)) + c.accounts.sync_lines(cust) + c.accounts.activate_alerts(cust) + everyone() + start = len(api.calls) + everyone() + assert api.writes(start) == [] + + +# ---------------------------------------------------------------------- S1: nested secrets + + +def test_nested_secrets_are_hidden_and_assignment_wraps(): + cs = ic.ConnectorSpec(type="examplepbx", config={"auth": {"api_key": "NESTED-1"}, "Credentials": "CRED-2", + "pwd": "PWD-3", "hosts": [{"name": "a", "token": "TOK-4"}], + "host": "pbx.example.com"}) + cust = ic.CustomerSpec(company_name="x", admin=person(1), team=EAST, connector=cs) + text = repr(cs) + repr(cust) + str(cs.config) + repr(cs.config["hosts"]) + for secret in ("NESTED-1", "CRED-2", "PWD-3", "TOK-4"): + assert secret not in text + assert "pbx.example.com" in text + cs.config = {"nested": {"client_secret": "LATER-5"}} + cs.config["extra"] = {"password": "LATER-6"} + assert "LATER-5" not in repr(cs) and "LATER-6" not in repr(cs) + assert cs.config["nested"]["client_secret"] == "LATER-5" # sent as given + with pytest.raises(ic.InvalidRequestError): + cs.config = "not a mapping" # type: ignore[assignment] + + +# ---------------------------------------------------------------------- S4: sync_lines and "other" + + +def test_sync_lines_never_strips_a_line_whose_owner_reads_as_other(): + api, c, cust = base() + t = cust.teams[0] + u = c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + m = c.accounts.add_base_manager(cust, person(9), teams=[t], line="900", invite=False) + api.products(u.user_id, t.location_id).add("first-alert-copilot") # switched on in the app + assert [x.license for x in c.accounts.list_members(cust) if x.user_id == u.user_id] == ["other"] + plan = c.accounts.sync_lines(cust, dry_run=True)["teams"][t.location_id] + assert plan["other"] == [u.user_id] and plan["first_alert"] == {"add": [], "remove": []} and plan["holders"] == {} + c.accounts.sync_lines(cust) + assert api.fa_numbers(t.location_id) == ["201"] and api.numbers(m.user_id, t.connector_id) == ["201"] + + +# ---------------------------------------------------------------------- S5: connector stops + + +def test_connector_timeout_stops_at_the_end_and_a_rerun_completes(): + api = FakeAPI(connector_outcome="connecting") + c = api.client() + slow = ic.ConnectorSpec.netsapiens(CONN.config["api_url"], CONN.config["domain"], "KEY-123", timeout=0) + with pytest.raises(ic.AccountError) as e: + c.accounts.create_customer(spec(connector=slow)) + err = e.value + assert err.step == "connectors" and isinstance(err.cause, ic.ConnectorTimeoutError) + assert err.result.teams[0].rules.low_sentiment and err.result.management.groups.weekly_reports + assert err.result.teams[0].connector_status == "connecting" + api.connector_outcome = "active" + done = c.accounts.create_customer(spec(connector=slow, company_id=err.result.company_id)) + assert done.teams[0].connector_status == "active" and done.management.connector_status == "active" + + +def test_add_team_and_set_connector_stop_on_a_connector_error(): + api, c, cust = base() + api.connector_outcome = "error" + with pytest.raises(ic.AccountError) as e: + c.accounts.add_team(cust, EAST, EAST_CONN) + assert isinstance(e.value.cause, ic.ConnectorError) and isinstance(e.value.result, ic.Team) + assert e.value.result.rules.low_sentiment + api2 = FakeAPI(connector_outcome="error") + c2 = api2.client() + bare = c2.accounts.create_customer(spec(connector=None, sso_domain=None)) + with pytest.raises(ic.AccountError) as e2: + c2.accounts.set_connector(bare, CONN) + assert e2.value.step == "connectors" and e2.value.cause.state_reason == "invalid_permissions" + + +# ---------------------------------------------------------------------- N2: monitor-all + + +def test_people_helpers_switch_monitor_all_off_on_teams_they_touch(): + api, c, cust = base() + t = cust.teams[0] + api.ih_config[t.location_id] = True + c.accounts.add_base_user(cust, person(1), team=t, line="201", invite=False) + assert api.ih_config[t.location_id] is False + api.ih_config[t.location_id] = True + c.accounts.sync_lines(cust, dry_run=True) + assert api.ih_config[t.location_id] is True # a dry run writes nothing + c.accounts.sync_lines(cust) + assert api.ih_config[t.location_id] is False + + +# ---------------------------------------------------------------------- N5: the fake follows the API + + +def test_fake_refuses_a_duplicate_email(): + api, c, cust = base() + body = {"email": "dup@example.com", "first_name": "A", "last_name": "B", "role": "frontline_user"} + c.users.create_company_user(cust.company_id, body) + with pytest.raises(ic.ConflictError): + c.users.create_company_user(cust.company_id, body) + + +# ---------------------------------------------------------------------- conversation layer + + +@pytest.fixture +def user_api(): + a = FakeAPI(role="frontline_user") + now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + cid, aid = new_id(), new_id() + a.call_rows = [{"id": cid, "call_date": now, "caller_name": "+1 555 867 5309", "caller_number": "+15558675309", + "callee_name": "WIRELESS 5558675309", "callee_number": "5558675309"}] + a.alert_rows = [{"id": aid, "call_id": cid, "call_date": now, "caller_name": "CALLER 555-867-5309", + "caller_number": "+15558675309", "summary": "billing question", "keywords": ["Upset Customer"]}] + a.call_details[cid] = dict(a.call_rows[0]) + a.ids = (cid, aid) + return a + + +def test_numbers_inside_names_are_masked(user_api): + b = user_api.client().conversations.calls()[0] + assert (b.caller_name, b.callee_name, b.callee_number) == ("***5309", "WIRELESS ***5309", "***5309") + a = user_api.client().conversations.alerts()[0] + assert a.caller_name == "CALLER ***5309" + assert ic.conversations.mask_name("Suite 1200 Desk") == "Suite 1200 Desk" # four digits are kept + full = user_api.client(mask_numbers=False).conversations.calls()[0] + assert full.caller_name == "+1 555 867 5309" + + +def test_alert_search_matches_text_and_an_exact_id(user_api): + conv = user_api.client().conversations + cid, aid = user_api.ids + assert conv.alert(aid).id == aid # the spec: search matches an exact lowercase alert id + assert len(user_api.client().alerts.list_alerts(search="billing").items) == 1 + + +def test_app_links(user_api): + cid, aid = user_api.ids + conv = user_api.client().conversations + b, a = conv.calls()[0], conv.alerts()[0] + assert b.link == f"https://app.intelligence.cloud/after-call-copilot/calls/{cid}" + assert a.link == f"https://app.intelligence.cloud/first-alert-copilot/alerts/{aid}" + assert conv.reference(b).link == b.link and conv.reference(a).link == a.link + assert conv.reference(cid).kind == "call" + custom = user_api.client(app_url="https://portal.example.com/").conversations + assert custom.reference(cid).link == f"https://portal.example.com/after-call-copilot/calls/{cid}" + assert custom.calls()[0].link.startswith("https://portal.example.com/after-call-copilot/calls/") + for bad in ("http://portal.example.com", "portal.example.com", ""): + with pytest.raises(ic.InvalidRequestError): + ic.Client(email="x@example.com", password="pw", app_url=bad) + assert "5309" not in repr(b) and "billing" not in repr(a) + + +@pytest.fixture +def new_york(monkeypatch): + monkeypatch.setenv("TZ", "America/New_York") + time.tzset() + yield + monkeypatch.undo() + time.tzset() + + +@pytest.mark.parametrize("day,offset", [(date(2026, 7, 1), -4), (date(2026, 1, 15), -5)]) +def test_day_window_uses_that_dates_offset(new_york, day, offset): + conv = FakeAPI(role="frontline_user").client().conversations + start, end = conv._window(day, None, None) + assert start.utcoffset() == timedelta(hours=offset) and (start.hour, start.minute) == (0, 0) + assert end == start + timedelta(days=1) - timedelta(seconds=1) + + +def test_day_window_across_a_clock_change(new_york): + conv = FakeAPI(role="frontline_user").client().conversations + start, end = conv._window(date(2026, 3, 8), None, None) # clocks go forward: a 23-hour day + assert (end.hour, end.minute, end.second) == (23, 59, 59) + assert end.astimezone(timezone.utc) - start.astimezone(timezone.utc) == timedelta(hours=23, seconds=-1) From a16979e239e27615272ad9c019da994e94dad2cc Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:15:51 -0700 Subject: [PATCH 05/12] README and CHANGELOG: review fixes and app links Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ README.md | 29 ++++++++++++++++------------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d42b6d6..9eee197 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ Two new layers. `client.accounts` replaces `client.workflows`; `client.conversat - Alert email is off for every person the helpers create, managers included (0.1.x switched it on for managers). Insights Hub "monitor all numbers" stays off. - `ConnectorSpec(type, config, name=None, timeout=600)` takes any connector type the API accepts with that type's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Values whose names contain key, secret, token or password are hidden when the spec is printed. `add_team` requires a connector; `set_connector` attaches one to a customer created without it. - **Conversation layer, `client.conversations`** (the person's own login): `me`, `teams`, `calls`, `brief`, `transcript`, `recording_link`, `caller_history`, `open_tasks`, `alerts`, `alert`, `team_view`, `topics`, `reference`, `parse_first_alert_event`. Caller numbers are masked to their last four digits unless the client is created with `mask_numbers=False`. Windows are at most 31 days and lists at most 200 (`caller_history` 50), checked before any request. Printing a `CallBrief` or `AlertBrief` shows only its id and time. +- `CallBrief.link`, `AlertBrief.link` and `reference()` give the call or alert page in the app. `Client(app_url=...)` sets the app address (https only; default `https://app.intelligence.cloud`). +- A connector that does not become active stops `create_customer`, `add_team` and `set_connector` with `AccountError` (step `"connectors"`, cause `ConnectorTimeoutError` or `ConnectorError`) once everything else is built; run again to finish. +- `add_base_user`, `add_base_manager` and `add_integration_user` refuse a person already set up with another license; `change_license` converts. `change_license` and `move_user` continue from where an earlier run stopped. - `parse_first_alert_event` and `FirstAlertEvent` parse the First Alert webhook, beside `parse_after_call_event`. - New errors: `AccountError` and `WrongLoginError` (an account helper with a user login, or a conversation helper with an administrator login). - Examples: `examples/create_customer.py` replaces the provisioning example; `examples/my_day.py` shows the conversation layer. diff --git a/README.md b/README.md index e7366ee..e7c72e1 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ admin = Client(email=os.environ["IC_ADMIN_EMAIL"], password=os.environ["IC_ADMIN data = Client(email=os.environ["IC_DATA_EMAIL"], password=os.environ["IC_DATA_PASSWORD"]) ``` -`Client(base_url="https://app.intelligence.cloud/api/v1", email, password, token_store=None, timeout=30)`; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you") and `mask_numbers=True` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. +`Client(base_url="https://app.intelligence.cloud/api/v1", email, password, token_store=None, timeout=30)`; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on. ### Sign-in, tokens and sign-out @@ -99,12 +99,13 @@ admin.accounts.activate_alerts(customer) # once each team has a manager in it - **Phrase lists come from you.** The SDK holds none; ask your Tresic contact for them. A customer can be created without them: Low Sentiment and every group are created, `customer.pending` lists `"customer_threat"` and `"upset_customer"`, and `set_alerts` creates those alerts when the lists arrive. - **Safe to re-run.** Every helper finds what exists before it writes; a second run with the same input writes nothing. A company is never adopted by its name alone: pass `company_id` from the first run. Without it, a same-named company is used only when its primary contact email is `admin.email`; otherwise `ConflictError` (code `company_name_conflict`) is raised before anything is written. -- **Stops are reported.** A helper that fails part-way raises `AccountError` with `.step`, `.result` (so far) and `.cause`. Run it again with the same input to continue. +- **Stops are reported.** A helper that fails part-way raises `AccountError` with `.step`, `.result` (so far) and `.cause`. Run it again with the same input to continue; `change_license` and `move_user` also recognise a person they left part-way. A connector that does not become active stops `create_customer`, `add_team` and `set_connector` at the end, once everything else is built: `.step` is `"connectors"` and `.cause` is `ConnectorTimeoutError` or `ConnectorError` (with `state_reason`). +- **Existing people keep their license.** `add_base_user`, `add_base_manager` and `add_integration_user` refuse (`InvalidRequestError`, before any write) a person already set up with another license; use `change_license`. - **Alerts start switched off.** `activate_alerts` switches them on only for teams with at least one Base Manager in each alert group, and reports the teams it skipped. - **Alert email is off** for every person the helpers create, managers included. People switch it on in their own settings. - **Insights Hub "monitor all numbers" stays off.** The helpers never switch it on and switch it off where they find it on. - **Invitations go last.** People are created without one; it is emailed once their products, groups and lines are in place (`invite=False` holds it back; `send_invitations` sends it later). -- **Connectors.** `ConnectorSpec(type, config, name=None, timeout=600)` takes the phone platform as the API names it and that platform's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Give the key in full each time: it is sent when a connector is created or repaired and is never kept, logged or shown when the object is printed. A new connector is checked every 10 seconds until it settles; its status is recorded on the team (`connector_status`, `connector_state_reason`). A re-run with a corrected key repairs a connector in `error`; it never creates a second one. +- **Connectors.** `ConnectorSpec(type, config, name=None, timeout=600)` takes the phone platform as the API names it and that platform's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Give the key in full each time: it is sent when a connector is created or repaired and is never kept, logged or shown when the object is printed (any setting whose name contains key, secret, token, password, pwd, credential or auth is hidden, at any depth). A new connector is checked every 10 seconds until it settles; its status is recorded on the team (`connector_status`, `connector_state_reason`). A re-run with a corrected key repairs a connector in `error`; it never creates a second one. | Helper | Does | Returns | |---|---|---| @@ -118,13 +119,13 @@ admin.accounts.activate_alerts(customer) # once each team has a manager in it | `add_integration_user(customer, person)` | A data-reading user across every team: password sign-in, tagged `department: "integration"`, every line | `Member` | | `change_license(customer, user_id, to, *, teams=None, line=None)` | `"base_manager"` or `"base_user"`, moving their own line between the team and Management | `Member` | | `move_user(customer, user_id, *, from_team, to_team)` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` | -| `change_line(customer, user_id, old, new)` | Releases the old line everywhere it is listed and maps the new one | `Member` | -| `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates | summary | -| `activate_alerts(customer, *, team=None)` | Switches alerts on where each alert group has a manager | `{"switched_on", "skipped"}` | +| `change_line(customer, user_id, old, new)` | A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | `Member` | +| `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | summary | +| `activate_alerts(customer, *, team=None)` | Switches alerts on where each alert group has a manager. Returns a dict: `switched_on` (rule ids) and `skipped` (teams, with the groups that have no manager) | `{"switched_on", "skipped"}` | | `send_invitations(customer, *, user_ids=None)` | Sends invitations not yet sent or expired; re-sends to `user_ids` | user ids | | `list_members(customer, *, license=None, team=None)` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `list[Member]` | | `license_report(customer)` | People by license and the number of teams (Management not counted) | counts and members | -| `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people | changes | +| `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | changes | | `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary | Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only: a clash raises `ConflictError` with the message "Extension is already monitored at another location." @@ -146,22 +147,24 @@ board = me.conversations.team_view(team_id) # for a manager: counts, al | Helper | Returns | Limits | |---|---|---| -| `me()`, `teams()` | Who is signed in and the teams they can see | | +| `me()`, `teams()` | Who is signed in and the teams they can see. `me().lines` is `None`: the API gives a user login no way to read its own lines | | | `calls(*, day=None, since=None, until=None, team=None, number=None, search=None, limit=50)` | `list[CallBrief]`, newest first; default today | window at most 31 days, `limit` at most 200 | -| `brief(call_id)` | One `CallBrief` with key points, tasks, topics and the alerts it raised | no transcript, no recording | +| `brief(call_id)` | One `CallBrief` with key points, tasks, topics and the alerts it raised (read from one page of that day's alerts, so a day with more than 100 alerts can miss some) | no transcript, no recording | | `transcript(call_id)` | The transcript of one call | one call per request | | `recording_link(call_id)` | A `RecordingLink` that expires; the SDK never downloads the audio | | | `caller_history(number, *, limit=10)` | Recent briefs for one caller (last 31 days) | `limit` at most 50 | | `open_tasks(*, due=None, team=None)` | Open tasks with the id of the call each came from | up to 200 | -| `alerts(*, since=None, until=None, team=None, limit=50)` | `list[AlertBrief]` on this person's teams | as `calls` | +| `alerts(*, since=None, until=None, team=None, limit=50)` | `list[AlertBrief]` on this person's teams. `status=` raises `InvalidRequestError` and `holder` is `None`: the API has no alert status or holder yet | as `calls` | | `alert(alert_id)` | One alert with its call brief | | | `team_view(team, *, day=None, since=None, until=None)` | Counts, alerts, open tasks and briefs for one team | as `calls` | | `topics(*, since=None, until=None, team=None)` | Topic volumes and rising topics (default last 7 days) | needs Insights Hub access | -| `reference(call_or_alert)` | The id only, to pass to another system in place of content | | +| `reference(call_or_alert)` | The id and its page in the app, to pass to another system in place of content | | | `parse_first_alert_event(payload)` | A `FirstAlertEvent` | | -- **Caller numbers are masked** to their last four digits (`***0142`) unless the client was created with `mask_numbers=False`. Extensions are shown as they are. -- **Limits are checked before any request**: a longer window, a larger limit, `number` with `search`, or a date without a time zone raises `InvalidRequestError`. +- **Caller numbers are masked** to their last four digits (`***0142`) unless the client was created with `mask_numbers=False`, also where a number appears in a name. Extensions are shown as they are. +- **Links**: `CallBrief.link`, `AlertBrief.link` and `reference()` give the page in the app, `/after-call-copilot/calls/` or `/first-alert-copilot/alerts/`; they carry only the id. +- `` is `https://app.intelligence.cloud` unless you pass your own address: `Client(app_url="https://...")`. +- **Limits are checked before any request**: a longer window, a larger limit, `number` with `search`, or a date without a time zone raises `InvalidRequestError`. "Today" and `day=` are midnight to midnight in this machine's time zone, daylight saving included. - **Nothing is logged.** Printing a brief shows its id and time only. Keep summaries, names and numbers out of your own logs too. - An administrator login raises `WrongLoginError`. There is no helper that walks every call; for a bounded daily job use `client.intelligence.iter_calls`. From ba6ebd441c6ab41008a410e1dd3c5fb786475d12 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:16:54 -0700 Subject: [PATCH 06/12] Live suite: correct the connector key variable name Co-Authored-By: Claude Fable 5.2 --- tests/live/test_live.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/live/test_live.py b/tests/live/test_live.py index ce5a0bd..3bcbc95 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -3,7 +3,7 @@ Everything comes from the environment; nothing about the test tenant is written here. IC_RESELLER_USER / IC_RESELLER_PASSWORD reseller admin integration user IC_FRONTLINE_USER / IC_FRONTLINE_PASSWORD frontline integration user, READ ONLY (shapes and counts only) - SBX_NS_API_URL / SBX_NS_DOMAIN / SBX_NA_API_KEY phone-system connector settings for the test company + SBX_NS_API_URL / SBX_NS_DOMAIN / SBX_NS_API_KEY phone-system connector settings for the test company IC_LIVE_COMPANY_NAME the test company this suite creates (or finds) and deactivates at the end IC_LIVE_COMPANY_CODE its company code (optional) IC_LIVE_LOCATION_NAME its first team (default "SDK Test - Main"); Management is " - Management" @@ -169,7 +169,7 @@ def _alerts(): def _connector(): - return ic.ConnectorSpec.netsapiens(env("SBX_NS_API_URL"), env("SBX_NS_DOMAIN"), env("SBX_NA_API_KEY"), timeout=90) + return ic.ConnectorSpec.netsapiens(env("SBX_NS_API_URL"), env("SBX_NS_DOMAIN"), env("SBX_NS_API_KEY"), timeout=90) def _spec_for(admin, **kw): @@ -278,7 +278,7 @@ def test_connector_polling_to_error(admin, customer): admin.connectors.reactivate_connector(team.location_id, team.connector_id, timeout=90) assert e.value.state_reason == "invalid_permissions" ok = unwrap(admin.connectors.test_connector(team.location_id, {"type": "netsapiens", "config": { - "api_url": env("SBX_NS_API_URL"), "domain": env("SBX_NS_DOMAIN"), "api_key": env("SBX_NA_API_KEY")}})) + "api_url": env("SBX_NS_API_URL"), "domain": env("SBX_NS_DOMAIN"), "api_key": env("SBX_NS_API_KEY")}})) assert set(ok) == {"success"} From f0b94f5374c997180a2f378271fba16778de78d4 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:54:50 -0700 Subject: [PATCH 07/12] Treat a connector that reports "connected" as running The live API reports a working connector as "connected" as well as "active". Waiting only for "active" timed out on a connector that was working. Co-Authored-By: Claude Fable 5.2 --- src/intelligence_cloud/accounts.py | 12 ++++++------ src/intelligence_cloud/resources.py | 9 ++++++--- tests/live/test_live.py | 2 +- tests/unit/fake_api.py | 2 +- tests/unit/test_review_fixes.py | 15 +++++++++++++++ 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index ccbb316..c52d7bb 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -40,7 +40,7 @@ ValidationError, WrongLoginError, ) -from .resources import PRODUCT_KEYS, merge_mappings, numbers_for +from .resources import PRODUCT_KEYS, RUNNING, merge_mappings, numbers_for AFTER_CALL = "after-call-copilot" FIRST_ALERT = "first-alert-copilot" @@ -78,7 +78,7 @@ class _RuleDef: PHRASE_ALERTS = ("customer_threat", "upset_customer") LICENSES = ("base_user", "base_manager", "integration", "other") _SECRET_WORDS = ("key", "secret", "token", "password", "passwd", "pwd", "credential", "auth") -_RANK = {"active": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4} +_RANK = {"active": 0, "connected": 0, "connecting": 1, "error": 2, "deactivating": 3, "inactive": 4} # ---------------------------------------------------------------------- specs @@ -808,7 +808,7 @@ def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Cust have = found.get("config") or {} unchanged = found.get("name") == name and all( have.get(k) == v for k, v in config.items() if k in have and not _is_secret(k)) - if found.get("status") in ("active", "connecting") and unchanged: + if found.get("status") in (*RUNNING, "connecting") and unchanged: if result is not None: result.existing.append(label) self._set_conn(team, found) @@ -823,7 +823,7 @@ def _ensure_connector(self, team: Team, cs: ConnectorSpec, result: Optional[Cust if found.get("status") == "inactive": conn = unwrap(conns.reactivate_connector(team.location_id, found["id"], timeout=cs.timeout)) else: - conn = conns.wait_for_status(team.location_id, found["id"], ("active", "error"), cs.timeout, + conn = conns.wait_for_status(team.location_id, found["id"], (*RUNNING, "error"), cs.timeout, raise_on_error=False) if conn.get("status") == "error": conns.deactivate_connector(team.location_id, found["id"], timeout=cs.timeout) @@ -943,8 +943,8 @@ def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, name = connector.name or f"{t.name} phone system" found = self._find_connector(t.location_id, connector, name) active = [x for x in self._c.connectors.iter_location_connectors(t.location_id) - if x.get("status") == "active"] - same = found is not None and found.get("status") == "active" and all( + if x.get("status") in RUNNING] + same = found is not None and found.get("status") in RUNNING and all( (found.get("config") or {}).get(k) == v for k, v in connector.config.items() if k in (found.get("config") or {}) and not _is_secret(k)) if active and not same: diff --git a/src/intelligence_cloud/resources.py b/src/intelligence_cloud/resources.py index e2519ce..2826231 100644 --- a/src/intelligence_cloud/resources.py +++ b/src/intelligence_cloud/resources.py @@ -163,6 +163,9 @@ def find_group(self, location_id: str, group_name: str) -> Optional[Dict[str, An return None +# A connector that is running reports either of these. +RUNNING = ("active", "connected") + class ConnectorsAPI(g.ConnectorsAPI): """Create, reactivate and deactivate return at once with 202; these methods wait for the result, checking the connector every ``check_interval`` seconds (10) for up to ``timeout`` seconds (600).""" @@ -186,12 +189,12 @@ def wait_for_status(self, location_id: str, connector_id: str, final: Sequence[s def create_connector(self, location_id: str, body: Mapping[str, Any], *, wait: bool = True, timeout: float = 600.0) -> Any: - """Create a connector and wait until it is ``active``. Raises ConnectorError on ``error``.""" + """Create a connector and wait until it is running (``active`` or ``connected``). Raises ConnectorError on ``error``.""" resp = super().create_connector(location_id, body) if not wait: return resp conn = unwrap(resp) - final = self.wait_for_status(location_id, conn["id"], ("active", "error"), timeout) + final = self.wait_for_status(location_id, conn["id"], (*RUNNING, "error"), timeout) return {"data": final} def reactivate_connector(self, location_id: str, connector_id: str, *, wait: bool = True, @@ -199,7 +202,7 @@ def reactivate_connector(self, location_id: str, connector_id: str, *, wait: boo resp = super().reactivate_connector(location_id, connector_id) if not wait: return resp - return {"data": self.wait_for_status(location_id, connector_id, ("active", "error"), timeout)} + return {"data": self.wait_for_status(location_id, connector_id, (*RUNNING, "error"), timeout)} def deactivate_connector(self, location_id: str, connector_id: str, *, wait: bool = True, timeout: float = 600.0) -> Any: diff --git a/tests/live/test_live.py b/tests/live/test_live.py index 3bcbc95..a06ecb6 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -234,7 +234,7 @@ def test_create_customer(admin, customer): assert mgmt.groups.weekly_reports and team.rules.low_sentiment company = unwrap(admin.companies.get_company(customer.company_id)) assert company["mfa_enforced"] is False and company["is_active"] - assert team.connector_status == EXPECT_CONNECTOR + assert team.connector_status in (("active", "connected") if EXPECT_CONNECTOR == "active" else ("error",)) if EXPECT_CONNECTOR == "error": assert team.connector_state_reason == "invalid_permissions" if SSO_DOMAIN: diff --git a/tests/unit/fake_api.py b/tests/unit/fake_api.py index 4a3a3fe..fe9ceba 100644 --- a/tests/unit/fake_api.py +++ b/tests/unit/fake_api.py @@ -439,7 +439,7 @@ def get_maps(req, body, cid, uid): @self.route("PUT", r"/companies/([^/]+)/users/([^/]+)/connector-mappings") def put_maps(req, body, cid, uid): for m in body["mappings"]: - if api.connectors.get(m["connector_id"], {}).get("status") != "active": + if api.connectors.get(m["connector_id"], {}).get("status") not in ("active", "connected"): return 422, {"error": {"code": "VALIDATION_ERROR", "message": "connector not found or inactive"}} for m in body["mappings"]: # one extension, one location lid = api.connectors[m["connector_id"]]["location_id"] diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py index 93b9841..01594aa 100644 --- a/tests/unit/test_review_fixes.py +++ b/tests/unit/test_review_fixes.py @@ -485,3 +485,18 @@ def test_day_window_across_a_clock_change(new_york): start, end = conv._window(date(2026, 3, 8), None, None) # clocks go forward: a 23-hour day assert (end.hour, end.minute, end.second) == (23, 59, 59) assert end.astimezone(timezone.utc) - start.astimezone(timezone.utc) == timedelta(hours=23, seconds=-1) + + +# ---------------------------------------------------------------------- a running connector may report "connected" + + +def test_a_connector_that_reports_connected_is_running(): + api = FakeAPI(connector_outcome="connected") + c = api.client() + cust = c.accounts.create_customer(spec(connector=CONN)) + assert cust.teams[0].connector_status == "connected" and cust.management.connector_status == "connected" + before = len([x for x in api.calls if x[0] != "GET"]) + again = c.accounts.create_customer(spec(connector=CONN, company_id=cust.company_id)) + assert len([x for x in api.calls if x[0] != "GET"]) == before # nothing written on the re-run + user = c.accounts.add_base_user(again, person(1), team=again.teams[0], line="201", invite=False) + assert user.lines == ["201"] From a9c82d888af557d1723800253fd7ffd7a27787f7 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 14:59:58 -0700 Subject: [PATCH 08/12] Regenerate the bundled spec: connector status "connected" Co-Authored-By: Claude Fable 5.2 --- src/intelligence_cloud/data/spec.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/intelligence_cloud/data/spec.json b/src/intelligence_cloud/data/spec.json index afc9379..bc02032 100644 --- a/src/intelligence_cloud/data/spec.json +++ b/src/intelligence_cloud/data/spec.json @@ -1352,6 +1352,7 @@ "enum": [ "connecting", "active", + "connected", "error", "deactivating", "inactive" @@ -1614,6 +1615,7 @@ "enum": [ "connecting", "active", + "connected", "error", "deactivating", "inactive" From be47253675995986eefe2aca6bb415e5585e914c Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 15:00:17 -0700 Subject: [PATCH 09/12] Tests: placeholder keys that do not look like ticket ids Co-Authored-By: Claude Fable 5.2 --- tests/unit/test_accounts.py | 8 ++++---- tests/unit/test_review_fixes.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index 2615f2b..745f8a1 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -17,8 +17,8 @@ country="US", zipcode="62701", vertical="service-providers") EAST = ic.TeamSpec(name="Riverbend - East", street="9 Lake St", city="Springfield", state="IL", country="US", zipcode="62702", vertical="service-providers") -CONN = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend.example.com", "KEY-123") -EAST_CONN = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend-east.example.com", "KEY-456") +CONN = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend.example.com", "test-key-123") +EAST_CONN = ic.ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend-east.example.com", "test-key-456") THREAT = ["example threat one", "example threat two"] UPSET = ["example upset one"] ALERTS = ic.AlertSettings(customer_threat=ic.AlertSetting(phrases=THREAT), @@ -239,7 +239,7 @@ def test_connector_spec_hides_secrets(): cs = ic.ConnectorSpec(type="examplepbx", config={"host": "pbx.example.com", "client_secret": "S3CRET", "API_TOKEN": "T0KEN", "password": "PW"}) text = repr(cs) + str(cs.config) + repr(CONN) - for secret in ("S3CRET", "T0KEN", "PW", "KEY-123"): + for secret in ("S3CRET", "T0KEN", "PW", "test-key-123"): assert secret not in text assert "pbx.example.com" in text and cs.config["client_secret"] == "S3CRET" @@ -279,7 +279,7 @@ def test_connector_error_is_recorded_and_a_fixed_key_repairs_it(api): c = api.client() err = create_with_connector_stop(c, spec(sso_domain=None)) assert isinstance(err.cause, ic.ConnectorError) and err.cause.state_reason == "invalid_permissions" - assert "KEY-123" not in str(err) + assert "test-key-123" not in str(err) first = err.result assert first.teams[0].connector_status == "error" assert first.teams[0].connector_state_reason == "invalid_permissions" diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py index 01594aa..c486ebb 100644 --- a/tests/unit/test_review_fixes.py +++ b/tests/unit/test_review_fixes.py @@ -358,7 +358,7 @@ def test_sync_lines_never_strips_a_line_whose_owner_reads_as_other(): def test_connector_timeout_stops_at_the_end_and_a_rerun_completes(): api = FakeAPI(connector_outcome="connecting") c = api.client() - slow = ic.ConnectorSpec.netsapiens(CONN.config["api_url"], CONN.config["domain"], "KEY-123", timeout=0) + slow = ic.ConnectorSpec.netsapiens(CONN.config["api_url"], CONN.config["domain"], "test-key-123", timeout=0) with pytest.raises(ic.AccountError) as e: c.accounts.create_customer(spec(connector=slow)) err = e.value From 6e0bb478f0497b53368eb81885eb7ebc2c581e91 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 15:27:35 -0700 Subject: [PATCH 10/12] activate_alerts: a team does not need a manager Alerts go on for every team. Teams whose alert groups have no manager are listed under no_manager; their alerts show in the app only. Co-Authored-By: Claude Fable 5.2 --- README.md | 4 ++-- examples/create_customer.py | 2 +- src/intelligence_cloud/accounts.py | 11 +++++------ tests/live/test_live.py | 2 +- tests/unit/test_accounts.py | 14 +++++++------- 5 files changed, 16 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index e7c72e1..adf1431 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ admin.accounts.activate_alerts(customer) # once each team has a manager in it - **Safe to re-run.** Every helper finds what exists before it writes; a second run with the same input writes nothing. A company is never adopted by its name alone: pass `company_id` from the first run. Without it, a same-named company is used only when its primary contact email is `admin.email`; otherwise `ConflictError` (code `company_name_conflict`) is raised before anything is written. - **Stops are reported.** A helper that fails part-way raises `AccountError` with `.step`, `.result` (so far) and `.cause`. Run it again with the same input to continue; `change_license` and `move_user` also recognise a person they left part-way. A connector that does not become active stops `create_customer`, `add_team` and `set_connector` at the end, once everything else is built: `.step` is `"connectors"` and `.cause` is `ConnectorTimeoutError` or `ConnectorError` (with `state_reason`). - **Existing people keep their license.** `add_base_user`, `add_base_manager` and `add_integration_user` refuse (`InvalidRequestError`, before any write) a person already set up with another license; use `change_license`. -- **Alerts start switched off.** `activate_alerts` switches them on only for teams with at least one Base Manager in each alert group, and reports the teams it skipped. +- **Alerts start switched off.** `activate_alerts` switches them on for every team. A team does not need a manager: its alerts then show in the app only, and the result lists it. - **Alert email is off** for every person the helpers create, managers included. People switch it on in their own settings. - **Insights Hub "monitor all numbers" stays off.** The helpers never switch it on and switch it off where they find it on. - **Invitations go last.** People are created without one; it is emailed once their products, groups and lines are in place (`invite=False` holds it back; `send_invitations` sends it later). @@ -121,7 +121,7 @@ admin.accounts.activate_alerts(customer) # once each team has a manager in it | `move_user(customer, user_id, *, from_team, to_team)` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` | | `change_line(customer, user_id, old, new)` | A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | `Member` | | `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | summary | -| `activate_alerts(customer, *, team=None)` | Switches alerts on where each alert group has a manager. Returns a dict: `switched_on` (rule ids) and `skipped` (teams, with the groups that have no manager) | `{"switched_on", "skipped"}` | +| `activate_alerts(customer, *, team=None)` | Switches alerts on for every team. Returns a dict: `switched_on` (rule ids) and `no_manager` (teams whose alert groups have no manager, so their alerts show in the app only) | `{"switched_on", "no_manager"}` | | `send_invitations(customer, *, user_ids=None)` | Sends invitations not yet sent or expired; re-sends to `user_ids` | user ids | | `list_members(customer, *, license=None, team=None)` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `list[Member]` | | `license_report(customer)` | People by license and the number of teams (Management not counted) | counts and members | diff --git a/examples/create_customer.py b/examples/create_customer.py index 09aa917..629b926 100644 --- a/examples/create_customer.py +++ b/examples/create_customer.py @@ -61,7 +61,7 @@ def phrases(env_name): admin.accounts.add_base_user(customer, user, team=team, line="2101", invite=False) admin.accounts.add_base_manager(customer, manager, teams=[team], line="2001", invite=False) result = admin.accounts.activate_alerts(customer) - print("alerts switched on:", len(result["switched_on"]), "teams skipped:", len(result["skipped"])) + print("alerts switched on:", len(result["switched_on"]), "teams with no manager:", len(result["no_manager"])) print("invitations sent:", len(admin.accounts.send_invitations(customer))) except AccountError as exc: # Log the step and the error code, not the content. Run the script again to continue. diff --git a/src/intelligence_cloud/accounts.py b/src/intelligence_cloud/accounts.py index c52d7bb..de2098d 100644 --- a/src/intelligence_cloud/accounts.py +++ b/src/intelligence_cloud/accounts.py @@ -967,13 +967,13 @@ def set_connector(self, customer: CustomerRef, connector: ConnectorSpec, *, return targets def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = None) -> Dict[str, Any]: - """Switch the rules on for teams that have at least one Base Manager in each alert group. - Teams that do not are skipped and reported. + """Switch the rules on for every team. A team does not need a manager: its alerts then show in the + app only, and the team is listed under ``no_manager`` with the alert groups that have none. - Returns ``{"switched_on": [rule ids], "skipped": [{"location_id", "team", "missing"}]}``.""" + Returns ``{"switched_on": [rule ids], "no_manager": [{"location_id", "team", "missing"}]}``.""" self._require_admin() cust = self._resolve(customer) - out: Dict[str, Any] = {"switched_on": [], "skipped": []} + out: Dict[str, Any] = {"switched_on": [], "no_manager": []} people = self._index(cust) managers = {p.id for p in people.values() if p.license == "base_manager"} run = self._run(out) @@ -990,8 +990,7 @@ def activate_alerts(self, customer: CustomerRef, *, team: Optional[TeamRef] = No if not members & managers: missing.append(TEAM_GROUPS[f]) if missing: - out["skipped"].append({"location_id": t.location_id, "team": t.name, "missing": missing}) - continue + out["no_manager"].append({"location_id": t.location_id, "team": t.name, "missing": missing}) for key in RULES: rid = getattr(t.rules, key) if not rid: diff --git a/tests/live/test_live.py b/tests/live/test_live.py index a06ecb6..6d26159 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -327,7 +327,7 @@ def test_add_base_user_mapping_success(admin, customer): assert FREE_EXT in admin.users.user_numbers(customer.company_id, STATE["manager"], team.connector_id) assert FREE_EXT in admin.accounts._fa_numbers(team) and FREE_EXT in admin.accounts._ih_numbers(team) out = admin.accounts.activate_alerts(customer) - assert out["skipped"] == [] + assert out["no_manager"] == [] def test_license_report(admin, customer): diff --git a/tests/unit/test_accounts.py b/tests/unit/test_accounts.py index 745f8a1..f40916a 100644 --- a/tests/unit/test_accounts.py +++ b/tests/unit/test_accounts.py @@ -405,18 +405,18 @@ def test_add_base_manager(api, client, customer): invariants(api) -def test_activate_alerts_needs_a_manager_in_each_group(api, client, customer): +def test_activate_alerts_does_not_need_a_manager(api, client, customer): team = customer.teams[0] - out = client.accounts.activate_alerts(customer) - assert out["switched_on"] == [] and out["skipped"][0]["missing"] == list(ALERT_GROUPS) + out = client.accounts.activate_alerts(customer) # a team with no manager: alerts go on, and it is reported + assert len(out["switched_on"]) == 3 and out["no_manager"][0]["missing"] == list(ALERT_GROUPS) + assert all(r["enabled"] for r in api.rules.values()) mgr = client.accounts.add_base_manager(customer, person(2), teams=[team], invite=False) api.groups[team.groups.upset_customers]["members"].remove(mgr.user_id) out = client.accounts.activate_alerts(customer) - assert out["skipped"][0]["missing"] == ["Upset Customers"] + assert out["switched_on"] == [] and out["no_manager"][0]["missing"] == ["Upset Customers"] api.groups[team.groups.upset_customers]["members"].append(mgr.user_id) out = client.accounts.activate_alerts(customer) - assert len(out["switched_on"]) == 3 and out["skipped"] == [] - assert all(r["enabled"] for r in api.rules.values()) + assert out == {"switched_on": [], "no_manager": []} start = len(api.calls) assert client.accounts.activate_alerts(customer)["switched_on"] == [] and api.writes(start) == [] @@ -612,7 +612,7 @@ def test_acceptance_scenario(api, client): assert out["released_lines"] == ["3109"] and "3109" not in api.numbers(dee.user_id) # activate act = acc.activate_alerts(cust) - assert len(act["switched_on"]) == 6 and act["skipped"] == [] + assert len(act["switched_on"]) == 6 and act["no_manager"] == [] assert all(r["enabled"] for r in api.rules.values()) # report rep = acc.license_report(cust) From 6c165dc4a14c63989807c8e9c19cc9048485a24f Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 15:36:31 -0700 Subject: [PATCH 11/12] Network failures raise NetworkError with no request attached The HTTP library's error held the request (password at sign-in, token, connector key) and escaped unwrapped. NetworkError carries only the kind of failure. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 1 + README.md | 1 + src/intelligence_cloud/__init__.py | 3 +- src/intelligence_cloud/client.py | 23 ++++++++++---- src/intelligence_cloud/errors.py | 13 ++++++++ src/intelligence_cloud/resources.py | 5 ++- tests/unit/test_review_fixes.py | 47 +++++++++++++++++++++++++++++ 7 files changed, 85 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9eee197..13cc754 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Two new layers. `client.accounts` replaces `client.workflows`; `client.conversat - Alert email is off for every person the helpers create, managers included (0.1.x switched it on for managers). Insights Hub "monitor all numbers" stays off. - `ConnectorSpec(type, config, name=None, timeout=600)` takes any connector type the API accepts with that type's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Values whose names contain key, secret, token or password are hidden when the spec is printed. `add_team` requires a connector; `set_connector` attaches one to a customer created without it. - **Conversation layer, `client.conversations`** (the person's own login): `me`, `teams`, `calls`, `brief`, `transcript`, `recording_link`, `caller_history`, `open_tasks`, `alerts`, `alert`, `team_view`, `topics`, `reference`, `parse_first_alert_event`. Caller numbers are masked to their last four digits unless the client is created with `mask_numbers=False`. Windows are at most 31 days and lists at most 200 (`caller_history` 50), checked before any request. Printing a `CallBrief` or `AlertBrief` shows only its id and time. +- **Network failures raise `NetworkError`** (an `ApiError` with status 0) in place of the HTTP library's own error, which held the request: a request can hold a password, a token or a connection key. - `CallBrief.link`, `AlertBrief.link` and `reference()` give the call or alert page in the app. `Client(app_url=...)` sets the app address (https only; default `https://app.intelligence.cloud`). - A connector that does not become active stops `create_customer`, `add_team` and `set_connector` with `AccountError` (step `"connectors"`, cause `ConnectorTimeoutError` or `ConnectorError`) once everything else is built; run again to finish. - `add_base_user`, `add_base_manager` and `add_integration_user` refuse a person already set up with another license; `change_license` converts. `change_license` and `move_user` continue from where an earlier run stopped. diff --git a/README.md b/README.md index adf1431..beebb1a 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,7 @@ Log `status`, `code` and `request_id`, not exception text or response bodies. `s | Error | When | |---|---| | `ApiError` | Any API error: `status`, `code`, `message`, `request_id` | +| `NetworkError` | The request did not complete (no connection, a timeout, an unreadable response): `status` 0, `code` `network_error` or `timeout`, `kind`. The HTTP library's own error is not attached, because it holds the request | | `AuthError` (401), `PasswordExpiredError` | Sign-in failed, or the token could not be renewed | | `NotFoundError` (404) | Not found, or outside what this login can see | | `ConflictError` (409) | Duplicate name or email, already active or inactive, extension already monitored (`.extensions`) | diff --git a/src/intelligence_cloud/__init__.py b/src/intelligence_cloud/__init__.py index c1d9560..a5cfc60 100644 --- a/src/intelligence_cloud/__init__.py +++ b/src/intelligence_cloud/__init__.py @@ -35,6 +35,7 @@ from .errors import ( AccountError, ApiError, + NetworkError, AuthError, ConflictError, ConnectorError, @@ -71,7 +72,7 @@ __all__ = [ "Client", "DEFAULT_BASE_URL", "Page", "unwrap", "__version__", "Tokens", "TokenStore", "MemoryTokenStore", "FileTokenStore", - "IntelligenceCloudError", "InvalidRequestError", "ApiError", "AuthError", "PasswordExpiredError", + "IntelligenceCloudError", "InvalidRequestError", "ApiError", "NetworkError", "AuthError", "PasswordExpiredError", "NotFoundError", "ConflictError", "ValidationError", "RateLimitError", "MfaRequiredError", "FrontlineRequiredError", "ConnectorError", "ConnectorTimeoutError", "ExtensionMappingError", "AccountError", "WrongLoginError", "WebhookPayloadError", "PayloadTooLargeError", "WebhookTestResult", "RecordingLink", diff --git a/src/intelligence_cloud/client.py b/src/intelligence_cloud/client.py index 348f7c9..51e7517 100644 --- a/src/intelligence_cloud/client.py +++ b/src/intelligence_cloud/client.py @@ -17,6 +17,7 @@ from ._version import __version__ from .auth import MemoryTokenStore, Tokens, TokenStore from .errors import ( + NetworkError, EXTENSION_CONFLICT_MESSAGE, ApiError, AuthError, @@ -254,7 +255,7 @@ def _renew_locked(self, tokens: Tokens) -> None: resp = self._send_with_retries("POST", "/auth/refresh", op_id="refresh", json_body={"refresh_token": refresh_token}, auth=False, retry_429=False) - except httpx.HTTPError: + except NetworkError: resp = None if resp is None or resp.status_code != 429: break @@ -294,8 +295,18 @@ def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Toke h.update(headers) if tokens is not None: h["Authorization"] = f"Bearer {tokens.access_token}" - return self._http.request(method, self._url(path), params=params or None, - json=json_body, headers=h) + failed = None + try: + return self._http.request(method, self._url(path), params=params or None, + json=json_body, headers=h) + except httpx.HTTPError as exc: + kind = ("timeout" if isinstance(exc, httpx.TimeoutException) + else "transport" if isinstance(exc, httpx.TransportError) + else "decoding" if isinstance(exc, httpx.DecodingError) else "transport") + failed = (kind, type(exc).__name__) + # Raised outside the except block so the HTTP library's error, which holds the request, is not kept + # on this error as its context. + raise NetworkError(*failed) def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, json_body=None, headers: Optional[Dict[str, str]] = None, auth: bool = True, @@ -311,12 +322,12 @@ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, try: resp = self._send_raw(method, path, op_id=op_id, tokens=tokens, params=params, json_body=json_body, headers=headers) - except (httpx.TransportError,) as exc: - if idempotent and attempt < self._max_retries: + except NetworkError as exc: + if exc.kind != "decoding" and idempotent and attempt < self._max_retries: self._sleep(self._backoff(attempt, None) or 0.0) attempt += 1 continue - raise exc + raise if resp.status_code == 401 and auth and not refreshed: refreshed = True self._renew(tokens) # type: ignore[arg-type] diff --git a/src/intelligence_cloud/errors.py b/src/intelligence_cloud/errors.py index a7b8a06..ad08643 100644 --- a/src/intelligence_cloud/errors.py +++ b/src/intelligence_cloud/errors.py @@ -49,6 +49,19 @@ def _text(self) -> str: return text +class NetworkError(ApiError): + """The request did not complete: no connection, a timeout, or a response that could not be read. + + ``status`` is 0 and ``code`` is ``network_error`` or ``timeout``. ``kind`` is ``transport``, ``timeout`` + or ``decoding``. The underlying HTTP library error is deliberately not attached: it holds the request, + and a request can hold a password, a token or a connection key.""" + + def __init__(self, kind: str, detail: str): + self.kind = kind + super().__init__(0, "timeout" if kind == "timeout" else "network_error", "The request did not complete.", + public_message=f"the request did not complete ({detail})") + + class AuthError(ApiError): """401: sign-in failed, or the token could not be renewed.""" diff --git a/src/intelligence_cloud/resources.py b/src/intelligence_cloud/resources.py index 2826231..1a1b4a6 100644 --- a/src/intelligence_cloud/resources.py +++ b/src/intelligence_cloud/resources.py @@ -14,6 +14,7 @@ from . import _generated as g from ._base import unwrap from .errors import ( + NetworkError, ConnectorError, ConnectorTimeoutError, InvalidRequestError, @@ -314,7 +315,9 @@ def create_company_user(self, company_id: str, body: Mapping[str, Any], *, if body.get("location_ids"): self.update_company_user(company_id, user["id"], {"location_ids": list(body["location_ids"])}) return self.get_company_user(company_id, user["id"]) - except httpx.DecodingError: + except NetworkError as exc: + if exc.kind != "decoding": + raise # A replayed create can come back with a body that cannot be decoded: read the user instead. user = self.find_user_by_email(company_id, email) if email else None if user is None: diff --git a/tests/unit/test_review_fixes.py b/tests/unit/test_review_fixes.py index c486ebb..9a3d9c5 100644 --- a/tests/unit/test_review_fixes.py +++ b/tests/unit/test_review_fixes.py @@ -500,3 +500,50 @@ def test_a_connector_that_reports_connected_is_running(): assert len([x for x in api.calls if x[0] != "GET"]) == before # nothing written on the re-run user = c.accounts.add_base_user(again, person(1), team=again.teams[0], line="201", invite=False) assert user.lines == ["201"] + + +# ---------------------------------------------------------------------- network failures carry no request + + +def _chain(exc): + seen = [] + while exc is not None and exc not in seen: + seen.append(exc) + exc = exc.__cause__ or exc.__context__ or getattr(exc, "cause", None) + return seen + + +@pytest.mark.parametrize("failure, kind, code", [ + (httpx.ConnectError, "transport", "network_error"), + (httpx.ReadTimeout, "timeout", "timeout"), +]) +def test_a_network_failure_at_sign_in_keeps_no_request(failure, kind, code): + def down(request): + raise failure("no route", request=request) + + c = ic.Client(email="admin@example.com", password="pw-do-not-keep", transport=httpx.MockTransport(down), + max_retries=0) + with pytest.raises(ic.NetworkError) as e: + c.login() + assert e.value.kind == kind and e.value.code == code and e.value.status == 0 + for x in _chain(e.value): + assert not isinstance(x, httpx.HTTPError) and not hasattr(x, "request") + assert "pw-do-not-keep" not in repr(e.value) + str(e.value) + + +def test_a_network_failure_on_a_connector_keeps_no_key(): + api = FakeAPI() + + def down(request): + if request.method == "POST" and request.url.path.endswith("/connectors"): + raise httpx.ConnectError("no route", request=request) + return api(request) + + c = ic.Client(email="integration@example.com", password="pw", transport=httpx.MockTransport(down), max_retries=0) + with pytest.raises(ic.AccountError) as e: + c.accounts.create_customer(spec(connector=CONN)) + chain = _chain(e.value) + assert any(isinstance(x, ic.NetworkError) for x in chain) + for x in chain: + assert not isinstance(x, httpx.HTTPError) and not hasattr(x, "request") + assert "test-key" not in repr(x) + str(x) From 7a3e9ce99d59af4c99c0fce3b68ca30387c951d6 Mon Sep 17 00:00:00 2001 From: Robert Galop Date: Sun, 29 Nov 2026 16:02:22 -0700 Subject: [PATCH 12/12] Live suite: exercise every conversation helper on the login's own data Compares types, counts, masking and link shape only. Co-Authored-By: Claude Fable 5.2 --- tests/live/test_live.py | 100 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/tests/live/test_live.py b/tests/live/test_live.py index 6d26159..0cc6b8c 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -31,6 +31,7 @@ import json import os +import re import uuid from datetime import datetime, timedelta, timezone @@ -407,6 +408,105 @@ def test_conversation_layer(frontline, admin): assert repr(b).startswith("CallBrief(id=") +APP = "https://app.intelligence.cloud" +_LONG_DIGITS = re.compile(r"\d{5,}") + + +def _masked(*values): + """No run of five or more digits is left in a name or number field.""" + return all(v is None or not _LONG_DIGITS.search(v) for v in values) + + +def _brief_ok(b): + assert isinstance(b, ic.conversations.CallBrief) and b.id + assert _masked(b.caller_number, b.callee_number, b.caller_name, b.callee_name) + assert b.link == f"{APP}/after-call-copilot/calls/{b.id}" + assert repr(b).startswith("CallBrief(id=") and (b.summary is None or b.summary not in repr(b)) + assert all(isinstance(x, str) for x in b.key_points + b.topics + b.alerts) + assert all(isinstance(t, ic.conversations.TaskBrief) for t in b.tasks) + + +def _alert_ok(a): + assert isinstance(a, ic.conversations.AlertBrief) and a.id + assert _masked(a.caller_number, a.callee_number, a.caller_name, a.callee_name) + assert a.link == f"{APP}/first-alert-copilot/alerts/{a.id}" + assert all(isinstance(x, str) for x in a.alerts + a.topics) and a.holder is None + + +def test_conversation_layer_on_real_data(frontline): + """Every conversation helper against the login's own data. Compares types, counts, masking and links only.""" + conv = frontline.conversations + me, teams = conv.me(), conv.teams() + assert me.user_id and me.lines is None and all(t.location_id and t.name for t in teams) + + briefs = conv.calls(since=NOW - timedelta(days=7), limit=10) + assert len(briefs) <= 10 + for b in briefs: + _brief_ok(b) + assert b.key_points == [] and b.tasks == [] # list results carry the summary fields only + if not briefs: + pytest.skip("no calls in the last 7 days for this login") + whens = [b.when for b in briefs if b.when] + assert whens == sorted(whens, reverse=True) # newest first + + first = conv.brief(briefs[0].id) + _brief_ok(first) + assert first.id == briefs[0].id + ref = conv.reference(first) + assert (ref.kind, ref.id, ref.link) == ("call", first.id, first.link) + transcript = conv.transcript(first.id) + assert isinstance(transcript, list) and all(set(seg) <= {"time", "speaker", "name", "text"} for seg in transcript) + link = conv.recording_link(first.id) + assert link is None or (link.url.startswith("https://") and link.url not in repr(link)) + + # caller history needs a full number: read one with the lower-level helper and keep it in memory only + raw = frontline.intelligence.search_calls(date_from=NOW - timedelta(days=7), limit=10).items + number = next((c.get("caller_number") for c in raw if _LONG_DIGITS.search(c.get("caller_number") or "")), None) + if number: + history = conv.caller_history(number, limit=3) + assert len(history) <= 3 + for b in history: + _brief_ok(b) + + alerts = conv.alerts(since=NOW - timedelta(days=14), limit=10) + assert len(alerts) <= 10 + for a in alerts: + _alert_ok(a) + if alerts: + one = conv.alert(alerts[0].id) + assert one is not None and one.id == alerts[0].id + _alert_ok(one) + if one.call is not None: + _brief_ok(one.call) + ref = conv.reference(one) + assert (ref.kind, ref.id, ref.link) == ("alert", one.id, one.link) + with pytest.raises(ic.InvalidRequestError): + conv.alerts(status="open") # the API has no status filter + + tasks = conv.open_tasks() + assert len(tasks) <= 200 and all(isinstance(t, ic.conversations.TaskBrief) and t.id for t in tasks) + + if teams: + view = conv.team_view(teams[0], since=NOW - timedelta(days=2)) + assert view.team == teams[0].location_id and all(isinstance(v, int) for v in view.counts.values()) + for b in view.briefs: + _brief_ok(b) + for a in view.alerts: + _alert_ok(a) + + try: + topics = conv.topics(since=NOW - timedelta(days=7)) + except ic.ApiError as exc: # the login has no Insights Hub access + assert exc.status in (403, 404) + else: + assert all(isinstance(v, int) for v in topics.calls.values()) + assert all({"name", "call_count"} <= set(t) for t in topics.topics) + + for bad in ({"since": NOW - timedelta(days=40)}, {"limit": 201}, {"day": NOW.date(), "since": NOW}): + with pytest.raises(ic.InvalidRequestError): + conv.calls(**bad) + + def test_frontline_calls(frontline): since = NOW - timedelta(days=2) page = frontline.intelligence.search_calls(date_from=since, limit=5)