@intelligence-cloud/sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/generated/spec.ts
4
- var OPERATIONS = { "login": { "method": "POST", "path": "/auth/login", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "access_token": "v", "refresh_token": "v", "token_type": "v", "expires_in": "v", "user": { "o": { "id": "v", "user_type": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "role": "v", "scopes": { "a": "v" } } }, "password_expired": "v", "status": "v" } }, "summary": "Sign in" }, "refresh": { "method": "POST", "path": "/auth/refresh", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "access_token": "v", "refresh_token": "v", "token_type": "v", "expires_in": "v", "user": { "o": { "id": "v", "user_type": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "role": "v", "scopes": { "a": "v" } } }, "password_expired": "v" } }, "summary": "Renew the access token" }, "logout": { "method": "POST", "path": "/auth/logout", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "message": "v" } }, "summary": "Sign out" }, "getResellerBranding": { "method": "GET", "path": "/resellers/{resellerId}/branding", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "support_portal_url": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "main_logo_url": "v", "favicon_url": "v", "email_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read reseller branding" }, "updateResellerBranding": { "method": "PATCH", "path": "/resellers/{resellerId}/branding", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "support_portal_url": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "main_logo_url": "v", "favicon_url": "v", "email_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update reseller branding" }, "getResellerSmtpSettings": { "method": "GET", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "smtp_host": "v", "smtp_port": "v", "smtp_username": "v", "smtp_password": "v", "sender_name": "v", "sender_email": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read outbound email (SMTP) settings" }, "saveResellerSmtpSettings": { "method": "PATCH", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "smtp_host": "v", "smtp_port": "v", "smtp_username": "v", "smtp_password": "v", "sender_name": "v", "sender_email": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Save outbound email (SMTP) settings" }, "deleteResellerSmtpSettings": { "method": "DELETE", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Remove outbound email (SMTP) settings" }, "listCompanies": { "method": "GET", "path": "/resellers/{resellerId}/companies", "tag": "Companies", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "has_more": "v", "next_cursor": "v", "total_count": "v" } }, "summary": "List customer companies" }, "createCompany": { "method": "POST", "path": "/resellers/{resellerId}/companies", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } }, "invited_user": { "o": { "id": "v", "email": "v", "display_name": "v", "status": "v", "role": "v", "invited_at": "v", "invite_expires_at": "v" } } } }, "summary": "Create a customer company" }, "getCompaniesMfaSummary": { "method": "GET", "path": "/resellers/{resellerId}/companies/mfa", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "total_active": "v", "with_mfa_required": "v", "companies_mfa_default": "v", "mfa_available": "v" } } } }, "summary": "Read the MFA default for new companies" }, "getCompany": { "method": "GET", "path": "/companies/{companyId}", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a company" }, "updateCompany": { "method": "PATCH", "path": "/companies/{companyId}", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a company" }, "deactivateCompany": { "method": "POST", "path": "/companies/{companyId}/deactivate", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a company" }, "reactivateCompany": { "method": "POST", "path": "/companies/{companyId}/reactivate", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a company" }, "getCompanySecuritySettings": { "method": "GET", "path": "/companies/{companyId}/security-settings", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "min_password_length": "v", "require_uppercase": "v", "require_numbers": "v", "require_special_chars": "v", "password_expiry_days": "v", "session_timeout_minutes": "v", "allowed_ip_ranges": { "a": "v" }, "password_policy_source": "v", "password_policy_inherited_fields": { "a": "v" } } } } }, "summary": "Read a company's security settings" }, "getCompanyBranding": { "method": "GET", "path": "/companies/{companyId}/branding", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "company_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "company_logo_url": "v", "favicon_url": "v", "email_header_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read company branding overrides" }, "updateCompanyBranding": { "method": "PATCH", "path": "/companies/{companyId}/branding", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "company_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "company_logo_url": "v", "favicon_url": "v", "email_header_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update company branding overrides" }, "listCompanyDomains": { "method": "GET", "path": "/companies/{companyId}/domains", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "domain": "v", "status": "v", "verification": { "o": { "type": "v", "name": "v", "value": "v" } }, "verified_at": "v", "last_checked_at": "v", "last_failure_reason": "v" } } } } }, "summary": "List claimed domains" }, "claimCompanyDomain": { "method": "POST", "path": "/companies/{companyId}/domains", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "domain": "v", "status": "v", "verification": { "o": { "type": "v", "name": "v", "value": "v" } }, "verified_at": "v", "last_checked_at": "v", "last_failure_reason": "v" } } } }, "summary": "Claim a domain" }, "removeCompanyDomain": { "method": "DELETE", "path": "/companies/{companyId}/domains/{domainId}", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Remove a domain claim" }, "listDomainVerifications": { "method": "GET", "path": "/companies/{companyId}/domains/{domainId}/verifications", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "checked_at": "v", "status": "v", "failure_reason": "v" } } } } }, "summary": "List verification attempts" }, "verifyDomain": { "method": "POST", "path": "/companies/{companyId}/domains/{domainId}/verifications", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "checked_at": "v", "status": "v", "failure_reason": "v" } } } }, "summary": "Check the TXT record now" }, "getIdentityProvider": { "method": "GET", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "display_name": "v", "type": "v", "is_active": "v", "issuer": "v", "well_known_endpoint": "v", "client_id": "v", "client_auth_method": "v", "supported_client_auth_methods": { "a": "v" }, "secret_held": "v", "link_callback_uri": "v", "instructions": { "a": "v" }, "created_at": "v" } } } }, "summary": "Read the identity provider connection" }, "connectIdentityProvider": { "method": "POST", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "display_name": "v", "type": "v", "is_active": "v", "issuer": "v", "well_known_endpoint": "v", "client_id": "v", "client_auth_method": "v", "supported_client_auth_methods": { "a": "v" }, "secret_held": "v", "link_callback_uri": "v", "instructions": { "a": "v" }, "created_at": "v" } } } }, "summary": "Connect an OpenID Connect provider" }, "disconnectIdentityProvider": { "method": "DELETE", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Disconnect the identity provider" }, "testIdentityProvider": { "method": "POST", "path": "/companies/{companyId}/identity-provider/test", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "reachable": "v", "checks": { "a": { "o": { "name": "v", "outcome": "v", "detail": "v" } } } } } } }, "summary": "Test the identity provider connection" }, "listProducts": { "method": "GET", "path": "/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "key": "v", "name": "v" } } } } }, "summary": "List products" }, "listCompanyProducts": { "method": "GET", "path": "/companies/{companyId}/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } } }, "summary": "Company products" }, "listUserProducts": { "method": "GET", "path": "/companies/{companyId}/users/{userId}/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } } }, "summary": "A user's products" }, "enableUserProduct": { "method": "POST", "path": "/locations/{locationId}/users/{userId}/products/{productKey}/enable", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId", "productKey"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } }, "summary": "Turn a product on for a user" }, "disableUserProduct": { "method": "POST", "path": "/locations/{locationId}/users/{userId}/products/{productKey}/disable", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId", "productKey"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } }, "summary": "Turn a product off for a user" }, "listVerticals": { "method": "GET", "path": "/verticals", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "key": "v", "name": "v", "description": "v", "is_active": "v", "display_order": "v" } } } } }, "summary": "List industries" }, "listCompanyLocations": { "method": "GET", "path": "/companies/{companyId}/locations", "tag": "Locations", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "offset", "in": "query", "type": "integer", "minimum": 0 }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a company's locations" }, "createLocation": { "method": "POST", "path": "/companies/{companyId}/locations", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a location" }, "getLocation": { "method": "GET", "path": "/companies/{companyId}/locations/{locationId}", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a location" }, "updateLocation": { "method": "PATCH", "path": "/companies/{companyId}/locations/{locationId}", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a location" }, "deactivateLocation": { "method": "POST", "path": "/companies/{companyId}/locations/{locationId}/deactivate", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a location" }, "reactivateLocation": { "method": "POST", "path": "/companies/{companyId}/locations/{locationId}/reactivate", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a location" }, "listUserGroups": { "method": "GET", "path": "/locations/{locationId}/user-groups", "tag": "User groups", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's groups" }, "createUserGroup": { "method": "POST", "path": "/locations/{locationId}/user-groups", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a group" }, "getUserGroup": { "method": "GET", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a group with its members" }, "updateUserGroup": { "method": "PATCH", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Rename a group or set its members" }, "deleteUserGroup": { "method": "DELETE", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [{ "name": "force", "in": "query", "type": "boolean" }], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Delete a group" }, "getUserGroupMembership": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/group-membership", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "name": "v", "is_member": "v", "product_keys": { "a": "v" } } } } } }, "summary": "A user's groups at a location" }, "setUserGroupMembership": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/group-membership", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "a": { "o": { "id": "v", "name": "v", "is_member": "v", "product_keys": { "a": "v" } } } } } }, "summary": "Set a user's groups at a location" }, "listConnectorTypes": { "method": "GET", "path": "/connector-types", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "key": "v", "name": "v" } } } } }, "summary": "List connector types" }, "testConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/test", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "success": "v" } } } }, "summary": "Dry-run a connector" }, "listLocationConnectors": { "method": "GET", "path": "/locations/{locationId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["connecting", "active", "error", "deactivating", "inactive"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "location_id": "v", "location_name": "v", "name": "v", "type": "v", "type_display_name": "v", "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's connectors" }, "createConnector": { "method": "POST", "path": "/locations/{locationId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Create a connector" }, "getConnector": { "method": "GET", "path": "/locations/{locationId}/connectors/{connectorId}", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Read a connector" }, "updateConnector": { "method": "PATCH", "path": "/locations/{locationId}/connectors/{connectorId}", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Update a connector" }, "deactivateConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/{connectorId}/deactivate", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Stop a connector" }, "reactivateConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/{connectorId}/reactivate", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Restart a connector" }, "listCompanyConnectors": { "method": "GET", "path": "/companies/{companyId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["connecting", "active", "error", "deactivating", "inactive"] }, { "name": "type", "in": "query", "type": "string", "enum": ["netsapiens"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "location_id": "v", "location_name": "v", "name": "v", "type": "v", "type_display_name": "v", "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } }, "errors": { "a": { "o": { "id": "v", "name": "v", "type": "v", "location_name": "v", "status_message": "v" } } } } }, "summary": "List a company's connectors" }, "listAlertRules": { "method": "GET", "path": "/locations/{locationId}/first-alert/rules", "tag": "First Alert", "role": "reseller_admin", "query": [{ "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's alert rules" }, "createAlertRule": { "method": "POST", "path": "/locations/{locationId}/first-alert/rules", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create an alert rule" }, "getAlertRule": { "method": "GET", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read an alert rule" }, "updateAlertRule": { "method": "PATCH", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update an alert rule" }, "deleteAlertRule": { "method": "DELETE", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Delete an alert rule" }, "duplicateAlertRule": { "method": "POST", "path": "/locations/{locationId}/first-alert/rules/{ruleId}/duplicate", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Copy an alert rule" }, "getFirstAlertConfig": { "method": "GET", "path": "/locations/{locationId}/first-alert/config", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "webhook_url": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" }, "id": "v" } } } } } } }, "summary": "Read monitored numbers and the alert webhook" }, "saveFirstAlertConfig": { "method": "PUT", "path": "/locations/{locationId}/first-alert/config", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "webhook_url": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" }, "id": "v" } } } } } } }, "summary": "Set monitored numbers and the alert webhook" }, "testFirstAlertWebhook": { "method": "POST", "path": "/locations/{locationId}/first-alert/config/test-webhook", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "success": "v", "status_code": "v" } } } }, "summary": "Test the alert webhook" }, "getAlertNotificationPreferences": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/first-alert/notification-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Read a user's alert email and digest" }, "setAlertEmailPreferences": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/first-alert/email-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Set a user's alert email" }, "setAlertDigestPreferences": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/first-alert/digest-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Set a user's alert digest" }, "getInsightsHubSetup": { "method": "GET", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Read Insights Hub setup" }, "saveInsightsHubSetup": { "method": "POST", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Save Insights Hub setup" }, "updateInsightsHubSetup": { "method": "PATCH", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Update Insights Hub setup" }, "getInsightsHubConfig": { "method": "GET", "path": "/locations/{locationId}/insights-hub/config", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "monitor_all_numbers": "v" } } } } } }, "summary": "Read Insights Hub coverage" }, "updateInsightsHubConfig": { "method": "PATCH", "path": "/locations/{locationId}/insights-hub/config", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "monitor_all_numbers": "v" } } } } } }, "summary": "Set Insights Hub coverage" }, "getUserInsightsHubAccess": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/insights-hub/access", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "enabled": "v", "group_name": "v" } } } } } }, "summary": "Check a user's Insights Hub access" }, "listCompanyUsers": { "method": "GET", "path": "/companies/{companyId}/users", "tag": "Users", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["invited", "active", "deactivated"] }, { "name": "role", "in": "query", "type": "string", "enum": ["customer_admin", "frontline_user"] }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a company's users" }, "createCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": ["Idempotency-Key"], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a user" }, "getCompanyUser": { "method": "GET", "path": "/companies/{companyId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a user" }, "updateCompanyUser": { "method": "PATCH", "path": "/companies/{companyId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a user, role or locations" }, "deactivateCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/deactivate", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a user" }, "reactivateCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/reactivate", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a user" }, "resendInvitation": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/resend-invitation", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "user_id": "v", "email": "v", "invite_expires_at": "v", "message": "v" } } } } } }, "summary": "Resend the invitation email" }, "resetPassword": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/reset-password", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "user_id": "v", "email": "v", "message": "v" } } } } } }, "summary": "Send a password reset email" }, "getUserNumberMappings": { "method": "GET", "path": "/companies/{companyId}/users/{userId}/connector-mappings", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } } } }, "summary": "Read a user's numbers" }, "setUserNumberMappings": { "method": "PUT", "path": "/companies/{companyId}/users/{userId}/connector-mappings", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } } } }, "summary": "Set a user's numbers" }, "listLocationUsers": { "method": "GET", "path": "/locations/{locationId}/users", "tag": "Users", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["invited", "active", "deactivated"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "role": "v", "status": "v", "invited_at": "v", "created_at": "v", "location_id": "v", "location_name": "v", "assigned_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "groups": { "a": "v" }, "enabled_products": { "a": "v" } } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's users with products and groups" }, "getLocationUser": { "method": "GET", "path": "/locations/{locationId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "role": "v", "status": "v", "invited_at": "v", "created_at": "v", "location_id": "v", "location_name": "v", "assigned_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "groups": { "a": "v" }, "enabled_products": { "a": "v" } } } } } } }, "summary": "Read a user at a location" }, "getUserAfterCallSettings": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/after-call-settings", "tag": "After Call settings", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "user_id": "v", "eoc_enabled": "v", "eod_enabled": "v", "eod_timezone": "v", "eod_time": "v", "digest_frequency": "v", "digest_time_format": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_status": "v", "monitored_numbers": { "a": "v" } } } }, "last_changed_by": "v", "last_changed_at": "v" } } } }, "summary": "Read a user's After Call settings" }, "updateUserAfterCallSettings": { "method": "PATCH", "path": "/locations/{locationId}/users/{userId}/after-call-settings", "tag": "After Call settings", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "user_id": "v", "eoc_enabled": "v", "eod_enabled": "v", "eod_timezone": "v", "eod_time": "v", "digest_frequency": "v", "digest_time_format": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_status": "v", "monitored_numbers": { "a": "v" } } } }, "last_changed_by": "v", "last_changed_at": "v" } } } }, "summary": "Update a user's After Call settings" }, "getMe": { "method": "GET", "path": "/me", "tag": "Account", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "user_type": "v", "role": "v", "status": "v", "scopes": { "a": "v" }, "reseller_id": "v", "company_id": "v", "location_ids": { "a": "v" }, "enabled_products": { "a": "v" }, "mfa_available": "v" } } } }, "summary": "Who is signed in" }, "listVisibleLocations": { "method": "GET", "path": "/locations", "tag": "Account", "role": "frontline_user", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "offset", "in": "query", "type": "integer", "minimum": 0 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "Locations this login can see" }, "listCalls": { "method": "GET", "path": "/calls", "tag": "Calls", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "status", "in": "query", "type": "string", "enum": ["completed", "missed", "voicemail", "failed", "cancelled"] }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["crisis", "very_negative", "negative", "mildly_negative", "below_neutral", "neutral", "positive", "none"] }, { "name": "has_open_tasks", "in": "query", "type": "string", "enum": ["true"] }, { "name": "multi_leg", "in": "query", "type": "boolean" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "search", "in": "query", "type": "string", "minLength": 2 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "summary": { "o": { "total_calls": "v", "completed_calls": "v", "missed_calls": "v", "total_duration": "v", "tasks_done": "v", "pending": "v", "total_tasks": "v" } }, "calls": { "a": { "o": { "id": "v", "location_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "status": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "summary": "v", "top_highlight": "v", "highlights": { "a": "v" }, "duration": "v", "leg_count": "v", "task_count": "v", "completed_task_count": "v" } } } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } } } }, "summary": "List calls" }, "getCall": { "method": "GET", "path": "/calls/{callId}", "tag": "Calls", "role": "frontline_user", "query": [], "pathParams": ["callId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "call_outcome": "v", "duration": "v", "leg_count": "v", "platform": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "summary": "v", "analysis": { "o": { "summary": { "o": { "text": "v", "key_points": { "a": "v" }, "action_items": { "a": "v" } } }, "sentiment": { "o": { "overall": "v" } }, "topics": { "a": { "o": { "name": "v" } } } } }, "vcon": { "o": { "recording_url": "v", "recording_url_expires_at": "v", "recording_mime_type": "v" } }, "tasks": { "a": { "o": { "id": "v", "title": "v", "description": "v", "status": "v", "source": "v", "assignee_user": { "o": { "id": "v", "display_name": "v", "email": "v" } }, "due_date": "v" } } }, "task_count": "v", "has_more_tasks": "v" } } } }, "summary": "Read a call" }, "getCallTranscript": { "method": "GET", "path": "/calls/{callId}/transcript", "tag": "Calls", "role": "frontline_user", "query": [], "pathParams": ["callId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "transcript": { "a": { "o": { "time": "v", "speaker": "v", "name": "v", "text": "v" } } } } } } }, "summary": "Read a call's transcript" }, "listAlerts": { "method": "GET", "path": "/alerts", "tag": "Alerts", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "keyword", "in": "query", "type": "string" }, { "name": "topic", "in": "query", "type": "string" }, { "name": "numbers", "in": "query", "type": "array", "maxItems": 25, "items": { "type": "string", "pattern": "^[A-Za-z0-9@#]+$" } }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["crisis", "very_negative", "negative", "mildly_negative", "below_neutral", "neutral", "positive", "none"] }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "summary": { "o": { "total": "v" } }, "alerts": { "a": { "o": { "id": "v", "call_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "summary": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "keywords": { "a": "v" }, "topics": { "a": "v" } } } } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } } } }, "summary": "List alerts" }, "getAlertsDashboard": { "method": "GET", "path": "/alerts/dashboard", "tag": "Alerts", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "kpis": { "o": { "new_alerts": "v", "monitored": "v", "alert_rate": "v" } }, "top_triggered": { "a": { "o": { "keyword": "v", "count": "v" } } }, "recent_alerts": { "a": { "o": { "id": "v", "call_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "summary": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "keywords": { "a": "v" }, "topics": { "a": "v" } } } } } } } }, "summary": "Alert totals" }, "listTasks": { "method": "GET", "path": "/tasks", "tag": "Tasks", "role": "frontline_user", "query": [{ "name": "status", "in": "query", "type": "string", "enum": ["pending", "in_progress", "done", "overdue", "open"] }, { "name": "today_start", "in": "query", "type": "string", "format": "date-time" }, { "name": "call_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "task_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "due_on", "in": "query", "type": "string", "format": "date" }, { "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "call_id": "v", "company_id": "v", "location_id": "v", "title": "v", "description": "v", "status": "v", "source": "v", "assignee_user": { "o": { "id": "v", "display_name": "v", "email": "v" } }, "due_date": "v", "completed_at": "v", "created_at": "v", "updated_at": "v" } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } }, "summary": { "o": { "total": "v", "done": "v", "in_progress": "v", "pending": "v", "overdue": "v" } } } }, "summary": "List tasks" }, "getInsightsDashboard": { "method": "GET", "path": "/insights/dashboard", "tag": "Insights", "role": "frontline_user", "query": [{ "name": "start", "in": "query", "type": "string", "required": true, "format": "date-time" }, { "name": "end", "in": "query", "type": "string", "required": true, "format": "date-time" }, { "name": "trending_limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 10 }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "stats": { "o": { "total_calls": "v", "answered_calls": "v", "unanswered_calls": "v" } }, "trending_topics": { "a": { "o": { "slug": "v", "name": "v", "call_count": "v", "previous_call_count": "v", "percentage_change": "v", "trend_data": { "a": { "o": { "day": "v", "current": "v", "previous": "v" } } } } } }, "topic_call_volumes": { "a": { "o": { "slug": "v", "name": "v", "call_count": "v" } } } } } } }, "summary": "Insights Hub dashboard" }, "listTopicCalls": { "method": "GET", "path": "/insights/topics/{slug}/calls", "tag": "Insights", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["positive", "neutral", "negative"] }, { "name": "outcome", "in": "query", "type": "string", "enum": ["completed", "missed", "pending"] }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": ["slug"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "date": "v", "caller_name": "v", "summary": "v", "phone_number": "v", "sentiment": "v", "sentiment_label": "v", "outcome": "v" } } }, "meta": { "o": { "total": "v", "has_more": "v", "next_cursor": "v" } } } }, "summary": "Calls for one topic" }, "getAfterCallWebhook": { "method": "GET", "path": "/locations/{locationId}/after-call/automation", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "webhook_url": "v", "enabled": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Read the After Call webhook" }, "saveAfterCallWebhook": { "method": "PUT", "path": "/locations/{locationId}/after-call/automation", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "webhook_url": "v", "enabled": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Set the After Call webhook" }, "testAfterCallWebhook": { "method": "POST", "path": "/locations/{locationId}/after-call/automation/test", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "success": "v", "http_status": "v", "response_time_ms": "v" } } } }, "summary": "Send a test After Call event" } };
4
+ var OPERATIONS = { "login": { "method": "POST", "path": "/auth/login", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "access_token": "v", "refresh_token": "v", "token_type": "v", "expires_in": "v", "user": { "o": { "id": "v", "user_type": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "role": "v", "scopes": { "a": "v" } } }, "password_expired": "v", "status": "v" } }, "summary": "Sign in" }, "refresh": { "method": "POST", "path": "/auth/refresh", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "access_token": "v", "refresh_token": "v", "token_type": "v", "expires_in": "v", "user": { "o": { "id": "v", "user_type": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "role": "v", "scopes": { "a": "v" } } }, "password_expired": "v" } }, "summary": "Renew the access token" }, "logout": { "method": "POST", "path": "/auth/logout", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "message": "v" } }, "summary": "Sign out" }, "getResellerBranding": { "method": "GET", "path": "/resellers/{resellerId}/branding", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "support_portal_url": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "main_logo_url": "v", "favicon_url": "v", "email_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read reseller branding" }, "updateResellerBranding": { "method": "PATCH", "path": "/resellers/{resellerId}/branding", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "support_portal_url": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "main_logo_url": "v", "favicon_url": "v", "email_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update reseller branding" }, "getResellerSmtpSettings": { "method": "GET", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "smtp_host": "v", "smtp_port": "v", "smtp_username": "v", "smtp_password": "v", "sender_name": "v", "sender_email": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read outbound email (SMTP) settings" }, "saveResellerSmtpSettings": { "method": "PATCH", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "reseller_id": "v", "smtp_host": "v", "smtp_port": "v", "smtp_username": "v", "smtp_password": "v", "sender_name": "v", "sender_email": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Save outbound email (SMTP) settings" }, "deleteResellerSmtpSettings": { "method": "DELETE", "path": "/resellers/{resellerId}/smtp-settings", "tag": "Resellers", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Remove outbound email (SMTP) settings" }, "listCompanies": { "method": "GET", "path": "/resellers/{resellerId}/companies", "tag": "Companies", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "has_more": "v", "next_cursor": "v", "total_count": "v" } }, "summary": "List customer companies" }, "createCompany": { "method": "POST", "path": "/resellers/{resellerId}/companies", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } }, "invited_user": { "o": { "id": "v", "email": "v", "display_name": "v", "status": "v", "role": "v", "invited_at": "v", "invite_expires_at": "v" } } } }, "summary": "Create a customer company" }, "getCompaniesMfaSummary": { "method": "GET", "path": "/resellers/{resellerId}/companies/mfa", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["resellerId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "total_active": "v", "with_mfa_required": "v", "companies_mfa_default": "v", "mfa_available": "v" } } } }, "summary": "Read the MFA default for new companies" }, "getCompany": { "method": "GET", "path": "/companies/{companyId}", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a company" }, "updateCompany": { "method": "PATCH", "path": "/companies/{companyId}", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a company" }, "deactivateCompany": { "method": "POST", "path": "/companies/{companyId}/deactivate", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a company" }, "reactivateCompany": { "method": "POST", "path": "/companies/{companyId}/reactivate", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "reseller_id": "v", "reseller_name": "v", "company_name": "v", "company_code": "v", "vertical": "v", "address": "v", "primary_admin_contact_name": "v", "primary_admin_contact_email": "v", "primary_admin_contact_phone": "v", "enabled_products": { "a": "v" }, "is_active": "v", "mfa_enforced": "v", "mfa_available": "v", "location_count": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a company" }, "getCompanySecuritySettings": { "method": "GET", "path": "/companies/{companyId}/security-settings", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "min_password_length": "v", "require_uppercase": "v", "require_numbers": "v", "require_special_chars": "v", "password_expiry_days": "v", "session_timeout_minutes": "v", "allowed_ip_ranges": { "a": "v" }, "password_policy_source": "v", "password_policy_inherited_fields": { "a": "v" } } } } }, "summary": "Read a company's security settings" }, "getCompanyBranding": { "method": "GET", "path": "/companies/{companyId}/branding", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "company_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "company_logo_url": "v", "favicon_url": "v", "email_header_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read company branding overrides" }, "updateCompanyBranding": { "method": "PATCH", "path": "/companies/{companyId}/branding", "tag": "Companies", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "company_id": "v", "display_name": "v", "primary_accent_color": "v", "secondary_accent_color": "v", "support_email": "v", "privacy_policy_url": "v", "terms_of_service_url": "v", "copyright_text": "v", "company_logo_url": "v", "favicon_url": "v", "email_header_logo_url": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update company branding overrides" }, "listCompanyDomains": { "method": "GET", "path": "/companies/{companyId}/domains", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "domain": "v", "status": "v", "verification": { "o": { "type": "v", "name": "v", "value": "v" } }, "verified_at": "v", "last_checked_at": "v", "last_failure_reason": "v" } } } } }, "summary": "List claimed domains" }, "claimCompanyDomain": { "method": "POST", "path": "/companies/{companyId}/domains", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "domain": "v", "status": "v", "verification": { "o": { "type": "v", "name": "v", "value": "v" } }, "verified_at": "v", "last_checked_at": "v", "last_failure_reason": "v" } } } }, "summary": "Claim a domain" }, "removeCompanyDomain": { "method": "DELETE", "path": "/companies/{companyId}/domains/{domainId}", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Remove a domain claim" }, "listDomainVerifications": { "method": "GET", "path": "/companies/{companyId}/domains/{domainId}/verifications", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "checked_at": "v", "status": "v", "failure_reason": "v" } } } } }, "summary": "List verification attempts" }, "verifyDomain": { "method": "POST", "path": "/companies/{companyId}/domains/{domainId}/verifications", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "domainId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "checked_at": "v", "status": "v", "failure_reason": "v" } } } }, "summary": "Check the TXT record now" }, "getIdentityProvider": { "method": "GET", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "display_name": "v", "type": "v", "is_active": "v", "issuer": "v", "well_known_endpoint": "v", "client_id": "v", "client_auth_method": "v", "supported_client_auth_methods": { "a": "v" }, "secret_held": "v", "link_callback_uri": "v", "instructions": { "a": "v" }, "created_at": "v" } } } }, "summary": "Read the identity provider connection" }, "connectIdentityProvider": { "method": "POST", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "display_name": "v", "type": "v", "is_active": "v", "issuer": "v", "well_known_endpoint": "v", "client_id": "v", "client_auth_method": "v", "supported_client_auth_methods": { "a": "v" }, "secret_held": "v", "link_callback_uri": "v", "instructions": { "a": "v" }, "created_at": "v" } } } }, "summary": "Connect an OpenID Connect provider" }, "disconnectIdentityProvider": { "method": "DELETE", "path": "/companies/{companyId}/identity-provider", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Disconnect the identity provider" }, "testIdentityProvider": { "method": "POST", "path": "/companies/{companyId}/identity-provider/test", "tag": "Single sign-on", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "reachable": "v", "checks": { "a": { "o": { "name": "v", "outcome": "v", "detail": "v" } } } } } } }, "summary": "Test the identity provider connection" }, "listProducts": { "method": "GET", "path": "/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "key": "v", "name": "v" } } } } }, "summary": "List products" }, "listCompanyProducts": { "method": "GET", "path": "/companies/{companyId}/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } } }, "summary": "Company products" }, "listUserProducts": { "method": "GET", "path": "/companies/{companyId}/users/{userId}/products", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } } }, "summary": "A user's products" }, "enableUserProduct": { "method": "POST", "path": "/locations/{locationId}/users/{userId}/products/{productKey}/enable", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId", "productKey"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } }, "summary": "Turn a product on for a user" }, "disableUserProduct": { "method": "POST", "path": "/locations/{locationId}/users/{userId}/products/{productKey}/disable", "tag": "Products", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId", "productKey"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "product_key": "v", "name": "v", "enabled": "v", "enabled_at": "v", "enabled_by": "v" } } } }, "summary": "Turn a product off for a user" }, "listVerticals": { "method": "GET", "path": "/verticals", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "key": "v", "name": "v", "description": "v", "is_active": "v", "display_order": "v" } } } } }, "summary": "List industries" }, "listCompanyLocations": { "method": "GET", "path": "/companies/{companyId}/locations", "tag": "Locations", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "offset", "in": "query", "type": "integer", "minimum": 0 }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a company's locations" }, "createLocation": { "method": "POST", "path": "/companies/{companyId}/locations", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a location" }, "getLocation": { "method": "GET", "path": "/companies/{companyId}/locations/{locationId}", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a location" }, "updateLocation": { "method": "PATCH", "path": "/companies/{companyId}/locations/{locationId}", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a location" }, "deactivateLocation": { "method": "POST", "path": "/companies/{companyId}/locations/{locationId}/deactivate", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a location" }, "reactivateLocation": { "method": "POST", "path": "/companies/{companyId}/locations/{locationId}/reactivate", "tag": "Locations", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a location" }, "listUserGroups": { "method": "GET", "path": "/locations/{locationId}/user-groups", "tag": "User groups", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's groups" }, "createUserGroup": { "method": "POST", "path": "/locations/{locationId}/user-groups", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a group" }, "getUserGroup": { "method": "GET", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a group with its members" }, "updateUserGroup": { "method": "PATCH", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "group_name": "v", "user_count": "v", "members": { "a": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Rename a group or set its members" }, "deleteUserGroup": { "method": "DELETE", "path": "/locations/{locationId}/user-groups/{groupId}", "tag": "User groups", "role": "reseller_admin", "query": [{ "name": "force", "in": "query", "type": "boolean" }], "pathParams": ["locationId", "groupId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Delete a group" }, "getUserGroupMembership": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/group-membership", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "name": "v", "is_member": "v", "product_keys": { "a": "v" } } } } } }, "summary": "A user's groups at a location" }, "setUserGroupMembership": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/group-membership", "tag": "User groups", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "a": { "o": { "id": "v", "name": "v", "is_member": "v", "product_keys": { "a": "v" } } } } } }, "summary": "Set a user's groups at a location" }, "listConnectorTypes": { "method": "GET", "path": "/connector-types", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "key": "v", "name": "v" } } } } }, "summary": "List connector types" }, "testConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/test", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "success": "v" } } } }, "summary": "Dry-run a connector" }, "listLocationConnectors": { "method": "GET", "path": "/locations/{locationId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["connecting", "active", "connected", "error", "deactivating", "inactive"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "location_id": "v", "location_name": "v", "name": "v", "type": "v", "type_display_name": "v", "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's connectors" }, "createConnector": { "method": "POST", "path": "/locations/{locationId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Create a connector" }, "getConnector": { "method": "GET", "path": "/locations/{locationId}/connectors/{connectorId}", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Read a connector" }, "updateConnector": { "method": "PATCH", "path": "/locations/{locationId}/connectors/{connectorId}", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Update a connector" }, "deactivateConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/{connectorId}/deactivate", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Stop a connector" }, "reactivateConnector": { "method": "POST", "path": "/locations/{locationId}/connectors/{connectorId}/reactivate", "tag": "Connectors", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "connectorId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "name": "v", "type": "v", "type_display_name": "v", "config": { "o": { "api_url": "v", "domain": "v" } }, "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Restart a connector" }, "listCompanyConnectors": { "method": "GET", "path": "/companies/{companyId}/connectors", "tag": "Connectors", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["connecting", "active", "connected", "error", "deactivating", "inactive"] }, { "name": "type", "in": "query", "type": "string", "enum": ["netsapiens"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "location_id": "v", "location_name": "v", "name": "v", "type": "v", "type_display_name": "v", "status": "v", "status_display": "v", "status_message": "v", "state_reason": "v", "last_synced_at": "v", "created_at": "v", "updated_at": "v" } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } }, "errors": { "a": { "o": { "id": "v", "name": "v", "type": "v", "location_name": "v", "status_message": "v" } } } } }, "summary": "List a company's connectors" }, "listAlertRules": { "method": "GET", "path": "/locations/{locationId}/first-alert/rules", "tag": "First Alert", "role": "reseller_admin", "query": [{ "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's alert rules" }, "createAlertRule": { "method": "POST", "path": "/locations/{locationId}/first-alert/rules", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create an alert rule" }, "getAlertRule": { "method": "GET", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read an alert rule" }, "updateAlertRule": { "method": "PATCH", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update an alert rule" }, "deleteAlertRule": { "method": "DELETE", "path": "/locations/{locationId}/first-alert/rules/{ruleId}", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": null, "summary": "Delete an alert rule" }, "duplicateAlertRule": { "method": "POST", "path": "/locations/{locationId}/first-alert/rules/{ruleId}/duplicate", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "ruleId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "location_id": "v", "name": "v", "priority": "v", "match_logic": "v", "enabled": "v", "is_default": "v", "triggers": { "a": { "o": { "id": "v", "trigger_type": "v", "config": { "o": { "operator": "v", "threshold": "v", "keywords": { "a": "v" }, "match_logic": "v", "topics": { "a": "v" } } } } } }, "trigger_types": { "a": "v" }, "groups": { "a": { "o": { "id": "v", "group_name": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Copy an alert rule" }, "getFirstAlertConfig": { "method": "GET", "path": "/locations/{locationId}/first-alert/config", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "webhook_url": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" }, "id": "v" } } } } } } }, "summary": "Read monitored numbers and the alert webhook" }, "saveFirstAlertConfig": { "method": "PUT", "path": "/locations/{locationId}/first-alert/config", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "webhook_url": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" }, "id": "v" } } } } } } }, "summary": "Set monitored numbers and the alert webhook" }, "testFirstAlertWebhook": { "method": "POST", "path": "/locations/{locationId}/first-alert/config/test-webhook", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "success": "v", "status_code": "v" } } } }, "summary": "Test the alert webhook" }, "getAlertNotificationPreferences": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/first-alert/notification-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Read a user's alert email and digest" }, "setAlertEmailPreferences": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/first-alert/email-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Set a user's alert email" }, "setAlertDigestPreferences": { "method": "PUT", "path": "/locations/{locationId}/users/{userId}/first-alert/digest-preferences", "tag": "First Alert", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "emailNotifications": { "o": { "masterEnabled": "v", "alerts": { "a": { "o": { "alertId": "v", "alertName": "v", "trigger": "v", "severity": "v", "description": "v", "emailEnabled": "v" } } } } }, "digest": { "o": { "enabled": "v", "frequency": "v", "sendTime": "v", "timezone": "v", "timeFormat": "v" } } } }, "summary": "Set a user's alert digest" }, "getInsightsHubSetup": { "method": "GET", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Read Insights Hub setup" }, "saveInsightsHubSetup": { "method": "POST", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Save Insights Hub setup" }, "updateInsightsHubSetup": { "method": "PATCH", "path": "/locations/{locationId}/insights-hub/setup", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } }, "group_access": { "a": "v" }, "available_connectors": { "a": { "o": { "id": "v", "name": "v", "type": "v" } } }, "groups": { "a": { "o": { "id": "v", "group_name": "v", "has_access": "v" } } } } } } } } }, "summary": "Update Insights Hub setup" }, "getInsightsHubConfig": { "method": "GET", "path": "/locations/{locationId}/insights-hub/config", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "monitor_all_numbers": "v" } } } } } }, "summary": "Read Insights Hub coverage" }, "updateInsightsHubConfig": { "method": "PATCH", "path": "/locations/{locationId}/insights-hub/config", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "monitor_all_numbers": "v" } } } } } }, "summary": "Set Insights Hub coverage" }, "getUserInsightsHubAccess": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/insights-hub/access", "tag": "Insights Hub", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "enabled": "v", "group_name": "v" } } } } } }, "summary": "Check a user's Insights Hub access" }, "listCompanyUsers": { "method": "GET", "path": "/companies/{companyId}/users", "tag": "Users", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["invited", "active", "deactivated"] }, { "name": "role", "in": "query", "type": "string", "enum": ["customer_admin", "frontline_user"] }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["companyId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a company's users" }, "createCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId"], "headers": ["Idempotency-Key"], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Create a user" }, "getCompanyUser": { "method": "GET", "path": "/companies/{companyId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Read a user" }, "updateCompanyUser": { "method": "PATCH", "path": "/companies/{companyId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Update a user, role or locations" }, "deactivateCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/deactivate", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Deactivate a user" }, "reactivateCompanyUser": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/reactivate", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "reseller_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "department": "v", "status": "v", "role": "v", "auth_method": "v", "invited_at": "v", "invite_expires_at": "v", "activated_at": "v", "last_login_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "created_at": "v", "updated_at": "v" } } } } } }, "summary": "Reactivate a user" }, "resendInvitation": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/resend-invitation", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "user_id": "v", "email": "v", "invite_expires_at": "v", "message": "v" } } } } } }, "summary": "Resend the invitation email" }, "resetPassword": { "method": "POST", "path": "/companies/{companyId}/users/{userId}/reset-password", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "user_id": "v", "email": "v", "message": "v" } } } } } }, "summary": "Send a password reset email" }, "getUserNumberMappings": { "method": "GET", "path": "/companies/{companyId}/users/{userId}/connector-mappings", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } } } }, "summary": "Read a user's numbers" }, "setUserNumberMappings": { "method": "PUT", "path": "/companies/{companyId}/users/{userId}/connector-mappings", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["companyId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_type": "v", "monitored_numbers": { "a": "v" } } } } } }, "summary": "Set a user's numbers" }, "listLocationUsers": { "method": "GET", "path": "/locations/{locationId}/users", "tag": "Users", "role": "reseller_admin", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "status", "in": "query", "type": "string", "enum": ["invited", "active", "deactivated"] }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "role": "v", "status": "v", "invited_at": "v", "created_at": "v", "location_id": "v", "location_name": "v", "assigned_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "groups": { "a": "v" }, "enabled_products": { "a": "v" } } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "List a location's users with products and groups" }, "getLocationUser": { "method": "GET", "path": "/locations/{locationId}/users/{userId}", "tag": "Users", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "phone_number": "v", "role": "v", "status": "v", "invited_at": "v", "created_at": "v", "location_id": "v", "location_name": "v", "assigned_at": "v", "locations": { "a": { "o": { "location_id": "v", "assigned_at": "v" } } }, "groups": { "a": "v" }, "enabled_products": { "a": "v" } } } } } } }, "summary": "Read a user at a location" }, "getUserAfterCallSettings": { "method": "GET", "path": "/locations/{locationId}/users/{userId}/after-call-settings", "tag": "After Call settings", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "user_id": "v", "eoc_enabled": "v", "eod_enabled": "v", "eod_timezone": "v", "eod_time": "v", "digest_frequency": "v", "digest_time_format": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_status": "v", "monitored_numbers": { "a": "v" } } } }, "last_changed_by": "v", "last_changed_at": "v" } } } }, "summary": "Read a user's After Call settings" }, "updateUserAfterCallSettings": { "method": "PATCH", "path": "/locations/{locationId}/users/{userId}/after-call-settings", "tag": "After Call settings", "role": "reseller_admin", "query": [], "pathParams": ["locationId", "userId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "user_id": "v", "eoc_enabled": "v", "eod_enabled": "v", "eod_timezone": "v", "eod_time": "v", "digest_frequency": "v", "digest_time_format": "v", "connector_mappings": { "a": { "o": { "connector_id": "v", "connector_name": "v", "connector_status": "v", "monitored_numbers": { "a": "v" } } } }, "last_changed_by": "v", "last_changed_at": "v" } } } }, "summary": "Update a user's After Call settings" }, "getMe": { "method": "GET", "path": "/me", "tag": "Account", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "email": "v", "first_name": "v", "last_name": "v", "display_name": "v", "user_type": "v", "role": "v", "status": "v", "scopes": { "a": "v" }, "reseller_id": "v", "company_id": "v", "location_ids": { "a": "v" }, "enabled_products": { "a": "v" }, "mfa_available": "v" } } } }, "summary": "Who is signed in" }, "listVisibleLocations": { "method": "GET", "path": "/locations", "tag": "Account", "role": "frontline_user", "query": [{ "name": "search", "in": "query", "type": "string" }, { "name": "is_active", "in": "query", "type": "boolean" }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "offset", "in": "query", "type": "integer", "minimum": 0 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "type": "v", "attributes": { "o": { "id": "v", "company_id": "v", "company_name": "v", "reseller_name": "v", "location_name": "v", "street": "v", "city": "v", "state": "v", "country": "v", "zipcode": "v", "support_contact_name": "v", "support_contact_email": "v", "support_contact_phone": "v", "vertical_id": "v", "vertical_name": "v", "enabled_products": { "a": "v" }, "is_active": "v", "user_count": "v", "created_at": "v", "updated_at": "v" } } } } }, "pagination": { "o": { "has_more": "v", "next_cursor": "v", "total_count": "v" } } } }, "summary": "Locations this login can see" }, "listCalls": { "method": "GET", "path": "/calls", "tag": "Calls", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "status", "in": "query", "type": "string", "enum": ["completed", "missed", "voicemail", "failed", "cancelled"] }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["crisis", "very_negative", "negative", "mildly_negative", "below_neutral", "neutral", "positive", "none"] }, { "name": "has_open_tasks", "in": "query", "type": "string", "enum": ["true"] }, { "name": "multi_leg", "in": "query", "type": "boolean" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "search", "in": "query", "type": "string", "minLength": 2 }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "summary": { "o": { "total_calls": "v", "completed_calls": "v", "missed_calls": "v", "total_duration": "v", "tasks_done": "v", "pending": "v", "total_tasks": "v" } }, "calls": { "a": { "o": { "id": "v", "location_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "status": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "summary": "v", "top_highlight": "v", "highlights": { "a": "v" }, "duration": "v", "leg_count": "v", "task_count": "v", "completed_task_count": "v" } } } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } } } }, "summary": "List calls" }, "getCall": { "method": "GET", "path": "/calls/{callId}", "tag": "Calls", "role": "frontline_user", "query": [], "pathParams": ["callId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "call_outcome": "v", "duration": "v", "leg_count": "v", "platform": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "summary": "v", "analysis": { "o": { "summary": { "o": { "text": "v", "key_points": { "a": "v" }, "action_items": { "a": "v" } } }, "sentiment": { "o": { "overall": "v" } }, "topics": { "a": { "o": { "name": "v" } } } } }, "vcon": { "o": { "recording_url": "v", "recording_url_expires_at": "v", "recording_mime_type": "v" } }, "tasks": { "a": { "o": { "id": "v", "title": "v", "description": "v", "status": "v", "source": "v", "assignee_user": { "o": { "id": "v", "display_name": "v", "email": "v" } }, "due_date": "v" } } }, "task_count": "v", "has_more_tasks": "v" } } } }, "summary": "Read a call" }, "getCallTranscript": { "method": "GET", "path": "/calls/{callId}/transcript", "tag": "Calls", "role": "frontline_user", "query": [], "pathParams": ["callId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "transcript": { "a": { "o": { "time": "v", "speaker": "v", "name": "v", "text": "v" } } } } } } }, "summary": "Read a call's transcript" }, "listAlerts": { "method": "GET", "path": "/alerts", "tag": "Alerts", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "keyword", "in": "query", "type": "string" }, { "name": "topic", "in": "query", "type": "string" }, { "name": "numbers", "in": "query", "type": "array", "maxItems": 25, "items": { "type": "string", "pattern": "^[A-Za-z0-9@#]+$" } }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["crisis", "very_negative", "negative", "mildly_negative", "below_neutral", "neutral", "positive", "none"] }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "summary": { "o": { "total": "v" } }, "alerts": { "a": { "o": { "id": "v", "call_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "summary": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "keywords": { "a": "v" }, "topics": { "a": "v" } } } } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } } } }, "summary": "List alerts" }, "getAlertsDashboard": { "method": "GET", "path": "/alerts/dashboard", "tag": "Alerts", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "kpis": { "o": { "new_alerts": "v", "monitored": "v", "alert_rate": "v" } }, "top_triggered": { "a": { "o": { "keyword": "v", "count": "v" } } }, "recent_alerts": { "a": { "o": { "id": "v", "call_id": "v", "call_date": "v", "caller_timezone": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "summary": "v", "sentiment": "v", "sentiment_score": "v", "sentiment_label": "v", "keywords": { "a": "v" }, "topics": { "a": "v" } } } } } } } }, "summary": "Alert totals" }, "listTasks": { "method": "GET", "path": "/tasks", "tag": "Tasks", "role": "frontline_user", "query": [{ "name": "status", "in": "query", "type": "string", "enum": ["pending", "in_progress", "done", "overdue", "open"] }, { "name": "today_start", "in": "query", "type": "string", "format": "date-time" }, { "name": "call_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "task_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "due_on", "in": "query", "type": "string", "format": "date" }, { "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "call_id": "v", "company_id": "v", "location_id": "v", "title": "v", "description": "v", "status": "v", "source": "v", "assignee_user": { "o": { "id": "v", "display_name": "v", "email": "v" } }, "due_date": "v", "completed_at": "v", "created_at": "v", "updated_at": "v" } } }, "meta": { "o": { "has_more": "v", "next_cursor": "v", "limit": "v" } }, "summary": { "o": { "total": "v", "done": "v", "in_progress": "v", "pending": "v", "overdue": "v" } } } }, "summary": "List tasks" }, "getInsightsDashboard": { "method": "GET", "path": "/insights/dashboard", "tag": "Insights", "role": "frontline_user", "query": [{ "name": "start", "in": "query", "type": "string", "required": true, "format": "date-time" }, { "name": "end", "in": "query", "type": "string", "required": true, "format": "date-time" }, { "name": "trending_limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 10 }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }], "pathParams": [], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "stats": { "o": { "total_calls": "v", "answered_calls": "v", "unanswered_calls": "v" } }, "trending_topics": { "a": { "o": { "slug": "v", "name": "v", "call_count": "v", "previous_call_count": "v", "percentage_change": "v", "trend_data": { "a": { "o": { "day": "v", "current": "v", "previous": "v" } } } } } }, "topic_call_volumes": { "a": { "o": { "slug": "v", "name": "v", "call_count": "v" } } } } } } }, "summary": "Insights Hub dashboard" }, "listTopicCalls": { "method": "GET", "path": "/insights/topics/{slug}/calls", "tag": "Insights", "role": "frontline_user", "query": [{ "name": "date_from", "in": "query", "type": "string", "format": "date-time" }, { "name": "date_to", "in": "query", "type": "string", "format": "date-time" }, { "name": "sentiment", "in": "query", "type": "string", "enum": ["positive", "neutral", "negative"] }, { "name": "outcome", "in": "query", "type": "string", "enum": ["completed", "missed", "pending"] }, { "name": "search", "in": "query", "type": "string" }, { "name": "location_id", "in": "query", "type": "array", "maxItems": 100, "items": { "type": "string", "format": "uuid" } }, { "name": "company_id", "in": "query", "type": "string", "format": "uuid" }, { "name": "cursor", "in": "query", "type": "string" }, { "name": "limit", "in": "query", "type": "integer", "minimum": 1, "maximum": 100 }], "pathParams": ["slug"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "a": { "o": { "id": "v", "date": "v", "caller_name": "v", "summary": "v", "phone_number": "v", "sentiment": "v", "sentiment_label": "v", "outcome": "v" } } }, "meta": { "o": { "total": "v", "has_more": "v", "next_cursor": "v" } } } }, "summary": "Calls for one topic" }, "getAfterCallWebhook": { "method": "GET", "path": "/locations/{locationId}/after-call/automation", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "webhook_url": "v", "enabled": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Read the After Call webhook" }, "saveAfterCallWebhook": { "method": "PUT", "path": "/locations/{locationId}/after-call/automation", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": true, "bodyRequired": true, "response": { "o": { "data": { "o": { "id": "v", "location_id": "v", "webhook_url": "v", "enabled": "v", "created_at": "v", "updated_at": "v" } } } }, "summary": "Set the After Call webhook" }, "testAfterCallWebhook": { "method": "POST", "path": "/locations/{locationId}/after-call/automation/test", "tag": "Events and webhooks", "role": "reseller_admin", "query": [], "pathParams": ["locationId"], "headers": [], "hasBody": false, "bodyRequired": false, "response": { "o": { "data": { "o": { "success": "v", "http_status": "v", "response_time_ms": "v" } } } }, "summary": "Send a test After Call event" } };
5
5
  var WEBHOOK_SHAPES = { "afterCallSummary": { "o": { "version": "v", "type": "v", "is_test": "v", "location_id": "v", "timestamp": "v", "call": { "o": { "id": "v", "caller_name": "v", "caller_number": "v", "callee_name": "v", "callee_number": "v", "call_type": "v", "duration_seconds": "v", "call_date": "v", "platform": "v" } }, "summary": { "o": { "text": "v", "sentiment": "v", "key_points": { "a": "v" }, "action_items": { "a": "v" } } }, "location": { "o": { "id": "v", "company_id": "v", "connector_id": "v" } } } }};
6
6
 
7
7
  // src/errors.ts
@@ -64,17 +64,36 @@ var RateLimitError = class extends ApiError {
64
64
  this.retryAfter = retryAfter;
65
65
  }
66
66
  };
67
- var FilterError = class extends IntelligenceCloudError {
67
+ var InvalidRequestError = class extends IntelligenceCloudError {
68
68
  };
69
+ var FilterError = InvalidRequestError;
69
70
  var ConnectorError = class extends IntelligenceCloudError {
71
+ connectorId;
70
72
  stateReason;
73
+ statusMessage;
71
74
  status;
72
75
  connector;
73
- constructor(message, stateReason, status, connector) {
74
- super(message);
75
- this.stateReason = stateReason;
76
- this.status = status;
76
+ constructor(connector) {
77
+ const c = connector ?? {};
78
+ const id = typeof c.id === "string" ? c.id : null;
79
+ const reason = typeof c.state_reason === "string" ? c.state_reason : null;
80
+ super(`Connector ${id ?? "unknown"} is in error: ${reason ?? "unknown reason"}`);
81
+ this.connector = connector;
82
+ this.connectorId = id;
83
+ this.status = typeof c.status === "string" ? c.status : null;
84
+ this.stateReason = reason;
85
+ this.statusMessage = typeof c.status_message === "string" ? c.status_message : null;
86
+ }
87
+ };
88
+ var ConnectorTimeoutError = class extends IntelligenceCloudError {
89
+ connector;
90
+ status;
91
+ constructor(connector, waitedSeconds) {
92
+ const c = connector ?? {};
93
+ const status = typeof c.status === "string" ? c.status : null;
94
+ super(`Connector ${typeof c.id === "string" ? c.id : "unknown"} still "${status ?? "unknown"}" after ${Math.round(waitedSeconds)} s`);
77
95
  this.connector = connector;
96
+ this.status = status;
78
97
  }
79
98
  };
80
99
  var FrontlineRequiredError = class extends IntelligenceCloudError {
@@ -86,14 +105,25 @@ var FrontlineRequiredError = class extends IntelligenceCloudError {
86
105
  this.role = role;
87
106
  }
88
107
  };
89
- var WorkflowError = class extends IntelligenceCloudError {
108
+ var AccountError = class extends IntelligenceCloudError {
90
109
  step;
91
- partial;
92
- constructor(step2, partial, cause) {
110
+ result;
111
+ constructor(step, result, cause) {
93
112
  const why = cause instanceof Error ? cause.message : String(cause);
94
- super(`Workflow stopped at "${step2}": ${why}`, { cause });
95
- this.step = step2;
96
- this.partial = partial;
113
+ super(`Stopped at step "${step}": ${why}. Run the helper again to continue.`, { cause });
114
+ this.step = step;
115
+ this.result = result;
116
+ }
117
+ };
118
+ var WrongLoginError = class extends IntelligenceCloudError {
119
+ role;
120
+ needed;
121
+ constructor(role, needed) {
122
+ super(
123
+ needed === "admin" ? `This login has role "${role ?? "unknown"}". Account helpers need an administrator login: create the client with an administrator's email and password.` : `This login has role "${role ?? "unknown"}". Conversation helpers need a user login: sign in as the person whose calls, tasks and alerts you want.`
124
+ );
125
+ this.role = role;
126
+ this.needed = needed;
97
127
  }
98
128
  };
99
129
  var ExtensionMappingError = class extends IntelligenceCloudError {
@@ -127,31 +157,31 @@ function toRfc3339(value, name) {
127
157
  d = value;
128
158
  } else if (typeof value === "string") {
129
159
  if (DATE_ONLY.test(value)) {
130
- throw new FilterError(`"${name}" needs a full timestamp, e.g. ${value}T00:00:00Z. A date alone is refused.`);
160
+ throw new InvalidRequestError(`"${name}" needs a full timestamp, e.g. ${value}T00:00:00Z. A date alone is refused.`);
131
161
  }
132
162
  if (!RFC3339.test(value)) {
133
- throw new FilterError(`"${name}" must be a full RFC 3339 timestamp with an offset, e.g. 2026-11-01T00:00:00Z.`);
163
+ throw new InvalidRequestError(`"${name}" must be a full RFC 3339 timestamp with an offset, e.g. 2026-11-01T00:00:00Z.`);
134
164
  }
135
165
  d = new Date(value);
136
166
  } else {
137
- throw new FilterError(`"${name}" must be a Date or an RFC 3339 timestamp string.`);
167
+ throw new InvalidRequestError(`"${name}" must be a Date or an RFC 3339 timestamp string.`);
138
168
  }
139
- if (Number.isNaN(d.getTime())) throw new FilterError(`"${name}" is not a valid date.`);
169
+ if (Number.isNaN(d.getTime())) throw new InvalidRequestError(`"${name}" is not a valid date.`);
140
170
  return d.toISOString().replace(/\.000Z$/, "Z");
141
171
  }
142
172
  function toDateOnly(value, name) {
143
173
  if (value instanceof Date) {
144
- if (Number.isNaN(value.getTime())) throw new FilterError(`"${name}" is not a valid date.`);
174
+ if (Number.isNaN(value.getTime())) throw new InvalidRequestError(`"${name}" is not a valid date.`);
145
175
  const y = value.getFullYear();
146
176
  const m = String(value.getMonth() + 1).padStart(2, "0");
147
177
  const d = String(value.getDate()).padStart(2, "0");
148
178
  return `${y}-${m}-${d}`;
149
179
  }
150
180
  if (typeof value === "string" && DATE_ONLY.test(value)) return value;
151
- throw new FilterError(`"${name}" must be a calendar date (YYYY-MM-DD) or a Date.`);
181
+ throw new InvalidRequestError(`"${name}" must be a calendar date (YYYY-MM-DD) or a Date.`);
152
182
  }
153
183
  function uuid(value, name) {
154
- if (typeof value !== "string" || !UUID.test(value)) throw new FilterError(`"${name}" must be a UUID.`);
184
+ if (typeof value !== "string" || !UUID.test(value)) throw new InvalidRequestError(`"${name}" must be a UUID.`);
155
185
  return value.toLowerCase();
156
186
  }
157
187
  function digitsOnly(value) {
@@ -163,13 +193,13 @@ function alertNumber(value) {
163
193
  }
164
194
  function scalar(rule, value, name) {
165
195
  if (rule.type === "boolean") {
166
- if (typeof value !== "boolean") throw new FilterError(`"${name}" must be true or false.`);
196
+ if (typeof value !== "boolean") throw new InvalidRequestError(`"${name}" must be true or false.`);
167
197
  return value ? "true" : "false";
168
198
  }
169
199
  if (rule.type === "integer" || rule.type === "number") {
170
- if (typeof value !== "number" || !Number.isInteger(value)) throw new FilterError(`"${name}" must be an integer.`);
171
- if (rule.minimum !== void 0 && value < rule.minimum) throw new FilterError(`"${name}" must be at least ${rule.minimum}.`);
172
- if (rule.maximum !== void 0 && value > rule.maximum) throw new FilterError(`"${name}" must be at most ${rule.maximum}.`);
200
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new InvalidRequestError(`"${name}" must be an integer.`);
201
+ if (rule.minimum !== void 0 && value < rule.minimum) throw new InvalidRequestError(`"${name}" must be at least ${rule.minimum}.`);
202
+ if (rule.maximum !== void 0 && value > rule.maximum) throw new InvalidRequestError(`"${name}" must be at most ${rule.maximum}.`);
173
203
  return String(value);
174
204
  }
175
205
  if (rule.format === "date-time") return toRfc3339(value, name);
@@ -177,44 +207,44 @@ function scalar(rule, value, name) {
177
207
  if (rule.format === "uuid") return uuid(value, name);
178
208
  if (rule.enum && rule.enum.length === 1 && rule.enum[0] === "true") {
179
209
  if (value === true || value === "true") return "true";
180
- throw new FilterError(`"${name}" only supports true. Leave it out to include every record.`);
210
+ throw new InvalidRequestError(`"${name}" only supports true. Leave it out to include every record.`);
181
211
  }
182
- if (typeof value !== "string") throw new FilterError(`"${name}" must be a string.`);
212
+ if (typeof value !== "string") throw new InvalidRequestError(`"${name}" must be a string.`);
183
213
  if (rule.enum && !rule.enum.includes(value)) {
184
- throw new FilterError(`"${name}" must be one of: ${rule.enum.join(", ")}.`);
214
+ throw new InvalidRequestError(`"${name}" must be one of: ${rule.enum.join(", ")}.`);
185
215
  }
186
216
  if (rule.minLength !== void 0 && value.trim().length < rule.minLength) {
187
- throw new FilterError(`"${name}" needs at least ${rule.minLength} characters; shorter values are ignored by the API.`);
217
+ throw new InvalidRequestError(`"${name}" needs at least ${rule.minLength} characters; shorter values are ignored by the API.`);
188
218
  }
189
219
  return value;
190
220
  }
191
221
  function list(rule, value, name) {
192
222
  const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : null;
193
- if (!raw) throw new FilterError(`"${name}" must be a list.`);
223
+ if (!raw) throw new InvalidRequestError(`"${name}" must be a list.`);
194
224
  let entries = raw.map((v) => typeof v === "string" ? v.trim() : v);
195
225
  if (rule.name === "numbers") {
196
226
  entries = entries.map((v) => {
197
- if (typeof v !== "string" && typeof v !== "number") throw new FilterError(`"${name}" entries must be strings.`);
227
+ if (typeof v !== "string" && typeof v !== "number") throw new InvalidRequestError(`"${name}" entries must be strings.`);
198
228
  const d = alertNumber(String(v));
199
- if (!d) throw new FilterError(`"${name}" entries must contain digits.`);
229
+ if (!d) throw new InvalidRequestError(`"${name}" entries must contain digits.`);
200
230
  return d;
201
231
  });
202
232
  } else if (rule.items?.format === "uuid") {
203
233
  entries = entries.map((v) => uuid(v, name));
204
234
  } else {
205
235
  entries = entries.map((v) => {
206
- if (typeof v !== "string" || v === "") throw new FilterError(`"${name}" entries must be non-empty strings.`);
236
+ if (typeof v !== "string" || v === "") throw new InvalidRequestError(`"${name}" entries must be non-empty strings.`);
207
237
  if (rule.items?.enum && !rule.items.enum.includes(v)) {
208
- throw new FilterError(`"${name}" entries must be one of: ${rule.items.enum.join(", ")}.`);
238
+ throw new InvalidRequestError(`"${name}" entries must be one of: ${rule.items.enum.join(", ")}.`);
209
239
  }
210
240
  return v;
211
241
  });
212
242
  }
213
243
  const unique = [...new Set(entries)];
214
- if (unique.length === 0) throw new FilterError(`"${name}" must not be empty.`);
244
+ if (unique.length === 0) throw new InvalidRequestError(`"${name}" must not be empty.`);
215
245
  const max = rule.name === "location_id" ? Math.min(MAX_LOCATION_IDS, rule.maxItems ?? MAX_LOCATION_IDS) : rule.maxItems;
216
246
  if (max !== void 0 && unique.length > max) {
217
- throw new FilterError(`"${name}" takes at most ${max} entries per request.`);
247
+ throw new InvalidRequestError(`"${name}" takes at most ${max} entries per request.`);
218
248
  }
219
249
  return unique.join(",");
220
250
  }
@@ -230,13 +260,13 @@ function buildQuery(operationId, rules, options) {
230
260
  const rule = byKey.get(key);
231
261
  if (!rule) {
232
262
  const supported = rules.map((r) => camel(r.name)).join(", ") || "none";
233
- throw new FilterError(`"${key}" is not a filter of ${operationId}. Supported: ${supported}.`);
263
+ throw new InvalidRequestError(`"${key}" is not a filter of ${operationId}. Supported: ${supported}.`);
234
264
  }
235
- if (rule.name in out) throw new FilterError(`"${key}" was given twice.`);
265
+ if (rule.name in out) throw new InvalidRequestError(`"${key}" was given twice.`);
236
266
  out[rule.name] = rule.type === "array" ? list(rule, value, key) : scalar(rule, value, key);
237
267
  }
238
268
  for (const r of rules) {
239
- if (r.required && !(r.name in out)) throw new FilterError(`"${camel(r.name)}" is required for ${operationId}.`);
269
+ if (r.required && !(r.name in out)) throw new InvalidRequestError(`"${camel(r.name)}" is required for ${operationId}.`);
240
270
  }
241
271
  return out;
242
272
  }
@@ -375,7 +405,7 @@ var FileTokenStore = class {
375
405
 
376
406
  // src/core.ts
377
407
  var DEFAULT_BASE_URL = "https://app.intelligence.cloud/api/v1";
378
- var SDK_VERSION = "0.1.0";
408
+ var SDK_VERSION = "0.2.0";
379
409
  var SUPPRESS_ERROR_TEXT = /* @__PURE__ */ new Set(["testConnector", "testAfterCallWebhook", "testFirstAlertWebhook"]);
380
410
  var NUMBER_MAPPING_OPS = /* @__PURE__ */ new Set(["setUserNumberMappings", "updateUserAfterCallSettings"]);
381
411
  var LOGIN_RATE_LIMIT_WAIT_S = 60;
@@ -400,11 +430,11 @@ function checkBaseUrl(baseUrl) {
400
430
  try {
401
431
  u = new URL(baseUrl);
402
432
  } catch {
403
- throw new FilterError(`baseUrl "${baseUrl}" is not a URL.`);
433
+ throw new InvalidRequestError(`baseUrl "${baseUrl}" is not a URL.`);
404
434
  }
405
435
  if (u.protocol === "https:") return baseUrl;
406
436
  if (u.protocol === "http:" && LOCAL_HOSTS.has(u.hostname)) return baseUrl;
407
- throw new FilterError("baseUrl must use https:// (plain http is accepted for localhost only).");
437
+ throw new InvalidRequestError("baseUrl must use https:// (plain http is accepted for localhost only).");
408
438
  }
409
439
  var Core = class {
410
440
  baseUrl;
@@ -421,6 +451,8 @@ var Core = class {
421
451
  random;
422
452
  now;
423
453
  renewing = null;
454
+ /** Write requests (anything but GET) attempted by this client. Account helpers use it to tell a clean stop from a partial one. */
455
+ writes = 0;
424
456
  constructor(opts) {
425
457
  if (!opts || !opts.email || !opts.password) {
426
458
  throw new TypeError("email and password are required (a dedicated integration user with MFA off).");
@@ -447,6 +479,7 @@ var Core = class {
447
479
  const op = OPERATIONS[operationId];
448
480
  const query = buildQuery(operationId, op.query, opts.query ?? {});
449
481
  const url = this.url(op, pathArgs, query);
482
+ if (op.method !== "GET") this.writes++;
450
483
  const res = await this.send(op.method, url, {
451
484
  body: op.hasBody ? opts.body ?? {} : void 0,
452
485
  headers: opts.headers,
@@ -1097,6 +1130,21 @@ function makeWebhooks(c) {
1097
1130
  }
1098
1131
 
1099
1132
  // src/intelligence.ts
1133
+ var RecordingLink = class {
1134
+ constructor(url, expiresAt) {
1135
+ this.url = url;
1136
+ this.expiresAt = expiresAt;
1137
+ const show = () => ({ url: this.url === null ? null : "***", expiresAt: this.expiresAt });
1138
+ Object.defineProperty(this, "toJSON", { value: show, enumerable: false });
1139
+ Object.defineProperty(this, "toString", { value: () => `RecordingLink(${JSON.stringify(show())})`, enumerable: false });
1140
+ Object.defineProperty(this, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
1141
+ value: (_d, o, inspect) => inspect ? `RecordingLink ${inspect(show(), o)}` : `RecordingLink(${JSON.stringify(show())})`,
1142
+ enumerable: false
1143
+ });
1144
+ }
1145
+ url;
1146
+ expiresAt;
1147
+ };
1100
1148
  var CALL_FILTERS = [
1101
1149
  "phone",
1102
1150
  "text",
@@ -1143,7 +1191,7 @@ function only(given, allowed, method) {
1143
1191
  for (const [k, v] of Object.entries(given)) {
1144
1192
  if (v === void 0) continue;
1145
1193
  if (!allowed.includes(k)) {
1146
- throw new FilterError(`"${k}" is not a filter of ${method}. Supported: ${allowed.join(", ")}.`);
1194
+ throw new InvalidRequestError(`"${k}" is not a filter of ${method}. Supported: ${allowed.join(", ")}.`);
1147
1195
  }
1148
1196
  }
1149
1197
  }
@@ -1185,7 +1233,7 @@ var Intelligence = class {
1185
1233
  callQuery(f) {
1186
1234
  only(f, CALL_FILTERS, "searchCalls");
1187
1235
  if (f.phone !== void 0 && f.text !== void 0) {
1188
- throw new FilterError("Give phone or text, not both: the API has one search field.");
1236
+ throw new InvalidRequestError("Give phone or text, not both: the API has one search field.");
1189
1237
  }
1190
1238
  return {
1191
1239
  date_from: f.dateFrom,
@@ -1235,7 +1283,7 @@ var Intelligence = class {
1235
1283
  async getRecordingUrl(callId) {
1236
1284
  const call = await this.getCall(callId);
1237
1285
  const v = call.vcon;
1238
- return { url: v?.recording_url ?? null, expiresAt: v?.recording_url_expires_at ?? null };
1286
+ return new RecordingLink(v?.recording_url ?? null, v?.recording_url_expires_at ?? null);
1239
1287
  }
1240
1288
  // ------------------------------------------------------------------ alerts
1241
1289
  alertQuery(f) {
@@ -1273,7 +1321,7 @@ var Intelligence = class {
1273
1321
  async getAlert(alertId, options = {}) {
1274
1322
  const id = alertId.trim().toLowerCase();
1275
1323
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) {
1276
- throw new FilterError("alertId must be a UUID.");
1324
+ throw new InvalidRequestError("alertId must be a UUID.");
1277
1325
  }
1278
1326
  const page = await this.searchAlerts({ text: id, limit: 10 });
1279
1327
  const alert = page.items.find((a) => (a.id ?? "").toLowerCase() === id);
@@ -1330,7 +1378,7 @@ var Intelligence = class {
1330
1378
  * whatever users' number mappings say. `enabled: false` pauses it (there is no delete).
1331
1379
  */
1332
1380
  async setAfterCallWebhook(locationId, url, enabled = true) {
1333
- if (!/^https:\/\//i.test(url)) throw new FilterError("The webhook URL must use HTTPS.");
1381
+ if (!/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1334
1382
  const r = await this.c.webhooks.saveAfterCallWebhook(locationId, { webhook_url: url, enabled });
1335
1383
  return r.data ?? {};
1336
1384
  }
@@ -1348,13 +1396,13 @@ var Intelligence = class {
1348
1396
  * configuration PUT would otherwise clear the monitored numbers.
1349
1397
  */
1350
1398
  async setFirstAlertWebhook(locationId, url) {
1351
- if (url !== null && !/^https:\/\//i.test(url)) throw new FilterError("The webhook URL must use HTTPS.");
1399
+ if (url !== null && !/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1352
1400
  return (await this.c.firstAlert.setWebhookUrl(locationId, url)).data ?? {};
1353
1401
  }
1354
1402
  /** Send a test request to `url` (default: the saved URL). Returns only success and your endpoint's status. */
1355
1403
  async testFirstAlertWebhook(locationId, url) {
1356
1404
  const target = url ?? await this.getFirstAlertWebhook(locationId);
1357
- if (!target) throw new FilterError("No First Alert webhook URL is set for this location; pass one.");
1405
+ if (!target) throw new InvalidRequestError("No First Alert webhook URL is set for this location; pass one.");
1358
1406
  const d = (await this.c.firstAlert.testFirstAlertWebhook(locationId, { url: target })).data ?? {};
1359
1407
  return { success: Boolean(d.success), http_status: d.status_code ?? null };
1360
1408
  }
@@ -1395,887 +1443,2590 @@ function mergeMappings(current, connectorId, add = [], remove = []) {
1395
1443
  byConnector.set(connectorId, mine);
1396
1444
  const out = [];
1397
1445
  for (const [connector_id, nums] of byConnector) {
1398
- const uniq2 = [...new Set(nums)];
1399
- if (uniq2.length) out.push({ connector_id, monitored_numbers: uniq2 });
1446
+ const uniq3 = [...new Set(nums)];
1447
+ if (uniq3.length) out.push({ connector_id, monitored_numbers: uniq3 });
1400
1448
  }
1401
1449
  return out;
1402
1450
  }
1403
- function sameSet(a, b) {
1404
- const sa = new Set(a);
1405
- const sb = new Set(b);
1406
- if (sa.size !== sb.size) return false;
1407
- for (const x of sa) if (!sb.has(x)) return false;
1408
- return true;
1451
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1452
+ function isUuid(value) {
1453
+ return typeof value === "string" && UUID_RE.test(value);
1454
+ }
1455
+
1456
+ // src/secrets.ts
1457
+ var SECRET_WORDS = ["key", "secret", "token", "password", "passwd", "pwd", "credential", "auth"];
1458
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
1459
+ function isSecretName(name) {
1460
+ const low = String(name).toLowerCase();
1461
+ return SECRET_WORDS.some((w) => low.includes(w));
1462
+ }
1463
+ function isPlainObject(v) {
1464
+ if (v === null || typeof v !== "object") return false;
1465
+ const proto = Object.getPrototypeOf(v);
1466
+ return proto === Object.prototype || proto === null;
1467
+ }
1468
+ function maskedConfig(value) {
1469
+ if (Array.isArray(value)) return value.map(maskedConfig);
1470
+ if (isPlainObject(value)) {
1471
+ const out = {};
1472
+ for (const k of Object.keys(value)) out[k] = isSecretName(k) ? "***" : maskedConfig(value[k]);
1473
+ return out;
1474
+ }
1475
+ return value;
1476
+ }
1477
+ function plainConfig(value) {
1478
+ if (Array.isArray(value)) return value.map((v) => plainConfig(v));
1479
+ if (isPlainObject(value)) {
1480
+ const out = {};
1481
+ for (const k of Object.keys(value)) out[k] = plainConfig(value[k]);
1482
+ return out;
1483
+ }
1484
+ return value;
1485
+ }
1486
+ var guarded = /* @__PURE__ */ new WeakSet();
1487
+ var BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.ConnectorSpec");
1488
+ function isConnectorSpec(v) {
1489
+ return v !== null && typeof v === "object" && v[BRAND] === true;
1490
+ }
1491
+ var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
1492
+ function assertSafeKeys(value) {
1493
+ if (Array.isArray(value)) value.forEach(assertSafeKeys);
1494
+ else if (value !== null && typeof value === "object") {
1495
+ for (const k of Object.keys(value)) {
1496
+ if (UNSAFE_KEYS.includes(k)) throw new InvalidRequestError(`ConnectorSpec.config: "${k}" is not allowed as a setting name`);
1497
+ assertSafeKeys(value[k]);
1498
+ }
1499
+ }
1500
+ }
1501
+ function hide(target, show) {
1502
+ const text = () => JSON.stringify(show());
1503
+ Object.defineProperty(target, "toJSON", { value: show, enumerable: false });
1504
+ Object.defineProperty(target, "toString", { value: text, enumerable: false });
1505
+ Object.defineProperty(target, INSPECT, {
1506
+ value: (_depth, options, inspect) => inspect ? inspect(show(), options) : text(),
1507
+ enumerable: false
1508
+ });
1409
1509
  }
1410
- function diff(current, target) {
1411
- const c = new Set(current);
1412
- const t = new Set(target);
1413
- return { add: [...t].filter((x) => !c.has(x)), remove: [...c].filter((x) => !t.has(x)) };
1510
+ function guardConfig(value) {
1511
+ if (value === null || typeof value !== "object") return value;
1512
+ if (guarded.has(value)) return value;
1513
+ if (!Array.isArray(value) && !isPlainObject(value)) return value;
1514
+ assertSafeKeys(value);
1515
+ const target = Array.isArray(value) ? [] : /* @__PURE__ */ Object.create(null);
1516
+ for (const k of Object.keys(value)) target[k] = guardConfig(value[k]);
1517
+ hide(target, () => maskedConfig(target));
1518
+ const proxy = new Proxy(target, {
1519
+ set(t, k, v) {
1520
+ if (typeof k === "string" && UNSAFE_KEYS.includes(k)) throw new InvalidRequestError(`ConnectorSpec.config: "${k}" is not allowed as a setting name`);
1521
+ t[k] = typeof k === "string" ? guardConfig(v) : v;
1522
+ return true;
1523
+ }
1524
+ });
1525
+ guarded.add(proxy);
1526
+ return proxy;
1414
1527
  }
1528
+ var ConnectorSpec = class _ConnectorSpec {
1529
+ type;
1530
+ /** Default `"<team name> phone system"`. */
1531
+ name;
1532
+ /** Seconds to wait for a new connector to settle. Default 600. */
1533
+ timeout;
1534
+ constructor(type, config, options = {}) {
1535
+ this.type = type;
1536
+ this.name = options.name;
1537
+ this.timeout = options.timeout ?? 600;
1538
+ Object.defineProperty(this, "_config", { value: void 0, writable: true, enumerable: false });
1539
+ this.config = config;
1540
+ }
1541
+ /** The platform's settings. Values whose names contain key, secret, token, password, passwd, pwd, credential or auth print as `***`. */
1542
+ get config() {
1543
+ return this._config;
1544
+ }
1545
+ set config(value) {
1546
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1547
+ throw new InvalidRequestError("ConnectorSpec.config must be an object");
1548
+ }
1549
+ this._config = guardConfig({ ...value });
1550
+ }
1551
+ /** The documented phone system: its API root (ending in /ns-api/v2), its domain and a read/write key. */
1552
+ static netsapiens(apiUrl, domain, apiKey, options = {}) {
1553
+ return new _ConnectorSpec("netsapiens", { api_url: apiUrl, domain, api_key: apiKey }, options);
1554
+ }
1555
+ get [BRAND]() {
1556
+ return true;
1557
+ }
1558
+ toJSON() {
1559
+ return { type: this.type, config: maskedConfig(this._config), name: this.name ?? null, timeout: this.timeout };
1560
+ }
1561
+ toString() {
1562
+ return `ConnectorSpec(${JSON.stringify(this.toJSON())})`;
1563
+ }
1564
+ [INSPECT](_depth, options, inspect) {
1565
+ return inspect ? `ConnectorSpec ${inspect(this.toJSON(), options)}` : this.toString();
1566
+ }
1567
+ };
1415
1568
 
1416
- // src/workflows.ts
1417
- var ALL_PRODUCTS = ["after-call-copilot", "first-alert-copilot", "insights-hub"];
1418
- var MANAGER_ALERTS_GROUP = "Manager Alerts";
1419
- var INSIGHTS_HUB_ACCESS_GROUP = "Insights Hub Access";
1420
- var UPSET_CUSTOMER_RULE = "Upset Customer";
1421
- var CUSTOMER_THREAT_RULE = "Customer Threat";
1422
- var DEFAULT_VERTICAL_KEY = "csps-msps";
1423
- var THREAT_PHRASES_MISSING = "Customer Threat phrases are provided by your Tresic contact.";
1569
+ // src/accounts.ts
1570
+ var PRODUCT_KEYS = ["after-call-copilot", "first-alert-copilot", "insights-hub"];
1571
+ var AFTER_CALL = "after-call-copilot";
1572
+ var FIRST_ALERT = "first-alert-copilot";
1573
+ var INSIGHTS_HUB = "insights-hub";
1424
1574
  var INTEGRATION_DEPARTMENT = "integration";
1425
- function companyNameConflictMessage(name) {
1426
- return `A company named '${name}' already exists with a different primary contact. Pass companyId to use an existing company, or choose a different company name.`;
1575
+ var COMPANY_NAME_CONFLICT = "company_name_conflict";
1576
+ var MANAGEMENT_SUFFIX = " - Management";
1577
+ var TEAM_GROUPS = {
1578
+ customerThreats: "Customer Threats",
1579
+ upsetCustomers: "Upset Customers",
1580
+ lowSentimentCalls: "Low Sentiment Calls",
1581
+ insightsHubAccess: "Insights Hub Access",
1582
+ weeklyReports: "Insights Hub Weekly Reports"
1583
+ };
1584
+ var GROUP_FIELDS = Object.keys(TEAM_GROUPS);
1585
+ var ALERT_GROUPS = ["customerThreats", "upsetCustomers", "lowSentimentCalls"];
1586
+ var RULES = {
1587
+ customerThreat: { name: "Customer Threat", priority: "high", hasPhrases: true, defaultLevel: -20, group: "customerThreats" },
1588
+ upsetCustomer: { name: "Upset Customer", priority: "medium", hasPhrases: true, defaultLevel: -20, group: "upsetCustomers" },
1589
+ lowSentiment: { name: "Low Sentiment", priority: "low", hasPhrases: false, defaultLevel: -40, group: "lowSentimentCalls" }
1590
+ };
1591
+ var RULE_FIELDS = Object.keys(RULES);
1592
+ var PHRASE_ALERTS = ["customerThreat", "upsetCustomer"];
1593
+ var LICENSES = ["base_user", "base_manager", "integration", "other"];
1594
+ var RANK = { active: 0, connected: 0, connecting: 1, error: 2, deactivating: 3, inactive: 4 };
1595
+ var rank = (status) => RANK[String(status)] ?? 5;
1596
+ function uniq(values) {
1597
+ return [...new Set(values)];
1427
1598
  }
1428
- function upsetCustomerRule(groupIds, enabled = false) {
1429
- return {
1430
- name: UPSET_CUSTOMER_RULE,
1431
- priority: "high",
1432
- match_logic: "any",
1433
- enabled,
1434
- triggers: [{ trigger_type: "sentiment", config: { operator: "lt", threshold: -40 } }],
1435
- group_ids: groupIds
1599
+ function deepEqual(a, b) {
1600
+ if (a === b) return true;
1601
+ if (Array.isArray(a) || Array.isArray(b)) {
1602
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => deepEqual(x, b[i]));
1603
+ }
1604
+ if (a && b && typeof a === "object" && typeof b === "object") {
1605
+ const ka = Object.keys(a);
1606
+ const kb = Object.keys(b);
1607
+ return ka.length === kb.length && ka.every((k) => k in b && deepEqual(a[k], b[k]));
1608
+ }
1609
+ return false;
1610
+ }
1611
+ function unwrap(body) {
1612
+ if (body && typeof body === "object" && "data" in body) {
1613
+ const d = body.data;
1614
+ if (d && typeof d === "object" && d.attributes && typeof d.attributes === "object") return d.attributes;
1615
+ return d;
1616
+ }
1617
+ return body;
1618
+ }
1619
+ function rowsOf(body) {
1620
+ const d = body?.data;
1621
+ return Array.isArray(d) ? d.map((x) => x && x.attributes && typeof x.attributes === "object" ? x.attributes : x) : [];
1622
+ }
1623
+ async function all(gen) {
1624
+ const out = [];
1625
+ for await (const x of gen) out.push(x);
1626
+ return out;
1627
+ }
1628
+ function line(value, name = "line") {
1629
+ const v = value === null || value === void 0 ? "" : String(value).trim();
1630
+ if (!v) throw new InvalidRequestError(`${name} is required`);
1631
+ return v;
1632
+ }
1633
+ function numbersOf(mappings, connectorId) {
1634
+ const out = [];
1635
+ for (const m of mappings ?? []) {
1636
+ if (connectorId === void 0 || connectorId === null || m.connector_id === connectorId) {
1637
+ for (const n of m.monitored_numbers ?? []) if (!out.includes(n)) out.push(n);
1638
+ }
1639
+ }
1640
+ return out;
1641
+ }
1642
+ function sameMappings(a, b) {
1643
+ const norm = (ms) => {
1644
+ const out = {};
1645
+ for (const m of ms) {
1646
+ const nums = [...m.monitored_numbers ?? []];
1647
+ if (nums.length) (out[m.connector_id ?? ""] ??= []).push(...nums);
1648
+ }
1649
+ return out;
1436
1650
  };
1651
+ return deepEqual(norm(a), norm(b));
1652
+ }
1653
+ function checkSetting(key, s) {
1654
+ if (s === null || s === void 0) return;
1655
+ if (typeof s !== "object") throw new InvalidRequestError(`alerts.${key} must be an AlertSetting`);
1656
+ if (s.sentimentBelow !== void 0 && s.sentimentBelow !== null) {
1657
+ const lvl = s.sentimentBelow;
1658
+ if (typeof lvl !== "number" || !Number.isInteger(lvl) || lvl < -100 || lvl > -1) {
1659
+ throw new InvalidRequestError(`alerts.${key}.sentimentBelow: a whole number from -100 to -1`);
1660
+ }
1661
+ }
1662
+ if (s.phrases !== void 0 && s.phrases !== null) {
1663
+ if (!RULES[key].hasPhrases) throw new InvalidRequestError(`alerts.${key} has no phrases; set sentimentBelow only`);
1664
+ if (!Array.isArray(s.phrases) || !s.phrases.every((p) => typeof p === "string")) {
1665
+ throw new InvalidRequestError(`alerts.${key}.phrases must be a list of strings`);
1666
+ }
1667
+ if (!s.phrases.some((p) => p.trim())) {
1668
+ throw new InvalidRequestError(`alerts.${key}.phrases is empty; pass null to keep the current phrases`);
1669
+ }
1670
+ }
1671
+ }
1672
+ function checkAlerts(alerts) {
1673
+ if (alerts === null || alerts === void 0) return;
1674
+ if (typeof alerts !== "object") throw new InvalidRequestError("alerts must be an AlertSettings");
1675
+ for (const key of RULE_FIELDS) checkSetting(key, alerts[key]);
1676
+ }
1677
+ function cleanPhrases(phrases) {
1678
+ if (phrases === null || phrases === void 0) return null;
1679
+ return uniq(phrases.filter((p) => p && p.trim()).map((p) => p.trim()));
1680
+ }
1681
+ function ruleSettings(rule) {
1682
+ let phrases = null;
1683
+ let level = null;
1684
+ for (const t of rule.triggers ?? []) {
1685
+ const cfg = t.config ?? {};
1686
+ if (t.trigger_type === "sentiment" && Number.isInteger(cfg.threshold)) level = cfg.threshold;
1687
+ else if (t.trigger_type === "keyword_match") phrases = [...cfg.keywords ?? []];
1688
+ }
1689
+ return [phrases, level];
1437
1690
  }
1438
- function customerThreatRule(groupIds, phrases, enabled = false) {
1439
- if (!phrases || phrases.length === 0) throw new FilterError(THREAT_PHRASES_MISSING);
1691
+ function triggers(key, phrases, level) {
1692
+ const out = [{ trigger_type: "sentiment", config: { operator: "lt", threshold: level } }];
1693
+ if (RULES[key].hasPhrases) out.push({ trigger_type: "keyword_match", config: { keywords: [...phrases ?? []], match_logic: "any" } });
1694
+ return out;
1695
+ }
1696
+ function ruleBody(key, groupId, phrases, level, enabled = false) {
1697
+ const d = RULES[key];
1698
+ if (d.hasPhrases && !phrases?.length) throw new InvalidRequestError(`${d.name} needs its phrases`);
1440
1699
  return {
1441
- name: CUSTOMER_THREAT_RULE,
1442
- priority: "critical",
1443
- match_logic: "all",
1700
+ name: d.name,
1701
+ priority: d.priority,
1702
+ match_logic: d.hasPhrases ? "all" : "any",
1444
1703
  enabled,
1445
- triggers: [
1446
- { trigger_type: "sentiment", config: { operator: "lt", threshold: -20 } },
1447
- { trigger_type: "keyword_match", config: { match_logic: "any", keywords: [...phrases] } }
1448
- ],
1449
- group_ids: groupIds
1704
+ triggers: triggers(key, phrases ?? null, level ?? d.defaultLevel),
1705
+ group_ids: [groupId]
1450
1706
  };
1451
1707
  }
1452
- async function step(name, partial, fn) {
1453
- try {
1454
- return await fn();
1455
- } catch (err) {
1456
- if (err instanceof WorkflowError || err instanceof ExtensionMappingError || err instanceof FilterError) throw err;
1457
- throw new WorkflowError(name, partial, err);
1458
- }
1708
+ function normTriggers(rule) {
1709
+ return (rule.triggers ?? []).map((t) => ({ trigger_type: t.trigger_type, config: t.config }));
1459
1710
  }
1460
- function canonical(v) {
1461
- if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
1462
- if (v && typeof v === "object") {
1463
- return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
1711
+ function isIntegration(row) {
1712
+ return String(row.department ?? "").trim().toLowerCase() === INTEGRATION_DEPARTMENT;
1713
+ }
1714
+ var Person = class {
1715
+ constructor(id, email, status) {
1716
+ this.id = id;
1717
+ this.email = email;
1718
+ this.status = status;
1719
+ }
1720
+ id;
1721
+ email;
1722
+ status;
1723
+ department = null;
1724
+ invitedAt = null;
1725
+ inviteExpiresAt = null;
1726
+ locs = /* @__PURE__ */ new Map();
1727
+ mappings = [];
1728
+ license = "other";
1729
+ teams = [];
1730
+ numbers(connectorId) {
1731
+ return numbersOf(this.mappings, connectorId);
1732
+ }
1733
+ get active() {
1734
+ return this.status !== "deactivated";
1464
1735
  }
1465
- return JSON.stringify(v ?? null);
1736
+ };
1737
+ var Run = class {
1738
+ constructor(client, result) {
1739
+ this.result = result;
1740
+ this.start = client.core.writes;
1741
+ }
1742
+ result;
1743
+ start;
1744
+ step = "start";
1745
+ };
1746
+ function newTeam(locationId, name, kind = "team") {
1747
+ return {
1748
+ locationId,
1749
+ name,
1750
+ kind,
1751
+ groups: { customerThreats: null, upsetCustomers: null, lowSentimentCalls: null, insightsHubAccess: null, weeklyReports: null },
1752
+ rules: { customerThreat: null, upsetCustomer: null, lowSentiment: null },
1753
+ connectorId: null,
1754
+ connectorStatus: null,
1755
+ connectorStateReason: null
1756
+ };
1757
+ }
1758
+ function newMember(userId, email, license, teams = [], lines = []) {
1759
+ return { userId, email, license, teams, lines, created: false, invited: false, notes: [] };
1466
1760
  }
1467
- var CONNECTOR_RANK = { active: 0, connecting: 1, error: 2, deactivating: 3, inactive: 4 };
1468
- function isIntegration(u) {
1469
- return (u.department ?? "").trim().toLowerCase() === INTEGRATION_DEPARTMENT;
1761
+ function dedupeTeams(teams) {
1762
+ const seen = /* @__PURE__ */ new Set();
1763
+ return teams.filter((t) => seen.has(t.locationId) ? false : (seen.add(t.locationId), true));
1470
1764
  }
1471
- function isManager(u) {
1472
- return !isIntegration(u) && ALL_PRODUCTS.every((p) => u.enabledProducts.includes(p));
1765
+ function expired(when, now) {
1766
+ if (!when) return false;
1767
+ const t = Date.parse(when);
1768
+ return Number.isNaN(t) ? false : t < now.getTime();
1473
1769
  }
1474
- function isFrontline(u) {
1475
- return !isIntegration(u) && u.enabledProducts.length === 1 && u.enabledProducts[0] === "after-call-copilot";
1770
+ function raiseConnectorFailure(failures, result) {
1771
+ if (failures.length) throw new AccountError("connectors", result, failures[0]);
1476
1772
  }
1477
- var norm = (s) => (s ?? "").trim().toLowerCase();
1478
- var Workflows = class {
1773
+ var Accounts = class _Accounts {
1479
1774
  constructor(c) {
1480
1775
  this.c = c;
1776
+ this.rawConnectors = makeConnectors(c.core);
1777
+ const writers = [
1778
+ "createCustomer",
1779
+ "addTeam",
1780
+ "setAlerts",
1781
+ "setConnector",
1782
+ "activateAlerts",
1783
+ "addBaseUser",
1784
+ "addBaseManager",
1785
+ "addIntegrationUser",
1786
+ "changeLicense",
1787
+ "moveUser",
1788
+ "changeLine",
1789
+ "removeUser",
1790
+ "sendInvitations",
1791
+ "syncLines",
1792
+ "offboardCustomer"
1793
+ ];
1794
+ for (const name of writers) {
1795
+ const original = this[name].bind(this);
1796
+ this[name] = (...args) => {
1797
+ const run = this.tail.then(
1798
+ () => original(...args),
1799
+ () => original(...args)
1800
+ );
1801
+ this.tail = run.then(
1802
+ () => void 0,
1803
+ () => void 0
1804
+ );
1805
+ return run;
1806
+ };
1807
+ }
1481
1808
  }
1482
1809
  c;
1483
- // ------------------------------------------------------------------ lookups
1484
- async bestConnector(locationId) {
1485
- let best = null;
1486
- for await (const row of this.c.connectors.iterLocationConnectors(locationId)) {
1487
- if (!best || (CONNECTOR_RANK[row.status ?? ""] ?? 9) < (CONNECTOR_RANK[best.status ?? ""] ?? 9)) best = row;
1810
+ me = null;
1811
+ verticals = null;
1812
+ connectorTypes = null;
1813
+ rawConnectors;
1814
+ tail = Promise.resolve();
1815
+ // ------------------------------------------------------------------ plumbing
1816
+ async requireAdmin() {
1817
+ if (this.me === null) this.me = unwrap(await this.c.account.getMe()) ?? {};
1818
+ if (this.me.role === "frontline_user") throw new WrongLoginError(this.me.role ?? null, "admin");
1819
+ return this.me;
1820
+ }
1821
+ run(result) {
1822
+ return new Run(this.c, result);
1823
+ }
1824
+ /** Throw `exc` as it is when nothing was written yet; otherwise as AccountError. */
1825
+ stop(run, exc) {
1826
+ if (!(exc instanceof IntelligenceCloudError)) throw exc;
1827
+ if (exc instanceof AccountError || this.c.core.writes === run.start) throw exc;
1828
+ throw new AccountError(run.step, run.result, exc);
1829
+ }
1830
+ async resolve(customer) {
1831
+ if (customer && typeof customer === "object") return customer;
1832
+ if (typeof customer === "string" && customer.trim()) return this.getCustomer(customer.trim());
1833
+ throw new InvalidRequestError("customer: a Customer or a company id");
1834
+ }
1835
+ teamOf(cust, team) {
1836
+ if (typeof team === "object" && team !== null) {
1837
+ const hit2 = cust.teams.find((t) => t.locationId === team.locationId);
1838
+ if (hit2) return hit2;
1839
+ throw new InvalidRequestError("team is not one of this customer's teams");
1488
1840
  }
1489
- return best;
1841
+ const hit = cust.teams.find((t) => t.locationId === team || t.name === team);
1842
+ if (hit) return hit;
1843
+ throw new InvalidRequestError(`Unknown team "${String(team)}": use a Team, its location id or its name`);
1490
1844
  }
1491
- async resolve(ref) {
1492
- return typeof ref === "string" ? this.getSeatCustomer(ref) : ref;
1845
+ teamsOf(cust, team) {
1846
+ return team !== void 0 && team !== null ? [this.teamOf(cust, team)] : [...cust.teams];
1493
1847
  }
1494
- requireConnector(customer) {
1495
- if (!customer.connectorId) {
1496
- throw new IntelligenceCloudError("This customer has no connector at its location, so numbers can't be mapped.");
1848
+ locationsOf(cust) {
1849
+ return [...cust.management ? [cust.management] : [], ...cust.teams];
1850
+ }
1851
+ async verticalId(vertical) {
1852
+ if (isUuid(vertical)) return vertical;
1853
+ if (this.verticals === null) this.verticals = rowsOf(await this.c.locations.listVerticals());
1854
+ for (const v of this.verticals) if (vertical === v.key || vertical === v.name) return v.id;
1855
+ throw new InvalidRequestError(`Unknown vertical "${vertical}": use an id or key from listVerticals()`);
1856
+ }
1857
+ async checkConnector(cs, required = false) {
1858
+ if (cs === null || cs === void 0) {
1859
+ if (required) throw new InvalidRequestError("A connector is required: pass a ConnectorSpec");
1860
+ return;
1861
+ }
1862
+ if (!isConnectorSpec(cs)) throw new InvalidRequestError("connector must be a ConnectorSpec");
1863
+ if (this.connectorTypes === null) {
1864
+ this.connectorTypes = rowsOf(await this.c.connectors.listConnectorTypes()).map((r) => r?.key).filter((k) => typeof k === "string" && !!k);
1865
+ }
1866
+ if (!this.connectorTypes.includes(cs.type)) {
1867
+ throw new InvalidRequestError(`Unknown connector type "${cs.type}": one of ${JSON.stringify(this.connectorTypes)}`);
1497
1868
  }
1498
- return customer.connectorId;
1499
1869
  }
1870
+ // ------------------------------------------------------------------ reading the layout
1500
1871
  /**
1501
- * Find the user by email (reactivating and assigning to the location if needed) or create them.
1502
- * Re-running a workflow therefore carries on with the same user.
1872
+ * Read the customer's layout back: Management, teams, groups, rules, connectors and what is
1873
+ * pending. A layout this SDK does not recognise (for example one built with 0.1.x) is returned with
1874
+ * what is missing listed in `pending`.
1503
1875
  */
1504
- async ensureUser(customer, u) {
1505
- if (!u?.email || !u.firstName || !u.lastName) throw new FilterError("email, firstName and lastName are required.");
1506
- const users = this.c.users;
1507
- const found = await users.findUserByEmail(customer.companyId, u.email);
1508
- if (!found?.id) {
1509
- const r = await users.createCompanyUser(
1510
- customer.companyId,
1511
- {
1512
- email: u.email,
1513
- first_name: u.firstName,
1514
- last_name: u.lastName,
1515
- phone_number: u.phoneNumber,
1516
- role: "frontline_user",
1517
- location_ids: [customer.locationId],
1518
- send_invitation: false,
1519
- // the invitation is emailed last, once the user is set up
1520
- auth_method: u.authMethod ?? "password"
1521
- },
1522
- { idempotencyKey: u.idempotencyKey }
1523
- );
1524
- const id = r.data?.attributes?.id;
1525
- if (!id) throw new IntelligenceCloudError("User create returned no id.");
1526
- return { id, created: true, status: r.data?.attributes?.status ?? "invited" };
1527
- }
1528
- if (found.status === "deactivated") await users.reactivateCompanyUser(customer.companyId, found.id);
1529
- const detail = (await users.getCompanyUser(customer.companyId, found.id)).data?.attributes ?? {};
1530
- if (detail.role !== "frontline_user") {
1531
- throw new FilterError(`${u.email} is a ${detail.role}; Seat users are frontline users.`);
1876
+ async getCustomer(companyId) {
1877
+ await this.requireAdmin();
1878
+ const c = this.c;
1879
+ const company = unwrap(await c.companies.getCompany(companyId)) ?? {};
1880
+ const name = company.company_name ?? "";
1881
+ const mgmtName = name + MANAGEMENT_SUFFIX;
1882
+ const locs = (await all(c.locations.iterCompanyLocations(companyId))).filter((x) => x.is_active ?? true);
1883
+ const key = (x) => [x.created_at ?? "", x.location_name ?? ""];
1884
+ locs.sort((a, b) => {
1885
+ const [a1, a2] = key(a);
1886
+ const [b1, b2] = key(b);
1887
+ return a1 < b1 ? -1 : a1 > b1 ? 1 : a2 < b2 ? -1 : a2 > b2 ? 1 : 0;
1888
+ });
1889
+ const cust = { companyId, management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [] };
1890
+ for (const loc of locs) {
1891
+ const kind = loc.location_name === mgmtName ? "management" : "team";
1892
+ const team = await this.readTeam(loc.id, loc.location_name ?? "", kind);
1893
+ if (kind === "management" && cust.management === null) cust.management = team;
1894
+ else cust.teams.push(team);
1532
1895
  }
1533
- if (!(detail.locations ?? []).some((l) => l.location_id === customer.locationId)) {
1534
- await users.addLocations(customer.companyId, found.id, [customer.locationId]);
1896
+ cust.pending = this.pendingOf(cust);
1897
+ for (const dom of rowsOf(await c.sso.listCompanyDomains(companyId))) {
1898
+ cust.ssoDomainId = dom.id ?? null;
1899
+ const ver = dom.verification ?? {};
1900
+ cust.ssoTxtRecord = { name: ver.name, value: ver.value };
1901
+ break;
1535
1902
  }
1536
- return { id: found.id, created: false, status: detail.status ?? null };
1537
- }
1538
- /** The last step: email the invitation to a user who has not accepted one yet. */
1539
- async invite(customer, u, userId, status) {
1540
- if (u.sendInvitation === false || status !== "invited") return false;
1541
- await this.c.users.resendInvitation(customer.companyId, userId);
1542
- return true;
1903
+ return cust;
1543
1904
  }
1544
- /** Replace the user's numbers on the customer's connector; a refusal becomes ExtensionMappingError. */
1545
- async mapNumbers(customer, userId, numbers) {
1546
- const connectorId = this.requireConnector(customer);
1547
- try {
1548
- await this.c.users.setNumbers(customer.companyId, userId, connectorId, numbers);
1549
- } catch (err) {
1550
- if (err instanceof ValidationError || err instanceof ConflictError) throw new ExtensionMappingError(userId, err);
1551
- throw err;
1905
+ async readTeam(locationId, name, kind) {
1906
+ const c = this.c;
1907
+ const team = newTeam(locationId, name, kind);
1908
+ const byName = /* @__PURE__ */ new Map();
1909
+ for (const g of await all(c.groups.iterUserGroups(locationId))) byName.set(g.group_name, g.id);
1910
+ for (const f of GROUP_FIELDS) team.groups[f] = byName.get(TEAM_GROUPS[f]) ?? null;
1911
+ const rules = /* @__PURE__ */ new Map();
1912
+ for (const r of await all(c.firstAlert.iterAlertRules(locationId))) rules.set(r.name, r.id);
1913
+ for (const key of RULE_FIELDS) team.rules[key] = rules.get(RULES[key].name) ?? null;
1914
+ await this.readConnector(team);
1915
+ return team;
1916
+ }
1917
+ async readConnector(team) {
1918
+ const conns = (await all(this.c.connectors.iterLocationConnectors(team.locationId))).sort((a, b) => rank(a.status) - rank(b.status));
1919
+ if (conns.length && conns[0].status !== "inactive") {
1920
+ team.connectorId = conns[0].id;
1921
+ team.connectorStatus = conns[0].status ?? null;
1922
+ team.connectorStateReason = conns[0].state_reason ?? null;
1552
1923
  }
1553
1924
  }
1554
- /** Lines at the location: First Alert's monitored numbers for the customer's connector. */
1555
- async locationLines(customer) {
1556
- if (!customer.connectorId) return [];
1557
- const cfg = (await this.c.firstAlert.getFirstAlertConfig(customer.locationId)).data;
1558
- return numbersFor(cfg?.connector_mappings, customer.connectorId);
1559
- }
1560
- excluded(customer, id, email) {
1561
- if ((customer.excludeUserIds ?? []).includes(id)) return true;
1562
- const e = (email ?? "").trim().toLowerCase();
1563
- return Boolean(e) && (customer.excludeEmails ?? []).some((x) => x.trim().toLowerCase() === e);
1564
- }
1565
- /** Active or invited frontline users at the location (not excluded), with their department. */
1566
- async seatUsers(customer) {
1567
- const departments = /* @__PURE__ */ new Map();
1568
- for await (const u of this.c.users.iterCompanyUsers(customer.companyId, { locationId: [customer.locationId] })) {
1569
- if (u?.id) departments.set(u.id, u.department ?? null);
1570
- }
1925
+ pendingOf(cust) {
1571
1926
  const out = [];
1572
- for await (const a of this.c.users.iterLocationUsers(customer.locationId)) {
1573
- if (!a?.id || a.status === "deactivated" || a.role !== "frontline_user") continue;
1574
- if (this.excluded(customer, a.id, a.email)) continue;
1575
- out.push({
1576
- id: a.id,
1577
- email: a.email ?? "",
1578
- displayName: a.display_name ?? "",
1579
- status: a.status ?? "",
1580
- enabledProducts: [...a.enabled_products ?? []],
1581
- groups: [...a.groups ?? []],
1582
- department: departments.get(a.id) ?? null
1583
- });
1927
+ for (const key of PHRASE_ALERTS) if (cust.teams.some((t) => t.rules[key] === null)) out.push(key);
1928
+ if (cust.management === null) {
1929
+ out.push("management location");
1930
+ } else {
1931
+ if (cust.management.groups.weeklyReports === null) out.push(`${cust.management.name}: group ${TEAM_GROUPS.weeklyReports}`);
1932
+ if (RULE_FIELDS.some((k) => cust.management.rules[k])) out.push(`${cust.management.name}: has alert rules (Management has none)`);
1933
+ }
1934
+ if (!cust.teams.length) out.push("team");
1935
+ for (const t of cust.teams) {
1936
+ for (const f of GROUP_FIELDS) if (t.groups[f] === null) out.push(`${t.name}: group ${TEAM_GROUPS[f]}`);
1937
+ if (t.rules.lowSentiment === null) out.push(`${t.name}: rule ${RULES.lowSentiment.name}`);
1584
1938
  }
1585
1939
  return out;
1586
1940
  }
1587
- /** Managers and integration users: the users who hold every line. */
1588
- async lineHolders(customer) {
1589
- const all = await this.seatUsers(customer);
1590
- return all.filter((u) => isManager(u) || isIntegration(u));
1591
- }
1592
- /** Lines held by end users who hold exactly one line (users holding several are not seats). */
1593
- async endUserLines(customer, connectorId, exceptUserId) {
1594
- const lines = /* @__PURE__ */ new Set();
1595
- for (const u of await this.listFrontlineUsers(customer)) {
1596
- if (u.id === exceptUserId) continue;
1597
- const nums = await this.c.users.userNumbers(customer.companyId, u.id, connectorId);
1598
- if (nums.length === 1) lines.add(nums[0]);
1599
- }
1600
- return lines;
1601
- }
1602
- // ------------------------------------------------------------------ workflows
1603
- /** Rebuild the customer object (location, groups, rules, connector) from a company id. */
1604
- async getSeatCustomer(companyId, options = {}) {
1605
- const company = (await this.c.companies.getCompany(companyId)).data?.attributes;
1606
- if (!company?.id) throw new NotFoundError(404, "NOT_FOUND", "Company not found.");
1607
- let loc = null;
1608
- if (options.locationName) {
1609
- loc = await this.c.locations.findLocation(companyId, options.locationName);
1610
- } else {
1611
- for await (const row of this.c.locations.iterCompanyLocations(companyId, { isActive: true })) {
1612
- loc = row;
1613
- break;
1941
+ // ------------------------------------------------------------------ create
1942
+ /**
1943
+ * Create the customer, or finish one an earlier run started.
1944
+ *
1945
+ * The company with all three products; the SSO domain claim (if `ssoDomain`); the first team and
1946
+ * `<Company> - Management`; the connector at each (if given); five groups on the team and the
1947
+ * weekly reports group at Management; the Low Sentiment rule, plus Customer Threat and Upset
1948
+ * Customer when their phrases are given, all switched off; Insights Hub with "monitor all numbers"
1949
+ * off. Alerts without phrases are listed in `Customer.pending` and follow with `setAlerts`. Store
1950
+ * `companyId` and pass it on later runs: a company is never adopted by its name alone.
1951
+ */
1952
+ async createCustomer(spec) {
1953
+ const me = await this.requireAdmin();
1954
+ const c = this.c;
1955
+ if (!spec || typeof spec !== "object" || !spec.admin || !spec.team) throw new InvalidRequestError("spec must be a CustomerSpec");
1956
+ if (!(spec.admin.phoneNumber ?? "").trim()) throw new InvalidRequestError("admin.phoneNumber is required for the primary contact");
1957
+ checkAlerts(spec.alerts);
1958
+ await this.checkConnector(spec.connector);
1959
+ const resellerId = spec.resellerId || me.reseller_id;
1960
+ if (!resellerId) throw new InvalidRequestError("resellerId is required (this login has none)");
1961
+ const mgmtName = spec.companyName + MANAGEMENT_SUFFIX;
1962
+ if (spec.team.name === mgmtName) throw new InvalidRequestError(`"${mgmtName}" is the Management location; name the team differently`);
1963
+ await this.verticalId(spec.team.vertical);
1964
+ const result = { companyId: "", management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [] };
1965
+ const failures = [];
1966
+ const run = this.run(result);
1967
+ try {
1968
+ run.step = "company";
1969
+ let company = await this.findCompany(resellerId, spec);
1970
+ if (company === null) {
1971
+ const body = {
1972
+ company_name: spec.companyName,
1973
+ primary_admin_contact_name: `${spec.admin.firstName} ${spec.admin.lastName}`.trim(),
1974
+ primary_admin_contact_email: spec.admin.email,
1975
+ primary_admin_contact_phone: spec.admin.phoneNumber,
1976
+ enabled_products: [...PRODUCT_KEYS]
1977
+ };
1978
+ if (spec.companyCode) body.company_code = spec.companyCode;
1979
+ company = unwrap(await c.companies.createCompany(resellerId, body));
1980
+ result.created.push("company");
1981
+ } else {
1982
+ result.existing.push("company");
1983
+ if (!(company.is_active ?? true)) {
1984
+ if (!spec.reactivate) {
1985
+ throw new InvalidRequestError(`Company "${spec.companyName}" exists but is inactive (set reactivate: true to reactivate it)`);
1986
+ }
1987
+ await c.companies.reactivateCompany(company.id);
1988
+ }
1989
+ }
1990
+ const companyId = result.companyId = company.id;
1991
+ run.step = "mfa";
1992
+ if (spec.mfaOff) {
1993
+ const current2 = unwrap(await c.companies.getCompany(companyId)) ?? {};
1994
+ if (current2.mfa_enforced) {
1995
+ await c.companies.updateCompany(companyId, { mfa_enforced: false });
1996
+ if ((unwrap(await c.companies.getCompany(companyId)) ?? {}).mfa_enforced) {
1997
+ const text = "MFA is still on for the company after the update";
1998
+ throw new ApiError(200, null, text, {});
1999
+ }
2000
+ }
2001
+ }
2002
+ run.step = "sso";
2003
+ if (spec.ssoDomain) await this.ensureDomain(companyId, spec.ssoDomain, result);
2004
+ run.step = "products";
2005
+ const current = unwrap(await c.companies.getCompany(companyId)) ?? {};
2006
+ const have = current.enabled_products ?? [];
2007
+ if (!PRODUCT_KEYS.every((k) => have.includes(k))) await c.companies.addProducts(companyId, [...PRODUCT_KEYS]);
2008
+ run.step = "locations";
2009
+ const team = await this.ensureLocation(companyId, spec.team.name, spec.team, "team", !!spec.reactivate, result);
2010
+ const mgmt = await this.ensureLocation(companyId, mgmtName, spec.team, "management", !!spec.reactivate, result);
2011
+ result.teams = [team];
2012
+ result.management = mgmt;
2013
+ run.step = "connectors";
2014
+ if (spec.connector) {
2015
+ for (const t of [team, mgmt]) {
2016
+ const failure = await this.ensureConnector(t, spec.connector, result);
2017
+ if (failure) failures.push(failure);
2018
+ }
2019
+ } else {
2020
+ await this.readConnector(team);
2021
+ await this.readConnector(mgmt);
1614
2022
  }
2023
+ run.step = "groups";
2024
+ await this.ensureGroups(team, result);
2025
+ await this.ensureGroups(mgmt, result);
2026
+ run.step = "rules";
2027
+ await this.ensureRules(team, this.settingsFrom(spec.alerts), result);
2028
+ run.step = "insights_hub";
2029
+ await this.ensureInsightsHub(team);
2030
+ await this.monitorAllOff(mgmt.locationId);
2031
+ result.pending = this.pendingOf(result);
2032
+ } catch (exc) {
2033
+ this.stop(run, exc);
1615
2034
  }
1616
- if (!loc?.id) throw new NotFoundError(404, "NOT_FOUND", "The company has no matching active location.");
1617
- const locationId = loc.id;
1618
- const ma = await this.c.groups.findGroup(locationId, MANAGER_ALERTS_GROUP);
1619
- const iha = await this.c.groups.findGroup(locationId, INSIGHTS_HUB_ACCESS_GROUP);
1620
- const upset = await this.c.firstAlert.findRule(locationId, UPSET_CUSTOMER_RULE);
1621
- const threat = await this.c.firstAlert.findRule(locationId, CUSTOMER_THREAT_RULE);
1622
- const conn = await this.bestConnector(locationId);
1623
- return {
1624
- companyId,
1625
- companyName: company.company_name ?? "",
1626
- locationId,
1627
- locationName: loc.location_name ?? "",
1628
- groups: { managerAlerts: ma?.id ?? null, insightsHubAccess: iha?.id ?? null },
1629
- rules: { upsetCustomer: upset?.id ?? null, customerThreat: threat?.id ?? null },
1630
- connectorId: conn?.id ?? null,
1631
- connectorStatus: conn?.status ?? null,
1632
- connectorStateReason: conn?.state_reason ?? null
1633
- };
2035
+ raiseConnectorFailure(failures, result);
2036
+ return result;
1634
2037
  }
1635
2038
  /**
1636
- * Create (or finish) a Base Intelligence Seat customer. Idempotent: objects that already exist
1637
- * (found by name) are kept, so a re-run completes a half-built customer.
2039
+ * `spec.companyId`, or the one company with this exact name whose primary contact email is
2040
+ * `spec.admin.email`. Throws ConflictError, before any write, when the name is taken by another.
1638
2041
  */
1639
- async provisionSeatCustomer(spec) {
2042
+ async findCompany(resellerId, spec) {
1640
2043
  const c = this.c;
1641
- if (!spec?.companyName || !spec.primaryAdmin || !spec.location?.name) {
1642
- throw new FilterError("companyName, primaryAdmin and location are required.");
1643
- }
1644
- const phrases = [...spec.threatPhrases ?? []];
1645
- const created = [];
1646
- const existing = [];
1647
- const partial = { created, existing };
1648
- const resellerId = spec.resellerId ?? await step("whoami", partial, async () => {
1649
- const me = await c.whoami();
1650
- if (!me.reseller_id) throw new IntelligenceCloudError("This login has no reseller id; pass resellerId.");
1651
- return me.reseller_id;
1652
- });
1653
- let company;
1654
- if (spec.companyId) {
1655
- const id = spec.companyId;
1656
- company = await step("get_company", partial, async () => (await c.companies.getCompany(id)).data?.attributes ?? null);
1657
- if (!company?.id) throw new NotFoundError(404, "NOT_FOUND", "Company not found.");
2044
+ if (spec.companyId) return unwrap(await c.companies.getCompany(spec.companyId));
2045
+ const sameName = await c.companies.findCompanies(resellerId, spec.companyName);
2046
+ if (!sameName.length) return null;
2047
+ const want = (spec.admin.email ?? "").trim().toLowerCase();
2048
+ const matches = [];
2049
+ for (const row of sameName) {
2050
+ const detail = unwrap(await c.companies.getCompany(row.id)) ?? {};
2051
+ if (String(detail.primary_admin_contact_email ?? "").trim().toLowerCase() === want) matches.push(detail);
2052
+ }
2053
+ if (matches.length === 1) return matches[0];
2054
+ const text = `A company named "${spec.companyName}" already exists with a different primary contact. Pass companyId to use an existing company, or choose a different company name.`;
2055
+ throw new ConflictError(409, COMPANY_NAME_CONFLICT, text, {});
2056
+ }
2057
+ async ensureDomain(companyId, domain, result) {
2058
+ const want = domain.trim().toLowerCase();
2059
+ let dom = rowsOf(await this.c.sso.listCompanyDomains(companyId)).find((d) => String(d.domain ?? "").trim().toLowerCase() === want);
2060
+ if (dom === void 0) {
2061
+ dom = unwrap(await this.c.sso.claimCompanyDomain(companyId, { domain })) ?? {};
2062
+ result.created.push("sso_domain");
1658
2063
  } else {
1659
- const sameName = await step("find_company", partial, () => c.companies.findCompanies(resellerId, spec.companyName));
1660
- const want = norm(spec.primaryAdmin.email);
1661
- const matches = [];
1662
- for (const row of sameName) {
1663
- if (!row.id) continue;
1664
- const id = row.id;
1665
- const detail = await step("find_company", partial, async () => (await c.companies.getCompany(id)).data?.attributes);
1666
- if (detail && norm(detail.primary_admin_contact_email) === want) matches.push(detail);
1667
- }
1668
- if (sameName.length && matches.length !== 1) {
1669
- throw new ConflictError(409, "company_name_conflict", companyNameConflictMessage(spec.companyName));
2064
+ result.existing.push("sso_domain");
2065
+ }
2066
+ result.ssoDomainId = dom.id ?? null;
2067
+ const ver = dom.verification ?? {};
2068
+ result.ssoTxtRecord = { name: ver.name, value: ver.value };
2069
+ }
2070
+ async ensureLocation(companyId, name, spec, kind, reactivate, result) {
2071
+ const c = this.c;
2072
+ let loc = await c.locations.findLocation(companyId, name);
2073
+ if (loc === null) {
2074
+ loc = unwrap(
2075
+ await c.locations.createLocation(companyId, {
2076
+ location_name: name,
2077
+ street: spec.street,
2078
+ city: spec.city,
2079
+ state: spec.state,
2080
+ country: spec.country,
2081
+ zipcode: spec.zipcode,
2082
+ vertical_id: await this.verticalId(spec.vertical),
2083
+ enabled_products: [...PRODUCT_KEYS]
2084
+ })
2085
+ );
2086
+ result.created.push(`location:${name}`);
2087
+ } else {
2088
+ result.existing.push(`location:${name}`);
2089
+ if (!(loc.is_active ?? true)) {
2090
+ if (!reactivate) throw new InvalidRequestError(`Location "${name}" exists but is inactive (set reactivate: true to reactivate it)`);
2091
+ await c.locations.reactivateLocation(companyId, loc.id);
1670
2092
  }
1671
- company = matches[0] ?? null;
2093
+ const have = loc.enabled_products ?? [];
2094
+ if (!PRODUCT_KEYS.every((k) => have.includes(k))) await c.locations.addProducts(companyId, loc.id, [...PRODUCT_KEYS]);
1672
2095
  }
1673
- if (company?.id && company.is_active === false) {
1674
- if (!spec.reactivate) {
1675
- throw new FilterError("The company exists but is deactivated. Set reactivate: true to reactivate it.");
2096
+ return newTeam(loc.id, name, kind);
2097
+ }
2098
+ async ensureGroups(team, result) {
2099
+ const fields = team.kind === "team" ? GROUP_FIELDS : ["weeklyReports"];
2100
+ const existing = /* @__PURE__ */ new Map();
2101
+ for (const g of await all(this.c.groups.iterUserGroups(team.locationId))) existing.set(g.group_name, g.id);
2102
+ for (const f of fields) {
2103
+ const gname = TEAM_GROUPS[f];
2104
+ let gid = existing.get(gname);
2105
+ if (gid === void 0) {
2106
+ gid = unwrap(await this.c.groups.createUserGroup(team.locationId, { group_name: gname })).id;
2107
+ result.created.push(`group:${team.name}:${gname}`);
2108
+ } else {
2109
+ result.existing.push(`group:${team.name}:${gname}`);
1676
2110
  }
1677
- const id = company.id;
1678
- await step("reactivate_company", partial, () => c.companies.reactivateCompany(id));
2111
+ team.groups[f] = gid;
1679
2112
  }
1680
- if (!company && phrases.length === 0) throw new FilterError(THREAT_PHRASES_MISSING);
1681
- if (!company) {
1682
- company = await step("create_company", partial, async () => {
1683
- const r = await c.companies.createCompany(resellerId, {
1684
- company_name: spec.companyName,
1685
- company_code: spec.companyCode,
1686
- primary_admin_contact_name: spec.primaryAdmin.name,
1687
- primary_admin_contact_email: spec.primaryAdmin.email,
1688
- primary_admin_contact_phone: spec.primaryAdmin.phone,
1689
- enabled_products: ALL_PRODUCTS
1690
- });
1691
- created.push("company");
1692
- return r.data.attributes;
1693
- });
1694
- } else {
1695
- existing.push("company");
1696
- }
1697
- const companyId = company.id;
1698
- partial.companyId = companyId;
1699
- if (spec.mfaOff) {
1700
- await step("mfa_off", partial, async () => {
1701
- const cur = (await c.companies.getCompany(companyId)).data?.attributes;
1702
- if (cur?.mfa_enforced !== false) await c.companies.updateCompany(companyId, { mfa_enforced: false });
1703
- const check = (await c.companies.getCompany(companyId)).data?.attributes;
1704
- if (check?.mfa_enforced !== false) throw new IntelligenceCloudError("MFA is still on after the update.");
1705
- });
2113
+ }
2114
+ settingsFrom(alerts) {
2115
+ const out = {};
2116
+ for (const key of RULE_FIELDS) {
2117
+ const s = alerts ? alerts[key] : null;
2118
+ out[key] = s ? [cleanPhrases(s.phrases), s.sentimentBelow ?? null] : [null, null];
1706
2119
  }
1707
- await step("company_products", partial, () => c.companies.addProducts(companyId, ALL_PRODUCTS));
1708
- let loc = await step("find_location", partial, () => c.locations.findLocation(companyId, spec.location.name));
1709
- if (!loc) {
1710
- loc = await step("create_location", partial, async () => {
1711
- let verticalId = spec.location.verticalId;
1712
- if (!verticalId) {
1713
- const key = spec.location.verticalKey ?? DEFAULT_VERTICAL_KEY;
1714
- const v = ((await c.locations.listVerticals()).data ?? []).find((x) => x.key === key);
1715
- if (!v?.id) throw new IntelligenceCloudError(`No industry with key "${key}".`);
1716
- verticalId = v.id;
1717
- }
1718
- const r = await c.locations.createLocation(companyId, {
1719
- location_name: spec.location.name,
1720
- street: spec.location.street,
1721
- city: spec.location.city,
1722
- state: spec.location.state,
1723
- country: spec.location.country,
1724
- zipcode: spec.location.zipcode,
1725
- vertical_id: verticalId,
1726
- enabled_products: ALL_PRODUCTS
1727
- });
1728
- created.push("location");
1729
- return r.data.attributes;
1730
- });
1731
- } else {
1732
- if (loc.is_active === false) {
1733
- if (!spec.reactivate) {
1734
- throw new FilterError("The location exists but is deactivated. Set reactivate: true to reactivate it.");
2120
+ return out;
2121
+ }
2122
+ /**
2123
+ * Create missing rules (switched off) and apply the given phrases and levels to existing ones.
2124
+ * Returns the ids of the rules created or changed.
2125
+ */
2126
+ async ensureRules(team, settings, result) {
2127
+ const fa = this.c.firstAlert;
2128
+ const changed = [];
2129
+ const found = /* @__PURE__ */ new Map();
2130
+ for (const r of await all(fa.iterAlertRules(team.locationId))) found.set(r.name, r);
2131
+ for (const key of RULE_FIELDS) {
2132
+ const d = RULES[key];
2133
+ const [phrases, level] = settings[key] ?? [null, null];
2134
+ const groupId = team.groups[d.group];
2135
+ const row = found.get(d.name);
2136
+ if (row === void 0) {
2137
+ if (d.hasPhrases && !phrases?.length) {
2138
+ team.rules[key] = null;
2139
+ continue;
1735
2140
  }
1736
- const lid = loc.id;
1737
- await step("reactivate_location", partial, () => c.locations.reactivateLocation(companyId, lid));
1738
- }
1739
- await step("location_products", partial, () => c.locations.addProducts(companyId, loc.id, ALL_PRODUCTS));
1740
- }
1741
- const locationId = loc.id;
1742
- partial.locationId = locationId;
1743
- const ensureGroup = (name) => step(`group:${name}`, partial, async () => {
1744
- const found = await c.groups.findGroup(locationId, name);
1745
- if (found?.id) return found.id;
1746
- const r = await c.groups.createUserGroup(locationId, { group_name: name });
1747
- created.push(`group:${name}`);
1748
- return r.data.attributes.id;
1749
- });
1750
- const managerAlerts = await ensureGroup(MANAGER_ALERTS_GROUP);
1751
- const ihAccess = await ensureGroup(INSIGHTS_HUB_ACCESS_GROUP);
1752
- partial.groups = { managerAlerts, insightsHubAccess: ihAccess };
1753
- const ensureRule = (name, body) => step(`rule:${name}`, partial, async () => {
1754
- const found = await c.firstAlert.findRule(locationId, name);
1755
- if (!found?.id) {
1756
- const r = await c.firstAlert.createAlertRule(locationId, body());
1757
- created.push(`rule:${name}`);
1758
- return r.data.attributes.id;
2141
+ if (!groupId) throw new InvalidRequestError(`${team.name}: group ${TEAM_GROUPS[d.group]} is missing`);
2142
+ const rule2 = unwrap(await fa.createAlertRule(team.locationId, ruleBody(key, groupId, phrases, level)));
2143
+ team.rules[key] = rule2.id;
2144
+ changed.push(rule2.id);
2145
+ result?.created.push(`rule:${team.name}:${d.name}`);
2146
+ continue;
1759
2147
  }
1760
- const rule = (await c.firstAlert.getAlertRule(locationId, found.id)).data?.attributes ?? {};
1761
- if (!(rule.groups ?? []).some((g) => g.id === managerAlerts)) {
1762
- await c.firstAlert.addRuleGroups(locationId, found.id, [managerAlerts]);
2148
+ result?.existing.push(`rule:${team.name}:${d.name}`);
2149
+ const rule = unwrap(await fa.getAlertRule(team.locationId, row.id)) ?? {};
2150
+ team.rules[key] = rule.id ?? row.id;
2151
+ const haveGroups = new Set((rule.groups ?? []).map((g) => g.id));
2152
+ if (groupId && !haveGroups.has(groupId)) await fa.addRuleGroups(team.locationId, row.id, [groupId]);
2153
+ const [curPhrases, curLevel] = ruleSettings(rule);
2154
+ const newPhrases = phrases ?? curPhrases;
2155
+ const newLevel = level ?? (curLevel ?? d.defaultLevel);
2156
+ if (d.hasPhrases && !newPhrases?.length) continue;
2157
+ const want = triggers(key, newPhrases, newLevel);
2158
+ if (!deepEqual(normTriggers(rule), want)) {
2159
+ await fa.updateAlertRule(team.locationId, row.id, { triggers: want });
2160
+ if (!changed.includes(row.id)) changed.push(row.id);
1763
2161
  }
1764
- const want = body();
1765
- if (want) {
1766
- const cur = (rule.triggers ?? []).map((t) => ({ trigger_type: t.trigger_type, config: t.config }));
1767
- if (canonical(cur) !== canonical(want.triggers)) {
1768
- await c.firstAlert.updateAlertRule(locationId, found.id, { triggers: want.triggers });
1769
- }
2162
+ }
2163
+ return changed;
2164
+ }
2165
+ async ensureInsightsHub(team) {
2166
+ const ih = this.c.insightsHub;
2167
+ const setup = unwrap(await ih.getInsightsHubSetup(team.locationId)) ?? {};
2168
+ const access = setup.group_access ?? [];
2169
+ const gid = team.groups.insightsHubAccess;
2170
+ if (gid && !access.includes(gid)) {
2171
+ if (!access.length && !(setup.connector_mappings ?? []).length) {
2172
+ await ih.saveInsightsHubSetup(team.locationId, { connector_mappings: [], group_access: [gid] });
2173
+ } else {
2174
+ await ih.updateInsightsHubSetup(team.locationId, { group_access: uniq([...access, gid]) });
1770
2175
  }
1771
- return found.id;
1772
- });
1773
- if (phrases.length === 0 && !await c.firstAlert.findRule(locationId, CUSTOMER_THREAT_RULE)) {
1774
- throw new FilterError(THREAT_PHRASES_MISSING);
1775
- }
1776
- const rules = {
1777
- upsetCustomer: await ensureRule(UPSET_CUSTOMER_RULE, () => upsetCustomerRule([managerAlerts])),
1778
- customerThreat: await ensureRule(
1779
- CUSTOMER_THREAT_RULE,
1780
- () => phrases.length ? customerThreatRule([managerAlerts], phrases) : null
1781
- )
1782
- };
1783
- partial.rules = rules;
1784
- await step("insights_hub", partial, async () => {
1785
- const setup = (await c.insightsHub.getInsightsHubSetup(locationId)).data?.attributes;
1786
- if (!(setup?.group_access ?? []).includes(ihAccess)) await c.insightsHub.addGroups(locationId, [ihAccess]);
1787
- const cfg = (await c.insightsHub.getInsightsHubConfig(locationId)).data?.attributes;
1788
- if (cfg?.monitor_all_numbers !== true) {
1789
- await c.insightsHub.updateInsightsHubConfig(locationId, { monitor_all_numbers: true });
2176
+ }
2177
+ await this.monitorAllOff(team.locationId);
2178
+ }
2179
+ async monitorAllOff(locationId) {
2180
+ const cfg = unwrap(await this.c.insightsHub.getInsightsHubConfig(locationId)) ?? {};
2181
+ if (cfg.monitor_all_numbers) await this.c.insightsHub.updateInsightsHubConfig(locationId, { monitor_all_numbers: false });
2182
+ }
2183
+ // ------------------------------------------------------------------ connectors
2184
+ /**
2185
+ * The location's connector of this type for the same phone-system domain (best status first),
2186
+ * else one of this type with this name.
2187
+ */
2188
+ async findConnector(locationId, cs, name) {
2189
+ const conns = this.c.connectors;
2190
+ const rows = (await all(conns.iterLocationConnectors(locationId))).sort((a, b) => rank(a.status) - rank(b.status));
2191
+ const wantDomain = String(cs.config.domain ?? "").trim().toLowerCase();
2192
+ let byName = null;
2193
+ for (const row of rows) {
2194
+ if (row.type && row.type !== cs.type) continue;
2195
+ const detail = unwrap(await conns.getConnector(locationId, row.id)) ?? {};
2196
+ const haveDomain = String((detail.config ?? {}).domain ?? "").trim().toLowerCase();
2197
+ if (wantDomain && haveDomain === wantDomain) return detail;
2198
+ if (byName === null && detail.name === name) byName = detail;
2199
+ }
2200
+ return byName;
2201
+ }
2202
+ static unchanged(found, name, config) {
2203
+ const have = found.config ?? {};
2204
+ return found.name === name && Object.entries(config).every(([k, v]) => !(k in have) || isSecretName(k) || deepEqual(have[k], v));
2205
+ }
2206
+ /**
2207
+ * Find, repair or create the team's connector and record its status on the team. Returns the
2208
+ * ConnectorError or ConnectorTimeoutError when it did not become active (the caller throws it at
2209
+ * the end, once everything else is built), else null.
2210
+ */
2211
+ async ensureConnector(team, cs, result) {
2212
+ const name = cs.name || `${team.name} phone system`;
2213
+ const conns = this.c.connectors;
2214
+ const config = plainConfig(cs.config);
2215
+ const found = await this.findConnector(team.locationId, cs, name);
2216
+ const label = `connector:${team.name}`;
2217
+ if (found !== null) {
2218
+ const unchanged = _Accounts.unchanged(found, name, config);
2219
+ if ([...RUNNING, "connecting"].includes(found.status) && unchanged) {
2220
+ result?.existing.push(label);
2221
+ this.setConn(team, found);
2222
+ return null;
1790
2223
  }
1791
- });
1792
- let connectorId = null;
1793
- let connectorStatus = null;
1794
- let connectorStateReason = null;
1795
- if (spec.connector) {
1796
- const cs = spec.connector;
1797
- const name = cs.name ?? `${spec.location.name} - NetSapiens`;
1798
- const conn = await step("connector", partial, async () => {
1799
- let byDomain = null;
1800
- let byName = null;
1801
- for await (const row of c.connectors.iterLocationConnectors(locationId)) {
1802
- if (!row.id) continue;
1803
- const detail = (await c.connectors.getConnector(locationId, row.id)).data ?? row;
1804
- const rank = (x) => x ? CONNECTOR_RANK[x.status ?? ""] ?? 9 : 99;
1805
- if (norm(detail.config?.domain) === norm(cs.domain) && rank(detail) < rank(byDomain)) byDomain = detail;
1806
- if (detail.name === name && rank(detail) < rank(byName)) byName = detail;
1807
- }
1808
- const found = byDomain ?? byName;
1809
- const wait = { timeout: cs.timeout };
1810
- try {
1811
- if (!found?.id) {
1812
- const r = await c.connectors.createConnector(
1813
- locationId,
1814
- { name, type: "netsapiens", config: { api_url: cs.apiUrl, domain: cs.domain, api_key: cs.apiKey } },
1815
- wait
1816
- );
1817
- created.push("connector");
1818
- return r.data ?? null;
1819
- }
1820
- existing.push("connector");
1821
- const fid = found.id;
1822
- const unchanged = found.name === name && found.config?.api_url === cs.apiUrl && norm(found.config?.domain) === norm(cs.domain);
1823
- if (unchanged && found.status === "active") return found;
1824
- if (unchanged && found.status === "connecting") {
1825
- return await c.connectors.waitForStatus(locationId, fid, ["active", "error"], wait);
1826
- }
1827
- await c.connectors.updateConnector(
1828
- locationId,
1829
- fid,
1830
- { name, config: { api_url: cs.apiUrl, domain: cs.domain, api_key: cs.apiKey } },
1831
- { wait: false }
1832
- );
1833
- existing.push("connector:updated");
1834
- if (found.status === "inactive") {
1835
- return (await c.connectors.reactivateConnector(locationId, fid, wait)).data ?? null;
2224
+ }
2225
+ let conn;
2226
+ try {
2227
+ if (found !== null) {
2228
+ if (result) result.existing.push(label, label + ":updated");
2229
+ await this.rawConnectors.updateConnector(team.locationId, found.id, { name, config });
2230
+ if (found.status === "inactive") {
2231
+ conn = unwrap(await conns.reactivateConnector(team.locationId, found.id, { timeout: cs.timeout }));
2232
+ } else {
2233
+ conn = await conns.waitForStatus(team.locationId, found.id, [...RUNNING, "error"], { timeout: cs.timeout, raiseOnError: false });
2234
+ if (conn.status === "error") {
2235
+ await conns.deactivateConnector(team.locationId, found.id, { timeout: cs.timeout });
2236
+ conn = unwrap(await conns.reactivateConnector(team.locationId, found.id, { timeout: cs.timeout }));
1836
2237
  }
1837
- const settled = await c.connectors.waitForStatus(locationId, fid, ["active", "error", "inactive"], wait);
1838
- if (settled.status === "active") return settled;
1839
- if (settled.status !== "inactive") await c.connectors.deactivateConnector(locationId, fid, wait);
1840
- return (await c.connectors.reactivateConnector(locationId, fid, wait)).data ?? null;
1841
- } catch (err) {
1842
- if (!(err instanceof ConnectorError)) throw err;
1843
- if (!found) created.push("connector");
1844
- return err.connector ?? null;
1845
2238
  }
1846
- });
1847
- connectorId = conn?.id ?? null;
1848
- connectorStatus = conn?.status ?? null;
1849
- connectorStateReason = conn?.state_reason ?? null;
1850
- partial.connectorId = connectorId;
1851
- if (connectorId && connectorStatus === "active" && cs.monitoredNumbers?.length) {
1852
- await step("monitored_numbers", partial, async () => {
1853
- await c.firstAlert.addMonitoredNumbers(locationId, connectorId, cs.monitoredNumbers);
1854
- await c.insightsHub.addNumbers(locationId, connectorId, cs.monitoredNumbers);
1855
- });
2239
+ } else {
2240
+ result?.created.push(label);
2241
+ conn = unwrap(await conns.createConnector(team.locationId, { name, type: cs.type, config }, { timeout: cs.timeout }));
1856
2242
  }
1857
- } else {
1858
- const found = await step("connector", partial, () => this.bestConnector(locationId));
1859
- connectorId = found?.id ?? null;
1860
- connectorStatus = found?.status ?? null;
1861
- connectorStateReason = found?.state_reason ?? null;
1862
- }
1863
- let ssoTxtRecord = null;
1864
- if (spec.sso?.domain) {
1865
- ssoTxtRecord = await step("sso_domain", partial, async () => {
1866
- const d = (await c.sso.claimCompanyDomain(companyId, { domain: spec.sso.domain })).data;
1867
- return { type: d?.verification?.type ?? "TXT", name: d?.verification?.name ?? "", value: d?.verification?.value ?? "" };
1868
- });
2243
+ } catch (exc) {
2244
+ if (exc instanceof ConnectorError || exc instanceof ConnectorTimeoutError) {
2245
+ this.setConn(team, exc.connector ?? {});
2246
+ return exc;
2247
+ }
2248
+ throw exc;
1869
2249
  }
1870
- return {
1871
- companyId,
1872
- companyName: spec.companyName,
1873
- locationId,
1874
- locationName: spec.location.name,
1875
- groups: { managerAlerts, insightsHubAccess: ihAccess },
1876
- rules,
1877
- connectorId,
1878
- connectorStatus,
1879
- connectorStateReason,
1880
- created,
1881
- existing,
1882
- ssoTxtRecord
1883
- };
2250
+ this.setConn(team, conn);
2251
+ if (conn.status === "error") return new ConnectorError(conn);
2252
+ return null;
2253
+ }
2254
+ setConn(team, conn) {
2255
+ team.connectorId = conn.id ?? null;
2256
+ team.connectorStatus = conn.status ?? null;
2257
+ team.connectorStateReason = conn.state_reason ?? null;
1884
2258
  }
2259
+ // ------------------------------------------------------------------ teams and alerts
1885
2260
  /**
1886
- * Switch on the customer's two alert rules (Upset Customer, Customer Threat). Rules already on are
1887
- * left as they are. Returns the ids of the rules this call switched on.
2261
+ * Add a further team: its location, connector (required; give the key in full each time), groups,
2262
+ * rules (copying the phrases and levels of the first team's rules, except where `alerts` sets them)
2263
+ * and Insights Hub setup. The rules are created switched off.
1888
2264
  */
1889
- async activateSeatAlerts(ref) {
1890
- const c = this.c;
1891
- const customer = await this.resolve(ref);
1892
- const switched = [];
1893
- await step("activate_alerts", { switched }, async () => {
1894
- for (const id of [customer.rules.upsetCustomer, customer.rules.customerThreat]) {
1895
- if (!id) continue;
1896
- const r = (await c.firstAlert.getAlertRule(customer.locationId, id)).data?.attributes;
1897
- if (r?.enabled !== true) {
1898
- await c.firstAlert.updateAlertRule(customer.locationId, id, { enabled: true });
1899
- switched.push(id);
2265
+ async addTeam(customer, team, connector, options = {}) {
2266
+ await this.requireAdmin();
2267
+ if (!team || typeof team !== "object") throw new InvalidRequestError("team must be a TeamSpec");
2268
+ await this.checkConnector(connector, true);
2269
+ checkAlerts(options.alerts);
2270
+ const cust = await this.resolve(customer);
2271
+ if (cust.management !== null && team.name === cust.management.name) {
2272
+ throw new InvalidRequestError("That name is the Management location; name the team differently");
2273
+ }
2274
+ await this.verticalId(team.vertical);
2275
+ const settings = this.settingsFrom(options.alerts);
2276
+ const first = cust.teams.find((t) => t.name !== team.name);
2277
+ const made = newTeam("", team.name);
2278
+ let failure = null;
2279
+ const run = this.run(made);
2280
+ try {
2281
+ run.step = "copy_alerts";
2282
+ if (first !== void 0) {
2283
+ for (const key of RULE_FIELDS) {
2284
+ const d = RULES[key];
2285
+ const rid = first.rules[key];
2286
+ if (rid === null) continue;
2287
+ const [phr, lvl] = ruleSettings(unwrap(await this.c.firstAlert.getAlertRule(first.locationId, rid)) ?? {});
2288
+ const [givenPhr, givenLvl] = settings[key];
2289
+ settings[key] = [givenPhr !== null ? givenPhr : d.hasPhrases ? phr : null, givenLvl !== null ? givenLvl : lvl];
1900
2290
  }
1901
2291
  }
1902
- });
1903
- return switched;
2292
+ run.step = "location";
2293
+ const loc = await this.ensureLocation(cust.companyId, team.name, team, "team", !!options.reactivate, cust);
2294
+ made.locationId = loc.locationId;
2295
+ run.step = "connector";
2296
+ failure = await this.ensureConnector(made, connector, cust);
2297
+ run.step = "groups";
2298
+ await this.ensureGroups(made, cust);
2299
+ run.step = "rules";
2300
+ await this.ensureRules(made, settings, cust);
2301
+ run.step = "insights_hub";
2302
+ await this.ensureInsightsHub(made);
2303
+ const existing = cust.teams.findIndex((t) => t.locationId === made.locationId);
2304
+ if (existing < 0) cust.teams.push(made);
2305
+ else cust.teams[existing] = made;
2306
+ cust.pending = this.pendingOf(cust);
2307
+ } catch (exc) {
2308
+ this.stop(run, exc);
2309
+ }
2310
+ raiseConnectorFailure(failure ? [failure] : [], made);
2311
+ return made;
1904
2312
  }
1905
2313
  /**
1906
- * End user: create (or find) the user without an invitation (frontline, After Call only, at the
1907
- * location), alert email off, map their extension, then add the extension to every manager's
1908
- * mapping and to the First Alert and Insights Hub numbers, and last email the invitation (unless
1909
- * `user.sendInvitation` is false). A refused mapping stops before managers, First Alert and
1910
- * Insights Hub are touched and throws ExtensionMappingError; no invitation has been sent.
2314
+ * Create or update the three rules' phrases and sentiment levels on one team or on every team.
2315
+ * Anything left out is kept. Existing rules keep their on or off state; a rule created here (one
2316
+ * that was pending its phrases) starts switched off: `activateAlerts` switches it on. Returns the
2317
+ * ids of the rules created or changed.
1911
2318
  */
1912
- async addFrontlineUser(ref, user, extension) {
1913
- const c = this.c;
1914
- const ext = String(extension ?? "").trim();
1915
- if (!ext) throw new FilterError("extension is required.");
1916
- const customer = await this.resolve(ref);
1917
- if (!customer.connectorId) throw new FilterError("This customer has no connector; add one before adding end users.");
1918
- const connectorId = customer.connectorId;
1919
- const partial = {};
1920
- const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
1921
- partial.userId = userId;
1922
- await step("enable_after_call", partial, () => c.products.enableUserProduct(customer.locationId, userId, "after-call-copilot"));
1923
- await step(
1924
- "alert_email_off",
1925
- partial,
1926
- () => c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: false, alerts: [] })
1927
- );
1928
- await step("map_extension", partial, () => this.mapNumbers(customer, userId, [ext]));
1929
- const managersUpdated = [];
1930
- partial.managersUpdated = managersUpdated;
1931
- await step("managers", partial, async () => {
1932
- for (const m of await this.lineHolders(customer)) {
1933
- if (m.id === userId) continue;
1934
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
1935
- if (cur.includes(ext)) continue;
1936
- await this.mapNumbers(customer, m.id, [...cur, ext]);
1937
- managersUpdated.push(m.id);
2319
+ async setAlerts(customer, alerts, options = {}) {
2320
+ await this.requireAdmin();
2321
+ checkAlerts(alerts);
2322
+ if (alerts === null || alerts === void 0) throw new InvalidRequestError("alerts is required");
2323
+ const cust = await this.resolve(customer);
2324
+ const teams = this.teamsOf(cust, options.team);
2325
+ const settings = this.settingsFrom(alerts);
2326
+ const changed = [];
2327
+ const run = this.run(changed);
2328
+ try {
2329
+ for (const t of teams) {
2330
+ run.step = `rules:${t.name}`;
2331
+ changed.push(...await this.ensureRules(t, settings, null));
1938
2332
  }
1939
- });
1940
- await step("first_alert_numbers", partial, () => c.firstAlert.addMonitoredNumbers(customer.locationId, connectorId, [ext]));
1941
- await step("insights_hub_numbers", partial, () => c.insightsHub.addNumbers(customer.locationId, connectorId, [ext]));
1942
- const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
1943
- return {
1944
- userId,
1945
- email: user.email,
1946
- kind: "frontline",
1947
- extensions: [ext],
1948
- managersUpdated,
1949
- created,
1950
- invited,
1951
- alertsActivated: []
1952
- };
2333
+ cust.pending = this.pendingOf(cust);
2334
+ } catch (exc) {
2335
+ this.stop(run, exc);
2336
+ }
2337
+ return changed;
1953
2338
  }
1954
2339
  /**
1955
- * Manager: create (or find) the user without an invitation, with After Call, First Alert and
1956
- * Insights Hub at the location, both groups, alert email on for every rule they receive, and a
1957
- * mapping of exactly the end-user lines at the location. The manager's own phone line is not
1958
- * captured on the Seat: it is never mapped, nor added to First Alert or Insights Hub, and an
1959
- * extension passed as the third argument throws FilterError. Then, with `activateAlerts`
1960
- * (default true), switch the customer's two alert rules on (see activateSeatAlerts), and last
1961
- * email the invitation (unless `user.sendInvitation` is false). A refused mapping throws
1962
- * ExtensionMappingError: the rules stay as they were and no invitation has been sent.
2340
+ * Attach a phone system to a customer created without one: the named team, or the first team and
2341
+ * Management. Refuses (InvalidRequestError, before any write) where an active connector exists.
2342
+ * Returns the teams it attached.
1963
2343
  */
1964
- async addManager(ref, user, options = {}) {
1965
- const c = this.c;
1966
- const opts = options ?? {};
1967
- if (typeof opts !== "object" || Object.keys(opts).some((k) => k !== "activateAlerts")) {
1968
- throw new FilterError("A manager's own phone line is not captured on the Seat: addManager takes no extension.");
1969
- }
1970
- const customer = await this.resolve(ref);
1971
- const partial = {};
1972
- const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
1973
- partial.userId = userId;
1974
- await step("enable_products", partial, async () => {
1975
- for (const key of ALL_PRODUCTS) await c.products.enableUserProduct(customer.locationId, userId, key);
1976
- });
1977
- await step("groups", partial, async () => {
1978
- const ids = [customer.groups.managerAlerts, customer.groups.insightsHubAccess].filter((x) => Boolean(x));
1979
- if (ids.length) await c.groups.addUserToGroups(customer.locationId, userId, ids);
1980
- });
1981
- await step("alert_email_on", partial, async () => {
1982
- const prefs = await c.firstAlert.getAlertNotificationPreferences(customer.locationId, userId);
1983
- const alerts = (prefs.emailNotifications?.alerts ?? []).filter((a) => a.alertId).map((a) => ({ alertId: a.alertId, emailEnabled: true }));
1984
- await c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: true, alerts });
1985
- });
1986
- const lines = await step("read_lines", partial, () => this.locationLines(customer));
1987
- const all = [...lines];
1988
- if (all.length) await step("map_all_lines", partial, () => this.mapNumbers(customer, userId, all));
1989
- const alertsActivated = opts.activateAlerts ?? true ? await this.activateSeatAlerts(customer) : [];
1990
- partial.alertsActivated = alertsActivated;
1991
- const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
1992
- return { userId, email: user.email, kind: "manager", extensions: all, managersUpdated: [], created, invited, alertsActivated };
2344
+ async setConnector(customer, connector, options = {}) {
2345
+ await this.requireAdmin();
2346
+ await this.checkConnector(connector, true);
2347
+ const cust = await this.resolve(customer);
2348
+ let targets;
2349
+ if (options.team !== void 0 && options.team !== null) {
2350
+ targets = [this.teamOf(cust, options.team)];
2351
+ } else {
2352
+ if (!cust.teams.length) throw new InvalidRequestError("This customer has no team");
2353
+ targets = [cust.teams[0], ...cust.management ? [cust.management] : []];
2354
+ }
2355
+ const todo = [];
2356
+ for (const t of targets) {
2357
+ const name = connector.name || `${t.name} phone system`;
2358
+ const found = await this.findConnector(t.locationId, connector, name);
2359
+ const active = (await all(this.c.connectors.iterLocationConnectors(t.locationId))).filter((x) => RUNNING.includes(x.status));
2360
+ const same = found !== null && RUNNING.includes(found.status) && Object.entries(plainConfig(connector.config)).every(
2361
+ ([k, v]) => !(k in (found.config ?? {})) || isSecretName(k) || deepEqual(found.config[k], v)
2362
+ );
2363
+ if (active.length && !same) throw new InvalidRequestError(`${t.name} already has an active connector`);
2364
+ if (same) {
2365
+ this.setConn(t, found);
2366
+ continue;
2367
+ }
2368
+ todo.push(t);
2369
+ }
2370
+ const run = this.run(targets);
2371
+ const failures = [];
2372
+ try {
2373
+ for (const t of todo) {
2374
+ run.step = `connector:${t.name}`;
2375
+ const failure = await this.ensureConnector(t, connector, cust);
2376
+ if (failure) failures.push(failure);
2377
+ }
2378
+ } catch (exc) {
2379
+ this.stop(run, exc);
2380
+ }
2381
+ raiseConnectorFailure(failures, targets);
2382
+ return targets;
1993
2383
  }
1994
2384
  /**
1995
- * Integration user (reads calls, alerts and insights for another system; never a seat or a
1996
- * manager): create (or find) the user without an invitation, tag it `department: "integration"`,
1997
- * switch on After Call, First Alert and Insights Hub, add it to both groups, switch every alert
1998
- * email off, map all lines, and last email the invitation (unless `user.sendInvitation` is false;
1999
- * the person who holds the integration's password accepts it). Integration users keep every line
2000
- * as end users come and go (like managers) and release no lines when removed. The user must sign
2001
- * in with a password (`authMethod: "password"`). Never switches alerts on.
2385
+ * Switch the rules on for every team. A team does not need a manager: its alerts then show in the app
2386
+ * only, and the team is listed under `noManager` with the alert groups that have none.
2002
2387
  */
2003
- async addIntegrationUser(ref, user) {
2004
- const c = this.c;
2005
- if ((user?.authMethod ?? "password") !== "password") {
2006
- throw new FilterError('An integration user signs in with a password (authMethod: "password").');
2007
- }
2008
- const customer = await this.resolve(ref);
2009
- const partial = {};
2010
- const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
2011
- partial.userId = userId;
2012
- await step(
2013
- "tag_integration",
2014
- partial,
2015
- () => c.users.updateCompanyUser(customer.companyId, userId, { department: INTEGRATION_DEPARTMENT })
2016
- );
2017
- await step("enable_products", partial, async () => {
2018
- for (const key of ALL_PRODUCTS) await c.products.enableUserProduct(customer.locationId, userId, key);
2019
- });
2020
- await step("groups", partial, async () => {
2021
- const ids = [customer.groups.managerAlerts, customer.groups.insightsHubAccess].filter((x) => Boolean(x));
2022
- if (ids.length) await c.groups.addUserToGroups(customer.locationId, userId, ids);
2023
- });
2024
- await step(
2025
- "alert_email_off",
2026
- partial,
2027
- () => c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: false, alerts: [] })
2028
- );
2029
- const lines = await step("read_lines", partial, () => this.locationLines(customer));
2030
- if (lines.length) await step("map_all_lines", partial, () => this.mapNumbers(customer, userId, lines));
2031
- const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
2032
- return { userId, email: user.email, kind: "integration", extensions: lines, managersUpdated: [], created, invited, alertsActivated: [] };
2033
- }
2034
- /** Move an end user from one extension to another: their mapping, every manager and integration user, First Alert, Insights Hub. */
2035
- async changeUserExtension(ref, userId, oldExtension, newExtension) {
2036
- const c = this.c;
2037
- const oldExt = String(oldExtension ?? "").trim();
2038
- const newExt = String(newExtension ?? "").trim();
2039
- if (!oldExt || !newExt) throw new FilterError("oldExtension and newExtension are required.");
2040
- const customer = await this.resolve(ref);
2041
- const connectorId = this.requireConnector(customer);
2042
- const swap = (cur) => [.../* @__PURE__ */ new Set([...cur.filter((n) => n !== oldExt), newExt])];
2043
- const partial = { userId };
2044
- await step(
2045
- "user_mapping",
2046
- partial,
2047
- async () => this.mapNumbers(customer, userId, swap(await c.users.userNumbers(customer.companyId, userId, connectorId)))
2048
- );
2049
- const managersUpdated = [];
2050
- partial.managersUpdated = managersUpdated;
2051
- await step("managers", partial, async () => {
2052
- for (const m of await this.lineHolders(customer)) {
2053
- if (m.id === userId) continue;
2054
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2055
- const target = swap(cur);
2056
- if (sameSet(cur, target)) continue;
2057
- await this.mapNumbers(customer, m.id, target);
2058
- managersUpdated.push(m.id);
2388
+ async activateAlerts(customer, options = {}) {
2389
+ await this.requireAdmin();
2390
+ const cust = await this.resolve(customer);
2391
+ const out = { switchedOn: [], noManager: [] };
2392
+ const people = await this.index(cust);
2393
+ const managers = new Set([...people.values()].filter((p) => p.license === "base_manager").map((p) => p.id));
2394
+ const run = this.run(out);
2395
+ try {
2396
+ for (const t of this.teamsOf(cust, options.team)) {
2397
+ run.step = `activate:${t.name}`;
2398
+ const missing = [];
2399
+ for (const f of ALERT_GROUPS) {
2400
+ const gid = t.groups[f];
2401
+ let members = /* @__PURE__ */ new Set();
2402
+ if (gid) {
2403
+ const grp = unwrap(await this.c.groups.getUserGroup(t.locationId, gid)) ?? {};
2404
+ members = new Set((grp.members ?? []).map((m) => m.id));
2405
+ }
2406
+ if (![...members].some((m) => managers.has(m))) missing.push(TEAM_GROUPS[f]);
2407
+ }
2408
+ if (missing.length) out.noManager.push({ locationId: t.locationId, team: t.name, missing });
2409
+ for (const key of RULE_FIELDS) {
2410
+ const rid = t.rules[key];
2411
+ if (!rid) continue;
2412
+ const rule = unwrap(await this.c.firstAlert.getAlertRule(t.locationId, rid)) ?? {};
2413
+ if (!rule.enabled) {
2414
+ await this.c.firstAlert.updateAlertRule(t.locationId, rid, { enabled: true });
2415
+ out.switchedOn.push(rid);
2416
+ }
2417
+ }
2059
2418
  }
2060
- });
2061
- await step("first_alert_numbers", partial, async () => {
2062
- const cfg = (await c.firstAlert.getFirstAlertConfig(customer.locationId)).data;
2063
- await c.firstAlert.setMonitoredNumbers(customer.locationId, connectorId, swap(numbersFor(cfg?.connector_mappings, connectorId)));
2064
- });
2065
- await step("insights_hub_numbers", partial, async () => {
2066
- const setup = (await c.insightsHub.getInsightsHubSetup(customer.locationId)).data?.attributes;
2067
- await c.insightsHub.setNumbers(customer.locationId, connectorId, swap(numbersFor(setup?.connector_mappings, connectorId)));
2068
- });
2069
- return { userId, oldExtension: oldExt, newExtension: newExt, managersUpdated };
2419
+ } catch (exc) {
2420
+ this.stop(run, exc);
2421
+ }
2422
+ return out;
2070
2423
  }
2071
- /**
2072
- * Remove a user, in this order: leave every group, clear their number mapping, take their line off
2073
- * managers, integration users, First Alert and Insights Hub (unless `keepExtensions`), then
2074
- * deactivate. Products are left as they are.
2075
- *
2076
- * Only an end user releases a line, and only a line no other end user at the location still
2077
- * holds. Managers, integration users (`department: "integration"`), excluded users and any
2078
- * non-manager holding more than one line release nothing: every other line stays where it is.
2079
- */
2080
- async removeUser(ref, userId, options = {}) {
2424
+ // ------------------------------------------------------------------ people: reading
2425
+ /** Everyone at the customer's locations, with products and groups per location, lines and license. */
2426
+ async index(cust, includeInactive = false) {
2081
2427
  const c = this.c;
2082
- const customer = await this.resolve(ref);
2083
- const partial = { userId };
2084
- const row = await step("read_user", partial, async () => (await c.users.getLocationUser(customer.locationId, userId)).data?.attributes ?? {});
2085
- const detail = await step("read_user", partial, async () => (await c.users.getCompanyUser(customer.companyId, userId)).data?.attributes ?? {});
2086
- const u = { enabledProducts: [...row.enabled_products ?? []], department: detail.department ?? null };
2087
- const connectorId = customer.connectorId;
2088
- const mappings = await step("read_mapping", partial, async () => (await c.users.getUserNumberMappings(customer.companyId, userId)).data ?? []);
2089
- const own = connectorId ? numbersFor(mappings, connectorId) : [];
2090
- const kind = isIntegration(u) || this.excluded(customer, userId, detail.email ?? row.email) ? "integration" : isManager(u) ? "manager" : own.length > 1 ? "integration" : "frontline";
2091
- let release = [];
2092
- if (kind === "frontline" && !options.keepExtensions && connectorId && own.length) {
2093
- const held = /* @__PURE__ */ new Set();
2094
- await step("read_end_user_lines", partial, async () => {
2095
- for (const f of await this.listFrontlineUsers(customer)) {
2096
- if (f.id === userId) continue;
2097
- for (const n of await c.users.userNumbers(customer.companyId, f.id, connectorId)) held.add(n);
2098
- }
2099
- });
2100
- release = own.filter((n) => !held.has(n));
2101
- }
2102
- await step("groups", partial, () => c.groups.removeUserFromGroups(customer.locationId, userId));
2103
- if (mappings.length) {
2104
- await step("clear_mapping", partial, () => c.users.setUserNumberMappings(customer.companyId, userId, { mappings: [] }));
2105
- }
2106
- const managersUpdated = [];
2107
- if (release.length && connectorId) {
2108
- partial.managersUpdated = managersUpdated;
2109
- await step("managers", partial, async () => {
2110
- for (const m of await this.lineHolders(customer)) {
2111
- if (m.id === userId) continue;
2112
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2113
- if (!cur.some((n) => release.includes(n))) continue;
2114
- await this.mapNumbers(customer, m.id, cur.filter((n) => !release.includes(n)));
2115
- managersUpdated.push(m.id);
2428
+ let people = /* @__PURE__ */ new Map();
2429
+ for (const t of this.locationsOf(cust)) {
2430
+ for (const r of await all(c.users.iterLocationUsers(t.locationId))) {
2431
+ let p = people.get(r.id);
2432
+ if (p === void 0) {
2433
+ p = new Person(r.id, r.email ?? "", r.status ?? null);
2434
+ people.set(r.id, p);
2116
2435
  }
2117
- });
2118
- await step("first_alert_numbers", partial, () => c.firstAlert.removeMonitoredNumbers(customer.locationId, connectorId, release));
2119
- await step("insights_hub_numbers", partial, () => c.insightsHub.removeNumbers(customer.locationId, connectorId, release));
2436
+ p.locs.set(t.locationId, { products: new Set(r.enabled_products ?? []), groups: new Set(r.groups ?? []) });
2437
+ }
2120
2438
  }
2121
- await step("deactivate", partial, async () => {
2122
- try {
2123
- await c.users.deactivateCompanyUser(customer.companyId, userId);
2124
- } catch (err) {
2125
- if (!(err instanceof ConflictError)) throw err;
2439
+ for (const u of await all(c.users.iterCompanyUsers(cust.companyId))) {
2440
+ const p = people.get(u.id);
2441
+ if (p !== void 0) {
2442
+ p.department = u.department ?? null;
2443
+ p.status = u.status ?? p.status;
2444
+ p.invitedAt = u.invited_at ?? null;
2445
+ p.inviteExpiresAt = u.invite_expires_at ?? null;
2126
2446
  }
2447
+ }
2448
+ if (!includeInactive) people = new Map([...people].filter(([, v]) => v.active));
2449
+ for (const p of people.values()) {
2450
+ if (p.active) p.mappings = unwrapMappings(await c.users.getUserNumberMappings(cust.companyId, p.id));
2451
+ this.classify(cust, p);
2452
+ }
2453
+ return people;
2454
+ }
2455
+ classify(cust, p) {
2456
+ const teamIds = cust.teams.map((t) => t.locationId);
2457
+ const mgmt = cust.management ? cust.management.locationId : null;
2458
+ const alertNames = new Set(ALERT_GROUPS.map((f) => TEAM_GROUPS[f]));
2459
+ p.teams = teamIds.filter((lid) => p.locs.has(lid));
2460
+ if (isIntegration({ department: p.department })) {
2461
+ p.license = "integration";
2462
+ return;
2463
+ }
2464
+ const allThree = [...p.locs.values()].some((v) => PRODUCT_KEYS.every((k) => v.products.has(k)));
2465
+ const inAlertGroups = p.teams.some((lid) => [...p.locs.get(lid).groups].some((g) => alertNames.has(g)));
2466
+ if (allThree && mgmt !== null && p.locs.has(mgmt) && inAlertGroups) {
2467
+ p.license = "base_manager";
2468
+ return;
2469
+ }
2470
+ const conn = new Map(cust.teams.map((t) => [t.locationId, t.connectorId]));
2471
+ const ownLine = p.teams.some((lid) => conn.get(lid) && p.numbers(conn.get(lid)).length > 0);
2472
+ const onlyAfterCall = p.teams.length > 0 && p.teams.every((lid) => {
2473
+ const prods = p.locs.get(lid).products;
2474
+ return prods.size === 1 && prods.has(AFTER_CALL);
2127
2475
  });
2128
- return { userId, kind, extensionsReleased: release, managersUpdated };
2129
- }
2130
- /** End users: invited or active frontline users with After Call only (integration and excluded users left out). */
2131
- async listFrontlineUsers(ref) {
2132
- const customer = await this.resolve(ref);
2133
- return (await this.seatUsers(customer)).filter(isFrontline);
2476
+ if (onlyAfterCall && ownLine && !(mgmt !== null && p.locs.has(mgmt))) {
2477
+ p.license = "base_user";
2478
+ return;
2479
+ }
2480
+ p.license = "other";
2481
+ }
2482
+ member(p) {
2483
+ return newMember(p.id, p.email, p.license, [...p.teams], p.numbers());
2484
+ }
2485
+ async person(cust, userId, includeInactive = false) {
2486
+ const people = await this.index(cust, includeInactive);
2487
+ const p = people.get(userId);
2488
+ if (p === void 0) throw new InvalidRequestError(`User ${userId} is not at any of this customer's locations`);
2489
+ return [p, people];
2490
+ }
2491
+ /** People who hold a team's lines: its Base Managers and integration users. */
2492
+ holders(team, people, exclude = []) {
2493
+ const skip = new Set(exclude);
2494
+ return [...people.values()].filter(
2495
+ (p) => p.active && !skip.has(p.id) && p.teams.includes(team.locationId) && (p.license === "base_manager" || p.license === "integration")
2496
+ );
2134
2497
  }
2135
- /** Managers: invited or active frontline users with After Call, First Alert and Insights Hub (integration and excluded users left out). */
2136
- async listManagers(ref) {
2137
- const customer = await this.resolve(ref);
2138
- return (await this.seatUsers(customer)).filter(isManager);
2498
+ /**
2499
+ * The team line this person owns: anyone active on the team, not a Base Manager or integration user,
2500
+ * with After Call on there and exactly one number on its connector. A Base User normally; also
2501
+ * someone read back as "other" (for example with First Alert switched on in the app), whose line is
2502
+ * never taken away.
2503
+ */
2504
+ ownedLine(p, team) {
2505
+ if (!p.active || p.license === "base_manager" || p.license === "integration" || !team.connectorId || !p.teams.includes(team.locationId) || !p.locs.get(team.locationId).products.has(AFTER_CALL)) {
2506
+ return null;
2507
+ }
2508
+ const nums = p.numbers(team.connectorId);
2509
+ return nums.length === 1 ? nums[0] : null;
2510
+ }
2511
+ /** user id -> the team line they own. */
2512
+ owners(team, people, exclude = []) {
2513
+ const skip = new Set(exclude);
2514
+ const out = /* @__PURE__ */ new Map();
2515
+ for (const p of people.values()) {
2516
+ if (skip.has(p.id)) continue;
2517
+ const l = this.ownedLine(p, team);
2518
+ if (l !== null) out.set(p.id, l);
2519
+ }
2520
+ return out;
2139
2521
  }
2140
- /** Integration users at the location: users tagged `department: "integration"`. */
2141
- async listIntegrationUsers(ref) {
2142
- const customer = await this.resolve(ref);
2143
- return (await this.seatUsers(customer)).filter(isIntegration);
2522
+ /** A team's lines: the line of every person who owns one there. */
2523
+ teamLines(team, people, exclude = []) {
2524
+ return uniq(this.owners(team, people, exclude).values());
2144
2525
  }
2145
2526
  /**
2146
- * A customer leaves. In order: pause the After Call webhook (the address is kept; it can't be
2147
- * deleted), clear the First Alert webhook address (numbers kept), deactivate the connector (which
2148
- * stops call capture), deactivate the integration users, and deactivate the company (unless
2149
- * `deactivateCompany: false`). Steps already done are skipped, so it is safe to run again.
2150
- * Ask your Tresic contact about the retention of the customer's data.
2527
+ * Refuse, before any write, to give an existing person a different license through an add helper:
2528
+ * that would take away lines they hold. `changeLicense` converts Base Users and Base Managers. A
2529
+ * person read back as "other" (for example one an earlier run of this helper left part-way) is
2530
+ * accepted when the helper cannot take anything away from them.
2151
2531
  */
2152
- async offboardCustomer(ref, options = {}) {
2153
- const c = this.c;
2154
- const customer = await this.resolve(ref);
2155
- const loc = customer.locationId;
2156
- const result = {
2157
- webhookPaused: false,
2158
- firstAlertWebhookCleared: false,
2159
- connectorDeactivated: false,
2160
- integrationUsersDeactivated: [],
2161
- companyDeactivated: false
2162
- };
2163
- const partial = result;
2164
- const already = (err) => {
2165
- if (!(err instanceof ConflictError)) throw err;
2532
+ async checkExisting(cust, email, target) {
2533
+ const found = await this.c.users.findUserByEmail(cust.companyId, email);
2534
+ if (found === null || !found.id) return;
2535
+ const p = (await this.index(cust, true)).get(found.id);
2536
+ if (p === void 0 || !p.active || p.license === target) return;
2537
+ const mgmt = cust.management ? cust.management.locationId : null;
2538
+ if (p.license === "other") {
2539
+ const nums = uniq(p.numbers());
2540
+ if (target === "base_user" && nums.length <= 1 && !(mgmt !== null && p.locs.has(mgmt))) return;
2541
+ if (target === "base_manager" && (!nums.length || mgmt !== null && p.locs.has(mgmt))) return;
2542
+ if (target === "integration" && !nums.length) return;
2543
+ }
2544
+ const hint = (target === "base_user" || target === "base_manager") && (p.license === "base_user" || p.license === "base_manager") ? "use changeLicense" : "remove them first, or use another person";
2545
+ throw new InvalidRequestError(`${email} is already set up as "${p.license}", not "${target}": ${hint}`);
2546
+ }
2547
+ /** Notes for the teams whose alert groups this person leaves with no Base Manager in them. */
2548
+ emptiedGroups(cust, people, uid, teamIds) {
2549
+ const notes = [];
2550
+ const p = people.get(uid);
2551
+ const wanted = new Set(teamIds);
2552
+ for (const t of cust.teams) {
2553
+ if (p === void 0 || !wanted.has(t.locationId) || !p.locs.has(t.locationId)) continue;
2554
+ const empty = [];
2555
+ for (const f of ALERT_GROUPS) {
2556
+ const name = TEAM_GROUPS[f];
2557
+ if (!p.locs.get(t.locationId).groups.has(name)) continue;
2558
+ const another = [...people.values()].some(
2559
+ (q) => q.id !== uid && q.active && q.license === "base_manager" && q.locs.has(t.locationId) && q.locs.get(t.locationId).groups.has(name)
2560
+ );
2561
+ if (!another) empty.push(name);
2562
+ }
2563
+ if (empty.length) notes.push(`${t.name} has no Base Manager left in ${empty.join(", ")}; its alerts were not changed.`);
2564
+ }
2565
+ return notes;
2566
+ }
2567
+ /**
2568
+ * Everyone active at the customer's locations, with license, teams and lines.
2569
+ *
2570
+ * `license`: "base_user", "base_manager", "integration" or "other". A Base User has After Call on and
2571
+ * their own line mapped; a Base Manager has all three products, is on Management and is in the alert
2572
+ * groups of at least one team; an integration user is tagged as one; anyone else is "other", listed
2573
+ * so it can be corrected.
2574
+ */
2575
+ async listMembers(customer, options = {}) {
2576
+ await this.requireAdmin();
2577
+ const license = options.license ?? null;
2578
+ if (license !== null && !LICENSES.includes(license)) throw new InvalidRequestError(`license: one of ${JSON.stringify(LICENSES)}`);
2579
+ const cust = await this.resolve(customer);
2580
+ const lid = options.team !== void 0 && options.team !== null ? this.teamOf(cust, options.team).locationId : null;
2581
+ const out = [];
2582
+ for (const p of (await this.index(cust)).values()) {
2583
+ if (license !== null && p.license !== license) continue;
2584
+ if (lid !== null && !p.teams.includes(lid)) continue;
2585
+ out.push(this.member(p));
2586
+ }
2587
+ return out;
2588
+ }
2589
+ /** People by license and the number of teams (Management not counted). */
2590
+ async licenseReport(customer) {
2591
+ const cust = await this.resolve(customer);
2592
+ const members = await this.listMembers(cust);
2593
+ const by = { baseUser: [], baseManager: [], integration: [], other: [] };
2594
+ for (const m of members) {
2595
+ if (m.license === "base_user") by.baseUser.push(m);
2596
+ else if (m.license === "base_manager") by.baseManager.push(m);
2597
+ else if (m.license === "integration") by.integration.push(m);
2598
+ else by.other.push(m);
2599
+ }
2600
+ return {
2601
+ baseUser: by.baseUser.length,
2602
+ baseManager: by.baseManager.length,
2603
+ integration: by.integration.length,
2604
+ other: by.other.length,
2605
+ teams: cust.teams.length,
2606
+ members: by
2166
2607
  };
2167
- await step("pause_after_call_webhook", partial, async () => {
2168
- let hook = null;
2608
+ }
2609
+ // ------------------------------------------------------------------ people: low-level steps
2610
+ /**
2611
+ * Find or create the person (never emailing an invitation here) and make sure they are on
2612
+ * `locationIds`. Returns (id, created, company user).
2613
+ */
2614
+ async ensureUser(cust, person, locationIds) {
2615
+ const users = this.c.users;
2616
+ const found = await users.findUserByEmail(cust.companyId, person.email);
2617
+ if (found === null) {
2618
+ const body = {
2619
+ email: person.email,
2620
+ first_name: person.firstName,
2621
+ last_name: person.lastName,
2622
+ role: "frontline_user",
2623
+ location_ids: [...locationIds],
2624
+ send_invitation: false,
2625
+ auth_method: person.authMethod ?? "password"
2626
+ };
2627
+ if (person.phoneNumber) body.phone_number = person.phoneNumber;
2628
+ let row = unwrap(await users.createCompanyUser(cust.companyId, body)) ?? {};
2629
+ if (!row || typeof row !== "object" || !row.id) {
2630
+ const again = await users.findUserByEmail(cust.companyId, person.email);
2631
+ if (!again?.id) throw new InvalidRequestError("The user was not found after it was created");
2632
+ row = { ...again };
2633
+ }
2634
+ row.status ??= "invited";
2635
+ return [row.id, true, row];
2636
+ }
2637
+ const uid = found.id;
2638
+ if (found.status === "deactivated") await users.reactivateCompanyUser(cust.companyId, uid);
2639
+ const detail = unwrap(await users.getCompanyUser(cust.companyId, uid)) ?? {};
2640
+ if (detail.role !== "frontline_user") {
2641
+ throw new InvalidRequestError(`${person.email} has role ${detail.role}; licensed people are frontline users`);
2642
+ }
2643
+ await this.addLocations(cust, uid, locationIds, detail);
2644
+ return [uid, false, detail];
2645
+ }
2646
+ async addLocations(cust, uid, locationIds, detail) {
2647
+ const d = detail ?? unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2648
+ const have = (d.locations ?? []).map((x) => x.location_id);
2649
+ if (locationIds.some((lid) => !have.includes(lid))) {
2650
+ await this.c.users.updateCompanyUser(cust.companyId, uid, { location_ids: uniq([...have, ...locationIds]) });
2651
+ }
2652
+ }
2653
+ async removeLocations(cust, uid, locationIds) {
2654
+ const d = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2655
+ const have = (d.locations ?? []).map((x) => x.location_id);
2656
+ const drop = new Set(locationIds);
2657
+ const keep = have.filter((x) => !drop.has(x));
2658
+ if (keep.length !== have.length) await this.c.users.updateCompanyUser(cust.companyId, uid, { location_ids: keep });
2659
+ }
2660
+ async productsOn(locationId, uid, keys) {
2661
+ const row = unwrap(await this.c.users.getLocationUser(locationId, uid)) ?? {};
2662
+ const have = new Set(row.enabled_products ?? []);
2663
+ for (const key of keys) if (!have.has(key)) await this.c.products.enableUserProduct(locationId, uid, key);
2664
+ }
2665
+ async productsOff(locationId, uid, keys) {
2666
+ const row = unwrap(await this.c.users.getLocationUser(locationId, uid)) ?? {};
2667
+ const have = new Set(row.enabled_products ?? []);
2668
+ for (const key of keys) if (have.has(key)) await this.c.products.disableUserProduct(locationId, uid, key);
2669
+ }
2670
+ async joinGroups(locationId, uid, groupIds) {
2671
+ const want = groupIds.filter((g) => !!g);
2672
+ const current = await this.c.groups.userGroupIds(locationId, uid);
2673
+ if (want.some((g) => !current.includes(g))) {
2674
+ await this.c.groups.setUserGroupMembership(locationId, uid, { group_ids: uniq([...current, ...want]) });
2675
+ }
2676
+ }
2677
+ async leaveGroups(locationId, uid, groupIds) {
2678
+ const current = await this.c.groups.userGroupIds(locationId, uid);
2679
+ const drop = new Set(groupIds ?? []);
2680
+ const keep = groupIds === void 0 ? [] : current.filter((g) => !drop.has(g));
2681
+ if (keep.length !== current.length || keep.some((g, i) => g !== current[i])) {
2682
+ await this.c.groups.setUserGroupMembership(locationId, uid, { group_ids: keep });
2683
+ }
2684
+ }
2685
+ /** Alert email off for a person the helpers create. Someone who has signed in keeps their own choice. */
2686
+ async emailOff(locationId, uid, created, status) {
2687
+ if (!(created || status === "invited")) return;
2688
+ const prefs = await this.c.firstAlert.getAlertNotificationPreferences(locationId, uid) ?? {};
2689
+ if ((prefs.emailNotifications ?? {}).masterEnabled !== false) {
2690
+ await this.c.firstAlert.setAlertEmailPreferences(locationId, uid, { masterEnabled: false, alerts: [] });
2691
+ }
2692
+ }
2693
+ async setMappings(cust, uid, mappings) {
2694
+ try {
2695
+ await this.c.users.setUserNumberMappings(cust.companyId, uid, { mappings });
2696
+ } catch (exc) {
2697
+ if (exc instanceof ValidationError || exc instanceof ConflictError) throw new ExtensionMappingError(uid, exc);
2698
+ throw exc;
2699
+ }
2700
+ }
2701
+ /** Set (`replace`) or add to the person's numbers on one connector; other connectors are kept. */
2702
+ async map(cust, uid, connectorId, numbers, current, replace = true) {
2703
+ const cur = current ?? unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, uid));
2704
+ const have = numbersOf(cur, connectorId);
2705
+ const target = replace ? [...numbers] : uniq([...have, ...numbers]);
2706
+ if (deepEqual(target, have)) return;
2707
+ const others = cur.filter((m) => m.connector_id !== connectorId);
2708
+ await this.setMappings(cust, uid, mergeMappings(others, connectorId, target));
2709
+ }
2710
+ /** The last step: email the invitation to a person who has none yet. */
2711
+ async invite(cust, uid, invite) {
2712
+ if (!invite) return false;
2713
+ const detail = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2714
+ if (detail.status !== "invited" || detail.invited_at) return false;
2715
+ await this.c.users.resendInvitation(cust.companyId, uid);
2716
+ return true;
2717
+ }
2718
+ async faNumbers(team) {
2719
+ const cfg = unwrap(await this.c.firstAlert.getFirstAlertConfig(team.locationId)) ?? {};
2720
+ return numbersOf(cfg.connector_mappings ?? [], team.connectorId);
2721
+ }
2722
+ async ihNumbers(team) {
2723
+ const setup = unwrap(await this.c.insightsHub.getInsightsHubSetup(team.locationId)) ?? {};
2724
+ return numbersOf(setup.connector_mappings ?? [], team.connectorId);
2725
+ }
2726
+ /** A team line onto First Alert, Insights Hub and every holder of the team's lines. */
2727
+ async attachLine(cust, team, ln, people, exclude = []) {
2728
+ const cid = team.connectorId;
2729
+ if (!(await this.faNumbers(team)).includes(ln)) await this.c.firstAlert.addMonitoredNumbers(team.locationId, cid, [ln]);
2730
+ if (!(await this.ihNumbers(team)).includes(ln)) await this.c.insightsHub.addNumbers(team.locationId, cid, [ln]);
2731
+ for (const h of this.holders(team, people, exclude)) {
2732
+ if (!h.numbers(cid).includes(ln)) await this.map(cust, h.id, cid, [ln], h.mappings, false);
2733
+ }
2734
+ }
2735
+ /**
2736
+ * Take a team line off its holders, First Alert and Insights Hub, unless another Base User at the
2737
+ * team still holds it. Returns true when it was released.
2738
+ */
2739
+ async releaseLine(cust, team, ln, people, leaving) {
2740
+ if (!team.connectorId) return false;
2741
+ if ([...this.owners(team, people, [leaving]).values()].includes(ln)) return false;
2742
+ for (const h of this.holders(team, people, [leaving])) {
2743
+ const have = h.numbers(team.connectorId);
2744
+ if (have.includes(ln)) await this.map(cust, h.id, team.connectorId, have.filter((n) => n !== ln), h.mappings);
2745
+ }
2746
+ if ((await this.faNumbers(team)).includes(ln)) await this.c.firstAlert.removeMonitoredNumbers(team.locationId, team.connectorId, [ln]);
2747
+ if ((await this.ihNumbers(team)).includes(ln)) await this.c.insightsHub.removeNumbers(team.locationId, team.connectorId, [ln]);
2748
+ return true;
2749
+ }
2750
+ needConnector(team) {
2751
+ if (!team.connectorId) throw new InvalidRequestError(`${team.name} has no connector: attach one with setConnector`);
2752
+ return team.connectorId;
2753
+ }
2754
+ /** Management and each team: products, groups, alert email off, lines. Returns the lines held. */
2755
+ async managerSetup(cust, uid, teams, ln, companyReports, created, status, run) {
2756
+ const mgmt = cust.management;
2757
+ run.step = "products";
2758
+ for (const t of [...teams, mgmt]) await this.productsOn(t.locationId, uid, PRODUCT_KEYS);
2759
+ run.step = "groups";
2760
+ for (const t of teams) await this.joinGroups(t.locationId, uid, GROUP_FIELDS.map((f) => t.groups[f]));
2761
+ if (companyReports) await this.joinGroups(mgmt.locationId, uid, [mgmt.groups.weeklyReports]);
2762
+ run.step = "alert_email";
2763
+ for (const t of teams) await this.emailOff(t.locationId, uid, created, status);
2764
+ run.step = "lines";
2765
+ const people = await this.index(cust);
2766
+ const current = unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, uid));
2767
+ let mappings = current.map((m) => ({ ...m }));
2768
+ if (ln) {
2769
+ mappings = mergeMappings(
2770
+ mappings.filter((m) => m.connector_id !== mgmt.connectorId),
2771
+ this.needConnector(mgmt),
2772
+ uniq([...numbersOf(current, mgmt.connectorId), ln])
2773
+ );
2774
+ }
2775
+ for (const t of teams) {
2776
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [uid]));
2777
+ }
2778
+ if (!sameMappings(mappings, current)) await this.setMappings(cust, uid, mappings);
2779
+ return numbersOf(mappings);
2780
+ }
2781
+ // ------------------------------------------------------------------ people: helpers
2782
+ /**
2783
+ * Add a Base User: created without an invitation, After Call on, their line mapped on the team's
2784
+ * connector and added to the team's First Alert and Insights Hub lines and to every Base Manager and
2785
+ * integration user of the team, then the invitation (if `invite`). If the line cannot be mapped,
2786
+ * AccountError (cause ExtensionMappingError) is thrown and no invitation is sent.
2787
+ */
2788
+ async addBaseUser(customer, person, options) {
2789
+ await this.requireAdmin();
2790
+ const cust = await this.resolve(customer);
2791
+ const t = this.teamOf(cust, options.team);
2792
+ const ln = line(options.line);
2793
+ this.needConnector(t);
2794
+ await this.checkExisting(cust, person.email, "base_user");
2795
+ const result = newMember("", person.email, "base_user", [t.locationId], [ln]);
2796
+ const run = this.run(result);
2797
+ try {
2798
+ run.step = "monitor_all";
2799
+ await this.monitorAllOff(t.locationId);
2800
+ run.step = "user";
2801
+ const [uid, created, detail] = await this.ensureUser(cust, person, [t.locationId]);
2802
+ result.userId = uid;
2803
+ result.created = created;
2804
+ run.step = "products";
2805
+ await this.productsOn(t.locationId, uid, [AFTER_CALL]);
2806
+ run.step = "alert_email";
2807
+ await this.emailOff(t.locationId, uid, created, detail.status);
2808
+ run.step = "line";
2809
+ await this.map(cust, uid, t.connectorId, [ln]);
2810
+ run.step = "team_lines";
2811
+ await this.attachLine(cust, t, ln, await this.index(cust), [uid]);
2812
+ run.step = "invitation";
2813
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
2814
+ } catch (exc) {
2815
+ this.stop(run, exc);
2816
+ }
2817
+ return result;
2818
+ }
2819
+ /**
2820
+ * Add a Base Manager on each team and on Management: all three products; their own line at
2821
+ * Management (if `line`); every Base User line of each team; the three alert groups, Insights Hub
2822
+ * Access and Insights Hub Weekly Reports of each team (and the company-wide weekly reports group
2823
+ * with `companyReports: true`); alert email off. The invitation is sent last.
2824
+ */
2825
+ async addBaseManager(customer, person, options) {
2826
+ await this.requireAdmin();
2827
+ const cust = await this.resolve(customer);
2828
+ const teams = options?.teams;
2829
+ if (!Array.isArray(teams) || !teams.length) throw new InvalidRequestError("teams: a list of one or more teams");
2830
+ const ts = dedupeTeams(teams.map((x) => this.teamOf(cust, x)));
2831
+ if (cust.management === null) throw new InvalidRequestError("This customer has no Management location: run createCustomer again");
2832
+ const own = options.line !== void 0 && options.line !== null ? line(options.line) : null;
2833
+ if (own) this.needConnector(cust.management);
2834
+ await this.checkExisting(cust, person.email, "base_manager");
2835
+ const result = newMember("", person.email, "base_manager", ts.map((t) => t.locationId));
2836
+ const run = this.run(result);
2837
+ try {
2838
+ run.step = "monitor_all";
2839
+ for (const t of ts) await this.monitorAllOff(t.locationId);
2840
+ run.step = "user";
2841
+ const [uid, created, detail] = await this.ensureUser(cust, person, [...ts.map((t) => t.locationId), cust.management.locationId]);
2842
+ result.userId = uid;
2843
+ result.created = created;
2844
+ result.lines = await this.managerSetup(cust, uid, ts, own, !!options.companyReports, created, detail.status, run);
2845
+ run.step = "invitation";
2846
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
2847
+ } catch (exc) {
2848
+ this.stop(run, exc);
2849
+ }
2850
+ return result;
2851
+ }
2852
+ /**
2853
+ * Add the customer's integration (data-reading) user across every team: password sign-in, tagged
2854
+ * `department: "integration"`, all three products, the alert groups and Insights Hub Access, alert
2855
+ * email off, every team's lines. Later Base Users' lines are added to it. The company needs MFA off
2856
+ * (`CustomerSpec.mfaOff`) for it to sign in.
2857
+ */
2858
+ async addIntegrationUser(customer, person, options = {}) {
2859
+ await this.requireAdmin();
2860
+ if ((person.authMethod ?? "password") !== "password") {
2861
+ throw new InvalidRequestError('An integration user signs in with a password: set authMethod: "password"');
2862
+ }
2863
+ const cust = await this.resolve(customer);
2864
+ if (!cust.teams.length) throw new InvalidRequestError("This customer has no team");
2865
+ await this.checkExisting(cust, person.email, "integration");
2866
+ const result = newMember("", person.email, "integration", cust.teams.map((t) => t.locationId));
2867
+ const run = this.run(result);
2868
+ try {
2869
+ run.step = "user";
2870
+ const [uid, created] = await this.ensureUser(cust, person, cust.teams.map((t) => t.locationId));
2871
+ result.userId = uid;
2872
+ result.created = created;
2873
+ run.step = "tag";
2874
+ const detail = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2875
+ if (!isIntegration(detail)) await this.c.users.updateCompanyUser(cust.companyId, uid, { department: INTEGRATION_DEPARTMENT });
2876
+ run.step = "products";
2877
+ for (const t of cust.teams) await this.productsOn(t.locationId, uid, PRODUCT_KEYS);
2878
+ run.step = "groups";
2879
+ for (const t of cust.teams) {
2880
+ await this.joinGroups(t.locationId, uid, [...ALERT_GROUPS, "insightsHubAccess"].map((f) => t.groups[f]));
2881
+ }
2882
+ run.step = "alert_email";
2883
+ for (const t of cust.teams) await this.emailOff(t.locationId, uid, created, detail.status);
2884
+ run.step = "lines";
2885
+ const people = await this.index(cust);
2886
+ const current = people.get(uid)?.mappings ?? [];
2887
+ let mappings = current.map((m) => ({ ...m }));
2888
+ for (const t of cust.teams) {
2889
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [uid]));
2890
+ }
2891
+ if (!sameMappings(mappings, current)) await this.setMappings(cust, uid, mappings);
2892
+ result.lines = numbersOf(mappings);
2893
+ run.step = "invitation";
2894
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
2895
+ } catch (exc) {
2896
+ this.stop(run, exc);
2897
+ }
2898
+ return result;
2899
+ }
2900
+ /**
2901
+ * Base User to Base Manager (`to: "base_manager"`): their own line moves to Management and they get
2902
+ * the products, team lines and groups of `teams` (default: their teams); teams they were on and that
2903
+ * are not in `teams` are left.
2904
+ * Base Manager to Base User (`to: "base_user"`): groups, team lines, the extra products and
2905
+ * Management are removed; they keep one team (`teams[0]`, default their first) and their own line
2906
+ * (`line`, default their Management line), which is added to that team's lists.
2907
+ *
2908
+ * Safe to run again, also after an AccountError: a person part-way through the change is recognised
2909
+ * and the change continues. Until it completes, `result.lines` and `result.teams` hold what the
2910
+ * person had before.
2911
+ */
2912
+ async changeLicense(customer, userId, to, options = {}) {
2913
+ await this.requireAdmin();
2914
+ if (to !== "base_user" && to !== "base_manager") throw new InvalidRequestError('to: "base_user" or "base_manager"');
2915
+ const cust = await this.resolve(customer);
2916
+ if (cust.management === null) throw new InvalidRequestError("This customer has no Management location: run createCustomer again");
2917
+ const [p, people] = await this.person(cust, userId);
2918
+ if (p.license !== "base_user" && p.license !== "base_manager" && p.license !== "other") {
2919
+ throw new InvalidRequestError(`User ${userId} is "${p.license}"; only Base Users and Base Managers change license`);
2920
+ }
2921
+ const ts = options.teams?.length ? dedupeTeams(options.teams.map((x) => this.teamOf(cust, x))) : cust.teams.filter((t) => p.teams.includes(t.locationId));
2922
+ if (!ts.length) throw new InvalidRequestError("teams: the person is on no team; pass teams");
2923
+ const result = this.member(p);
2924
+ const run = this.run(result);
2925
+ try {
2926
+ if (to === "base_manager") await this.toManager(cust, p, people, ts, options.line ?? null, run, result);
2927
+ else await this.toUser(cust, p, people, ts[0], options.line ?? null, run, result);
2928
+ } catch (exc) {
2929
+ this.stop(run, exc);
2930
+ }
2931
+ return result;
2932
+ }
2933
+ async toManager(cust, p, people, ts, lineArg, run, result) {
2934
+ const mgmt = cust.management;
2935
+ const stray = [];
2936
+ for (const t of cust.teams) {
2937
+ if (t.connectorId) {
2938
+ const lines = this.teamLines(t, people, [p.id]);
2939
+ for (const n of p.numbers(t.connectorId)) if (!lines.includes(n)) stray.push([t, n]);
2940
+ }
2941
+ }
2942
+ const mgNums = mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
2943
+ const own = lineArg !== null ? line(lineArg) : mgNums[0] ?? (stray.length ? stray[0][1] : null);
2944
+ if (own) this.needConnector(mgmt);
2945
+ const keepIds = new Set(ts.map((t) => t.locationId));
2946
+ const former = cust.teams.filter((t) => p.locs.has(t.locationId) && !keepIds.has(t.locationId));
2947
+ const notes = this.emptiedGroups(cust, people, p.id, former.map((t) => t.locationId));
2948
+ run.step = "locations";
2949
+ await this.addLocations(cust, p.id, [...ts.map((t) => t.locationId), mgmt.locationId]);
2950
+ run.step = "products";
2951
+ for (const t of [...ts, mgmt]) await this.productsOn(t.locationId, p.id, PRODUCT_KEYS);
2952
+ run.step = "groups";
2953
+ for (const t of ts) await this.joinGroups(t.locationId, p.id, GROUP_FIELDS.map((f) => t.groups[f]));
2954
+ run.step = "alert_email";
2955
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
2956
+ for (const t of ts) await this.emailOff(t.locationId, p.id, false, status);
2957
+ run.step = "monitor_all";
2958
+ for (const t of ts) await this.monitorAllOff(t.locationId);
2959
+ run.step = "release_line";
2960
+ for (const [t, n] of stray) await this.releaseLine(cust, t, n, people, p.id);
2961
+ run.step = "lines";
2962
+ let mappings = own ? mergeMappings([], mgmt.connectorId, [own]) : [];
2963
+ for (const t of ts) {
2964
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [p.id]));
2965
+ }
2966
+ if (!sameMappings(mappings, p.mappings)) await this.setMappings(cust, p.id, mappings);
2967
+ run.step = "former_teams";
2968
+ for (const t of former) await this.leaveGroups(t.locationId, p.id);
2969
+ await this.removeLocations(cust, p.id, former.map((t) => t.locationId));
2970
+ result.license = "base_manager";
2971
+ result.teams = ts.map((t) => t.locationId);
2972
+ result.lines = numbersOf(mappings);
2973
+ result.notes.push(...notes);
2974
+ }
2975
+ async toUser(cust, p, people, keep, lineArg, run, result) {
2976
+ const mgmt = cust.management;
2977
+ this.needConnector(keep);
2978
+ const mgNums = mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
2979
+ const lines = this.teamLines(keep, people, [p.id]);
2980
+ const mine = p.numbers(keep.connectorId).filter((n) => !lines.includes(n));
2981
+ const own = lineArg !== null ? line(lineArg) : mgNums[0] ?? mine[0] ?? null;
2982
+ if (!own) throw new InvalidRequestError("line: this manager has no own line at Management; pass line");
2983
+ const notes = this.emptiedGroups(cust, people, p.id, p.teams);
2984
+ const others = this.locationsOf(cust).filter((t) => t.locationId !== keep.locationId && p.locs.has(t.locationId)).map((t) => t.locationId);
2985
+ run.step = "groups";
2986
+ for (const t of this.locationsOf(cust)) if (p.locs.has(t.locationId)) await this.leaveGroups(t.locationId, p.id);
2987
+ run.step = "products";
2988
+ await this.productsOff(keep.locationId, p.id, [FIRST_ALERT, INSIGHTS_HUB]);
2989
+ await this.productsOn(keep.locationId, p.id, [AFTER_CALL]);
2990
+ run.step = "monitor_all";
2991
+ await this.monitorAllOff(keep.locationId);
2992
+ run.step = "lines";
2993
+ const target = mergeMappings([], keep.connectorId, [own]);
2994
+ if (!sameMappings(target, p.mappings)) await this.setMappings(cust, p.id, target);
2995
+ run.step = "team_lines";
2996
+ await this.attachLine(cust, keep, own, people, [p.id]);
2997
+ run.step = "locations";
2998
+ await this.addLocations(cust, p.id, [keep.locationId]);
2999
+ await this.removeLocations(cust, p.id, others);
3000
+ result.license = "base_user";
3001
+ result.teams = [keep.locationId];
3002
+ result.lines = [own];
3003
+ result.notes.push(...notes);
3004
+ }
3005
+ /**
3006
+ * Move a Base User (membership and line) to another team, or swap one of a Base Manager's teams for
3007
+ * another. Calls captured before the move stay with the old team (`Member.notes` says so). Safe to
3008
+ * run again, also after an AccountError: the move continues.
3009
+ */
3010
+ async moveUser(customer, userId, options) {
3011
+ await this.requireAdmin();
3012
+ const cust = await this.resolve(customer);
3013
+ if (!options || options.fromTeam === void 0 || options.toTeam === void 0) throw new InvalidRequestError("fromTeam and toTeam are required");
3014
+ const src = this.teamOf(cust, options.fromTeam);
3015
+ const dst = this.teamOf(cust, options.toTeam);
3016
+ if (src.locationId === dst.locationId) throw new InvalidRequestError("fromTeam and toTeam are the same team");
3017
+ const [p, people] = await this.person(cust, userId);
3018
+ const note = `Call history stays with ${src.name}: calls captured before the move remain there.`;
3019
+ const result = this.member(p);
3020
+ result.notes.push(note);
3021
+ if (!p.teams.includes(src.locationId) && p.teams.includes(dst.locationId)) return result;
3022
+ if (!p.teams.includes(src.locationId)) throw new InvalidRequestError(`User ${userId} is not on ${src.name}`);
3023
+ if (p.license === "integration") throw new InvalidRequestError(`User ${userId} is an integration user; it is on every team already`);
3024
+ const run = this.run(result);
3025
+ try {
3026
+ if (p.license === "base_manager") {
3027
+ await this.moveManager(cust, p, people, src, dst, run, result);
3028
+ } else {
3029
+ this.needConnector(dst);
3030
+ const nums = uniq([...src.connectorId ? p.numbers(src.connectorId) : [], ...p.numbers(dst.connectorId)]);
3031
+ if (nums.length !== 1) throw new InvalidRequestError("A Base User holds exactly one line; fix it with changeLine first");
3032
+ const ln = nums[0];
3033
+ run.step = "monitor_all";
3034
+ for (const t of [src, dst]) await this.monitorAllOff(t.locationId);
3035
+ run.step = "release_line";
3036
+ await this.releaseLine(cust, src, ln, people, p.id);
3037
+ run.step = "locations";
3038
+ await this.addLocations(cust, p.id, [dst.locationId]);
3039
+ run.step = "products";
3040
+ await this.productsOn(dst.locationId, p.id, [AFTER_CALL]);
3041
+ run.step = "alert_email";
3042
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
3043
+ await this.emailOff(dst.locationId, p.id, false, status);
3044
+ run.step = "line";
3045
+ const target = mergeMappings(p.mappings.filter((m) => m.connector_id !== src.connectorId), dst.connectorId, [ln]);
3046
+ if (!sameMappings(target, p.mappings)) await this.setMappings(cust, p.id, target);
3047
+ run.step = "team_lines";
3048
+ await this.attachLine(cust, dst, ln, await this.index(cust), [p.id]);
3049
+ run.step = "leave_team";
3050
+ await this.removeLocations(cust, p.id, [src.locationId]);
3051
+ result.teams = [dst.locationId];
3052
+ result.lines = [ln];
3053
+ }
3054
+ } catch (exc) {
3055
+ this.stop(run, exc);
3056
+ }
3057
+ return result;
3058
+ }
3059
+ async moveManager(cust, p, people, src, dst, run, result) {
3060
+ const notes = this.emptiedGroups(cust, people, p.id, [src.locationId]);
3061
+ run.step = "locations";
3062
+ await this.addLocations(cust, p.id, [dst.locationId]);
3063
+ run.step = "products";
3064
+ await this.productsOn(dst.locationId, p.id, PRODUCT_KEYS);
3065
+ run.step = "groups";
3066
+ await this.joinGroups(dst.locationId, p.id, GROUP_FIELDS.map((f) => dst.groups[f]));
3067
+ run.step = "alert_email";
3068
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
3069
+ await this.emailOff(dst.locationId, p.id, false, status);
3070
+ run.step = "monitor_all";
3071
+ for (const t of [src, dst]) await this.monitorAllOff(t.locationId);
3072
+ run.step = "lines";
3073
+ let mappings = p.mappings.filter((m) => m.connector_id !== src.connectorId).map((m) => ({ ...m }));
3074
+ if (dst.connectorId) mappings = mergeMappings(mappings, dst.connectorId, this.teamLines(dst, people, [p.id]));
3075
+ if (!sameMappings(mappings, p.mappings)) await this.setMappings(cust, p.id, mappings);
3076
+ run.step = "leave_team";
3077
+ if (p.locs.has(src.locationId)) await this.leaveGroups(src.locationId, p.id);
3078
+ await this.removeLocations(cust, p.id, [src.locationId]);
3079
+ result.teams = uniq([...p.teams.filter((x) => x !== src.locationId), dst.locationId]);
3080
+ result.lines = numbersOf(mappings);
3081
+ result.notes.push(...notes);
3082
+ }
3083
+ /**
3084
+ * Change a person's own line from `old` to `new`.
3085
+ *
3086
+ * A Base User: their mapping, and the team's First Alert and Insights Hub lists and holders, where
3087
+ * `old` is released only when no other Base User of the team still holds it. A Base Manager: their
3088
+ * own line at Management only; a team line belongs to the Base User who holds it, so `old` must be
3089
+ * the manager's own line.
3090
+ */
3091
+ async changeLine(customer, userId, oldLine, newLine) {
3092
+ await this.requireAdmin();
3093
+ const old = line(oldLine, "old");
3094
+ const nw = line(newLine, "new");
3095
+ const cust = await this.resolve(customer);
3096
+ const [p, people] = await this.person(cust, userId);
3097
+ const result = this.member(p);
3098
+ const mgmt = cust.management;
3099
+ if (p.license === "integration") throw new InvalidRequestError("An integration user holds every line; it has no line of its own");
3100
+ if (p.license === "base_manager") {
3101
+ const mine = mgmt && mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
3102
+ if (!mine.includes(old) && !mine.includes(nw)) {
3103
+ throw new InvalidRequestError(`${old} is not this manager's own line; a team line changes with the Base User who holds it`);
3104
+ }
3105
+ const run2 = this.run(result);
2169
3106
  try {
2170
- hook = (await c.webhooks.getAfterCallWebhook(loc)).data ?? null;
2171
- } catch (err) {
2172
- if (!(err instanceof NotFoundError)) throw err;
3107
+ run2.step = "line";
3108
+ if (mine.includes(old)) {
3109
+ await this.map(cust, p.id, mgmt.connectorId, uniq(mine.map((n) => n === old ? nw : n)), p.mappings);
3110
+ result.lines = result.lines.map((n) => n === old ? nw : n);
3111
+ }
3112
+ } catch (exc) {
3113
+ this.stop(run2, exc);
2173
3114
  }
2174
- if (hook?.webhook_url && hook.enabled !== false) {
2175
- await c.webhooks.saveAfterCallWebhook(loc, { webhook_url: hook.webhook_url, enabled: false });
2176
- result.webhookPaused = true;
3115
+ return result;
3116
+ }
3117
+ const team = cust.teams.find(
3118
+ (t) => t.connectorId && p.teams.includes(t.locationId) && (p.numbers(t.connectorId).includes(old) || p.numbers(t.connectorId).includes(nw))
3119
+ );
3120
+ if (team === void 0) throw new InvalidRequestError(`${old} is not one of this person's lines`);
3121
+ const cid = team.connectorId;
3122
+ const shared = [...this.owners(team, people, [p.id]).values()].includes(old);
3123
+ const run = this.run(result);
3124
+ const swap = (have) => {
3125
+ const out = shared ? [...have] : have.filter((n) => n !== old);
3126
+ return out.includes(nw) ? out : [...out, nw];
3127
+ };
3128
+ try {
3129
+ run.step = "monitor_all";
3130
+ await this.monitorAllOff(team.locationId);
3131
+ run.step = "line";
3132
+ const nums = p.numbers(cid);
3133
+ if (nums.includes(old)) {
3134
+ await this.map(cust, p.id, cid, uniq(nums.map((n) => n === old ? nw : n)), p.mappings);
3135
+ result.lines = uniq(result.lines.map((n) => n === old ? nw : n));
2177
3136
  }
2178
- });
2179
- await step("clear_first_alert_webhook", partial, async () => {
2180
- const cfg = (await c.firstAlert.getFirstAlertConfig(loc)).data;
2181
- if (cfg?.webhook_url) {
2182
- await c.firstAlert.setWebhookUrl(loc, null);
2183
- result.firstAlertWebhookCleared = true;
3137
+ run.step = "team_lines";
3138
+ for (const h of this.holders(team, people, [p.id])) {
3139
+ const have = h.numbers(cid);
3140
+ if (!deepEqual(swap(have), have)) await this.map(cust, h.id, cid, swap(have), h.mappings);
2184
3141
  }
2185
- });
2186
- await step("deactivate_connector", partial, async () => {
2187
- const conn = customer.connectorId ? (await c.connectors.getConnector(loc, customer.connectorId)).data ?? null : await this.bestConnector(loc);
2188
- if (conn?.id && conn.status !== "inactive" && conn.status !== "deactivating") {
2189
- try {
2190
- await c.connectors.deactivateConnector(loc, conn.id);
2191
- result.connectorDeactivated = true;
2192
- } catch (err) {
2193
- already(err);
3142
+ const targets = [
3143
+ [() => this.faNumbers(team), (n) => this.c.firstAlert.setMonitoredNumbers(team.locationId, cid, n)],
3144
+ [() => this.ihNumbers(team), (n) => this.c.insightsHub.setNumbers(team.locationId, cid, n)]
3145
+ ];
3146
+ for (const [getter, setter] of targets) {
3147
+ const have = await getter();
3148
+ if (!deepEqual(swap(have), have)) await setter(swap(have));
3149
+ }
3150
+ } catch (exc) {
3151
+ this.stop(run, exc);
3152
+ }
3153
+ return result;
3154
+ }
3155
+ /**
3156
+ * Take the person out of every group, release a Base User's line (unless `keepLines`, and only when
3157
+ * no other Base User of the team holds it), clear their lines, then deactivate them. Removing a Base
3158
+ * Manager or an integration user never takes a line off anyone else. `notes` names any team whose
3159
+ * alert groups are left with no Base Manager (its alerts are not changed).
3160
+ */
3161
+ async removeUser(customer, userId, options = {}) {
3162
+ await this.requireAdmin();
3163
+ const cust = await this.resolve(customer);
3164
+ const [p, people] = await this.person(cust, userId, true);
3165
+ if (!p.active) {
3166
+ p.mappings = unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, p.id));
3167
+ this.classify(cust, p);
3168
+ }
3169
+ const out = {
3170
+ userId,
3171
+ license: p.license,
3172
+ releasedLines: [],
3173
+ deactivated: false,
3174
+ notes: p.active ? this.emptiedGroups(cust, people, p.id, p.teams) : []
3175
+ };
3176
+ const run = this.run(out);
3177
+ try {
3178
+ run.step = "groups";
3179
+ for (const t of this.locationsOf(cust)) if (p.locs.has(t.locationId)) await this.leaveGroups(t.locationId, p.id);
3180
+ run.step = "release_lines";
3181
+ if (p.license === "base_user" && !options.keepLines) {
3182
+ for (const t of cust.teams) {
3183
+ if (p.teams.includes(t.locationId) && t.connectorId) {
3184
+ for (const n of p.numbers(t.connectorId)) {
3185
+ if (await this.releaseLine(cust, t, n, people, p.id)) out.releasedLines.push(n);
3186
+ }
3187
+ }
2194
3188
  }
2195
3189
  }
2196
- });
2197
- await step("deactivate_integration_users", partial, async () => {
2198
- for (const u of await this.listIntegrationUsers(customer)) {
3190
+ run.step = "lines";
3191
+ if (p.mappings.length) await this.setMappings(cust, p.id, []);
3192
+ run.step = "deactivate";
3193
+ if (p.active) {
2199
3194
  try {
2200
- await c.users.deactivateCompanyUser(customer.companyId, u.id);
2201
- result.integrationUsersDeactivated.push(u.id);
2202
- } catch (err) {
2203
- already(err);
3195
+ await this.c.users.deactivateCompanyUser(cust.companyId, p.id);
3196
+ out.deactivated = true;
3197
+ } catch (exc) {
3198
+ if (!(exc instanceof ConflictError)) throw exc;
2204
3199
  }
2205
3200
  }
2206
- });
2207
- if (options.deactivateCompany ?? true) {
2208
- await step("deactivate_company", partial, async () => {
2209
- try {
2210
- await c.companies.deactivateCompany(customer.companyId);
2211
- result.companyDeactivated = true;
2212
- } catch (err) {
2213
- already(err);
3201
+ } catch (exc) {
3202
+ this.stop(run, exc);
3203
+ }
3204
+ return out;
3205
+ }
3206
+ /**
3207
+ * Email invitations to people who have not signed in. Without `userIds`: everyone who was never
3208
+ * sent one, or whose invitation has expired. With `userIds`: re-send to those of them who have not
3209
+ * signed in. Returns the ids invited.
3210
+ */
3211
+ async sendInvitations(customer, options = {}) {
3212
+ await this.requireAdmin();
3213
+ const cust = await this.resolve(customer);
3214
+ const now = /* @__PURE__ */ new Date();
3215
+ const wanted = options.userIds ? new Set(options.userIds) : null;
3216
+ const sent = [];
3217
+ const run = this.run(sent);
3218
+ try {
3219
+ for (const p of (await this.index(cust)).values()) {
3220
+ if (p.status !== "invited") continue;
3221
+ if (wanted !== null) {
3222
+ if (!wanted.has(p.id)) continue;
3223
+ } else if (p.invitedAt && !expired(p.inviteExpiresAt, now)) {
3224
+ continue;
2214
3225
  }
2215
- });
3226
+ run.step = `invite:${p.id}`;
3227
+ await this.c.users.resendInvitation(cust.companyId, p.id);
3228
+ sent.push(p.id);
3229
+ }
3230
+ } catch (exc) {
3231
+ this.stop(run, exc);
2216
3232
  }
2217
- return result;
3233
+ return sent;
3234
+ }
3235
+ // ------------------------------------------------------------------ lines
3236
+ /**
3237
+ * Make the line lists match the people: every Base User's line is on their team's First Alert and
3238
+ * Insights Hub lists and on its holders; Base Managers and integration users hold exactly their
3239
+ * teams' lines on each team's connector; nothing else is listed. `dryRun: true` returns the changes
3240
+ * without making them.
3241
+ *
3242
+ * Anyone with After Call on and exactly one line on a team's connector owns that line, also when they
3243
+ * read back as "other" (listed under `other`): their line is never released.
3244
+ */
3245
+ async syncLines(customer, options = {}) {
3246
+ await this.requireAdmin();
3247
+ const cust = await this.resolve(customer);
3248
+ const people = await this.index(cust);
3249
+ const diff = { teams: {}, applied: false };
3250
+ const plans = [];
3251
+ for (const t of cust.teams) {
3252
+ if (!t.connectorId) continue;
3253
+ const owners = this.owners(t, people);
3254
+ const lines = uniq(owners.values());
3255
+ const fa = await this.faNumbers(t);
3256
+ const ih = await this.ihNumbers(t);
3257
+ const d = {
3258
+ team: t.name,
3259
+ lines,
3260
+ other: [...owners.keys()].filter((uid) => people.get(uid).license === "other"),
3261
+ firstAlert: { add: lines.filter((n) => !fa.includes(n)), remove: fa.filter((n) => !lines.includes(n)) },
3262
+ insightsHub: { add: lines.filter((n) => !ih.includes(n)), remove: ih.filter((n) => !lines.includes(n)) },
3263
+ holders: {}
3264
+ };
3265
+ for (const h of this.holders(t, people)) {
3266
+ const have = h.numbers(t.connectorId);
3267
+ const add = lines.filter((n) => !have.includes(n));
3268
+ const remove = have.filter((n) => !lines.includes(n));
3269
+ if (add.length || remove.length) d.holders[h.id] = { add, remove };
3270
+ }
3271
+ diff.teams[t.locationId] = d;
3272
+ plans.push([t, lines, d]);
3273
+ }
3274
+ if (options.dryRun) return diff;
3275
+ const run = this.run(diff);
3276
+ try {
3277
+ for (const [t, lines, d] of plans) {
3278
+ run.step = `sync:${t.name}`;
3279
+ await this.monitorAllOff(t.locationId);
3280
+ for (const uid of Object.keys(d.holders)) await this.map(cust, uid, t.connectorId, lines, people.get(uid).mappings);
3281
+ if (d.firstAlert.add.length || d.firstAlert.remove.length) await this.c.firstAlert.setMonitoredNumbers(t.locationId, t.connectorId, lines);
3282
+ if (d.insightsHub.add.length || d.insightsHub.remove.length) await this.c.insightsHub.setNumbers(t.locationId, t.connectorId, lines);
3283
+ }
3284
+ } catch (exc) {
3285
+ this.stop(run, exc);
3286
+ }
3287
+ diff.applied = true;
3288
+ return diff;
2218
3289
  }
3290
+ // ------------------------------------------------------------------ offboarding
2219
3291
  /**
2220
- * Recompute the union of end-user extensions (end users holding exactly one line) and push it to
2221
- * every manager, integration user, First Alert and Insights Hub. Managers and integration users end up with exactly
2222
- * these lines; any other number on their mapping is removed. `dryRun: true` returns the diff without writing.
3292
+ * Stop everything for a customer who leaves, at every team and at Management, in this order: pause
3293
+ * each After Call webhook (its address is kept; it can't be deleted), clear each First Alert webhook,
3294
+ * stop each connector (ends the phone-system subscription), deactivate the integration users, then
3295
+ * deactivate the company. Ask your Tresic contact about retention of the customer's data.
2223
3296
  */
2224
- async syncNumbers(ref, options = {}) {
3297
+ async offboardCustomer(customer, options = {}) {
3298
+ await this.requireAdmin();
3299
+ const cust = await this.resolve(customer);
2225
3300
  const c = this.c;
2226
- const customer = await this.resolve(ref);
2227
- const connectorId = this.requireConnector(customer);
2228
- const partial = {};
2229
- const lines = await step("read_frontline_numbers", partial, () => this.endUserLines(customer, connectorId));
2230
- const union = [...lines].sort();
2231
- const fa = await step(
2232
- "read_first_alert",
2233
- partial,
2234
- async () => numbersFor((await c.firstAlert.getFirstAlertConfig(customer.locationId)).data?.connector_mappings, connectorId)
2235
- );
2236
- const ih = await step(
2237
- "read_insights_hub",
2238
- partial,
2239
- async () => numbersFor(
2240
- (await c.insightsHub.getInsightsHubSetup(customer.locationId)).data?.attributes?.connector_mappings,
2241
- connectorId
2242
- )
2243
- );
2244
- const managers = [];
2245
- await step("read_managers", partial, async () => {
2246
- for (const m of await this.lineHolders(customer)) {
2247
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2248
- const target = union;
2249
- const d = diff(cur, target);
2250
- if (d.add.length || d.remove.length) managers.push({ userId: m.id, ...d });
3301
+ const out = {
3302
+ webhooksPaused: [],
3303
+ firstAlertWebhooksCleared: [],
3304
+ connectorsDeactivated: [],
3305
+ integrationUsersDeactivated: [],
3306
+ companyDeactivated: false
3307
+ };
3308
+ const run = this.run(out);
3309
+ try {
3310
+ const locs = this.locationsOf(cust);
3311
+ run.step = "webhooks";
3312
+ for (const t of locs) {
3313
+ const hook = await c.intelligence.getAfterCallWebhook(t.locationId) ?? {};
3314
+ if (hook.webhook_url && hook.enabled) {
3315
+ await c.intelligence.setAfterCallWebhook(t.locationId, hook.webhook_url, false);
3316
+ out.webhooksPaused.push(t.locationId);
3317
+ }
3318
+ if (await c.intelligence.getFirstAlertWebhook(t.locationId)) {
3319
+ await c.intelligence.setFirstAlertWebhook(t.locationId, null);
3320
+ out.firstAlertWebhooksCleared.push(t.locationId);
3321
+ }
2251
3322
  }
2252
- });
2253
- const result = {
2254
- dryRun: Boolean(options.dryRun),
2255
- lines: union,
2256
- managers,
2257
- firstAlert: diff(fa, union),
2258
- insightsHub: diff(ih, union)
3323
+ run.step = "connectors";
3324
+ for (const t of locs) {
3325
+ for (const row of await all(c.connectors.iterLocationConnectors(t.locationId))) {
3326
+ if (row.status === "inactive" || row.status === "deactivating") continue;
3327
+ try {
3328
+ await c.connectors.deactivateConnector(t.locationId, row.id);
3329
+ } catch (exc) {
3330
+ if (exc instanceof ConflictError) continue;
3331
+ throw exc;
3332
+ }
3333
+ out.connectorsDeactivated.push(row.id);
3334
+ }
3335
+ }
3336
+ run.step = "integration_users";
3337
+ for (const p of (await this.index(cust)).values()) {
3338
+ if (p.license !== "integration") continue;
3339
+ try {
3340
+ await c.users.deactivateCompanyUser(cust.companyId, p.id);
3341
+ } catch (exc) {
3342
+ if (exc instanceof ConflictError) continue;
3343
+ throw exc;
3344
+ }
3345
+ out.integrationUsersDeactivated.push(p.id);
3346
+ }
3347
+ run.step = "company";
3348
+ if (options.deactivateCompany ?? true) {
3349
+ const company = unwrap(await c.companies.getCompany(cust.companyId)) ?? {};
3350
+ if (company.is_active ?? true) {
3351
+ try {
3352
+ await c.companies.deactivateCompany(cust.companyId);
3353
+ out.companyDeactivated = true;
3354
+ } catch (exc) {
3355
+ if (!(exc instanceof ConflictError)) throw exc;
3356
+ }
3357
+ }
3358
+ }
3359
+ } catch (exc) {
3360
+ this.stop(run, exc);
3361
+ }
3362
+ return out;
3363
+ }
3364
+ };
3365
+ function unwrapMappings(body) {
3366
+ const d = body?.data;
3367
+ return Array.isArray(d) ? d : [];
3368
+ }
3369
+
3370
+ // src/webhooks.ts
3371
+ var MAX_EVENT_BYTES = 262144;
3372
+ function isUnknownEvent(e) {
3373
+ return e.kind === "unknown";
3374
+ }
3375
+ function parseAfterCallEvent(body, options = {}) {
3376
+ const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
3377
+ let obj = body;
3378
+ if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
3379
+ const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
3380
+ if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
3381
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
3382
+ try {
3383
+ obj = JSON.parse(text);
3384
+ } catch {
3385
+ throw new WebhookPayloadError("Body is not JSON.");
3386
+ }
3387
+ }
3388
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
3389
+ const o = obj;
3390
+ if (o.type !== "end_of_call_summary") {
3391
+ return {
3392
+ kind: "unknown",
3393
+ type: typeof o.type === "string" ? o.type : null,
3394
+ version: typeof o.version === "string" ? o.version : null,
3395
+ raw: o
2259
3396
  };
2260
- if (options.dryRun) return result;
2261
- await step("apply_managers", partial, async () => {
2262
- for (const m of managers) {
2263
- const cur = await c.users.userNumbers(customer.companyId, m.userId, connectorId);
2264
- await this.mapNumbers(customer, m.userId, [...cur.filter((n) => !m.remove.includes(n)), ...m.add]);
3397
+ }
3398
+ if (typeof o.version !== "string" || !o.version.startsWith("1.")) {
3399
+ throw new WebhookPayloadError("Unsupported event version.");
3400
+ }
3401
+ if (!o.call || typeof o.call !== "object" || typeof o.call.id !== "string" || !o.call.id) {
3402
+ throw new WebhookPayloadError("Event has no call.id.");
3403
+ }
3404
+ if (typeof o.location_id !== "string") throw new WebhookPayloadError("Event has no location_id.");
3405
+ const event = project(o, WEBHOOK_SHAPES.afterCallSummary);
3406
+ return { ...event, is_test: o.is_test === true };
3407
+ }
3408
+ var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
3409
+ var iso = (d) => d.toISOString().replace(/\.000Z$/, "Z");
3410
+ var EVENT_BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.FirstAlertEvent");
3411
+ function isFirstAlertEvent(v) {
3412
+ return v !== null && typeof v === "object" && v[EVENT_BRAND] === true;
3413
+ }
3414
+ var FirstAlertEvent = class {
3415
+ get [EVENT_BRAND]() {
3416
+ return true;
3417
+ }
3418
+ alertId;
3419
+ rule;
3420
+ locationId;
3421
+ callId;
3422
+ timestamp;
3423
+ isTest;
3424
+ constructor(f) {
3425
+ this.alertId = f.alertId;
3426
+ this.rule = f.rule ?? null;
3427
+ this.locationId = f.locationId ?? null;
3428
+ this.callId = f.callId ?? null;
3429
+ this.timestamp = f.timestamp ?? null;
3430
+ this.isTest = f.isTest ?? false;
3431
+ Object.defineProperty(this, "raw", { value: f.raw ?? {}, enumerable: false });
3432
+ }
3433
+ toString() {
3434
+ return `FirstAlertEvent(alertId='${this.alertId}', timestamp='${this.timestamp ? iso(this.timestamp) : null}')`;
3435
+ }
3436
+ toJSON() {
3437
+ return { alertId: this.alertId, timestamp: this.timestamp ? iso(this.timestamp) : null };
3438
+ }
3439
+ [INSPECT2]() {
3440
+ return this.toString();
3441
+ }
3442
+ };
3443
+ function firstStr(...values) {
3444
+ for (const v of values) if (typeof v === "string" && v.trim()) return v.trim();
3445
+ return null;
3446
+ }
3447
+ function lowerUuid(v) {
3448
+ return v !== null && isUuid(v) ? v.toLowerCase() : null;
3449
+ }
3450
+ function parseFirstAlertEvent(body, options = {}) {
3451
+ const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
3452
+ let obj = body;
3453
+ if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
3454
+ const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
3455
+ if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
3456
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
3457
+ try {
3458
+ obj = JSON.parse(text);
3459
+ } catch {
3460
+ throw new WebhookPayloadError("Body is not JSON.");
3461
+ }
3462
+ }
3463
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
3464
+ const data = obj;
3465
+ const sub = (k) => data[k] && typeof data[k] === "object" && !Array.isArray(data[k]) ? data[k] : {};
3466
+ const alert = sub("alert");
3467
+ const rule = sub("rule");
3468
+ const call = sub("call");
3469
+ const loc = sub("location");
3470
+ const alertId = lowerUuid(firstStr(data.alert_id, alert.id, data.id));
3471
+ if (alertId === null) throw new WebhookPayloadError("Event has no alert id.");
3472
+ const stamp = firstStr(data.timestamp, data.fired_at, data.created_at, alert.created_at);
3473
+ let when = null;
3474
+ if (stamp) {
3475
+ const t = new Date(stamp);
3476
+ when = Number.isNaN(t.getTime()) ? null : t;
3477
+ }
3478
+ return new FirstAlertEvent({
3479
+ alertId,
3480
+ rule: firstStr(data.rule_name, rule.name, typeof data.rule === "string" ? data.rule : null, data.alert_name, alert.rule_name, alert.name),
3481
+ locationId: lowerUuid(firstStr(data.location_id, loc.id, alert.location_id)),
3482
+ callId: lowerUuid(firstStr(data.call_id, call.id, alert.call_id)),
3483
+ timestamp: when,
3484
+ isTest: data.is_test === true,
3485
+ raw: { ...data }
3486
+ });
3487
+ }
3488
+ var MemoryDedupStore = class {
3489
+ constructor(maxSize = 1e4) {
3490
+ this.maxSize = maxSize;
3491
+ }
3492
+ maxSize;
3493
+ keys = /* @__PURE__ */ new Map();
3494
+ checkAndAdd(key) {
3495
+ if (this.keys.has(key)) {
3496
+ this.keys.delete(key);
3497
+ this.keys.set(key, true);
3498
+ return true;
3499
+ }
3500
+ this.keys.set(key, true);
3501
+ if (this.keys.size > this.maxSize) {
3502
+ const oldest = this.keys.keys().next().value;
3503
+ if (oldest !== void 0) this.keys.delete(oldest);
3504
+ }
3505
+ return false;
3506
+ }
3507
+ };
3508
+ var Deduplicator = class {
3509
+ store;
3510
+ constructor(options = {}) {
3511
+ this.store = options.store ?? new MemoryDedupStore(options.maxSize ?? 1e4);
3512
+ }
3513
+ /** True if this id was seen before. The first call for an id records it and returns false. */
3514
+ async isDuplicate(id) {
3515
+ return Boolean(await this.store.checkAndAdd(id));
3516
+ }
3517
+ /** @deprecated Use `isDuplicate` (same result). */
3518
+ seen(id) {
3519
+ return this.isDuplicate(id);
3520
+ }
3521
+ };
3522
+
3523
+ // src/conversations.ts
3524
+ var MAX_WINDOW_DAYS = 31;
3525
+ var MAX_LIMIT = 200;
3526
+ var MAX_HISTORY = 50;
3527
+ var PAGE = 100;
3528
+ var DAY_MS = 864e5;
3529
+ var INSPECT3 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
3530
+ var CALL_BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.CallBrief");
3531
+ var ALERT_BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.AlertBrief");
3532
+ var brand = (v, b) => v !== null && typeof v === "object" && v[b] === true;
3533
+ var iso2 = (d) => d ? d.toISOString().replace(/\.000Z$/, "Z") : null;
3534
+ function maskNumber(number) {
3535
+ if (!number) return number;
3536
+ const digits = String(number).replace(/\D/g, "");
3537
+ return digits.length <= 4 ? number : "***" + digits.slice(-4);
3538
+ }
3539
+ var NUMBER_RUN = /\+?\d[\d\s().-]*\d/g;
3540
+ function maskName(name) {
3541
+ if (!name) return name;
3542
+ return name.replace(NUMBER_RUN, (m) => {
3543
+ const digits = m.replace(/\D/g, "");
3544
+ return digits.length >= 5 ? "***" + digits.slice(-4) : m;
3545
+ });
3546
+ }
3547
+ function parseTime(value) {
3548
+ if (typeof value !== "string" || !value) return null;
3549
+ const d = new Date(/T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(value) ? value + "Z" : value);
3550
+ return Number.isNaN(d.getTime()) ? null : d;
3551
+ }
3552
+ function localMidnight(y, m, d) {
3553
+ return new Date(y, m - 1, d, 0, 0, 0, 0);
3554
+ }
3555
+ var DATE_ONLY2 = /^(\d{4})-(\d{2})-(\d{2})$/;
3556
+ var RFC33392 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/i;
3557
+ function camelKey(k) {
3558
+ return k.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
3559
+ }
3560
+ function camelKeys(o) {
3561
+ const out = {};
3562
+ for (const [k, v] of Object.entries(o)) out[camelKey(k)] = v;
3563
+ return out;
3564
+ }
3565
+ var TaskBrief = class {
3566
+ id;
3567
+ title;
3568
+ status;
3569
+ dueDate;
3570
+ callId;
3571
+ description;
3572
+ constructor(f) {
3573
+ this.id = f.id;
3574
+ this.title = f.title ?? null;
3575
+ this.status = f.status ?? null;
3576
+ this.dueDate = f.dueDate ?? null;
3577
+ this.callId = f.callId ?? null;
3578
+ this.description = f.description ?? null;
3579
+ }
3580
+ toString() {
3581
+ return `TaskBrief(id='${this.id}', status='${this.status}', dueDate='${this.dueDate}')`;
3582
+ }
3583
+ [INSPECT3]() {
3584
+ return this.toString();
3585
+ }
3586
+ };
3587
+ var CallBrief = class {
3588
+ id = "";
3589
+ when = null;
3590
+ /** inbound, outbound, internal, missed, forwarded or unknown. */
3591
+ direction = null;
3592
+ status = null;
3593
+ durationSeconds = null;
3594
+ callerName = null;
3595
+ /** Last four digits unless the client has `maskNumbers: false`. */
3596
+ callerNumber = null;
3597
+ calleeName = null;
3598
+ calleeNumber = null;
3599
+ summary = null;
3600
+ /** From `brief()`; empty in list results. */
3601
+ keyPoints = [];
3602
+ /** From `brief()`; see `taskCount` in list results. */
3603
+ tasks = [];
3604
+ taskCount = null;
3605
+ sentiment = null;
3606
+ sentimentScore = null;
3607
+ topics = [];
3608
+ /** Names of the alerts the call raised (`brief()` only). */
3609
+ alerts = [];
3610
+ locationId = null;
3611
+ /** The call's page in the app (an id-only address). */
3612
+ link = null;
3613
+ constructor(f = {}) {
3614
+ Object.assign(this, f);
3615
+ }
3616
+ get [CALL_BRAND]() {
3617
+ return true;
3618
+ }
3619
+ toString() {
3620
+ return `CallBrief(id='${this.id}', when='${iso2(this.when)}')`;
3621
+ }
3622
+ [INSPECT3]() {
3623
+ return this.toString();
3624
+ }
3625
+ };
3626
+ var AlertBrief = class {
3627
+ id = "";
3628
+ callId = null;
3629
+ when = null;
3630
+ /** The alert (rule) names that fired. */
3631
+ alerts = [];
3632
+ callerName = null;
3633
+ callerNumber = null;
3634
+ calleeName = null;
3635
+ calleeNumber = null;
3636
+ summary = null;
3637
+ sentiment = null;
3638
+ sentimentScore = null;
3639
+ topics = [];
3640
+ /** Who holds the alert; the API does not publish it yet. */
3641
+ holder = null;
3642
+ /** Set by `alert()`. */
3643
+ call = null;
3644
+ /** The alert's page in the app (an id-only address). */
3645
+ link = null;
3646
+ constructor(f = {}) {
3647
+ Object.assign(this, f);
3648
+ }
3649
+ get [ALERT_BRAND]() {
3650
+ return true;
3651
+ }
3652
+ toString() {
3653
+ return `AlertBrief(id='${this.id}', when='${iso2(this.when)}')`;
3654
+ }
3655
+ [INSPECT3]() {
3656
+ return this.toString();
3657
+ }
3658
+ };
3659
+ var Conversations = class _Conversations {
3660
+ constructor(c) {
3661
+ this.c = c;
3662
+ }
3663
+ c;
3664
+ me_ = null;
3665
+ // ------------------------------------------------------------------ plumbing
3666
+ async requireUser() {
3667
+ if (this.me_ === null) this.me_ = unwrap2(await this.c.account.getMe()) ?? {};
3668
+ if (this.me_.role !== "frontline_user") throw new WrongLoginError(this.me_.role ?? null, "user");
3669
+ return this.me_;
3670
+ }
3671
+ mask(n) {
3672
+ return (this.c.maskNumbers ? maskNumber(n) : n) ?? null;
3673
+ }
3674
+ maskNm(n) {
3675
+ return (this.c.maskNumbers ? maskName(n) : n) ?? null;
3676
+ }
3677
+ link(kind, id) {
3678
+ if (!id) return null;
3679
+ const page = kind === "call" ? "after-call-copilot/calls" : "first-alert-copilot/alerts";
3680
+ return `${this.c.appUrl}/${page}/${encodeURIComponent(id)}`;
3681
+ }
3682
+ static limit(limit, top) {
3683
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > top) {
3684
+ throw new InvalidRequestError(`limit: 1 to ${top}`);
3685
+ }
3686
+ return limit;
3687
+ }
3688
+ static when(value, name) {
3689
+ if (typeof value === "string") {
3690
+ if (!RFC33392.test(value.trim())) throw new InvalidRequestError(`${name}: an RFC 3339 date-time with a time zone`);
3691
+ return new Date(value.trim());
3692
+ }
3693
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) throw new InvalidRequestError(`${name}: a Date or an RFC 3339 date-time`);
3694
+ return value;
3695
+ }
3696
+ /** (start, end). Default: today (local time), or the last `defaultDays` days. At most 31 days. */
3697
+ window(day, since, until, defaultDays) {
3698
+ const has = (v) => v !== void 0 && v !== null;
3699
+ if (has(day) && (has(since) || has(until))) throw new InvalidRequestError("Pass day, or since/until, not both");
3700
+ if (has(day)) {
3701
+ let y, m, d;
3702
+ if (typeof day === "string") {
3703
+ const mm = DATE_ONLY2.exec(day.trim());
3704
+ if (!mm) throw new InvalidRequestError("day: a date (YYYY-MM-DD) or a Date");
3705
+ [y, m, d] = [Number(mm[1]), Number(mm[2]), Number(mm[3])];
3706
+ } else if (day instanceof Date && !Number.isNaN(day.getTime())) {
3707
+ [y, m, d] = [day.getFullYear(), day.getMonth() + 1, day.getDate()];
3708
+ } else {
3709
+ throw new InvalidRequestError("day: a date (YYYY-MM-DD) or a Date");
2265
3710
  }
3711
+ const start2 = localMidnight(y, m, d);
3712
+ return [start2, new Date(localMidnight(y, m, d + 1).getTime() - 1e3)];
3713
+ }
3714
+ const end = has(until) ? _Conversations.when(until, "until") : /* @__PURE__ */ new Date();
3715
+ let start;
3716
+ if (has(since)) start = _Conversations.when(since, "since");
3717
+ else if (defaultDays) start = new Date(end.getTime() - defaultDays * DAY_MS);
3718
+ else start = localMidnight(end.getFullYear(), end.getMonth() + 1, end.getDate());
3719
+ if (end.getTime() <= start.getTime()) throw new InvalidRequestError("until must be after since");
3720
+ if (end.getTime() - start.getTime() > MAX_WINDOW_DAYS * DAY_MS) throw new InvalidRequestError(`The window is at most ${MAX_WINDOW_DAYS} days`);
3721
+ return [start, end];
3722
+ }
3723
+ async teamId(team) {
3724
+ if (team === void 0 || team === null) return null;
3725
+ if (typeof team === "object" && typeof team.locationId === "string") return team.locationId;
3726
+ if (typeof team === "string" && isUuid(team.trim())) return team.trim().toLowerCase();
3727
+ if (typeof team === "string") {
3728
+ for (const t of await this.teams()) if (t.name === team) return t.locationId;
3729
+ }
3730
+ throw new InvalidRequestError(`Unknown team "${String(team)}": use a TeamRef, its location id or its name`);
3731
+ }
3732
+ static searchTerm(phone, text) {
3733
+ if (phone !== void 0 && phone !== null && text !== void 0 && text !== null) {
3734
+ throw new InvalidRequestError("Pass number or search, not both: the API has one search field");
3735
+ }
3736
+ const term = phone ?? text;
3737
+ if (term === void 0 || term === null) return void 0;
3738
+ const t = String(term).trim();
3739
+ if (t.length < 2) throw new InvalidRequestError("search terms need at least 2 characters (shorter ones are ignored by the API)");
3740
+ return t;
3741
+ }
3742
+ async pages(fetch, limit) {
3743
+ const out = [];
3744
+ let cursor;
3745
+ while (out.length < limit) {
3746
+ const page = await fetch(Math.min(PAGE, limit - out.length), cursor);
3747
+ out.push(...page.items);
3748
+ if (!page.hasMore || !page.nextCursor) break;
3749
+ cursor = page.nextCursor;
3750
+ }
3751
+ return out.slice(0, limit);
3752
+ }
3753
+ briefFromRow(row) {
3754
+ return new CallBrief({
3755
+ id: row.id ?? "",
3756
+ when: parseTime(row.call_date),
3757
+ direction: row.call_type ?? null,
3758
+ status: row.status ?? null,
3759
+ durationSeconds: row.duration ?? null,
3760
+ callerName: this.maskNm(row.caller_name),
3761
+ callerNumber: this.mask(row.caller_number),
3762
+ calleeName: this.maskNm(row.callee_name),
3763
+ calleeNumber: this.mask(row.callee_number),
3764
+ summary: row.summary ?? null,
3765
+ taskCount: row.task_count ?? null,
3766
+ sentiment: row.sentiment ?? row.sentiment_label ?? null,
3767
+ sentimentScore: row.sentiment_score ?? null,
3768
+ locationId: row.location_id ?? null,
3769
+ link: this.link("call", row.id ?? "")
2266
3770
  });
2267
- if (result.firstAlert.add.length || result.firstAlert.remove.length) {
2268
- await step("apply_first_alert", partial, () => c.firstAlert.setMonitoredNumbers(customer.locationId, connectorId, union));
3771
+ }
3772
+ alertFromRow(row) {
3773
+ return new AlertBrief({
3774
+ id: row.id ?? "",
3775
+ callId: row.call_id ?? null,
3776
+ when: parseTime(row.call_date),
3777
+ alerts: [...row.keywords ?? []],
3778
+ callerName: this.maskNm(row.caller_name),
3779
+ callerNumber: this.mask(row.caller_number),
3780
+ calleeName: this.maskNm(row.callee_name),
3781
+ calleeNumber: this.mask(row.callee_number),
3782
+ summary: row.summary ?? null,
3783
+ sentiment: row.sentiment ?? row.sentiment_label ?? null,
3784
+ sentimentScore: row.sentiment_score ?? null,
3785
+ topics: [...row.topics ?? []],
3786
+ link: this.link("alert", row.id ?? "")
3787
+ });
3788
+ }
3789
+ static taskFromRow(row) {
3790
+ return new TaskBrief({
3791
+ id: row.id ?? "",
3792
+ title: row.title,
3793
+ status: row.status,
3794
+ dueDate: row.due_date,
3795
+ callId: row.call_id,
3796
+ description: row.description
3797
+ });
3798
+ }
3799
+ // ------------------------------------------------------------------ who
3800
+ /** Who is signed in, and their teams. (Their own lines are not readable with a user login yet.) */
3801
+ async me() {
3802
+ const me = await this.requireUser();
3803
+ const name = me.display_name || [me.first_name, me.last_name].filter(Boolean).join(" ") || null;
3804
+ return {
3805
+ userId: me.id ?? "",
3806
+ email: me.email ?? null,
3807
+ name,
3808
+ role: me.role ?? null,
3809
+ companyId: me.company_id ?? null,
3810
+ teams: await this.teams(),
3811
+ lines: null
3812
+ };
3813
+ }
3814
+ /** The teams (locations) this person can see. Management is listed with `kind: "management"`. */
3815
+ async teams() {
3816
+ await this.requireUser();
3817
+ const out = [];
3818
+ for await (const loc of this.c.account.iterVisibleLocations()) {
3819
+ const name = loc.location_name ?? "";
3820
+ out.push({ locationId: loc.id ?? "", name, kind: name.endsWith(" - Management") ? "management" : "team" });
2269
3821
  }
2270
- if (result.insightsHub.add.length || result.insightsHub.remove.length) {
2271
- await step("apply_insights_hub", partial, () => c.insightsHub.setNumbers(customer.locationId, connectorId, union));
3822
+ return out;
3823
+ }
3824
+ // ------------------------------------------------------------------ calls
3825
+ /**
3826
+ * Calls, newest first, as briefs. Default: today. The window is at most 31 days and `limit` at most
3827
+ * 200. `number` and `search` share the API's one search field: pass one or the other.
3828
+ */
3829
+ async calls(options = {}) {
3830
+ await this.requireUser();
3831
+ const limit = _Conversations.limit(options.limit ?? 50, MAX_LIMIT);
3832
+ const [start, end] = this.window(options.day, options.since, options.until);
3833
+ const term = _Conversations.searchTerm(options.number, options.search);
3834
+ const lid = await this.teamId(options.team);
3835
+ const rows = await this.pages(
3836
+ (n, cursor) => this.c.calls.listCalls({ dateFrom: start, dateTo: end, search: term, locationId: lid ?? void 0, limit: n, cursor }),
3837
+ limit
3838
+ );
3839
+ return rows.map((r) => this.briefFromRow(r));
3840
+ }
3841
+ /**
3842
+ * One call: when, direction, parties, summary, key points, tasks, sentiment, topics and the alerts
3843
+ * it raised. No transcript and no recording.
3844
+ */
3845
+ async brief(callId) {
3846
+ await this.requireUser();
3847
+ const data = unwrap2(await this.c.calls.getCall(callId)) ?? {};
3848
+ const b = this.briefFromRow(data);
3849
+ const analysis = data.analysis ?? {};
3850
+ const summ = analysis.summary ?? {};
3851
+ b.summary = b.summary ?? summ.text ?? null;
3852
+ b.keyPoints = [...summ.key_points ?? []];
3853
+ b.sentiment = b.sentiment ?? analysis.sentiment?.overall ?? null;
3854
+ b.topics = (analysis.topics ?? []).filter((t) => t && typeof t === "object" && t.name).map((t) => t.name);
3855
+ b.tasks = (data.tasks ?? []).map((t) => _Conversations.taskFromRow({ ...t, call_id: b.id }));
3856
+ b.taskCount = data.task_count ?? b.tasks.length;
3857
+ if (b.when !== null) {
3858
+ const t = b.when;
3859
+ const day0 = new Date(Date.UTC(t.getUTCFullYear(), t.getUTCMonth(), t.getUTCDate()));
3860
+ const page = await this.c.alerts.listAlerts({ dateFrom: day0, dateTo: new Date(day0.getTime() + DAY_MS - 1e3), limit: PAGE });
3861
+ const names = [];
3862
+ for (const a of page.items) {
3863
+ if (a.call_id === b.id) {
3864
+ for (const k of a.keywords ?? []) if (!names.includes(k)) names.push(k);
3865
+ }
3866
+ }
3867
+ b.alerts = names;
2272
3868
  }
2273
- return result;
3869
+ return b;
3870
+ }
3871
+ /** The transcript of one call: segments with `time`, `speaker`, `name` and `text`. */
3872
+ async transcript(callId) {
3873
+ await this.requireUser();
3874
+ const data = unwrap2(await this.c.calls.getCallTranscript(callId)) ?? {};
3875
+ return data.transcript ?? [];
3876
+ }
3877
+ /**
3878
+ * A link to the call's audio that expires, or null when the call has no recording. The SDK never
3879
+ * downloads the audio. Treat the link as a secret: never log or store it.
3880
+ */
3881
+ async recordingLink(callId) {
3882
+ await this.requireUser();
3883
+ const link = await this.c.intelligence.getRecordingUrl(callId);
3884
+ return link.url ? link : null;
3885
+ }
3886
+ /** Recent briefs for one caller (the last 31 days), for use before a callback. `limit` at most 50. */
3887
+ async callerHistory(number, options = {}) {
3888
+ await this.requireUser();
3889
+ const limit = _Conversations.limit(options.limit ?? 10, MAX_HISTORY);
3890
+ const term = _Conversations.searchTerm(number, null);
3891
+ const [start, end] = this.window(null, null, null, MAX_WINDOW_DAYS);
3892
+ const rows = await this.pages((n, cursor) => this.c.calls.listCalls({ dateFrom: start, dateTo: end, search: term, limit: n, cursor }), limit);
3893
+ return rows.map((r) => this.briefFromRow(r));
3894
+ }
3895
+ // ------------------------------------------------------------------ tasks and alerts
3896
+ /** Open tasks (up to 200), each with the id of the call it came from. `due`: only tasks due that day. */
3897
+ async openTasks(options = {}) {
3898
+ await this.requireUser();
3899
+ const lid = await this.teamId(options.team);
3900
+ const rows = await this.pages(
3901
+ (n, cursor) => this.c.tasks.listTasks({ status: "open", dueOn: options.due ?? void 0, locationId: lid ?? void 0, limit: n, cursor }),
3902
+ MAX_LIMIT
3903
+ );
3904
+ return rows.map((r) => _Conversations.taskFromRow(r));
3905
+ }
3906
+ /**
3907
+ * Alerts on this person's teams, newest first. Default: today; at most 31 days and 200 alerts.
3908
+ * `status` is refused: the API has no alert status filter yet.
3909
+ */
3910
+ async alerts(options = {}) {
3911
+ await this.requireUser();
3912
+ if (options.status !== void 0 && options.status !== null) {
3913
+ throw new InvalidRequestError("status: the API has no alert status filter yet");
3914
+ }
3915
+ const limit = _Conversations.limit(options.limit ?? 50, MAX_LIMIT);
3916
+ const [start, end] = this.window(null, options.since, options.until);
3917
+ const lid = await this.teamId(options.team);
3918
+ const rows = await this.pages(
3919
+ (n, cursor) => this.c.alerts.listAlerts({ dateFrom: start, dateTo: end, locationId: lid ?? void 0, limit: n, cursor }),
3920
+ limit
3921
+ );
3922
+ return rows.map((r) => this.alertFromRow(r));
3923
+ }
3924
+ /** One alert with its call brief, or null when this login cannot see it. */
3925
+ async alert(alertId) {
3926
+ await this.requireUser();
3927
+ const aid = String(alertId).trim().toLowerCase();
3928
+ const page = await this.c.alerts.listAlerts({ search: aid, limit: 10 });
3929
+ const row = page.items.find((a) => a.id === aid);
3930
+ if (row === void 0) return null;
3931
+ const out = this.alertFromRow(row);
3932
+ if (out.callId) out.call = await this.brief(out.callId);
3933
+ return out;
3934
+ }
3935
+ /**
3936
+ * For a manager: one team's counts, alerts, open tasks and briefs (up to 200) for a day or a window of
3937
+ * at most 31 days. Default: today.
3938
+ */
3939
+ async teamView(team, options = {}) {
3940
+ await this.requireUser();
3941
+ const lid = await this.teamId(team);
3942
+ if (lid === null) throw new InvalidRequestError("team is required");
3943
+ const [start, end] = this.window(options.day, options.since, options.until);
3944
+ const first = await this.c.calls.listCalls({ dateFrom: start, dateTo: end, locationId: lid, limit: PAGE });
3945
+ let rows = [...first.items];
3946
+ if (first.hasMore && first.nextCursor) {
3947
+ rows = rows.concat((await this.c.calls.listCalls({ dateFrom: start, dateTo: end, locationId: lid, limit: PAGE, cursor: first.nextCursor })).items);
3948
+ }
3949
+ const raw = first.raw ?? {};
3950
+ const summary = raw.data && typeof raw.data === "object" ? raw.data.summary ?? {} : {};
3951
+ const counts = {};
3952
+ for (const [k, v] of Object.entries(summary)) if (Number.isInteger(v)) counts[camelKey(k)] = v;
3953
+ const alerts = await this.pages((n, cursor) => this.c.alerts.listAlerts({ dateFrom: start, dateTo: end, locationId: lid, limit: n, cursor }), MAX_LIMIT);
3954
+ const tasks = await this.pages((n, cursor) => this.c.tasks.listTasks({ status: "open", locationId: lid, limit: n, cursor }), MAX_LIMIT);
3955
+ return {
3956
+ team: lid,
3957
+ since: start,
3958
+ until: end,
3959
+ counts,
3960
+ alerts: alerts.map((a) => this.alertFromRow(a)),
3961
+ openTasks: tasks.map((t) => _Conversations.taskFromRow(t)),
3962
+ briefs: rows.slice(0, MAX_LIMIT).map((r) => this.briefFromRow(r))
3963
+ };
3964
+ }
3965
+ /**
3966
+ * What customers are raising and which topics are rising. Default: the last 7 days; at most 31.
3967
+ * Needs Insights Hub access.
3968
+ */
3969
+ async topics(options = {}) {
3970
+ await this.requireUser();
3971
+ const [start, end] = this.window(null, options.since, options.until, 7);
3972
+ const lid = await this.teamId(options.team);
3973
+ const data = unwrap2(await this.c.insights.getInsightsDashboard({ start, end, locationId: lid ?? void 0 })) ?? {};
3974
+ const stats = data.stats ?? {};
3975
+ const rising = (data.trending_topics ?? []).filter((t) => (t.percentage_change ?? 0) > 0).map((t) => {
3976
+ const { trend_data: _drop, ...rest } = t;
3977
+ return camelKeys(rest);
3978
+ }).sort((a, b) => (b.percentageChange ?? 0) - (a.percentageChange ?? 0));
3979
+ return {
3980
+ since: start,
3981
+ until: end,
3982
+ calls: { total: stats.total_calls ?? 0, answered: stats.answered_calls ?? 0, unanswered: stats.unanswered_calls ?? 0 },
3983
+ topics: (data.topic_call_volumes ?? []).map((t) => camelKeys(t)),
3984
+ rising
3985
+ };
3986
+ }
3987
+ // ------------------------------------------------------------------ passing on
3988
+ /**
3989
+ * The id and its page in the app, for passing to another system in place of content. A string is
3990
+ * taken as a call id. The link uses the client's `appUrl` (default https://app.intelligence.cloud).
3991
+ */
3992
+ reference(callOrAlert) {
3993
+ let kind;
3994
+ let id;
3995
+ if (brand(callOrAlert, CALL_BRAND)) [kind, id] = ["call", callOrAlert.id];
3996
+ else if (brand(callOrAlert, ALERT_BRAND)) [kind, id] = ["alert", callOrAlert.id];
3997
+ else if (isFirstAlertEvent(callOrAlert)) [kind, id] = ["alert", callOrAlert.alertId];
3998
+ else if (typeof callOrAlert === "string" && callOrAlert.trim()) [kind, id] = ["call", callOrAlert.trim()];
3999
+ else throw new InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id");
4000
+ return { kind, id, link: this.link(kind, id) };
4001
+ }
4002
+ /** A typed First Alert event, beside `parseAfterCallEvent`. See `parseFirstAlertEvent`. */
4003
+ parseFirstAlertEvent(payload) {
4004
+ return parseFirstAlertEvent(payload);
2274
4005
  }
2275
4006
  };
4007
+ function unwrap2(body) {
4008
+ if (body && typeof body === "object" && "data" in body) {
4009
+ const d = body.data;
4010
+ if (d && typeof d === "object" && d.attributes && typeof d.attributes === "object") return d.attributes;
4011
+ return d;
4012
+ }
4013
+ return body;
4014
+ }
2276
4015
 
2277
4016
  // src/client.ts
2278
- function uniq(xs) {
4017
+ var RUNNING = ["active", "connected"];
4018
+ var DEFAULT_APP_URL = "https://app.intelligence.cloud";
4019
+ function checkAppUrl(appUrl) {
4020
+ let u;
4021
+ try {
4022
+ u = new URL(appUrl);
4023
+ } catch {
4024
+ throw new InvalidRequestError("appUrl must be an https:// URL.");
4025
+ }
4026
+ if (u.protocol !== "https:" || !u.hostname) throw new InvalidRequestError("appUrl must be an https:// URL.");
4027
+ return appUrl.replace(/\/+$/, "");
4028
+ }
4029
+ function uniq2(xs) {
2279
4030
  return [...new Set(xs)];
2280
4031
  }
2281
4032
  var Client = class {
@@ -2300,10 +4051,18 @@ var Client = class {
2300
4051
  webhooks;
2301
4052
  /** Conversation intelligence helpers (frontline credentials). */
2302
4053
  intelligence;
2303
- /** Base Intelligence Seat workflows (admin credentials). */
2304
- workflows;
4054
+ /** Create and maintain customers: teams, people, lines, alerts (administrator login). */
4055
+ accounts;
4056
+ /** A signed-in person's own calls, tasks and alerts, with careful defaults (user login). */
4057
+ conversations;
4058
+ /** Whether `conversations` masks caller numbers. */
4059
+ maskNumbers;
4060
+ /** The app's address for page links. */
4061
+ appUrl;
2305
4062
  constructor(options) {
2306
4063
  const c = this.core = new Core(options);
4064
+ this.maskNumbers = options.maskNumbers ?? true;
4065
+ this.appUrl = checkAppUrl(options.appUrl ?? DEFAULT_APP_URL);
2307
4066
  this.resellers = makeResellers(c);
2308
4067
  this.sso = makeSso(c);
2309
4068
  this.products = makeProducts(c);
@@ -2321,7 +4080,7 @@ var Client = class {
2321
4080
  /** Turn products on for a company, keeping the others (`enabled_products` is a full replacement). */
2322
4081
  addProducts: async (companyId, productKeys) => {
2323
4082
  const cur = await companyProducts(companyId);
2324
- const next = uniq([...cur, ...productKeys]);
4083
+ const next = uniq2([...cur, ...productKeys]);
2325
4084
  if (next.length === cur.length) return companies.getCompany(companyId);
2326
4085
  return companies.updateCompany(companyId, { enabled_products: next });
2327
4086
  },
@@ -2329,7 +4088,7 @@ var Client = class {
2329
4088
  removeProducts: async (companyId, productKeys) => {
2330
4089
  const cur = await companyProducts(companyId);
2331
4090
  const next = cur.filter((k) => !productKeys.includes(k));
2332
- if (next.length === 0) throw new FilterError("A company keeps at least one product; the API ignores an empty list.");
4091
+ if (next.length === 0) throw new InvalidRequestError("A company keeps at least one product; the API ignores an empty list.");
2333
4092
  if (next.length === cur.length) return companies.getCompany(companyId);
2334
4093
  return companies.updateCompany(companyId, { enabled_products: next });
2335
4094
  },
@@ -2359,7 +4118,7 @@ var Client = class {
2359
4118
  /** Turn products on for a location, keeping the others. They must be on for the company. */
2360
4119
  addProducts: async (companyId, locationId, productKeys) => {
2361
4120
  const cur = await locationProducts(companyId, locationId);
2362
- const next = uniq([...cur, ...productKeys]);
4121
+ const next = uniq2([...cur, ...productKeys]);
2363
4122
  if (next.length === cur.length) return locations.getLocation(companyId, locationId);
2364
4123
  return locations.updateLocation(companyId, locationId, { enabled_products: next });
2365
4124
  },
@@ -2383,7 +4142,7 @@ var Client = class {
2383
4142
  this.groups = {
2384
4143
  ...groups,
2385
4144
  /** Add members to a group (`member_ids` is a full replacement underneath). */
2386
- addMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, { member_ids: uniq([...await memberIds(locationId, groupId), ...userIds]) }),
4145
+ addMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, { member_ids: uniq2([...await memberIds(locationId, groupId), ...userIds]) }),
2387
4146
  removeMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, {
2388
4147
  member_ids: (await memberIds(locationId, groupId)).filter((id) => !userIds.includes(id))
2389
4148
  }),
@@ -2391,7 +4150,7 @@ var Client = class {
2391
4150
  userGroupIds,
2392
4151
  /** Add a user to groups at a location (`group_ids` is a full replacement underneath). */
2393
4152
  addUserToGroups: async (locationId, userId, groupIds) => groups.setUserGroupMembership(locationId, userId, {
2394
- group_ids: uniq([...await userGroupIds(locationId, userId), ...groupIds])
4153
+ group_ids: uniq2([...await userGroupIds(locationId, userId), ...groupIds])
2395
4154
  }),
2396
4155
  /** Remove a user from some groups, or from every group when `groupIds` is omitted. */
2397
4156
  removeUserFromGroups: async (locationId, userId, groupIds) => groups.setUserGroupMembership(locationId, userId, {
@@ -2407,21 +4166,17 @@ var Client = class {
2407
4166
  };
2408
4167
  const connectors = makeConnectors(c);
2409
4168
  const waitForStatus = async (locationId, connectorId, final, o = {}) => {
2410
- const deadline = c.now() + (o.timeout ?? 600) * 1e3;
4169
+ const start = c.now();
4170
+ const deadline = start + (o.timeout ?? 600) * 1e3;
2411
4171
  for (; ; ) {
2412
4172
  const conn = (await connectors.getConnector(locationId, connectorId)).data ?? {};
2413
4173
  const st = conn.status ?? null;
2414
4174
  if (st === "error" && (o.raiseOnError ?? true) && !final.includes("error")) {
2415
- throw new ConnectorError(
2416
- `Connector is in error${conn.state_reason ? ` (${conn.state_reason})` : ""}.`,
2417
- conn.state_reason ?? null,
2418
- st,
2419
- conn
2420
- );
4175
+ throw new ConnectorError(conn);
2421
4176
  }
2422
4177
  if (st && final.includes(st)) return conn;
2423
4178
  if (c.now() >= deadline) {
2424
- throw new ConnectorError(`Connector did not settle in time (status ${st ?? "unknown"}).`, null, st, conn);
4179
+ throw new ConnectorTimeoutError(conn, (c.now() - start) / 1e3);
2425
4180
  }
2426
4181
  await c.sleep((o.checkInterval ?? 10) * 1e3);
2427
4182
  }
@@ -2434,17 +4189,17 @@ var Client = class {
2434
4189
  ...connectors,
2435
4190
  waitForStatus,
2436
4191
  /**
2437
- * Create a connector (202) and, by default, wait until it is `active`.
4192
+ * Create a connector (202) and, by default, wait until it is running (`active` or `connected`).
2438
4193
  * Throws `ConnectorError` with `stateReason` (e.g. `invalid_permissions`) when it ends in `error`.
2439
4194
  */
2440
- createConnector: async (locationId, body, o = {}) => settle(locationId, await connectors.createConnector(locationId, body), ["active"], o),
2441
- /** Update a connector; when it reconnects (202), wait until it is `active`. */
4195
+ createConnector: async (locationId, body, o = {}) => settle(locationId, await connectors.createConnector(locationId, body), [...RUNNING], o),
4196
+ /** Update a connector; when it reconnects (202), wait until it is running. */
2442
4197
  updateConnector: async (locationId, connectorId, body, o = {}) => {
2443
4198
  const r = await connectors.updateConnector(locationId, connectorId, body);
2444
- return r.data?.status === "connecting" ? settle(locationId, r, ["active"], o) : r;
4199
+ return r.data?.status === "connecting" ? settle(locationId, r, [...RUNNING], o) : r;
2445
4200
  },
2446
- /** Restart a connector and, by default, wait until it is `active` (ConnectorError on `error`). */
2447
- reactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.reactivateConnector(locationId, connectorId), ["active"], o),
4201
+ /** Restart a connector and, by default, wait until it is running, `active` or `connected` (ConnectorError on `error`). */
4202
+ reactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.reactivateConnector(locationId, connectorId), [...RUNNING], o),
2448
4203
  /** Stop a connector and, by default, wait until it is `inactive`. */
2449
4204
  deactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.deactivateConnector(locationId, connectorId), ["inactive"], o, false),
2450
4205
  /** The connector with exactly this name at the location, or null. */
@@ -2484,7 +4239,7 @@ var Client = class {
2484
4239
  /** Set (null clears) the location alert webhook URL, keeping the monitored numbers. */
2485
4240
  setWebhookUrl: (locationId, url) => faSave(locationId, (cfg) => ({ webhook_url: url, connector_mappings: mergeMappings(cfg.connector_mappings, "") })),
2486
4241
  /** Route a rule to more groups (`group_ids` is a full replacement underneath). */
2487
- addRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, { group_ids: uniq([...await ruleGroupIds(locationId, ruleId), ...groupIds]) }),
4242
+ addRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, { group_ids: uniq2([...await ruleGroupIds(locationId, ruleId), ...groupIds]) }),
2488
4243
  removeRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, {
2489
4244
  group_ids: (await ruleGroupIds(locationId, ruleId)).filter((id) => !groupIds.includes(id))
2490
4245
  }),
@@ -2519,7 +4274,7 @@ var Client = class {
2519
4274
  const cur = await ihSetup(locationId);
2520
4275
  return insightsHub.saveInsightsHubSetup(locationId, {
2521
4276
  connector_mappings: mergeMappings(cur.connector_mappings, ""),
2522
- group_access: uniq([...cur.group_access ?? [], ...groupIds])
4277
+ group_access: uniq2([...cur.group_access ?? [], ...groupIds])
2523
4278
  });
2524
4279
  },
2525
4280
  removeGroups: async (locationId, groupIds) => insightsHub.updateInsightsHubSetup(locationId, {
@@ -2564,14 +4319,14 @@ var Client = class {
2564
4319
  /** The user with exactly this email, or null. */
2565
4320
  findUserByEmail,
2566
4321
  /** Assign the user to more locations (`location_ids` is a full replacement underneath). */
2567
- addLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, { location_ids: uniq([...await userLocationIds(companyId, userId), ...locationIds]) }),
4322
+ addLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, { location_ids: uniq2([...await userLocationIds(companyId, userId), ...locationIds]) }),
2568
4323
  removeLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, {
2569
4324
  location_ids: (await userLocationIds(companyId, userId)).filter((id) => !locationIds.includes(id))
2570
4325
  }),
2571
4326
  /** The numbers mapped to the user (for one connector, or all). */
2572
4327
  userNumbers: async (companyId, userId, connectorId) => {
2573
4328
  const cur = await currentMappings(companyId, userId);
2574
- return connectorId ? numbersFor(cur, connectorId) : uniq(cur.flatMap((m) => m.monitored_numbers ?? []));
4329
+ return connectorId ? numbersFor(cur, connectorId) : uniq2(cur.flatMap((m) => m.monitored_numbers ?? []));
2575
4330
  },
2576
4331
  /** Map more numbers to the user for one connector (read, merge, PUT). The connector must be `active`. */
2577
4332
  addNumbers: async (companyId, userId, connectorId, numbers) => users.setUserNumberMappings(companyId, userId, {
@@ -2594,7 +4349,8 @@ var Client = class {
2594
4349
  })
2595
4350
  };
2596
4351
  this.intelligence = new Intelligence(this, options.checkRole ?? true);
2597
- this.workflows = new Workflows(this);
4352
+ this.accounts = new Accounts(this);
4353
+ this.conversations = new Conversations(this);
2598
4354
  }
2599
4355
  // ================================================================ session
2600
4356
  /** Ends ALL sessions of this user (web app and other jobs too). The SDK never calls it on its own. */
@@ -2672,167 +4428,61 @@ var Client = class {
2672
4428
  testFirstAlertWebhook(locationId, url) {
2673
4429
  return this.intelligence.testFirstAlertWebhook(locationId, url);
2674
4430
  }
2675
- // ================================================================ workflow shortcuts
2676
- provisionSeatCustomer(...a) {
2677
- return this.workflows.provisionSeatCustomer(...a);
2678
- }
2679
- getSeatCustomer(...a) {
2680
- return this.workflows.getSeatCustomer(...a);
2681
- }
2682
- addFrontlineUser(...a) {
2683
- return this.workflows.addFrontlineUser(...a);
2684
- }
2685
- addManager(...a) {
2686
- return this.workflows.addManager(...a);
2687
- }
2688
- activateSeatAlerts(...a) {
2689
- return this.workflows.activateSeatAlerts(...a);
2690
- }
2691
- changeUserExtension(...a) {
2692
- return this.workflows.changeUserExtension(...a);
2693
- }
2694
- removeUser(...a) {
2695
- return this.workflows.removeUser(...a);
2696
- }
2697
- listFrontlineUsers(...a) {
2698
- return this.workflows.listFrontlineUsers(...a);
2699
- }
2700
- listManagers(...a) {
2701
- return this.workflows.listManagers(...a);
2702
- }
2703
- addIntegrationUser(...a) {
2704
- return this.workflows.addIntegrationUser(...a);
2705
- }
2706
- listIntegrationUsers(...a) {
2707
- return this.workflows.listIntegrationUsers(...a);
2708
- }
2709
- offboardCustomer(...a) {
2710
- return this.workflows.offboardCustomer(...a);
2711
- }
2712
- syncNumbers(...a) {
2713
- return this.workflows.syncNumbers(...a);
2714
- }
2715
- };
2716
-
2717
- // src/webhooks.ts
2718
- var MAX_EVENT_BYTES = 262144;
2719
- function isUnknownEvent(e) {
2720
- return e.kind === "unknown";
2721
- }
2722
- function parseAfterCallEvent(body, options = {}) {
2723
- const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
2724
- let obj = body;
2725
- if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
2726
- const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
2727
- if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
2728
- const text = typeof body === "string" ? body : new TextDecoder().decode(body);
2729
- try {
2730
- obj = JSON.parse(text);
2731
- } catch {
2732
- throw new WebhookPayloadError("Body is not JSON.");
2733
- }
2734
- }
2735
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
2736
- const o = obj;
2737
- if (o.type !== "end_of_call_summary") {
2738
- return {
2739
- kind: "unknown",
2740
- type: typeof o.type === "string" ? o.type : null,
2741
- version: typeof o.version === "string" ? o.version : null,
2742
- raw: o
2743
- };
2744
- }
2745
- if (typeof o.version !== "string" || !o.version.startsWith("1.")) {
2746
- throw new WebhookPayloadError("Unsupported event version.");
2747
- }
2748
- if (!o.call || typeof o.call !== "object" || typeof o.call.id !== "string" || !o.call.id) {
2749
- throw new WebhookPayloadError("Event has no call.id.");
2750
- }
2751
- if (typeof o.location_id !== "string") throw new WebhookPayloadError("Event has no location_id.");
2752
- const event = project(o, WEBHOOK_SHAPES.afterCallSummary);
2753
- return { ...event, is_test: o.is_test === true };
2754
- }
2755
- var MemoryDedupStore = class {
2756
- constructor(maxSize = 1e4) {
2757
- this.maxSize = maxSize;
2758
- }
2759
- maxSize;
2760
- keys = /* @__PURE__ */ new Map();
2761
- checkAndAdd(key) {
2762
- if (this.keys.has(key)) {
2763
- this.keys.delete(key);
2764
- this.keys.set(key, true);
2765
- return true;
2766
- }
2767
- this.keys.set(key, true);
2768
- if (this.keys.size > this.maxSize) {
2769
- const oldest = this.keys.keys().next().value;
2770
- if (oldest !== void 0) this.keys.delete(oldest);
2771
- }
2772
- return false;
2773
- }
2774
- };
2775
- var Deduplicator = class {
2776
- store;
2777
- constructor(options = {}) {
2778
- this.store = options.store ?? new MemoryDedupStore(options.maxSize ?? 1e4);
2779
- }
2780
- /** True if this id was seen before. The first call for an id records it and returns false. */
2781
- async isDuplicate(id) {
2782
- return Boolean(await this.store.checkAndAdd(id));
2783
- }
2784
- /** @deprecated Use `isDuplicate` (same result). */
2785
- seen(id) {
2786
- return this.isDuplicate(id);
2787
- }
2788
4431
  };
2789
4432
 
2790
- exports.ALL_PRODUCTS = ALL_PRODUCTS;
2791
4433
  exports.ALWAYS_REMOVED_FIELDS = ALWAYS_REMOVED_FIELDS;
4434
+ exports.AccountError = AccountError;
4435
+ exports.Accounts = Accounts;
4436
+ exports.AlertBrief = AlertBrief;
2792
4437
  exports.ApiError = ApiError;
2793
4438
  exports.AuthError = AuthError;
2794
- exports.CUSTOMER_THREAT_RULE = CUSTOMER_THREAT_RULE;
4439
+ exports.CallBrief = CallBrief;
2795
4440
  exports.Client = Client;
2796
4441
  exports.ConflictError = ConflictError;
2797
4442
  exports.ConnectorError = ConnectorError;
4443
+ exports.ConnectorSpec = ConnectorSpec;
4444
+ exports.ConnectorTimeoutError = ConnectorTimeoutError;
4445
+ exports.Conversations = Conversations;
4446
+ exports.DEFAULT_APP_URL = DEFAULT_APP_URL;
2798
4447
  exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
2799
4448
  exports.Deduplicator = Deduplicator;
2800
4449
  exports.EXTENSION_CONFLICT_MESSAGE = EXTENSION_CONFLICT_MESSAGE;
2801
4450
  exports.ExtensionMappingError = ExtensionMappingError;
2802
4451
  exports.FileTokenStore = FileTokenStore;
2803
4452
  exports.FilterError = FilterError;
4453
+ exports.FirstAlertEvent = FirstAlertEvent;
2804
4454
  exports.FrontlineRequiredError = FrontlineRequiredError;
2805
- exports.INSIGHTS_HUB_ACCESS_GROUP = INSIGHTS_HUB_ACCESS_GROUP;
2806
- exports.INTEGRATION_DEPARTMENT = INTEGRATION_DEPARTMENT;
2807
4455
  exports.Intelligence = Intelligence;
2808
4456
  exports.IntelligenceCloudError = IntelligenceCloudError;
2809
- exports.MANAGER_ALERTS_GROUP = MANAGER_ALERTS_GROUP;
4457
+ exports.InvalidRequestError = InvalidRequestError;
4458
+ exports.LICENSES = LICENSES;
2810
4459
  exports.MAX_EVENT_BYTES = MAX_EVENT_BYTES;
4460
+ exports.MAX_HISTORY = MAX_HISTORY;
4461
+ exports.MAX_LIMIT = MAX_LIMIT;
2811
4462
  exports.MAX_LOCATION_IDS = MAX_LOCATION_IDS;
2812
4463
  exports.MAX_NUMBERS = MAX_NUMBERS;
2813
4464
  exports.MAX_RETRY_AFTER_MS = MAX_RETRY_AFTER_MS;
4465
+ exports.MAX_WINDOW_DAYS = MAX_WINDOW_DAYS;
2814
4466
  exports.MemoryDedupStore = MemoryDedupStore;
2815
4467
  exports.MemoryTokenStore = MemoryTokenStore;
2816
4468
  exports.MfaRequiredError = MfaRequiredError;
2817
4469
  exports.NotFoundError = NotFoundError;
4470
+ exports.PRODUCT_KEYS = PRODUCT_KEYS;
2818
4471
  exports.PasswordExpiredError = PasswordExpiredError;
2819
4472
  exports.PayloadTooLargeError = PayloadTooLargeError;
4473
+ exports.RUNNING = RUNNING;
2820
4474
  exports.RateLimitError = RateLimitError;
4475
+ exports.RecordingLink = RecordingLink;
2821
4476
  exports.SDK_VERSION = SDK_VERSION;
2822
- exports.THREAT_PHRASES_MISSING = THREAT_PHRASES_MISSING;
2823
- exports.UPSET_CUSTOMER_RULE = UPSET_CUSTOMER_RULE;
4477
+ exports.TaskBrief = TaskBrief;
2824
4478
  exports.ValidationError = ValidationError;
2825
4479
  exports.WebhookPayloadError = WebhookPayloadError;
2826
- exports.WorkflowError = WorkflowError;
2827
- exports.Workflows = Workflows;
4480
+ exports.WrongLoginError = WrongLoginError;
2828
4481
  exports.alertNumber = alertNumber;
2829
- exports.companyNameConflictMessage = companyNameConflictMessage;
2830
- exports.customerThreatRule = customerThreatRule;
2831
4482
  exports.digitsOnly = digitsOnly;
2832
- exports.isFrontline = isFrontline;
2833
- exports.isIntegration = isIntegration;
2834
- exports.isManager = isManager;
2835
4483
  exports.isUnknownEvent = isUnknownEvent;
4484
+ exports.maskName = maskName;
4485
+ exports.maskNumber = maskNumber;
2836
4486
  exports.parseAfterCallEvent = parseAfterCallEvent;
4487
+ exports.parseFirstAlertEvent = parseFirstAlertEvent;
2837
4488
  exports.toRfc3339 = toRfc3339;
2838
- exports.upsetCustomerRule = upsetCustomerRule;