@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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/generated/spec.ts
2
- 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" } };
2
+ 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" } };
3
3
  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" } } } }};
4
4
 
5
5
  // src/errors.ts
@@ -62,17 +62,36 @@ var RateLimitError = class extends ApiError {
62
62
  this.retryAfter = retryAfter;
63
63
  }
64
64
  };
65
- var FilterError = class extends IntelligenceCloudError {
65
+ var InvalidRequestError = class extends IntelligenceCloudError {
66
66
  };
67
+ var FilterError = InvalidRequestError;
67
68
  var ConnectorError = class extends IntelligenceCloudError {
69
+ connectorId;
68
70
  stateReason;
71
+ statusMessage;
69
72
  status;
70
73
  connector;
71
- constructor(message, stateReason, status, connector) {
72
- super(message);
73
- this.stateReason = stateReason;
74
- this.status = status;
74
+ constructor(connector) {
75
+ const c = connector ?? {};
76
+ const id = typeof c.id === "string" ? c.id : null;
77
+ const reason = typeof c.state_reason === "string" ? c.state_reason : null;
78
+ super(`Connector ${id ?? "unknown"} is in error: ${reason ?? "unknown reason"}`);
79
+ this.connector = connector;
80
+ this.connectorId = id;
81
+ this.status = typeof c.status === "string" ? c.status : null;
82
+ this.stateReason = reason;
83
+ this.statusMessage = typeof c.status_message === "string" ? c.status_message : null;
84
+ }
85
+ };
86
+ var ConnectorTimeoutError = class extends IntelligenceCloudError {
87
+ connector;
88
+ status;
89
+ constructor(connector, waitedSeconds) {
90
+ const c = connector ?? {};
91
+ const status = typeof c.status === "string" ? c.status : null;
92
+ super(`Connector ${typeof c.id === "string" ? c.id : "unknown"} still "${status ?? "unknown"}" after ${Math.round(waitedSeconds)} s`);
75
93
  this.connector = connector;
94
+ this.status = status;
76
95
  }
77
96
  };
78
97
  var FrontlineRequiredError = class extends IntelligenceCloudError {
@@ -84,14 +103,25 @@ var FrontlineRequiredError = class extends IntelligenceCloudError {
84
103
  this.role = role;
85
104
  }
86
105
  };
87
- var WorkflowError = class extends IntelligenceCloudError {
106
+ var AccountError = class extends IntelligenceCloudError {
88
107
  step;
89
- partial;
90
- constructor(step2, partial, cause) {
108
+ result;
109
+ constructor(step, result, cause) {
91
110
  const why = cause instanceof Error ? cause.message : String(cause);
92
- super(`Workflow stopped at "${step2}": ${why}`, { cause });
93
- this.step = step2;
94
- this.partial = partial;
111
+ super(`Stopped at step "${step}": ${why}. Run the helper again to continue.`, { cause });
112
+ this.step = step;
113
+ this.result = result;
114
+ }
115
+ };
116
+ var WrongLoginError = class extends IntelligenceCloudError {
117
+ role;
118
+ needed;
119
+ constructor(role, needed) {
120
+ super(
121
+ 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.`
122
+ );
123
+ this.role = role;
124
+ this.needed = needed;
95
125
  }
96
126
  };
97
127
  var ExtensionMappingError = class extends IntelligenceCloudError {
@@ -125,31 +155,31 @@ function toRfc3339(value, name) {
125
155
  d = value;
126
156
  } else if (typeof value === "string") {
127
157
  if (DATE_ONLY.test(value)) {
128
- throw new FilterError(`"${name}" needs a full timestamp, e.g. ${value}T00:00:00Z. A date alone is refused.`);
158
+ throw new InvalidRequestError(`"${name}" needs a full timestamp, e.g. ${value}T00:00:00Z. A date alone is refused.`);
129
159
  }
130
160
  if (!RFC3339.test(value)) {
131
- throw new FilterError(`"${name}" must be a full RFC 3339 timestamp with an offset, e.g. 2026-11-01T00:00:00Z.`);
161
+ throw new InvalidRequestError(`"${name}" must be a full RFC 3339 timestamp with an offset, e.g. 2026-11-01T00:00:00Z.`);
132
162
  }
133
163
  d = new Date(value);
134
164
  } else {
135
- throw new FilterError(`"${name}" must be a Date or an RFC 3339 timestamp string.`);
165
+ throw new InvalidRequestError(`"${name}" must be a Date or an RFC 3339 timestamp string.`);
136
166
  }
137
- if (Number.isNaN(d.getTime())) throw new FilterError(`"${name}" is not a valid date.`);
167
+ if (Number.isNaN(d.getTime())) throw new InvalidRequestError(`"${name}" is not a valid date.`);
138
168
  return d.toISOString().replace(/\.000Z$/, "Z");
139
169
  }
140
170
  function toDateOnly(value, name) {
141
171
  if (value instanceof Date) {
142
- if (Number.isNaN(value.getTime())) throw new FilterError(`"${name}" is not a valid date.`);
172
+ if (Number.isNaN(value.getTime())) throw new InvalidRequestError(`"${name}" is not a valid date.`);
143
173
  const y = value.getFullYear();
144
174
  const m = String(value.getMonth() + 1).padStart(2, "0");
145
175
  const d = String(value.getDate()).padStart(2, "0");
146
176
  return `${y}-${m}-${d}`;
147
177
  }
148
178
  if (typeof value === "string" && DATE_ONLY.test(value)) return value;
149
- throw new FilterError(`"${name}" must be a calendar date (YYYY-MM-DD) or a Date.`);
179
+ throw new InvalidRequestError(`"${name}" must be a calendar date (YYYY-MM-DD) or a Date.`);
150
180
  }
151
181
  function uuid(value, name) {
152
- if (typeof value !== "string" || !UUID.test(value)) throw new FilterError(`"${name}" must be a UUID.`);
182
+ if (typeof value !== "string" || !UUID.test(value)) throw new InvalidRequestError(`"${name}" must be a UUID.`);
153
183
  return value.toLowerCase();
154
184
  }
155
185
  function digitsOnly(value) {
@@ -161,13 +191,13 @@ function alertNumber(value) {
161
191
  }
162
192
  function scalar(rule, value, name) {
163
193
  if (rule.type === "boolean") {
164
- if (typeof value !== "boolean") throw new FilterError(`"${name}" must be true or false.`);
194
+ if (typeof value !== "boolean") throw new InvalidRequestError(`"${name}" must be true or false.`);
165
195
  return value ? "true" : "false";
166
196
  }
167
197
  if (rule.type === "integer" || rule.type === "number") {
168
- if (typeof value !== "number" || !Number.isInteger(value)) throw new FilterError(`"${name}" must be an integer.`);
169
- if (rule.minimum !== void 0 && value < rule.minimum) throw new FilterError(`"${name}" must be at least ${rule.minimum}.`);
170
- if (rule.maximum !== void 0 && value > rule.maximum) throw new FilterError(`"${name}" must be at most ${rule.maximum}.`);
198
+ if (typeof value !== "number" || !Number.isInteger(value)) throw new InvalidRequestError(`"${name}" must be an integer.`);
199
+ if (rule.minimum !== void 0 && value < rule.minimum) throw new InvalidRequestError(`"${name}" must be at least ${rule.minimum}.`);
200
+ if (rule.maximum !== void 0 && value > rule.maximum) throw new InvalidRequestError(`"${name}" must be at most ${rule.maximum}.`);
171
201
  return String(value);
172
202
  }
173
203
  if (rule.format === "date-time") return toRfc3339(value, name);
@@ -175,44 +205,44 @@ function scalar(rule, value, name) {
175
205
  if (rule.format === "uuid") return uuid(value, name);
176
206
  if (rule.enum && rule.enum.length === 1 && rule.enum[0] === "true") {
177
207
  if (value === true || value === "true") return "true";
178
- throw new FilterError(`"${name}" only supports true. Leave it out to include every record.`);
208
+ throw new InvalidRequestError(`"${name}" only supports true. Leave it out to include every record.`);
179
209
  }
180
- if (typeof value !== "string") throw new FilterError(`"${name}" must be a string.`);
210
+ if (typeof value !== "string") throw new InvalidRequestError(`"${name}" must be a string.`);
181
211
  if (rule.enum && !rule.enum.includes(value)) {
182
- throw new FilterError(`"${name}" must be one of: ${rule.enum.join(", ")}.`);
212
+ throw new InvalidRequestError(`"${name}" must be one of: ${rule.enum.join(", ")}.`);
183
213
  }
184
214
  if (rule.minLength !== void 0 && value.trim().length < rule.minLength) {
185
- throw new FilterError(`"${name}" needs at least ${rule.minLength} characters; shorter values are ignored by the API.`);
215
+ throw new InvalidRequestError(`"${name}" needs at least ${rule.minLength} characters; shorter values are ignored by the API.`);
186
216
  }
187
217
  return value;
188
218
  }
189
219
  function list(rule, value, name) {
190
220
  const raw = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : null;
191
- if (!raw) throw new FilterError(`"${name}" must be a list.`);
221
+ if (!raw) throw new InvalidRequestError(`"${name}" must be a list.`);
192
222
  let entries = raw.map((v) => typeof v === "string" ? v.trim() : v);
193
223
  if (rule.name === "numbers") {
194
224
  entries = entries.map((v) => {
195
- if (typeof v !== "string" && typeof v !== "number") throw new FilterError(`"${name}" entries must be strings.`);
225
+ if (typeof v !== "string" && typeof v !== "number") throw new InvalidRequestError(`"${name}" entries must be strings.`);
196
226
  const d = alertNumber(String(v));
197
- if (!d) throw new FilterError(`"${name}" entries must contain digits.`);
227
+ if (!d) throw new InvalidRequestError(`"${name}" entries must contain digits.`);
198
228
  return d;
199
229
  });
200
230
  } else if (rule.items?.format === "uuid") {
201
231
  entries = entries.map((v) => uuid(v, name));
202
232
  } else {
203
233
  entries = entries.map((v) => {
204
- if (typeof v !== "string" || v === "") throw new FilterError(`"${name}" entries must be non-empty strings.`);
234
+ if (typeof v !== "string" || v === "") throw new InvalidRequestError(`"${name}" entries must be non-empty strings.`);
205
235
  if (rule.items?.enum && !rule.items.enum.includes(v)) {
206
- throw new FilterError(`"${name}" entries must be one of: ${rule.items.enum.join(", ")}.`);
236
+ throw new InvalidRequestError(`"${name}" entries must be one of: ${rule.items.enum.join(", ")}.`);
207
237
  }
208
238
  return v;
209
239
  });
210
240
  }
211
241
  const unique = [...new Set(entries)];
212
- if (unique.length === 0) throw new FilterError(`"${name}" must not be empty.`);
242
+ if (unique.length === 0) throw new InvalidRequestError(`"${name}" must not be empty.`);
213
243
  const max = rule.name === "location_id" ? Math.min(MAX_LOCATION_IDS, rule.maxItems ?? MAX_LOCATION_IDS) : rule.maxItems;
214
244
  if (max !== void 0 && unique.length > max) {
215
- throw new FilterError(`"${name}" takes at most ${max} entries per request.`);
245
+ throw new InvalidRequestError(`"${name}" takes at most ${max} entries per request.`);
216
246
  }
217
247
  return unique.join(",");
218
248
  }
@@ -228,13 +258,13 @@ function buildQuery(operationId, rules, options) {
228
258
  const rule = byKey.get(key);
229
259
  if (!rule) {
230
260
  const supported = rules.map((r) => camel(r.name)).join(", ") || "none";
231
- throw new FilterError(`"${key}" is not a filter of ${operationId}. Supported: ${supported}.`);
261
+ throw new InvalidRequestError(`"${key}" is not a filter of ${operationId}. Supported: ${supported}.`);
232
262
  }
233
- if (rule.name in out) throw new FilterError(`"${key}" was given twice.`);
263
+ if (rule.name in out) throw new InvalidRequestError(`"${key}" was given twice.`);
234
264
  out[rule.name] = rule.type === "array" ? list(rule, value, key) : scalar(rule, value, key);
235
265
  }
236
266
  for (const r of rules) {
237
- if (r.required && !(r.name in out)) throw new FilterError(`"${camel(r.name)}" is required for ${operationId}.`);
267
+ if (r.required && !(r.name in out)) throw new InvalidRequestError(`"${camel(r.name)}" is required for ${operationId}.`);
238
268
  }
239
269
  return out;
240
270
  }
@@ -373,7 +403,7 @@ var FileTokenStore = class {
373
403
 
374
404
  // src/core.ts
375
405
  var DEFAULT_BASE_URL = "https://app.intelligence.cloud/api/v1";
376
- var SDK_VERSION = "0.1.0";
406
+ var SDK_VERSION = "0.2.0";
377
407
  var SUPPRESS_ERROR_TEXT = /* @__PURE__ */ new Set(["testConnector", "testAfterCallWebhook", "testFirstAlertWebhook"]);
378
408
  var NUMBER_MAPPING_OPS = /* @__PURE__ */ new Set(["setUserNumberMappings", "updateUserAfterCallSettings"]);
379
409
  var LOGIN_RATE_LIMIT_WAIT_S = 60;
@@ -398,11 +428,11 @@ function checkBaseUrl(baseUrl) {
398
428
  try {
399
429
  u = new URL(baseUrl);
400
430
  } catch {
401
- throw new FilterError(`baseUrl "${baseUrl}" is not a URL.`);
431
+ throw new InvalidRequestError(`baseUrl "${baseUrl}" is not a URL.`);
402
432
  }
403
433
  if (u.protocol === "https:") return baseUrl;
404
434
  if (u.protocol === "http:" && LOCAL_HOSTS.has(u.hostname)) return baseUrl;
405
- throw new FilterError("baseUrl must use https:// (plain http is accepted for localhost only).");
435
+ throw new InvalidRequestError("baseUrl must use https:// (plain http is accepted for localhost only).");
406
436
  }
407
437
  var Core = class {
408
438
  baseUrl;
@@ -419,6 +449,8 @@ var Core = class {
419
449
  random;
420
450
  now;
421
451
  renewing = null;
452
+ /** Write requests (anything but GET) attempted by this client. Account helpers use it to tell a clean stop from a partial one. */
453
+ writes = 0;
422
454
  constructor(opts) {
423
455
  if (!opts || !opts.email || !opts.password) {
424
456
  throw new TypeError("email and password are required (a dedicated integration user with MFA off).");
@@ -445,6 +477,7 @@ var Core = class {
445
477
  const op = OPERATIONS[operationId];
446
478
  const query = buildQuery(operationId, op.query, opts.query ?? {});
447
479
  const url = this.url(op, pathArgs, query);
480
+ if (op.method !== "GET") this.writes++;
448
481
  const res = await this.send(op.method, url, {
449
482
  body: op.hasBody ? opts.body ?? {} : void 0,
450
483
  headers: opts.headers,
@@ -1095,6 +1128,21 @@ function makeWebhooks(c) {
1095
1128
  }
1096
1129
 
1097
1130
  // src/intelligence.ts
1131
+ var RecordingLink = class {
1132
+ constructor(url, expiresAt) {
1133
+ this.url = url;
1134
+ this.expiresAt = expiresAt;
1135
+ const show = () => ({ url: this.url === null ? null : "***", expiresAt: this.expiresAt });
1136
+ Object.defineProperty(this, "toJSON", { value: show, enumerable: false });
1137
+ Object.defineProperty(this, "toString", { value: () => `RecordingLink(${JSON.stringify(show())})`, enumerable: false });
1138
+ Object.defineProperty(this, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
1139
+ value: (_d, o, inspect) => inspect ? `RecordingLink ${inspect(show(), o)}` : `RecordingLink(${JSON.stringify(show())})`,
1140
+ enumerable: false
1141
+ });
1142
+ }
1143
+ url;
1144
+ expiresAt;
1145
+ };
1098
1146
  var CALL_FILTERS = [
1099
1147
  "phone",
1100
1148
  "text",
@@ -1141,7 +1189,7 @@ function only(given, allowed, method) {
1141
1189
  for (const [k, v] of Object.entries(given)) {
1142
1190
  if (v === void 0) continue;
1143
1191
  if (!allowed.includes(k)) {
1144
- throw new FilterError(`"${k}" is not a filter of ${method}. Supported: ${allowed.join(", ")}.`);
1192
+ throw new InvalidRequestError(`"${k}" is not a filter of ${method}. Supported: ${allowed.join(", ")}.`);
1145
1193
  }
1146
1194
  }
1147
1195
  }
@@ -1183,7 +1231,7 @@ var Intelligence = class {
1183
1231
  callQuery(f) {
1184
1232
  only(f, CALL_FILTERS, "searchCalls");
1185
1233
  if (f.phone !== void 0 && f.text !== void 0) {
1186
- throw new FilterError("Give phone or text, not both: the API has one search field.");
1234
+ throw new InvalidRequestError("Give phone or text, not both: the API has one search field.");
1187
1235
  }
1188
1236
  return {
1189
1237
  date_from: f.dateFrom,
@@ -1233,7 +1281,7 @@ var Intelligence = class {
1233
1281
  async getRecordingUrl(callId) {
1234
1282
  const call = await this.getCall(callId);
1235
1283
  const v = call.vcon;
1236
- return { url: v?.recording_url ?? null, expiresAt: v?.recording_url_expires_at ?? null };
1284
+ return new RecordingLink(v?.recording_url ?? null, v?.recording_url_expires_at ?? null);
1237
1285
  }
1238
1286
  // ------------------------------------------------------------------ alerts
1239
1287
  alertQuery(f) {
@@ -1271,7 +1319,7 @@ var Intelligence = class {
1271
1319
  async getAlert(alertId, options = {}) {
1272
1320
  const id = alertId.trim().toLowerCase();
1273
1321
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) {
1274
- throw new FilterError("alertId must be a UUID.");
1322
+ throw new InvalidRequestError("alertId must be a UUID.");
1275
1323
  }
1276
1324
  const page = await this.searchAlerts({ text: id, limit: 10 });
1277
1325
  const alert = page.items.find((a) => (a.id ?? "").toLowerCase() === id);
@@ -1328,7 +1376,7 @@ var Intelligence = class {
1328
1376
  * whatever users' number mappings say. `enabled: false` pauses it (there is no delete).
1329
1377
  */
1330
1378
  async setAfterCallWebhook(locationId, url, enabled = true) {
1331
- if (!/^https:\/\//i.test(url)) throw new FilterError("The webhook URL must use HTTPS.");
1379
+ if (!/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1332
1380
  const r = await this.c.webhooks.saveAfterCallWebhook(locationId, { webhook_url: url, enabled });
1333
1381
  return r.data ?? {};
1334
1382
  }
@@ -1346,13 +1394,13 @@ var Intelligence = class {
1346
1394
  * configuration PUT would otherwise clear the monitored numbers.
1347
1395
  */
1348
1396
  async setFirstAlertWebhook(locationId, url) {
1349
- if (url !== null && !/^https:\/\//i.test(url)) throw new FilterError("The webhook URL must use HTTPS.");
1397
+ if (url !== null && !/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1350
1398
  return (await this.c.firstAlert.setWebhookUrl(locationId, url)).data ?? {};
1351
1399
  }
1352
1400
  /** Send a test request to `url` (default: the saved URL). Returns only success and your endpoint's status. */
1353
1401
  async testFirstAlertWebhook(locationId, url) {
1354
1402
  const target = url ?? await this.getFirstAlertWebhook(locationId);
1355
- if (!target) throw new FilterError("No First Alert webhook URL is set for this location; pass one.");
1403
+ if (!target) throw new InvalidRequestError("No First Alert webhook URL is set for this location; pass one.");
1356
1404
  const d = (await this.c.firstAlert.testFirstAlertWebhook(locationId, { url: target })).data ?? {};
1357
1405
  return { success: Boolean(d.success), http_status: d.status_code ?? null };
1358
1406
  }
@@ -1393,887 +1441,2590 @@ function mergeMappings(current, connectorId, add = [], remove = []) {
1393
1441
  byConnector.set(connectorId, mine);
1394
1442
  const out = [];
1395
1443
  for (const [connector_id, nums] of byConnector) {
1396
- const uniq2 = [...new Set(nums)];
1397
- if (uniq2.length) out.push({ connector_id, monitored_numbers: uniq2 });
1444
+ const uniq3 = [...new Set(nums)];
1445
+ if (uniq3.length) out.push({ connector_id, monitored_numbers: uniq3 });
1398
1446
  }
1399
1447
  return out;
1400
1448
  }
1401
- function sameSet(a, b) {
1402
- const sa = new Set(a);
1403
- const sb = new Set(b);
1404
- if (sa.size !== sb.size) return false;
1405
- for (const x of sa) if (!sb.has(x)) return false;
1406
- return true;
1449
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1450
+ function isUuid(value) {
1451
+ return typeof value === "string" && UUID_RE.test(value);
1452
+ }
1453
+
1454
+ // src/secrets.ts
1455
+ var SECRET_WORDS = ["key", "secret", "token", "password", "passwd", "pwd", "credential", "auth"];
1456
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
1457
+ function isSecretName(name) {
1458
+ const low = String(name).toLowerCase();
1459
+ return SECRET_WORDS.some((w) => low.includes(w));
1460
+ }
1461
+ function isPlainObject(v) {
1462
+ if (v === null || typeof v !== "object") return false;
1463
+ const proto = Object.getPrototypeOf(v);
1464
+ return proto === Object.prototype || proto === null;
1465
+ }
1466
+ function maskedConfig(value) {
1467
+ if (Array.isArray(value)) return value.map(maskedConfig);
1468
+ if (isPlainObject(value)) {
1469
+ const out = {};
1470
+ for (const k of Object.keys(value)) out[k] = isSecretName(k) ? "***" : maskedConfig(value[k]);
1471
+ return out;
1472
+ }
1473
+ return value;
1474
+ }
1475
+ function plainConfig(value) {
1476
+ if (Array.isArray(value)) return value.map((v) => plainConfig(v));
1477
+ if (isPlainObject(value)) {
1478
+ const out = {};
1479
+ for (const k of Object.keys(value)) out[k] = plainConfig(value[k]);
1480
+ return out;
1481
+ }
1482
+ return value;
1483
+ }
1484
+ var guarded = /* @__PURE__ */ new WeakSet();
1485
+ var BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.ConnectorSpec");
1486
+ function isConnectorSpec(v) {
1487
+ return v !== null && typeof v === "object" && v[BRAND] === true;
1488
+ }
1489
+ var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
1490
+ function assertSafeKeys(value) {
1491
+ if (Array.isArray(value)) value.forEach(assertSafeKeys);
1492
+ else if (value !== null && typeof value === "object") {
1493
+ for (const k of Object.keys(value)) {
1494
+ if (UNSAFE_KEYS.includes(k)) throw new InvalidRequestError(`ConnectorSpec.config: "${k}" is not allowed as a setting name`);
1495
+ assertSafeKeys(value[k]);
1496
+ }
1497
+ }
1498
+ }
1499
+ function hide(target, show) {
1500
+ const text = () => JSON.stringify(show());
1501
+ Object.defineProperty(target, "toJSON", { value: show, enumerable: false });
1502
+ Object.defineProperty(target, "toString", { value: text, enumerable: false });
1503
+ Object.defineProperty(target, INSPECT, {
1504
+ value: (_depth, options, inspect) => inspect ? inspect(show(), options) : text(),
1505
+ enumerable: false
1506
+ });
1407
1507
  }
1408
- function diff(current, target) {
1409
- const c = new Set(current);
1410
- const t = new Set(target);
1411
- return { add: [...t].filter((x) => !c.has(x)), remove: [...c].filter((x) => !t.has(x)) };
1508
+ function guardConfig(value) {
1509
+ if (value === null || typeof value !== "object") return value;
1510
+ if (guarded.has(value)) return value;
1511
+ if (!Array.isArray(value) && !isPlainObject(value)) return value;
1512
+ assertSafeKeys(value);
1513
+ const target = Array.isArray(value) ? [] : /* @__PURE__ */ Object.create(null);
1514
+ for (const k of Object.keys(value)) target[k] = guardConfig(value[k]);
1515
+ hide(target, () => maskedConfig(target));
1516
+ const proxy = new Proxy(target, {
1517
+ set(t, k, v) {
1518
+ if (typeof k === "string" && UNSAFE_KEYS.includes(k)) throw new InvalidRequestError(`ConnectorSpec.config: "${k}" is not allowed as a setting name`);
1519
+ t[k] = typeof k === "string" ? guardConfig(v) : v;
1520
+ return true;
1521
+ }
1522
+ });
1523
+ guarded.add(proxy);
1524
+ return proxy;
1412
1525
  }
1526
+ var ConnectorSpec = class _ConnectorSpec {
1527
+ type;
1528
+ /** Default `"<team name> phone system"`. */
1529
+ name;
1530
+ /** Seconds to wait for a new connector to settle. Default 600. */
1531
+ timeout;
1532
+ constructor(type, config, options = {}) {
1533
+ this.type = type;
1534
+ this.name = options.name;
1535
+ this.timeout = options.timeout ?? 600;
1536
+ Object.defineProperty(this, "_config", { value: void 0, writable: true, enumerable: false });
1537
+ this.config = config;
1538
+ }
1539
+ /** The platform's settings. Values whose names contain key, secret, token, password, passwd, pwd, credential or auth print as `***`. */
1540
+ get config() {
1541
+ return this._config;
1542
+ }
1543
+ set config(value) {
1544
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1545
+ throw new InvalidRequestError("ConnectorSpec.config must be an object");
1546
+ }
1547
+ this._config = guardConfig({ ...value });
1548
+ }
1549
+ /** The documented phone system: its API root (ending in /ns-api/v2), its domain and a read/write key. */
1550
+ static netsapiens(apiUrl, domain, apiKey, options = {}) {
1551
+ return new _ConnectorSpec("netsapiens", { api_url: apiUrl, domain, api_key: apiKey }, options);
1552
+ }
1553
+ get [BRAND]() {
1554
+ return true;
1555
+ }
1556
+ toJSON() {
1557
+ return { type: this.type, config: maskedConfig(this._config), name: this.name ?? null, timeout: this.timeout };
1558
+ }
1559
+ toString() {
1560
+ return `ConnectorSpec(${JSON.stringify(this.toJSON())})`;
1561
+ }
1562
+ [INSPECT](_depth, options, inspect) {
1563
+ return inspect ? `ConnectorSpec ${inspect(this.toJSON(), options)}` : this.toString();
1564
+ }
1565
+ };
1413
1566
 
1414
- // src/workflows.ts
1415
- var ALL_PRODUCTS = ["after-call-copilot", "first-alert-copilot", "insights-hub"];
1416
- var MANAGER_ALERTS_GROUP = "Manager Alerts";
1417
- var INSIGHTS_HUB_ACCESS_GROUP = "Insights Hub Access";
1418
- var UPSET_CUSTOMER_RULE = "Upset Customer";
1419
- var CUSTOMER_THREAT_RULE = "Customer Threat";
1420
- var DEFAULT_VERTICAL_KEY = "csps-msps";
1421
- var THREAT_PHRASES_MISSING = "Customer Threat phrases are provided by your Tresic contact.";
1567
+ // src/accounts.ts
1568
+ var PRODUCT_KEYS = ["after-call-copilot", "first-alert-copilot", "insights-hub"];
1569
+ var AFTER_CALL = "after-call-copilot";
1570
+ var FIRST_ALERT = "first-alert-copilot";
1571
+ var INSIGHTS_HUB = "insights-hub";
1422
1572
  var INTEGRATION_DEPARTMENT = "integration";
1423
- function companyNameConflictMessage(name) {
1424
- 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.`;
1573
+ var COMPANY_NAME_CONFLICT = "company_name_conflict";
1574
+ var MANAGEMENT_SUFFIX = " - Management";
1575
+ var TEAM_GROUPS = {
1576
+ customerThreats: "Customer Threats",
1577
+ upsetCustomers: "Upset Customers",
1578
+ lowSentimentCalls: "Low Sentiment Calls",
1579
+ insightsHubAccess: "Insights Hub Access",
1580
+ weeklyReports: "Insights Hub Weekly Reports"
1581
+ };
1582
+ var GROUP_FIELDS = Object.keys(TEAM_GROUPS);
1583
+ var ALERT_GROUPS = ["customerThreats", "upsetCustomers", "lowSentimentCalls"];
1584
+ var RULES = {
1585
+ customerThreat: { name: "Customer Threat", priority: "high", hasPhrases: true, defaultLevel: -20, group: "customerThreats" },
1586
+ upsetCustomer: { name: "Upset Customer", priority: "medium", hasPhrases: true, defaultLevel: -20, group: "upsetCustomers" },
1587
+ lowSentiment: { name: "Low Sentiment", priority: "low", hasPhrases: false, defaultLevel: -40, group: "lowSentimentCalls" }
1588
+ };
1589
+ var RULE_FIELDS = Object.keys(RULES);
1590
+ var PHRASE_ALERTS = ["customerThreat", "upsetCustomer"];
1591
+ var LICENSES = ["base_user", "base_manager", "integration", "other"];
1592
+ var RANK = { active: 0, connected: 0, connecting: 1, error: 2, deactivating: 3, inactive: 4 };
1593
+ var rank = (status) => RANK[String(status)] ?? 5;
1594
+ function uniq(values) {
1595
+ return [...new Set(values)];
1425
1596
  }
1426
- function upsetCustomerRule(groupIds, enabled = false) {
1427
- return {
1428
- name: UPSET_CUSTOMER_RULE,
1429
- priority: "high",
1430
- match_logic: "any",
1431
- enabled,
1432
- triggers: [{ trigger_type: "sentiment", config: { operator: "lt", threshold: -40 } }],
1433
- group_ids: groupIds
1597
+ function deepEqual(a, b) {
1598
+ if (a === b) return true;
1599
+ if (Array.isArray(a) || Array.isArray(b)) {
1600
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => deepEqual(x, b[i]));
1601
+ }
1602
+ if (a && b && typeof a === "object" && typeof b === "object") {
1603
+ const ka = Object.keys(a);
1604
+ const kb = Object.keys(b);
1605
+ return ka.length === kb.length && ka.every((k) => k in b && deepEqual(a[k], b[k]));
1606
+ }
1607
+ return false;
1608
+ }
1609
+ function unwrap(body) {
1610
+ if (body && typeof body === "object" && "data" in body) {
1611
+ const d = body.data;
1612
+ if (d && typeof d === "object" && d.attributes && typeof d.attributes === "object") return d.attributes;
1613
+ return d;
1614
+ }
1615
+ return body;
1616
+ }
1617
+ function rowsOf(body) {
1618
+ const d = body?.data;
1619
+ return Array.isArray(d) ? d.map((x) => x && x.attributes && typeof x.attributes === "object" ? x.attributes : x) : [];
1620
+ }
1621
+ async function all(gen) {
1622
+ const out = [];
1623
+ for await (const x of gen) out.push(x);
1624
+ return out;
1625
+ }
1626
+ function line(value, name = "line") {
1627
+ const v = value === null || value === void 0 ? "" : String(value).trim();
1628
+ if (!v) throw new InvalidRequestError(`${name} is required`);
1629
+ return v;
1630
+ }
1631
+ function numbersOf(mappings, connectorId) {
1632
+ const out = [];
1633
+ for (const m of mappings ?? []) {
1634
+ if (connectorId === void 0 || connectorId === null || m.connector_id === connectorId) {
1635
+ for (const n of m.monitored_numbers ?? []) if (!out.includes(n)) out.push(n);
1636
+ }
1637
+ }
1638
+ return out;
1639
+ }
1640
+ function sameMappings(a, b) {
1641
+ const norm = (ms) => {
1642
+ const out = {};
1643
+ for (const m of ms) {
1644
+ const nums = [...m.monitored_numbers ?? []];
1645
+ if (nums.length) (out[m.connector_id ?? ""] ??= []).push(...nums);
1646
+ }
1647
+ return out;
1434
1648
  };
1649
+ return deepEqual(norm(a), norm(b));
1650
+ }
1651
+ function checkSetting(key, s) {
1652
+ if (s === null || s === void 0) return;
1653
+ if (typeof s !== "object") throw new InvalidRequestError(`alerts.${key} must be an AlertSetting`);
1654
+ if (s.sentimentBelow !== void 0 && s.sentimentBelow !== null) {
1655
+ const lvl = s.sentimentBelow;
1656
+ if (typeof lvl !== "number" || !Number.isInteger(lvl) || lvl < -100 || lvl > -1) {
1657
+ throw new InvalidRequestError(`alerts.${key}.sentimentBelow: a whole number from -100 to -1`);
1658
+ }
1659
+ }
1660
+ if (s.phrases !== void 0 && s.phrases !== null) {
1661
+ if (!RULES[key].hasPhrases) throw new InvalidRequestError(`alerts.${key} has no phrases; set sentimentBelow only`);
1662
+ if (!Array.isArray(s.phrases) || !s.phrases.every((p) => typeof p === "string")) {
1663
+ throw new InvalidRequestError(`alerts.${key}.phrases must be a list of strings`);
1664
+ }
1665
+ if (!s.phrases.some((p) => p.trim())) {
1666
+ throw new InvalidRequestError(`alerts.${key}.phrases is empty; pass null to keep the current phrases`);
1667
+ }
1668
+ }
1669
+ }
1670
+ function checkAlerts(alerts) {
1671
+ if (alerts === null || alerts === void 0) return;
1672
+ if (typeof alerts !== "object") throw new InvalidRequestError("alerts must be an AlertSettings");
1673
+ for (const key of RULE_FIELDS) checkSetting(key, alerts[key]);
1674
+ }
1675
+ function cleanPhrases(phrases) {
1676
+ if (phrases === null || phrases === void 0) return null;
1677
+ return uniq(phrases.filter((p) => p && p.trim()).map((p) => p.trim()));
1678
+ }
1679
+ function ruleSettings(rule) {
1680
+ let phrases = null;
1681
+ let level = null;
1682
+ for (const t of rule.triggers ?? []) {
1683
+ const cfg = t.config ?? {};
1684
+ if (t.trigger_type === "sentiment" && Number.isInteger(cfg.threshold)) level = cfg.threshold;
1685
+ else if (t.trigger_type === "keyword_match") phrases = [...cfg.keywords ?? []];
1686
+ }
1687
+ return [phrases, level];
1435
1688
  }
1436
- function customerThreatRule(groupIds, phrases, enabled = false) {
1437
- if (!phrases || phrases.length === 0) throw new FilterError(THREAT_PHRASES_MISSING);
1689
+ function triggers(key, phrases, level) {
1690
+ const out = [{ trigger_type: "sentiment", config: { operator: "lt", threshold: level } }];
1691
+ if (RULES[key].hasPhrases) out.push({ trigger_type: "keyword_match", config: { keywords: [...phrases ?? []], match_logic: "any" } });
1692
+ return out;
1693
+ }
1694
+ function ruleBody(key, groupId, phrases, level, enabled = false) {
1695
+ const d = RULES[key];
1696
+ if (d.hasPhrases && !phrases?.length) throw new InvalidRequestError(`${d.name} needs its phrases`);
1438
1697
  return {
1439
- name: CUSTOMER_THREAT_RULE,
1440
- priority: "critical",
1441
- match_logic: "all",
1698
+ name: d.name,
1699
+ priority: d.priority,
1700
+ match_logic: d.hasPhrases ? "all" : "any",
1442
1701
  enabled,
1443
- triggers: [
1444
- { trigger_type: "sentiment", config: { operator: "lt", threshold: -20 } },
1445
- { trigger_type: "keyword_match", config: { match_logic: "any", keywords: [...phrases] } }
1446
- ],
1447
- group_ids: groupIds
1702
+ triggers: triggers(key, phrases ?? null, level ?? d.defaultLevel),
1703
+ group_ids: [groupId]
1448
1704
  };
1449
1705
  }
1450
- async function step(name, partial, fn) {
1451
- try {
1452
- return await fn();
1453
- } catch (err) {
1454
- if (err instanceof WorkflowError || err instanceof ExtensionMappingError || err instanceof FilterError) throw err;
1455
- throw new WorkflowError(name, partial, err);
1456
- }
1706
+ function normTriggers(rule) {
1707
+ return (rule.triggers ?? []).map((t) => ({ trigger_type: t.trigger_type, config: t.config }));
1457
1708
  }
1458
- function canonical(v) {
1459
- if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
1460
- if (v && typeof v === "object") {
1461
- return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
1709
+ function isIntegration(row) {
1710
+ return String(row.department ?? "").trim().toLowerCase() === INTEGRATION_DEPARTMENT;
1711
+ }
1712
+ var Person = class {
1713
+ constructor(id, email, status) {
1714
+ this.id = id;
1715
+ this.email = email;
1716
+ this.status = status;
1717
+ }
1718
+ id;
1719
+ email;
1720
+ status;
1721
+ department = null;
1722
+ invitedAt = null;
1723
+ inviteExpiresAt = null;
1724
+ locs = /* @__PURE__ */ new Map();
1725
+ mappings = [];
1726
+ license = "other";
1727
+ teams = [];
1728
+ numbers(connectorId) {
1729
+ return numbersOf(this.mappings, connectorId);
1730
+ }
1731
+ get active() {
1732
+ return this.status !== "deactivated";
1462
1733
  }
1463
- return JSON.stringify(v ?? null);
1734
+ };
1735
+ var Run = class {
1736
+ constructor(client, result) {
1737
+ this.result = result;
1738
+ this.start = client.core.writes;
1739
+ }
1740
+ result;
1741
+ start;
1742
+ step = "start";
1743
+ };
1744
+ function newTeam(locationId, name, kind = "team") {
1745
+ return {
1746
+ locationId,
1747
+ name,
1748
+ kind,
1749
+ groups: { customerThreats: null, upsetCustomers: null, lowSentimentCalls: null, insightsHubAccess: null, weeklyReports: null },
1750
+ rules: { customerThreat: null, upsetCustomer: null, lowSentiment: null },
1751
+ connectorId: null,
1752
+ connectorStatus: null,
1753
+ connectorStateReason: null
1754
+ };
1755
+ }
1756
+ function newMember(userId, email, license, teams = [], lines = []) {
1757
+ return { userId, email, license, teams, lines, created: false, invited: false, notes: [] };
1464
1758
  }
1465
- var CONNECTOR_RANK = { active: 0, connecting: 1, error: 2, deactivating: 3, inactive: 4 };
1466
- function isIntegration(u) {
1467
- return (u.department ?? "").trim().toLowerCase() === INTEGRATION_DEPARTMENT;
1759
+ function dedupeTeams(teams) {
1760
+ const seen = /* @__PURE__ */ new Set();
1761
+ return teams.filter((t) => seen.has(t.locationId) ? false : (seen.add(t.locationId), true));
1468
1762
  }
1469
- function isManager(u) {
1470
- return !isIntegration(u) && ALL_PRODUCTS.every((p) => u.enabledProducts.includes(p));
1763
+ function expired(when, now) {
1764
+ if (!when) return false;
1765
+ const t = Date.parse(when);
1766
+ return Number.isNaN(t) ? false : t < now.getTime();
1471
1767
  }
1472
- function isFrontline(u) {
1473
- return !isIntegration(u) && u.enabledProducts.length === 1 && u.enabledProducts[0] === "after-call-copilot";
1768
+ function raiseConnectorFailure(failures, result) {
1769
+ if (failures.length) throw new AccountError("connectors", result, failures[0]);
1474
1770
  }
1475
- var norm = (s) => (s ?? "").trim().toLowerCase();
1476
- var Workflows = class {
1771
+ var Accounts = class _Accounts {
1477
1772
  constructor(c) {
1478
1773
  this.c = c;
1774
+ this.rawConnectors = makeConnectors(c.core);
1775
+ const writers = [
1776
+ "createCustomer",
1777
+ "addTeam",
1778
+ "setAlerts",
1779
+ "setConnector",
1780
+ "activateAlerts",
1781
+ "addBaseUser",
1782
+ "addBaseManager",
1783
+ "addIntegrationUser",
1784
+ "changeLicense",
1785
+ "moveUser",
1786
+ "changeLine",
1787
+ "removeUser",
1788
+ "sendInvitations",
1789
+ "syncLines",
1790
+ "offboardCustomer"
1791
+ ];
1792
+ for (const name of writers) {
1793
+ const original = this[name].bind(this);
1794
+ this[name] = (...args) => {
1795
+ const run = this.tail.then(
1796
+ () => original(...args),
1797
+ () => original(...args)
1798
+ );
1799
+ this.tail = run.then(
1800
+ () => void 0,
1801
+ () => void 0
1802
+ );
1803
+ return run;
1804
+ };
1805
+ }
1479
1806
  }
1480
1807
  c;
1481
- // ------------------------------------------------------------------ lookups
1482
- async bestConnector(locationId) {
1483
- let best = null;
1484
- for await (const row of this.c.connectors.iterLocationConnectors(locationId)) {
1485
- if (!best || (CONNECTOR_RANK[row.status ?? ""] ?? 9) < (CONNECTOR_RANK[best.status ?? ""] ?? 9)) best = row;
1808
+ me = null;
1809
+ verticals = null;
1810
+ connectorTypes = null;
1811
+ rawConnectors;
1812
+ tail = Promise.resolve();
1813
+ // ------------------------------------------------------------------ plumbing
1814
+ async requireAdmin() {
1815
+ if (this.me === null) this.me = unwrap(await this.c.account.getMe()) ?? {};
1816
+ if (this.me.role === "frontline_user") throw new WrongLoginError(this.me.role ?? null, "admin");
1817
+ return this.me;
1818
+ }
1819
+ run(result) {
1820
+ return new Run(this.c, result);
1821
+ }
1822
+ /** Throw `exc` as it is when nothing was written yet; otherwise as AccountError. */
1823
+ stop(run, exc) {
1824
+ if (!(exc instanceof IntelligenceCloudError)) throw exc;
1825
+ if (exc instanceof AccountError || this.c.core.writes === run.start) throw exc;
1826
+ throw new AccountError(run.step, run.result, exc);
1827
+ }
1828
+ async resolve(customer) {
1829
+ if (customer && typeof customer === "object") return customer;
1830
+ if (typeof customer === "string" && customer.trim()) return this.getCustomer(customer.trim());
1831
+ throw new InvalidRequestError("customer: a Customer or a company id");
1832
+ }
1833
+ teamOf(cust, team) {
1834
+ if (typeof team === "object" && team !== null) {
1835
+ const hit2 = cust.teams.find((t) => t.locationId === team.locationId);
1836
+ if (hit2) return hit2;
1837
+ throw new InvalidRequestError("team is not one of this customer's teams");
1486
1838
  }
1487
- return best;
1839
+ const hit = cust.teams.find((t) => t.locationId === team || t.name === team);
1840
+ if (hit) return hit;
1841
+ throw new InvalidRequestError(`Unknown team "${String(team)}": use a Team, its location id or its name`);
1488
1842
  }
1489
- async resolve(ref) {
1490
- return typeof ref === "string" ? this.getSeatCustomer(ref) : ref;
1843
+ teamsOf(cust, team) {
1844
+ return team !== void 0 && team !== null ? [this.teamOf(cust, team)] : [...cust.teams];
1491
1845
  }
1492
- requireConnector(customer) {
1493
- if (!customer.connectorId) {
1494
- throw new IntelligenceCloudError("This customer has no connector at its location, so numbers can't be mapped.");
1846
+ locationsOf(cust) {
1847
+ return [...cust.management ? [cust.management] : [], ...cust.teams];
1848
+ }
1849
+ async verticalId(vertical) {
1850
+ if (isUuid(vertical)) return vertical;
1851
+ if (this.verticals === null) this.verticals = rowsOf(await this.c.locations.listVerticals());
1852
+ for (const v of this.verticals) if (vertical === v.key || vertical === v.name) return v.id;
1853
+ throw new InvalidRequestError(`Unknown vertical "${vertical}": use an id or key from listVerticals()`);
1854
+ }
1855
+ async checkConnector(cs, required = false) {
1856
+ if (cs === null || cs === void 0) {
1857
+ if (required) throw new InvalidRequestError("A connector is required: pass a ConnectorSpec");
1858
+ return;
1859
+ }
1860
+ if (!isConnectorSpec(cs)) throw new InvalidRequestError("connector must be a ConnectorSpec");
1861
+ if (this.connectorTypes === null) {
1862
+ this.connectorTypes = rowsOf(await this.c.connectors.listConnectorTypes()).map((r) => r?.key).filter((k) => typeof k === "string" && !!k);
1863
+ }
1864
+ if (!this.connectorTypes.includes(cs.type)) {
1865
+ throw new InvalidRequestError(`Unknown connector type "${cs.type}": one of ${JSON.stringify(this.connectorTypes)}`);
1495
1866
  }
1496
- return customer.connectorId;
1497
1867
  }
1868
+ // ------------------------------------------------------------------ reading the layout
1498
1869
  /**
1499
- * Find the user by email (reactivating and assigning to the location if needed) or create them.
1500
- * Re-running a workflow therefore carries on with the same user.
1870
+ * Read the customer's layout back: Management, teams, groups, rules, connectors and what is
1871
+ * pending. A layout this SDK does not recognise (for example one built with 0.1.x) is returned with
1872
+ * what is missing listed in `pending`.
1501
1873
  */
1502
- async ensureUser(customer, u) {
1503
- if (!u?.email || !u.firstName || !u.lastName) throw new FilterError("email, firstName and lastName are required.");
1504
- const users = this.c.users;
1505
- const found = await users.findUserByEmail(customer.companyId, u.email);
1506
- if (!found?.id) {
1507
- const r = await users.createCompanyUser(
1508
- customer.companyId,
1509
- {
1510
- email: u.email,
1511
- first_name: u.firstName,
1512
- last_name: u.lastName,
1513
- phone_number: u.phoneNumber,
1514
- role: "frontline_user",
1515
- location_ids: [customer.locationId],
1516
- send_invitation: false,
1517
- // the invitation is emailed last, once the user is set up
1518
- auth_method: u.authMethod ?? "password"
1519
- },
1520
- { idempotencyKey: u.idempotencyKey }
1521
- );
1522
- const id = r.data?.attributes?.id;
1523
- if (!id) throw new IntelligenceCloudError("User create returned no id.");
1524
- return { id, created: true, status: r.data?.attributes?.status ?? "invited" };
1525
- }
1526
- if (found.status === "deactivated") await users.reactivateCompanyUser(customer.companyId, found.id);
1527
- const detail = (await users.getCompanyUser(customer.companyId, found.id)).data?.attributes ?? {};
1528
- if (detail.role !== "frontline_user") {
1529
- throw new FilterError(`${u.email} is a ${detail.role}; Seat users are frontline users.`);
1874
+ async getCustomer(companyId) {
1875
+ await this.requireAdmin();
1876
+ const c = this.c;
1877
+ const company = unwrap(await c.companies.getCompany(companyId)) ?? {};
1878
+ const name = company.company_name ?? "";
1879
+ const mgmtName = name + MANAGEMENT_SUFFIX;
1880
+ const locs = (await all(c.locations.iterCompanyLocations(companyId))).filter((x) => x.is_active ?? true);
1881
+ const key = (x) => [x.created_at ?? "", x.location_name ?? ""];
1882
+ locs.sort((a, b) => {
1883
+ const [a1, a2] = key(a);
1884
+ const [b1, b2] = key(b);
1885
+ return a1 < b1 ? -1 : a1 > b1 ? 1 : a2 < b2 ? -1 : a2 > b2 ? 1 : 0;
1886
+ });
1887
+ const cust = { companyId, management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [] };
1888
+ for (const loc of locs) {
1889
+ const kind = loc.location_name === mgmtName ? "management" : "team";
1890
+ const team = await this.readTeam(loc.id, loc.location_name ?? "", kind);
1891
+ if (kind === "management" && cust.management === null) cust.management = team;
1892
+ else cust.teams.push(team);
1530
1893
  }
1531
- if (!(detail.locations ?? []).some((l) => l.location_id === customer.locationId)) {
1532
- await users.addLocations(customer.companyId, found.id, [customer.locationId]);
1894
+ cust.pending = this.pendingOf(cust);
1895
+ for (const dom of rowsOf(await c.sso.listCompanyDomains(companyId))) {
1896
+ cust.ssoDomainId = dom.id ?? null;
1897
+ const ver = dom.verification ?? {};
1898
+ cust.ssoTxtRecord = { name: ver.name, value: ver.value };
1899
+ break;
1533
1900
  }
1534
- return { id: found.id, created: false, status: detail.status ?? null };
1535
- }
1536
- /** The last step: email the invitation to a user who has not accepted one yet. */
1537
- async invite(customer, u, userId, status) {
1538
- if (u.sendInvitation === false || status !== "invited") return false;
1539
- await this.c.users.resendInvitation(customer.companyId, userId);
1540
- return true;
1901
+ return cust;
1541
1902
  }
1542
- /** Replace the user's numbers on the customer's connector; a refusal becomes ExtensionMappingError. */
1543
- async mapNumbers(customer, userId, numbers) {
1544
- const connectorId = this.requireConnector(customer);
1545
- try {
1546
- await this.c.users.setNumbers(customer.companyId, userId, connectorId, numbers);
1547
- } catch (err) {
1548
- if (err instanceof ValidationError || err instanceof ConflictError) throw new ExtensionMappingError(userId, err);
1549
- throw err;
1903
+ async readTeam(locationId, name, kind) {
1904
+ const c = this.c;
1905
+ const team = newTeam(locationId, name, kind);
1906
+ const byName = /* @__PURE__ */ new Map();
1907
+ for (const g of await all(c.groups.iterUserGroups(locationId))) byName.set(g.group_name, g.id);
1908
+ for (const f of GROUP_FIELDS) team.groups[f] = byName.get(TEAM_GROUPS[f]) ?? null;
1909
+ const rules = /* @__PURE__ */ new Map();
1910
+ for (const r of await all(c.firstAlert.iterAlertRules(locationId))) rules.set(r.name, r.id);
1911
+ for (const key of RULE_FIELDS) team.rules[key] = rules.get(RULES[key].name) ?? null;
1912
+ await this.readConnector(team);
1913
+ return team;
1914
+ }
1915
+ async readConnector(team) {
1916
+ const conns = (await all(this.c.connectors.iterLocationConnectors(team.locationId))).sort((a, b) => rank(a.status) - rank(b.status));
1917
+ if (conns.length && conns[0].status !== "inactive") {
1918
+ team.connectorId = conns[0].id;
1919
+ team.connectorStatus = conns[0].status ?? null;
1920
+ team.connectorStateReason = conns[0].state_reason ?? null;
1550
1921
  }
1551
1922
  }
1552
- /** Lines at the location: First Alert's monitored numbers for the customer's connector. */
1553
- async locationLines(customer) {
1554
- if (!customer.connectorId) return [];
1555
- const cfg = (await this.c.firstAlert.getFirstAlertConfig(customer.locationId)).data;
1556
- return numbersFor(cfg?.connector_mappings, customer.connectorId);
1557
- }
1558
- excluded(customer, id, email) {
1559
- if ((customer.excludeUserIds ?? []).includes(id)) return true;
1560
- const e = (email ?? "").trim().toLowerCase();
1561
- return Boolean(e) && (customer.excludeEmails ?? []).some((x) => x.trim().toLowerCase() === e);
1562
- }
1563
- /** Active or invited frontline users at the location (not excluded), with their department. */
1564
- async seatUsers(customer) {
1565
- const departments = /* @__PURE__ */ new Map();
1566
- for await (const u of this.c.users.iterCompanyUsers(customer.companyId, { locationId: [customer.locationId] })) {
1567
- if (u?.id) departments.set(u.id, u.department ?? null);
1568
- }
1923
+ pendingOf(cust) {
1569
1924
  const out = [];
1570
- for await (const a of this.c.users.iterLocationUsers(customer.locationId)) {
1571
- if (!a?.id || a.status === "deactivated" || a.role !== "frontline_user") continue;
1572
- if (this.excluded(customer, a.id, a.email)) continue;
1573
- out.push({
1574
- id: a.id,
1575
- email: a.email ?? "",
1576
- displayName: a.display_name ?? "",
1577
- status: a.status ?? "",
1578
- enabledProducts: [...a.enabled_products ?? []],
1579
- groups: [...a.groups ?? []],
1580
- department: departments.get(a.id) ?? null
1581
- });
1925
+ for (const key of PHRASE_ALERTS) if (cust.teams.some((t) => t.rules[key] === null)) out.push(key);
1926
+ if (cust.management === null) {
1927
+ out.push("management location");
1928
+ } else {
1929
+ if (cust.management.groups.weeklyReports === null) out.push(`${cust.management.name}: group ${TEAM_GROUPS.weeklyReports}`);
1930
+ if (RULE_FIELDS.some((k) => cust.management.rules[k])) out.push(`${cust.management.name}: has alert rules (Management has none)`);
1931
+ }
1932
+ if (!cust.teams.length) out.push("team");
1933
+ for (const t of cust.teams) {
1934
+ for (const f of GROUP_FIELDS) if (t.groups[f] === null) out.push(`${t.name}: group ${TEAM_GROUPS[f]}`);
1935
+ if (t.rules.lowSentiment === null) out.push(`${t.name}: rule ${RULES.lowSentiment.name}`);
1582
1936
  }
1583
1937
  return out;
1584
1938
  }
1585
- /** Managers and integration users: the users who hold every line. */
1586
- async lineHolders(customer) {
1587
- const all = await this.seatUsers(customer);
1588
- return all.filter((u) => isManager(u) || isIntegration(u));
1589
- }
1590
- /** Lines held by end users who hold exactly one line (users holding several are not seats). */
1591
- async endUserLines(customer, connectorId, exceptUserId) {
1592
- const lines = /* @__PURE__ */ new Set();
1593
- for (const u of await this.listFrontlineUsers(customer)) {
1594
- if (u.id === exceptUserId) continue;
1595
- const nums = await this.c.users.userNumbers(customer.companyId, u.id, connectorId);
1596
- if (nums.length === 1) lines.add(nums[0]);
1597
- }
1598
- return lines;
1599
- }
1600
- // ------------------------------------------------------------------ workflows
1601
- /** Rebuild the customer object (location, groups, rules, connector) from a company id. */
1602
- async getSeatCustomer(companyId, options = {}) {
1603
- const company = (await this.c.companies.getCompany(companyId)).data?.attributes;
1604
- if (!company?.id) throw new NotFoundError(404, "NOT_FOUND", "Company not found.");
1605
- let loc = null;
1606
- if (options.locationName) {
1607
- loc = await this.c.locations.findLocation(companyId, options.locationName);
1608
- } else {
1609
- for await (const row of this.c.locations.iterCompanyLocations(companyId, { isActive: true })) {
1610
- loc = row;
1611
- break;
1939
+ // ------------------------------------------------------------------ create
1940
+ /**
1941
+ * Create the customer, or finish one an earlier run started.
1942
+ *
1943
+ * The company with all three products; the SSO domain claim (if `ssoDomain`); the first team and
1944
+ * `<Company> - Management`; the connector at each (if given); five groups on the team and the
1945
+ * weekly reports group at Management; the Low Sentiment rule, plus Customer Threat and Upset
1946
+ * Customer when their phrases are given, all switched off; Insights Hub with "monitor all numbers"
1947
+ * off. Alerts without phrases are listed in `Customer.pending` and follow with `setAlerts`. Store
1948
+ * `companyId` and pass it on later runs: a company is never adopted by its name alone.
1949
+ */
1950
+ async createCustomer(spec) {
1951
+ const me = await this.requireAdmin();
1952
+ const c = this.c;
1953
+ if (!spec || typeof spec !== "object" || !spec.admin || !spec.team) throw new InvalidRequestError("spec must be a CustomerSpec");
1954
+ if (!(spec.admin.phoneNumber ?? "").trim()) throw new InvalidRequestError("admin.phoneNumber is required for the primary contact");
1955
+ checkAlerts(spec.alerts);
1956
+ await this.checkConnector(spec.connector);
1957
+ const resellerId = spec.resellerId || me.reseller_id;
1958
+ if (!resellerId) throw new InvalidRequestError("resellerId is required (this login has none)");
1959
+ const mgmtName = spec.companyName + MANAGEMENT_SUFFIX;
1960
+ if (spec.team.name === mgmtName) throw new InvalidRequestError(`"${mgmtName}" is the Management location; name the team differently`);
1961
+ await this.verticalId(spec.team.vertical);
1962
+ const result = { companyId: "", management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [] };
1963
+ const failures = [];
1964
+ const run = this.run(result);
1965
+ try {
1966
+ run.step = "company";
1967
+ let company = await this.findCompany(resellerId, spec);
1968
+ if (company === null) {
1969
+ const body = {
1970
+ company_name: spec.companyName,
1971
+ primary_admin_contact_name: `${spec.admin.firstName} ${spec.admin.lastName}`.trim(),
1972
+ primary_admin_contact_email: spec.admin.email,
1973
+ primary_admin_contact_phone: spec.admin.phoneNumber,
1974
+ enabled_products: [...PRODUCT_KEYS]
1975
+ };
1976
+ if (spec.companyCode) body.company_code = spec.companyCode;
1977
+ company = unwrap(await c.companies.createCompany(resellerId, body));
1978
+ result.created.push("company");
1979
+ } else {
1980
+ result.existing.push("company");
1981
+ if (!(company.is_active ?? true)) {
1982
+ if (!spec.reactivate) {
1983
+ throw new InvalidRequestError(`Company "${spec.companyName}" exists but is inactive (set reactivate: true to reactivate it)`);
1984
+ }
1985
+ await c.companies.reactivateCompany(company.id);
1986
+ }
1987
+ }
1988
+ const companyId = result.companyId = company.id;
1989
+ run.step = "mfa";
1990
+ if (spec.mfaOff) {
1991
+ const current2 = unwrap(await c.companies.getCompany(companyId)) ?? {};
1992
+ if (current2.mfa_enforced) {
1993
+ await c.companies.updateCompany(companyId, { mfa_enforced: false });
1994
+ if ((unwrap(await c.companies.getCompany(companyId)) ?? {}).mfa_enforced) {
1995
+ const text = "MFA is still on for the company after the update";
1996
+ throw new ApiError(200, null, text, {});
1997
+ }
1998
+ }
1999
+ }
2000
+ run.step = "sso";
2001
+ if (spec.ssoDomain) await this.ensureDomain(companyId, spec.ssoDomain, result);
2002
+ run.step = "products";
2003
+ const current = unwrap(await c.companies.getCompany(companyId)) ?? {};
2004
+ const have = current.enabled_products ?? [];
2005
+ if (!PRODUCT_KEYS.every((k) => have.includes(k))) await c.companies.addProducts(companyId, [...PRODUCT_KEYS]);
2006
+ run.step = "locations";
2007
+ const team = await this.ensureLocation(companyId, spec.team.name, spec.team, "team", !!spec.reactivate, result);
2008
+ const mgmt = await this.ensureLocation(companyId, mgmtName, spec.team, "management", !!spec.reactivate, result);
2009
+ result.teams = [team];
2010
+ result.management = mgmt;
2011
+ run.step = "connectors";
2012
+ if (spec.connector) {
2013
+ for (const t of [team, mgmt]) {
2014
+ const failure = await this.ensureConnector(t, spec.connector, result);
2015
+ if (failure) failures.push(failure);
2016
+ }
2017
+ } else {
2018
+ await this.readConnector(team);
2019
+ await this.readConnector(mgmt);
1612
2020
  }
2021
+ run.step = "groups";
2022
+ await this.ensureGroups(team, result);
2023
+ await this.ensureGroups(mgmt, result);
2024
+ run.step = "rules";
2025
+ await this.ensureRules(team, this.settingsFrom(spec.alerts), result);
2026
+ run.step = "insights_hub";
2027
+ await this.ensureInsightsHub(team);
2028
+ await this.monitorAllOff(mgmt.locationId);
2029
+ result.pending = this.pendingOf(result);
2030
+ } catch (exc) {
2031
+ this.stop(run, exc);
1613
2032
  }
1614
- if (!loc?.id) throw new NotFoundError(404, "NOT_FOUND", "The company has no matching active location.");
1615
- const locationId = loc.id;
1616
- const ma = await this.c.groups.findGroup(locationId, MANAGER_ALERTS_GROUP);
1617
- const iha = await this.c.groups.findGroup(locationId, INSIGHTS_HUB_ACCESS_GROUP);
1618
- const upset = await this.c.firstAlert.findRule(locationId, UPSET_CUSTOMER_RULE);
1619
- const threat = await this.c.firstAlert.findRule(locationId, CUSTOMER_THREAT_RULE);
1620
- const conn = await this.bestConnector(locationId);
1621
- return {
1622
- companyId,
1623
- companyName: company.company_name ?? "",
1624
- locationId,
1625
- locationName: loc.location_name ?? "",
1626
- groups: { managerAlerts: ma?.id ?? null, insightsHubAccess: iha?.id ?? null },
1627
- rules: { upsetCustomer: upset?.id ?? null, customerThreat: threat?.id ?? null },
1628
- connectorId: conn?.id ?? null,
1629
- connectorStatus: conn?.status ?? null,
1630
- connectorStateReason: conn?.state_reason ?? null
1631
- };
2033
+ raiseConnectorFailure(failures, result);
2034
+ return result;
1632
2035
  }
1633
2036
  /**
1634
- * Create (or finish) a Base Intelligence Seat customer. Idempotent: objects that already exist
1635
- * (found by name) are kept, so a re-run completes a half-built customer.
2037
+ * `spec.companyId`, or the one company with this exact name whose primary contact email is
2038
+ * `spec.admin.email`. Throws ConflictError, before any write, when the name is taken by another.
1636
2039
  */
1637
- async provisionSeatCustomer(spec) {
2040
+ async findCompany(resellerId, spec) {
1638
2041
  const c = this.c;
1639
- if (!spec?.companyName || !spec.primaryAdmin || !spec.location?.name) {
1640
- throw new FilterError("companyName, primaryAdmin and location are required.");
1641
- }
1642
- const phrases = [...spec.threatPhrases ?? []];
1643
- const created = [];
1644
- const existing = [];
1645
- const partial = { created, existing };
1646
- const resellerId = spec.resellerId ?? await step("whoami", partial, async () => {
1647
- const me = await c.whoami();
1648
- if (!me.reseller_id) throw new IntelligenceCloudError("This login has no reseller id; pass resellerId.");
1649
- return me.reseller_id;
1650
- });
1651
- let company;
1652
- if (spec.companyId) {
1653
- const id = spec.companyId;
1654
- company = await step("get_company", partial, async () => (await c.companies.getCompany(id)).data?.attributes ?? null);
1655
- if (!company?.id) throw new NotFoundError(404, "NOT_FOUND", "Company not found.");
2042
+ if (spec.companyId) return unwrap(await c.companies.getCompany(spec.companyId));
2043
+ const sameName = await c.companies.findCompanies(resellerId, spec.companyName);
2044
+ if (!sameName.length) return null;
2045
+ const want = (spec.admin.email ?? "").trim().toLowerCase();
2046
+ const matches = [];
2047
+ for (const row of sameName) {
2048
+ const detail = unwrap(await c.companies.getCompany(row.id)) ?? {};
2049
+ if (String(detail.primary_admin_contact_email ?? "").trim().toLowerCase() === want) matches.push(detail);
2050
+ }
2051
+ if (matches.length === 1) return matches[0];
2052
+ 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.`;
2053
+ throw new ConflictError(409, COMPANY_NAME_CONFLICT, text, {});
2054
+ }
2055
+ async ensureDomain(companyId, domain, result) {
2056
+ const want = domain.trim().toLowerCase();
2057
+ let dom = rowsOf(await this.c.sso.listCompanyDomains(companyId)).find((d) => String(d.domain ?? "").trim().toLowerCase() === want);
2058
+ if (dom === void 0) {
2059
+ dom = unwrap(await this.c.sso.claimCompanyDomain(companyId, { domain })) ?? {};
2060
+ result.created.push("sso_domain");
1656
2061
  } else {
1657
- const sameName = await step("find_company", partial, () => c.companies.findCompanies(resellerId, spec.companyName));
1658
- const want = norm(spec.primaryAdmin.email);
1659
- const matches = [];
1660
- for (const row of sameName) {
1661
- if (!row.id) continue;
1662
- const id = row.id;
1663
- const detail = await step("find_company", partial, async () => (await c.companies.getCompany(id)).data?.attributes);
1664
- if (detail && norm(detail.primary_admin_contact_email) === want) matches.push(detail);
1665
- }
1666
- if (sameName.length && matches.length !== 1) {
1667
- throw new ConflictError(409, "company_name_conflict", companyNameConflictMessage(spec.companyName));
2062
+ result.existing.push("sso_domain");
2063
+ }
2064
+ result.ssoDomainId = dom.id ?? null;
2065
+ const ver = dom.verification ?? {};
2066
+ result.ssoTxtRecord = { name: ver.name, value: ver.value };
2067
+ }
2068
+ async ensureLocation(companyId, name, spec, kind, reactivate, result) {
2069
+ const c = this.c;
2070
+ let loc = await c.locations.findLocation(companyId, name);
2071
+ if (loc === null) {
2072
+ loc = unwrap(
2073
+ await c.locations.createLocation(companyId, {
2074
+ location_name: name,
2075
+ street: spec.street,
2076
+ city: spec.city,
2077
+ state: spec.state,
2078
+ country: spec.country,
2079
+ zipcode: spec.zipcode,
2080
+ vertical_id: await this.verticalId(spec.vertical),
2081
+ enabled_products: [...PRODUCT_KEYS]
2082
+ })
2083
+ );
2084
+ result.created.push(`location:${name}`);
2085
+ } else {
2086
+ result.existing.push(`location:${name}`);
2087
+ if (!(loc.is_active ?? true)) {
2088
+ if (!reactivate) throw new InvalidRequestError(`Location "${name}" exists but is inactive (set reactivate: true to reactivate it)`);
2089
+ await c.locations.reactivateLocation(companyId, loc.id);
1668
2090
  }
1669
- company = matches[0] ?? null;
2091
+ const have = loc.enabled_products ?? [];
2092
+ if (!PRODUCT_KEYS.every((k) => have.includes(k))) await c.locations.addProducts(companyId, loc.id, [...PRODUCT_KEYS]);
1670
2093
  }
1671
- if (company?.id && company.is_active === false) {
1672
- if (!spec.reactivate) {
1673
- throw new FilterError("The company exists but is deactivated. Set reactivate: true to reactivate it.");
2094
+ return newTeam(loc.id, name, kind);
2095
+ }
2096
+ async ensureGroups(team, result) {
2097
+ const fields = team.kind === "team" ? GROUP_FIELDS : ["weeklyReports"];
2098
+ const existing = /* @__PURE__ */ new Map();
2099
+ for (const g of await all(this.c.groups.iterUserGroups(team.locationId))) existing.set(g.group_name, g.id);
2100
+ for (const f of fields) {
2101
+ const gname = TEAM_GROUPS[f];
2102
+ let gid = existing.get(gname);
2103
+ if (gid === void 0) {
2104
+ gid = unwrap(await this.c.groups.createUserGroup(team.locationId, { group_name: gname })).id;
2105
+ result.created.push(`group:${team.name}:${gname}`);
2106
+ } else {
2107
+ result.existing.push(`group:${team.name}:${gname}`);
1674
2108
  }
1675
- const id = company.id;
1676
- await step("reactivate_company", partial, () => c.companies.reactivateCompany(id));
2109
+ team.groups[f] = gid;
1677
2110
  }
1678
- if (!company && phrases.length === 0) throw new FilterError(THREAT_PHRASES_MISSING);
1679
- if (!company) {
1680
- company = await step("create_company", partial, async () => {
1681
- const r = await c.companies.createCompany(resellerId, {
1682
- company_name: spec.companyName,
1683
- company_code: spec.companyCode,
1684
- primary_admin_contact_name: spec.primaryAdmin.name,
1685
- primary_admin_contact_email: spec.primaryAdmin.email,
1686
- primary_admin_contact_phone: spec.primaryAdmin.phone,
1687
- enabled_products: ALL_PRODUCTS
1688
- });
1689
- created.push("company");
1690
- return r.data.attributes;
1691
- });
1692
- } else {
1693
- existing.push("company");
1694
- }
1695
- const companyId = company.id;
1696
- partial.companyId = companyId;
1697
- if (spec.mfaOff) {
1698
- await step("mfa_off", partial, async () => {
1699
- const cur = (await c.companies.getCompany(companyId)).data?.attributes;
1700
- if (cur?.mfa_enforced !== false) await c.companies.updateCompany(companyId, { mfa_enforced: false });
1701
- const check = (await c.companies.getCompany(companyId)).data?.attributes;
1702
- if (check?.mfa_enforced !== false) throw new IntelligenceCloudError("MFA is still on after the update.");
1703
- });
2111
+ }
2112
+ settingsFrom(alerts) {
2113
+ const out = {};
2114
+ for (const key of RULE_FIELDS) {
2115
+ const s = alerts ? alerts[key] : null;
2116
+ out[key] = s ? [cleanPhrases(s.phrases), s.sentimentBelow ?? null] : [null, null];
1704
2117
  }
1705
- await step("company_products", partial, () => c.companies.addProducts(companyId, ALL_PRODUCTS));
1706
- let loc = await step("find_location", partial, () => c.locations.findLocation(companyId, spec.location.name));
1707
- if (!loc) {
1708
- loc = await step("create_location", partial, async () => {
1709
- let verticalId = spec.location.verticalId;
1710
- if (!verticalId) {
1711
- const key = spec.location.verticalKey ?? DEFAULT_VERTICAL_KEY;
1712
- const v = ((await c.locations.listVerticals()).data ?? []).find((x) => x.key === key);
1713
- if (!v?.id) throw new IntelligenceCloudError(`No industry with key "${key}".`);
1714
- verticalId = v.id;
1715
- }
1716
- const r = await c.locations.createLocation(companyId, {
1717
- location_name: spec.location.name,
1718
- street: spec.location.street,
1719
- city: spec.location.city,
1720
- state: spec.location.state,
1721
- country: spec.location.country,
1722
- zipcode: spec.location.zipcode,
1723
- vertical_id: verticalId,
1724
- enabled_products: ALL_PRODUCTS
1725
- });
1726
- created.push("location");
1727
- return r.data.attributes;
1728
- });
1729
- } else {
1730
- if (loc.is_active === false) {
1731
- if (!spec.reactivate) {
1732
- throw new FilterError("The location exists but is deactivated. Set reactivate: true to reactivate it.");
2118
+ return out;
2119
+ }
2120
+ /**
2121
+ * Create missing rules (switched off) and apply the given phrases and levels to existing ones.
2122
+ * Returns the ids of the rules created or changed.
2123
+ */
2124
+ async ensureRules(team, settings, result) {
2125
+ const fa = this.c.firstAlert;
2126
+ const changed = [];
2127
+ const found = /* @__PURE__ */ new Map();
2128
+ for (const r of await all(fa.iterAlertRules(team.locationId))) found.set(r.name, r);
2129
+ for (const key of RULE_FIELDS) {
2130
+ const d = RULES[key];
2131
+ const [phrases, level] = settings[key] ?? [null, null];
2132
+ const groupId = team.groups[d.group];
2133
+ const row = found.get(d.name);
2134
+ if (row === void 0) {
2135
+ if (d.hasPhrases && !phrases?.length) {
2136
+ team.rules[key] = null;
2137
+ continue;
1733
2138
  }
1734
- const lid = loc.id;
1735
- await step("reactivate_location", partial, () => c.locations.reactivateLocation(companyId, lid));
1736
- }
1737
- await step("location_products", partial, () => c.locations.addProducts(companyId, loc.id, ALL_PRODUCTS));
1738
- }
1739
- const locationId = loc.id;
1740
- partial.locationId = locationId;
1741
- const ensureGroup = (name) => step(`group:${name}`, partial, async () => {
1742
- const found = await c.groups.findGroup(locationId, name);
1743
- if (found?.id) return found.id;
1744
- const r = await c.groups.createUserGroup(locationId, { group_name: name });
1745
- created.push(`group:${name}`);
1746
- return r.data.attributes.id;
1747
- });
1748
- const managerAlerts = await ensureGroup(MANAGER_ALERTS_GROUP);
1749
- const ihAccess = await ensureGroup(INSIGHTS_HUB_ACCESS_GROUP);
1750
- partial.groups = { managerAlerts, insightsHubAccess: ihAccess };
1751
- const ensureRule = (name, body) => step(`rule:${name}`, partial, async () => {
1752
- const found = await c.firstAlert.findRule(locationId, name);
1753
- if (!found?.id) {
1754
- const r = await c.firstAlert.createAlertRule(locationId, body());
1755
- created.push(`rule:${name}`);
1756
- return r.data.attributes.id;
2139
+ if (!groupId) throw new InvalidRequestError(`${team.name}: group ${TEAM_GROUPS[d.group]} is missing`);
2140
+ const rule2 = unwrap(await fa.createAlertRule(team.locationId, ruleBody(key, groupId, phrases, level)));
2141
+ team.rules[key] = rule2.id;
2142
+ changed.push(rule2.id);
2143
+ result?.created.push(`rule:${team.name}:${d.name}`);
2144
+ continue;
1757
2145
  }
1758
- const rule = (await c.firstAlert.getAlertRule(locationId, found.id)).data?.attributes ?? {};
1759
- if (!(rule.groups ?? []).some((g) => g.id === managerAlerts)) {
1760
- await c.firstAlert.addRuleGroups(locationId, found.id, [managerAlerts]);
2146
+ result?.existing.push(`rule:${team.name}:${d.name}`);
2147
+ const rule = unwrap(await fa.getAlertRule(team.locationId, row.id)) ?? {};
2148
+ team.rules[key] = rule.id ?? row.id;
2149
+ const haveGroups = new Set((rule.groups ?? []).map((g) => g.id));
2150
+ if (groupId && !haveGroups.has(groupId)) await fa.addRuleGroups(team.locationId, row.id, [groupId]);
2151
+ const [curPhrases, curLevel] = ruleSettings(rule);
2152
+ const newPhrases = phrases ?? curPhrases;
2153
+ const newLevel = level ?? (curLevel ?? d.defaultLevel);
2154
+ if (d.hasPhrases && !newPhrases?.length) continue;
2155
+ const want = triggers(key, newPhrases, newLevel);
2156
+ if (!deepEqual(normTriggers(rule), want)) {
2157
+ await fa.updateAlertRule(team.locationId, row.id, { triggers: want });
2158
+ if (!changed.includes(row.id)) changed.push(row.id);
1761
2159
  }
1762
- const want = body();
1763
- if (want) {
1764
- const cur = (rule.triggers ?? []).map((t) => ({ trigger_type: t.trigger_type, config: t.config }));
1765
- if (canonical(cur) !== canonical(want.triggers)) {
1766
- await c.firstAlert.updateAlertRule(locationId, found.id, { triggers: want.triggers });
1767
- }
2160
+ }
2161
+ return changed;
2162
+ }
2163
+ async ensureInsightsHub(team) {
2164
+ const ih = this.c.insightsHub;
2165
+ const setup = unwrap(await ih.getInsightsHubSetup(team.locationId)) ?? {};
2166
+ const access = setup.group_access ?? [];
2167
+ const gid = team.groups.insightsHubAccess;
2168
+ if (gid && !access.includes(gid)) {
2169
+ if (!access.length && !(setup.connector_mappings ?? []).length) {
2170
+ await ih.saveInsightsHubSetup(team.locationId, { connector_mappings: [], group_access: [gid] });
2171
+ } else {
2172
+ await ih.updateInsightsHubSetup(team.locationId, { group_access: uniq([...access, gid]) });
1768
2173
  }
1769
- return found.id;
1770
- });
1771
- if (phrases.length === 0 && !await c.firstAlert.findRule(locationId, CUSTOMER_THREAT_RULE)) {
1772
- throw new FilterError(THREAT_PHRASES_MISSING);
1773
- }
1774
- const rules = {
1775
- upsetCustomer: await ensureRule(UPSET_CUSTOMER_RULE, () => upsetCustomerRule([managerAlerts])),
1776
- customerThreat: await ensureRule(
1777
- CUSTOMER_THREAT_RULE,
1778
- () => phrases.length ? customerThreatRule([managerAlerts], phrases) : null
1779
- )
1780
- };
1781
- partial.rules = rules;
1782
- await step("insights_hub", partial, async () => {
1783
- const setup = (await c.insightsHub.getInsightsHubSetup(locationId)).data?.attributes;
1784
- if (!(setup?.group_access ?? []).includes(ihAccess)) await c.insightsHub.addGroups(locationId, [ihAccess]);
1785
- const cfg = (await c.insightsHub.getInsightsHubConfig(locationId)).data?.attributes;
1786
- if (cfg?.monitor_all_numbers !== true) {
1787
- await c.insightsHub.updateInsightsHubConfig(locationId, { monitor_all_numbers: true });
2174
+ }
2175
+ await this.monitorAllOff(team.locationId);
2176
+ }
2177
+ async monitorAllOff(locationId) {
2178
+ const cfg = unwrap(await this.c.insightsHub.getInsightsHubConfig(locationId)) ?? {};
2179
+ if (cfg.monitor_all_numbers) await this.c.insightsHub.updateInsightsHubConfig(locationId, { monitor_all_numbers: false });
2180
+ }
2181
+ // ------------------------------------------------------------------ connectors
2182
+ /**
2183
+ * The location's connector of this type for the same phone-system domain (best status first),
2184
+ * else one of this type with this name.
2185
+ */
2186
+ async findConnector(locationId, cs, name) {
2187
+ const conns = this.c.connectors;
2188
+ const rows = (await all(conns.iterLocationConnectors(locationId))).sort((a, b) => rank(a.status) - rank(b.status));
2189
+ const wantDomain = String(cs.config.domain ?? "").trim().toLowerCase();
2190
+ let byName = null;
2191
+ for (const row of rows) {
2192
+ if (row.type && row.type !== cs.type) continue;
2193
+ const detail = unwrap(await conns.getConnector(locationId, row.id)) ?? {};
2194
+ const haveDomain = String((detail.config ?? {}).domain ?? "").trim().toLowerCase();
2195
+ if (wantDomain && haveDomain === wantDomain) return detail;
2196
+ if (byName === null && detail.name === name) byName = detail;
2197
+ }
2198
+ return byName;
2199
+ }
2200
+ static unchanged(found, name, config) {
2201
+ const have = found.config ?? {};
2202
+ return found.name === name && Object.entries(config).every(([k, v]) => !(k in have) || isSecretName(k) || deepEqual(have[k], v));
2203
+ }
2204
+ /**
2205
+ * Find, repair or create the team's connector and record its status on the team. Returns the
2206
+ * ConnectorError or ConnectorTimeoutError when it did not become active (the caller throws it at
2207
+ * the end, once everything else is built), else null.
2208
+ */
2209
+ async ensureConnector(team, cs, result) {
2210
+ const name = cs.name || `${team.name} phone system`;
2211
+ const conns = this.c.connectors;
2212
+ const config = plainConfig(cs.config);
2213
+ const found = await this.findConnector(team.locationId, cs, name);
2214
+ const label = `connector:${team.name}`;
2215
+ if (found !== null) {
2216
+ const unchanged = _Accounts.unchanged(found, name, config);
2217
+ if ([...RUNNING, "connecting"].includes(found.status) && unchanged) {
2218
+ result?.existing.push(label);
2219
+ this.setConn(team, found);
2220
+ return null;
1788
2221
  }
1789
- });
1790
- let connectorId = null;
1791
- let connectorStatus = null;
1792
- let connectorStateReason = null;
1793
- if (spec.connector) {
1794
- const cs = spec.connector;
1795
- const name = cs.name ?? `${spec.location.name} - NetSapiens`;
1796
- const conn = await step("connector", partial, async () => {
1797
- let byDomain = null;
1798
- let byName = null;
1799
- for await (const row of c.connectors.iterLocationConnectors(locationId)) {
1800
- if (!row.id) continue;
1801
- const detail = (await c.connectors.getConnector(locationId, row.id)).data ?? row;
1802
- const rank = (x) => x ? CONNECTOR_RANK[x.status ?? ""] ?? 9 : 99;
1803
- if (norm(detail.config?.domain) === norm(cs.domain) && rank(detail) < rank(byDomain)) byDomain = detail;
1804
- if (detail.name === name && rank(detail) < rank(byName)) byName = detail;
1805
- }
1806
- const found = byDomain ?? byName;
1807
- const wait = { timeout: cs.timeout };
1808
- try {
1809
- if (!found?.id) {
1810
- const r = await c.connectors.createConnector(
1811
- locationId,
1812
- { name, type: "netsapiens", config: { api_url: cs.apiUrl, domain: cs.domain, api_key: cs.apiKey } },
1813
- wait
1814
- );
1815
- created.push("connector");
1816
- return r.data ?? null;
1817
- }
1818
- existing.push("connector");
1819
- const fid = found.id;
1820
- const unchanged = found.name === name && found.config?.api_url === cs.apiUrl && norm(found.config?.domain) === norm(cs.domain);
1821
- if (unchanged && found.status === "active") return found;
1822
- if (unchanged && found.status === "connecting") {
1823
- return await c.connectors.waitForStatus(locationId, fid, ["active", "error"], wait);
1824
- }
1825
- await c.connectors.updateConnector(
1826
- locationId,
1827
- fid,
1828
- { name, config: { api_url: cs.apiUrl, domain: cs.domain, api_key: cs.apiKey } },
1829
- { wait: false }
1830
- );
1831
- existing.push("connector:updated");
1832
- if (found.status === "inactive") {
1833
- return (await c.connectors.reactivateConnector(locationId, fid, wait)).data ?? null;
2222
+ }
2223
+ let conn;
2224
+ try {
2225
+ if (found !== null) {
2226
+ if (result) result.existing.push(label, label + ":updated");
2227
+ await this.rawConnectors.updateConnector(team.locationId, found.id, { name, config });
2228
+ if (found.status === "inactive") {
2229
+ conn = unwrap(await conns.reactivateConnector(team.locationId, found.id, { timeout: cs.timeout }));
2230
+ } else {
2231
+ conn = await conns.waitForStatus(team.locationId, found.id, [...RUNNING, "error"], { timeout: cs.timeout, raiseOnError: false });
2232
+ if (conn.status === "error") {
2233
+ await conns.deactivateConnector(team.locationId, found.id, { timeout: cs.timeout });
2234
+ conn = unwrap(await conns.reactivateConnector(team.locationId, found.id, { timeout: cs.timeout }));
1834
2235
  }
1835
- const settled = await c.connectors.waitForStatus(locationId, fid, ["active", "error", "inactive"], wait);
1836
- if (settled.status === "active") return settled;
1837
- if (settled.status !== "inactive") await c.connectors.deactivateConnector(locationId, fid, wait);
1838
- return (await c.connectors.reactivateConnector(locationId, fid, wait)).data ?? null;
1839
- } catch (err) {
1840
- if (!(err instanceof ConnectorError)) throw err;
1841
- if (!found) created.push("connector");
1842
- return err.connector ?? null;
1843
2236
  }
1844
- });
1845
- connectorId = conn?.id ?? null;
1846
- connectorStatus = conn?.status ?? null;
1847
- connectorStateReason = conn?.state_reason ?? null;
1848
- partial.connectorId = connectorId;
1849
- if (connectorId && connectorStatus === "active" && cs.monitoredNumbers?.length) {
1850
- await step("monitored_numbers", partial, async () => {
1851
- await c.firstAlert.addMonitoredNumbers(locationId, connectorId, cs.monitoredNumbers);
1852
- await c.insightsHub.addNumbers(locationId, connectorId, cs.monitoredNumbers);
1853
- });
2237
+ } else {
2238
+ result?.created.push(label);
2239
+ conn = unwrap(await conns.createConnector(team.locationId, { name, type: cs.type, config }, { timeout: cs.timeout }));
1854
2240
  }
1855
- } else {
1856
- const found = await step("connector", partial, () => this.bestConnector(locationId));
1857
- connectorId = found?.id ?? null;
1858
- connectorStatus = found?.status ?? null;
1859
- connectorStateReason = found?.state_reason ?? null;
1860
- }
1861
- let ssoTxtRecord = null;
1862
- if (spec.sso?.domain) {
1863
- ssoTxtRecord = await step("sso_domain", partial, async () => {
1864
- const d = (await c.sso.claimCompanyDomain(companyId, { domain: spec.sso.domain })).data;
1865
- return { type: d?.verification?.type ?? "TXT", name: d?.verification?.name ?? "", value: d?.verification?.value ?? "" };
1866
- });
2241
+ } catch (exc) {
2242
+ if (exc instanceof ConnectorError || exc instanceof ConnectorTimeoutError) {
2243
+ this.setConn(team, exc.connector ?? {});
2244
+ return exc;
2245
+ }
2246
+ throw exc;
1867
2247
  }
1868
- return {
1869
- companyId,
1870
- companyName: spec.companyName,
1871
- locationId,
1872
- locationName: spec.location.name,
1873
- groups: { managerAlerts, insightsHubAccess: ihAccess },
1874
- rules,
1875
- connectorId,
1876
- connectorStatus,
1877
- connectorStateReason,
1878
- created,
1879
- existing,
1880
- ssoTxtRecord
1881
- };
2248
+ this.setConn(team, conn);
2249
+ if (conn.status === "error") return new ConnectorError(conn);
2250
+ return null;
2251
+ }
2252
+ setConn(team, conn) {
2253
+ team.connectorId = conn.id ?? null;
2254
+ team.connectorStatus = conn.status ?? null;
2255
+ team.connectorStateReason = conn.state_reason ?? null;
1882
2256
  }
2257
+ // ------------------------------------------------------------------ teams and alerts
1883
2258
  /**
1884
- * Switch on the customer's two alert rules (Upset Customer, Customer Threat). Rules already on are
1885
- * left as they are. Returns the ids of the rules this call switched on.
2259
+ * Add a further team: its location, connector (required; give the key in full each time), groups,
2260
+ * rules (copying the phrases and levels of the first team's rules, except where `alerts` sets them)
2261
+ * and Insights Hub setup. The rules are created switched off.
1886
2262
  */
1887
- async activateSeatAlerts(ref) {
1888
- const c = this.c;
1889
- const customer = await this.resolve(ref);
1890
- const switched = [];
1891
- await step("activate_alerts", { switched }, async () => {
1892
- for (const id of [customer.rules.upsetCustomer, customer.rules.customerThreat]) {
1893
- if (!id) continue;
1894
- const r = (await c.firstAlert.getAlertRule(customer.locationId, id)).data?.attributes;
1895
- if (r?.enabled !== true) {
1896
- await c.firstAlert.updateAlertRule(customer.locationId, id, { enabled: true });
1897
- switched.push(id);
2263
+ async addTeam(customer, team, connector, options = {}) {
2264
+ await this.requireAdmin();
2265
+ if (!team || typeof team !== "object") throw new InvalidRequestError("team must be a TeamSpec");
2266
+ await this.checkConnector(connector, true);
2267
+ checkAlerts(options.alerts);
2268
+ const cust = await this.resolve(customer);
2269
+ if (cust.management !== null && team.name === cust.management.name) {
2270
+ throw new InvalidRequestError("That name is the Management location; name the team differently");
2271
+ }
2272
+ await this.verticalId(team.vertical);
2273
+ const settings = this.settingsFrom(options.alerts);
2274
+ const first = cust.teams.find((t) => t.name !== team.name);
2275
+ const made = newTeam("", team.name);
2276
+ let failure = null;
2277
+ const run = this.run(made);
2278
+ try {
2279
+ run.step = "copy_alerts";
2280
+ if (first !== void 0) {
2281
+ for (const key of RULE_FIELDS) {
2282
+ const d = RULES[key];
2283
+ const rid = first.rules[key];
2284
+ if (rid === null) continue;
2285
+ const [phr, lvl] = ruleSettings(unwrap(await this.c.firstAlert.getAlertRule(first.locationId, rid)) ?? {});
2286
+ const [givenPhr, givenLvl] = settings[key];
2287
+ settings[key] = [givenPhr !== null ? givenPhr : d.hasPhrases ? phr : null, givenLvl !== null ? givenLvl : lvl];
1898
2288
  }
1899
2289
  }
1900
- });
1901
- return switched;
2290
+ run.step = "location";
2291
+ const loc = await this.ensureLocation(cust.companyId, team.name, team, "team", !!options.reactivate, cust);
2292
+ made.locationId = loc.locationId;
2293
+ run.step = "connector";
2294
+ failure = await this.ensureConnector(made, connector, cust);
2295
+ run.step = "groups";
2296
+ await this.ensureGroups(made, cust);
2297
+ run.step = "rules";
2298
+ await this.ensureRules(made, settings, cust);
2299
+ run.step = "insights_hub";
2300
+ await this.ensureInsightsHub(made);
2301
+ const existing = cust.teams.findIndex((t) => t.locationId === made.locationId);
2302
+ if (existing < 0) cust.teams.push(made);
2303
+ else cust.teams[existing] = made;
2304
+ cust.pending = this.pendingOf(cust);
2305
+ } catch (exc) {
2306
+ this.stop(run, exc);
2307
+ }
2308
+ raiseConnectorFailure(failure ? [failure] : [], made);
2309
+ return made;
1902
2310
  }
1903
2311
  /**
1904
- * End user: create (or find) the user without an invitation (frontline, After Call only, at the
1905
- * location), alert email off, map their extension, then add the extension to every manager's
1906
- * mapping and to the First Alert and Insights Hub numbers, and last email the invitation (unless
1907
- * `user.sendInvitation` is false). A refused mapping stops before managers, First Alert and
1908
- * Insights Hub are touched and throws ExtensionMappingError; no invitation has been sent.
2312
+ * Create or update the three rules' phrases and sentiment levels on one team or on every team.
2313
+ * Anything left out is kept. Existing rules keep their on or off state; a rule created here (one
2314
+ * that was pending its phrases) starts switched off: `activateAlerts` switches it on. Returns the
2315
+ * ids of the rules created or changed.
1909
2316
  */
1910
- async addFrontlineUser(ref, user, extension) {
1911
- const c = this.c;
1912
- const ext = String(extension ?? "").trim();
1913
- if (!ext) throw new FilterError("extension is required.");
1914
- const customer = await this.resolve(ref);
1915
- if (!customer.connectorId) throw new FilterError("This customer has no connector; add one before adding end users.");
1916
- const connectorId = customer.connectorId;
1917
- const partial = {};
1918
- const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
1919
- partial.userId = userId;
1920
- await step("enable_after_call", partial, () => c.products.enableUserProduct(customer.locationId, userId, "after-call-copilot"));
1921
- await step(
1922
- "alert_email_off",
1923
- partial,
1924
- () => c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: false, alerts: [] })
1925
- );
1926
- await step("map_extension", partial, () => this.mapNumbers(customer, userId, [ext]));
1927
- const managersUpdated = [];
1928
- partial.managersUpdated = managersUpdated;
1929
- await step("managers", partial, async () => {
1930
- for (const m of await this.lineHolders(customer)) {
1931
- if (m.id === userId) continue;
1932
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
1933
- if (cur.includes(ext)) continue;
1934
- await this.mapNumbers(customer, m.id, [...cur, ext]);
1935
- managersUpdated.push(m.id);
2317
+ async setAlerts(customer, alerts, options = {}) {
2318
+ await this.requireAdmin();
2319
+ checkAlerts(alerts);
2320
+ if (alerts === null || alerts === void 0) throw new InvalidRequestError("alerts is required");
2321
+ const cust = await this.resolve(customer);
2322
+ const teams = this.teamsOf(cust, options.team);
2323
+ const settings = this.settingsFrom(alerts);
2324
+ const changed = [];
2325
+ const run = this.run(changed);
2326
+ try {
2327
+ for (const t of teams) {
2328
+ run.step = `rules:${t.name}`;
2329
+ changed.push(...await this.ensureRules(t, settings, null));
1936
2330
  }
1937
- });
1938
- await step("first_alert_numbers", partial, () => c.firstAlert.addMonitoredNumbers(customer.locationId, connectorId, [ext]));
1939
- await step("insights_hub_numbers", partial, () => c.insightsHub.addNumbers(customer.locationId, connectorId, [ext]));
1940
- const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
1941
- return {
1942
- userId,
1943
- email: user.email,
1944
- kind: "frontline",
1945
- extensions: [ext],
1946
- managersUpdated,
1947
- created,
1948
- invited,
1949
- alertsActivated: []
1950
- };
2331
+ cust.pending = this.pendingOf(cust);
2332
+ } catch (exc) {
2333
+ this.stop(run, exc);
2334
+ }
2335
+ return changed;
1951
2336
  }
1952
2337
  /**
1953
- * Manager: create (or find) the user without an invitation, with After Call, First Alert and
1954
- * Insights Hub at the location, both groups, alert email on for every rule they receive, and a
1955
- * mapping of exactly the end-user lines at the location. The manager's own phone line is not
1956
- * captured on the Seat: it is never mapped, nor added to First Alert or Insights Hub, and an
1957
- * extension passed as the third argument throws FilterError. Then, with `activateAlerts`
1958
- * (default true), switch the customer's two alert rules on (see activateSeatAlerts), and last
1959
- * email the invitation (unless `user.sendInvitation` is false). A refused mapping throws
1960
- * ExtensionMappingError: the rules stay as they were and no invitation has been sent.
2338
+ * Attach a phone system to a customer created without one: the named team, or the first team and
2339
+ * Management. Refuses (InvalidRequestError, before any write) where an active connector exists.
2340
+ * Returns the teams it attached.
1961
2341
  */
1962
- async addManager(ref, user, options = {}) {
1963
- const c = this.c;
1964
- const opts = options ?? {};
1965
- if (typeof opts !== "object" || Object.keys(opts).some((k) => k !== "activateAlerts")) {
1966
- throw new FilterError("A manager's own phone line is not captured on the Seat: addManager takes no extension.");
1967
- }
1968
- const customer = await this.resolve(ref);
1969
- const partial = {};
1970
- const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
1971
- partial.userId = userId;
1972
- await step("enable_products", partial, async () => {
1973
- for (const key of ALL_PRODUCTS) await c.products.enableUserProduct(customer.locationId, userId, key);
1974
- });
1975
- await step("groups", partial, async () => {
1976
- const ids = [customer.groups.managerAlerts, customer.groups.insightsHubAccess].filter((x) => Boolean(x));
1977
- if (ids.length) await c.groups.addUserToGroups(customer.locationId, userId, ids);
1978
- });
1979
- await step("alert_email_on", partial, async () => {
1980
- const prefs = await c.firstAlert.getAlertNotificationPreferences(customer.locationId, userId);
1981
- const alerts = (prefs.emailNotifications?.alerts ?? []).filter((a) => a.alertId).map((a) => ({ alertId: a.alertId, emailEnabled: true }));
1982
- await c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: true, alerts });
1983
- });
1984
- const lines = await step("read_lines", partial, () => this.locationLines(customer));
1985
- const all = [...lines];
1986
- if (all.length) await step("map_all_lines", partial, () => this.mapNumbers(customer, userId, all));
1987
- const alertsActivated = opts.activateAlerts ?? true ? await this.activateSeatAlerts(customer) : [];
1988
- partial.alertsActivated = alertsActivated;
1989
- const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
1990
- return { userId, email: user.email, kind: "manager", extensions: all, managersUpdated: [], created, invited, alertsActivated };
2342
+ async setConnector(customer, connector, options = {}) {
2343
+ await this.requireAdmin();
2344
+ await this.checkConnector(connector, true);
2345
+ const cust = await this.resolve(customer);
2346
+ let targets;
2347
+ if (options.team !== void 0 && options.team !== null) {
2348
+ targets = [this.teamOf(cust, options.team)];
2349
+ } else {
2350
+ if (!cust.teams.length) throw new InvalidRequestError("This customer has no team");
2351
+ targets = [cust.teams[0], ...cust.management ? [cust.management] : []];
2352
+ }
2353
+ const todo = [];
2354
+ for (const t of targets) {
2355
+ const name = connector.name || `${t.name} phone system`;
2356
+ const found = await this.findConnector(t.locationId, connector, name);
2357
+ const active = (await all(this.c.connectors.iterLocationConnectors(t.locationId))).filter((x) => RUNNING.includes(x.status));
2358
+ const same = found !== null && RUNNING.includes(found.status) && Object.entries(plainConfig(connector.config)).every(
2359
+ ([k, v]) => !(k in (found.config ?? {})) || isSecretName(k) || deepEqual(found.config[k], v)
2360
+ );
2361
+ if (active.length && !same) throw new InvalidRequestError(`${t.name} already has an active connector`);
2362
+ if (same) {
2363
+ this.setConn(t, found);
2364
+ continue;
2365
+ }
2366
+ todo.push(t);
2367
+ }
2368
+ const run = this.run(targets);
2369
+ const failures = [];
2370
+ try {
2371
+ for (const t of todo) {
2372
+ run.step = `connector:${t.name}`;
2373
+ const failure = await this.ensureConnector(t, connector, cust);
2374
+ if (failure) failures.push(failure);
2375
+ }
2376
+ } catch (exc) {
2377
+ this.stop(run, exc);
2378
+ }
2379
+ raiseConnectorFailure(failures, targets);
2380
+ return targets;
1991
2381
  }
1992
2382
  /**
1993
- * Integration user (reads calls, alerts and insights for another system; never a seat or a
1994
- * manager): create (or find) the user without an invitation, tag it `department: "integration"`,
1995
- * switch on After Call, First Alert and Insights Hub, add it to both groups, switch every alert
1996
- * email off, map all lines, and last email the invitation (unless `user.sendInvitation` is false;
1997
- * the person who holds the integration's password accepts it). Integration users keep every line
1998
- * as end users come and go (like managers) and release no lines when removed. The user must sign
1999
- * in with a password (`authMethod: "password"`). Never switches alerts on.
2383
+ * Switch the rules on for every team. A team does not need a manager: its alerts then show in the app
2384
+ * only, and the team is listed under `noManager` with the alert groups that have none.
2000
2385
  */
2001
- async addIntegrationUser(ref, user) {
2002
- const c = this.c;
2003
- if ((user?.authMethod ?? "password") !== "password") {
2004
- throw new FilterError('An integration user signs in with a password (authMethod: "password").');
2005
- }
2006
- const customer = await this.resolve(ref);
2007
- const partial = {};
2008
- const { id: userId, created, status } = await step("create_user", partial, () => this.ensureUser(customer, user));
2009
- partial.userId = userId;
2010
- await step(
2011
- "tag_integration",
2012
- partial,
2013
- () => c.users.updateCompanyUser(customer.companyId, userId, { department: INTEGRATION_DEPARTMENT })
2014
- );
2015
- await step("enable_products", partial, async () => {
2016
- for (const key of ALL_PRODUCTS) await c.products.enableUserProduct(customer.locationId, userId, key);
2017
- });
2018
- await step("groups", partial, async () => {
2019
- const ids = [customer.groups.managerAlerts, customer.groups.insightsHubAccess].filter((x) => Boolean(x));
2020
- if (ids.length) await c.groups.addUserToGroups(customer.locationId, userId, ids);
2021
- });
2022
- await step(
2023
- "alert_email_off",
2024
- partial,
2025
- () => c.firstAlert.setAlertEmailPreferences(customer.locationId, userId, { masterEnabled: false, alerts: [] })
2026
- );
2027
- const lines = await step("read_lines", partial, () => this.locationLines(customer));
2028
- if (lines.length) await step("map_all_lines", partial, () => this.mapNumbers(customer, userId, lines));
2029
- const invited = await step("invitation", partial, () => this.invite(customer, user, userId, status));
2030
- return { userId, email: user.email, kind: "integration", extensions: lines, managersUpdated: [], created, invited, alertsActivated: [] };
2031
- }
2032
- /** Move an end user from one extension to another: their mapping, every manager and integration user, First Alert, Insights Hub. */
2033
- async changeUserExtension(ref, userId, oldExtension, newExtension) {
2034
- const c = this.c;
2035
- const oldExt = String(oldExtension ?? "").trim();
2036
- const newExt = String(newExtension ?? "").trim();
2037
- if (!oldExt || !newExt) throw new FilterError("oldExtension and newExtension are required.");
2038
- const customer = await this.resolve(ref);
2039
- const connectorId = this.requireConnector(customer);
2040
- const swap = (cur) => [.../* @__PURE__ */ new Set([...cur.filter((n) => n !== oldExt), newExt])];
2041
- const partial = { userId };
2042
- await step(
2043
- "user_mapping",
2044
- partial,
2045
- async () => this.mapNumbers(customer, userId, swap(await c.users.userNumbers(customer.companyId, userId, connectorId)))
2046
- );
2047
- const managersUpdated = [];
2048
- partial.managersUpdated = managersUpdated;
2049
- await step("managers", partial, async () => {
2050
- for (const m of await this.lineHolders(customer)) {
2051
- if (m.id === userId) continue;
2052
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2053
- const target = swap(cur);
2054
- if (sameSet(cur, target)) continue;
2055
- await this.mapNumbers(customer, m.id, target);
2056
- managersUpdated.push(m.id);
2386
+ async activateAlerts(customer, options = {}) {
2387
+ await this.requireAdmin();
2388
+ const cust = await this.resolve(customer);
2389
+ const out = { switchedOn: [], noManager: [] };
2390
+ const people = await this.index(cust);
2391
+ const managers = new Set([...people.values()].filter((p) => p.license === "base_manager").map((p) => p.id));
2392
+ const run = this.run(out);
2393
+ try {
2394
+ for (const t of this.teamsOf(cust, options.team)) {
2395
+ run.step = `activate:${t.name}`;
2396
+ const missing = [];
2397
+ for (const f of ALERT_GROUPS) {
2398
+ const gid = t.groups[f];
2399
+ let members = /* @__PURE__ */ new Set();
2400
+ if (gid) {
2401
+ const grp = unwrap(await this.c.groups.getUserGroup(t.locationId, gid)) ?? {};
2402
+ members = new Set((grp.members ?? []).map((m) => m.id));
2403
+ }
2404
+ if (![...members].some((m) => managers.has(m))) missing.push(TEAM_GROUPS[f]);
2405
+ }
2406
+ if (missing.length) out.noManager.push({ locationId: t.locationId, team: t.name, missing });
2407
+ for (const key of RULE_FIELDS) {
2408
+ const rid = t.rules[key];
2409
+ if (!rid) continue;
2410
+ const rule = unwrap(await this.c.firstAlert.getAlertRule(t.locationId, rid)) ?? {};
2411
+ if (!rule.enabled) {
2412
+ await this.c.firstAlert.updateAlertRule(t.locationId, rid, { enabled: true });
2413
+ out.switchedOn.push(rid);
2414
+ }
2415
+ }
2057
2416
  }
2058
- });
2059
- await step("first_alert_numbers", partial, async () => {
2060
- const cfg = (await c.firstAlert.getFirstAlertConfig(customer.locationId)).data;
2061
- await c.firstAlert.setMonitoredNumbers(customer.locationId, connectorId, swap(numbersFor(cfg?.connector_mappings, connectorId)));
2062
- });
2063
- await step("insights_hub_numbers", partial, async () => {
2064
- const setup = (await c.insightsHub.getInsightsHubSetup(customer.locationId)).data?.attributes;
2065
- await c.insightsHub.setNumbers(customer.locationId, connectorId, swap(numbersFor(setup?.connector_mappings, connectorId)));
2066
- });
2067
- return { userId, oldExtension: oldExt, newExtension: newExt, managersUpdated };
2417
+ } catch (exc) {
2418
+ this.stop(run, exc);
2419
+ }
2420
+ return out;
2068
2421
  }
2069
- /**
2070
- * Remove a user, in this order: leave every group, clear their number mapping, take their line off
2071
- * managers, integration users, First Alert and Insights Hub (unless `keepExtensions`), then
2072
- * deactivate. Products are left as they are.
2073
- *
2074
- * Only an end user releases a line, and only a line no other end user at the location still
2075
- * holds. Managers, integration users (`department: "integration"`), excluded users and any
2076
- * non-manager holding more than one line release nothing: every other line stays where it is.
2077
- */
2078
- async removeUser(ref, userId, options = {}) {
2422
+ // ------------------------------------------------------------------ people: reading
2423
+ /** Everyone at the customer's locations, with products and groups per location, lines and license. */
2424
+ async index(cust, includeInactive = false) {
2079
2425
  const c = this.c;
2080
- const customer = await this.resolve(ref);
2081
- const partial = { userId };
2082
- const row = await step("read_user", partial, async () => (await c.users.getLocationUser(customer.locationId, userId)).data?.attributes ?? {});
2083
- const detail = await step("read_user", partial, async () => (await c.users.getCompanyUser(customer.companyId, userId)).data?.attributes ?? {});
2084
- const u = { enabledProducts: [...row.enabled_products ?? []], department: detail.department ?? null };
2085
- const connectorId = customer.connectorId;
2086
- const mappings = await step("read_mapping", partial, async () => (await c.users.getUserNumberMappings(customer.companyId, userId)).data ?? []);
2087
- const own = connectorId ? numbersFor(mappings, connectorId) : [];
2088
- const kind = isIntegration(u) || this.excluded(customer, userId, detail.email ?? row.email) ? "integration" : isManager(u) ? "manager" : own.length > 1 ? "integration" : "frontline";
2089
- let release = [];
2090
- if (kind === "frontline" && !options.keepExtensions && connectorId && own.length) {
2091
- const held = /* @__PURE__ */ new Set();
2092
- await step("read_end_user_lines", partial, async () => {
2093
- for (const f of await this.listFrontlineUsers(customer)) {
2094
- if (f.id === userId) continue;
2095
- for (const n of await c.users.userNumbers(customer.companyId, f.id, connectorId)) held.add(n);
2096
- }
2097
- });
2098
- release = own.filter((n) => !held.has(n));
2099
- }
2100
- await step("groups", partial, () => c.groups.removeUserFromGroups(customer.locationId, userId));
2101
- if (mappings.length) {
2102
- await step("clear_mapping", partial, () => c.users.setUserNumberMappings(customer.companyId, userId, { mappings: [] }));
2103
- }
2104
- const managersUpdated = [];
2105
- if (release.length && connectorId) {
2106
- partial.managersUpdated = managersUpdated;
2107
- await step("managers", partial, async () => {
2108
- for (const m of await this.lineHolders(customer)) {
2109
- if (m.id === userId) continue;
2110
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2111
- if (!cur.some((n) => release.includes(n))) continue;
2112
- await this.mapNumbers(customer, m.id, cur.filter((n) => !release.includes(n)));
2113
- managersUpdated.push(m.id);
2426
+ let people = /* @__PURE__ */ new Map();
2427
+ for (const t of this.locationsOf(cust)) {
2428
+ for (const r of await all(c.users.iterLocationUsers(t.locationId))) {
2429
+ let p = people.get(r.id);
2430
+ if (p === void 0) {
2431
+ p = new Person(r.id, r.email ?? "", r.status ?? null);
2432
+ people.set(r.id, p);
2114
2433
  }
2115
- });
2116
- await step("first_alert_numbers", partial, () => c.firstAlert.removeMonitoredNumbers(customer.locationId, connectorId, release));
2117
- await step("insights_hub_numbers", partial, () => c.insightsHub.removeNumbers(customer.locationId, connectorId, release));
2434
+ p.locs.set(t.locationId, { products: new Set(r.enabled_products ?? []), groups: new Set(r.groups ?? []) });
2435
+ }
2118
2436
  }
2119
- await step("deactivate", partial, async () => {
2120
- try {
2121
- await c.users.deactivateCompanyUser(customer.companyId, userId);
2122
- } catch (err) {
2123
- if (!(err instanceof ConflictError)) throw err;
2437
+ for (const u of await all(c.users.iterCompanyUsers(cust.companyId))) {
2438
+ const p = people.get(u.id);
2439
+ if (p !== void 0) {
2440
+ p.department = u.department ?? null;
2441
+ p.status = u.status ?? p.status;
2442
+ p.invitedAt = u.invited_at ?? null;
2443
+ p.inviteExpiresAt = u.invite_expires_at ?? null;
2124
2444
  }
2445
+ }
2446
+ if (!includeInactive) people = new Map([...people].filter(([, v]) => v.active));
2447
+ for (const p of people.values()) {
2448
+ if (p.active) p.mappings = unwrapMappings(await c.users.getUserNumberMappings(cust.companyId, p.id));
2449
+ this.classify(cust, p);
2450
+ }
2451
+ return people;
2452
+ }
2453
+ classify(cust, p) {
2454
+ const teamIds = cust.teams.map((t) => t.locationId);
2455
+ const mgmt = cust.management ? cust.management.locationId : null;
2456
+ const alertNames = new Set(ALERT_GROUPS.map((f) => TEAM_GROUPS[f]));
2457
+ p.teams = teamIds.filter((lid) => p.locs.has(lid));
2458
+ if (isIntegration({ department: p.department })) {
2459
+ p.license = "integration";
2460
+ return;
2461
+ }
2462
+ const allThree = [...p.locs.values()].some((v) => PRODUCT_KEYS.every((k) => v.products.has(k)));
2463
+ const inAlertGroups = p.teams.some((lid) => [...p.locs.get(lid).groups].some((g) => alertNames.has(g)));
2464
+ if (allThree && mgmt !== null && p.locs.has(mgmt) && inAlertGroups) {
2465
+ p.license = "base_manager";
2466
+ return;
2467
+ }
2468
+ const conn = new Map(cust.teams.map((t) => [t.locationId, t.connectorId]));
2469
+ const ownLine = p.teams.some((lid) => conn.get(lid) && p.numbers(conn.get(lid)).length > 0);
2470
+ const onlyAfterCall = p.teams.length > 0 && p.teams.every((lid) => {
2471
+ const prods = p.locs.get(lid).products;
2472
+ return prods.size === 1 && prods.has(AFTER_CALL);
2125
2473
  });
2126
- return { userId, kind, extensionsReleased: release, managersUpdated };
2127
- }
2128
- /** End users: invited or active frontline users with After Call only (integration and excluded users left out). */
2129
- async listFrontlineUsers(ref) {
2130
- const customer = await this.resolve(ref);
2131
- return (await this.seatUsers(customer)).filter(isFrontline);
2474
+ if (onlyAfterCall && ownLine && !(mgmt !== null && p.locs.has(mgmt))) {
2475
+ p.license = "base_user";
2476
+ return;
2477
+ }
2478
+ p.license = "other";
2479
+ }
2480
+ member(p) {
2481
+ return newMember(p.id, p.email, p.license, [...p.teams], p.numbers());
2482
+ }
2483
+ async person(cust, userId, includeInactive = false) {
2484
+ const people = await this.index(cust, includeInactive);
2485
+ const p = people.get(userId);
2486
+ if (p === void 0) throw new InvalidRequestError(`User ${userId} is not at any of this customer's locations`);
2487
+ return [p, people];
2488
+ }
2489
+ /** People who hold a team's lines: its Base Managers and integration users. */
2490
+ holders(team, people, exclude = []) {
2491
+ const skip = new Set(exclude);
2492
+ return [...people.values()].filter(
2493
+ (p) => p.active && !skip.has(p.id) && p.teams.includes(team.locationId) && (p.license === "base_manager" || p.license === "integration")
2494
+ );
2132
2495
  }
2133
- /** Managers: invited or active frontline users with After Call, First Alert and Insights Hub (integration and excluded users left out). */
2134
- async listManagers(ref) {
2135
- const customer = await this.resolve(ref);
2136
- return (await this.seatUsers(customer)).filter(isManager);
2496
+ /**
2497
+ * The team line this person owns: anyone active on the team, not a Base Manager or integration user,
2498
+ * with After Call on there and exactly one number on its connector. A Base User normally; also
2499
+ * someone read back as "other" (for example with First Alert switched on in the app), whose line is
2500
+ * never taken away.
2501
+ */
2502
+ ownedLine(p, team) {
2503
+ 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)) {
2504
+ return null;
2505
+ }
2506
+ const nums = p.numbers(team.connectorId);
2507
+ return nums.length === 1 ? nums[0] : null;
2508
+ }
2509
+ /** user id -> the team line they own. */
2510
+ owners(team, people, exclude = []) {
2511
+ const skip = new Set(exclude);
2512
+ const out = /* @__PURE__ */ new Map();
2513
+ for (const p of people.values()) {
2514
+ if (skip.has(p.id)) continue;
2515
+ const l = this.ownedLine(p, team);
2516
+ if (l !== null) out.set(p.id, l);
2517
+ }
2518
+ return out;
2137
2519
  }
2138
- /** Integration users at the location: users tagged `department: "integration"`. */
2139
- async listIntegrationUsers(ref) {
2140
- const customer = await this.resolve(ref);
2141
- return (await this.seatUsers(customer)).filter(isIntegration);
2520
+ /** A team's lines: the line of every person who owns one there. */
2521
+ teamLines(team, people, exclude = []) {
2522
+ return uniq(this.owners(team, people, exclude).values());
2142
2523
  }
2143
2524
  /**
2144
- * A customer leaves. In order: pause the After Call webhook (the address is kept; it can't be
2145
- * deleted), clear the First Alert webhook address (numbers kept), deactivate the connector (which
2146
- * stops call capture), deactivate the integration users, and deactivate the company (unless
2147
- * `deactivateCompany: false`). Steps already done are skipped, so it is safe to run again.
2148
- * Ask your Tresic contact about the retention of the customer's data.
2525
+ * Refuse, before any write, to give an existing person a different license through an add helper:
2526
+ * that would take away lines they hold. `changeLicense` converts Base Users and Base Managers. A
2527
+ * person read back as "other" (for example one an earlier run of this helper left part-way) is
2528
+ * accepted when the helper cannot take anything away from them.
2149
2529
  */
2150
- async offboardCustomer(ref, options = {}) {
2151
- const c = this.c;
2152
- const customer = await this.resolve(ref);
2153
- const loc = customer.locationId;
2154
- const result = {
2155
- webhookPaused: false,
2156
- firstAlertWebhookCleared: false,
2157
- connectorDeactivated: false,
2158
- integrationUsersDeactivated: [],
2159
- companyDeactivated: false
2160
- };
2161
- const partial = result;
2162
- const already = (err) => {
2163
- if (!(err instanceof ConflictError)) throw err;
2530
+ async checkExisting(cust, email, target) {
2531
+ const found = await this.c.users.findUserByEmail(cust.companyId, email);
2532
+ if (found === null || !found.id) return;
2533
+ const p = (await this.index(cust, true)).get(found.id);
2534
+ if (p === void 0 || !p.active || p.license === target) return;
2535
+ const mgmt = cust.management ? cust.management.locationId : null;
2536
+ if (p.license === "other") {
2537
+ const nums = uniq(p.numbers());
2538
+ if (target === "base_user" && nums.length <= 1 && !(mgmt !== null && p.locs.has(mgmt))) return;
2539
+ if (target === "base_manager" && (!nums.length || mgmt !== null && p.locs.has(mgmt))) return;
2540
+ if (target === "integration" && !nums.length) return;
2541
+ }
2542
+ 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";
2543
+ throw new InvalidRequestError(`${email} is already set up as "${p.license}", not "${target}": ${hint}`);
2544
+ }
2545
+ /** Notes for the teams whose alert groups this person leaves with no Base Manager in them. */
2546
+ emptiedGroups(cust, people, uid, teamIds) {
2547
+ const notes = [];
2548
+ const p = people.get(uid);
2549
+ const wanted = new Set(teamIds);
2550
+ for (const t of cust.teams) {
2551
+ if (p === void 0 || !wanted.has(t.locationId) || !p.locs.has(t.locationId)) continue;
2552
+ const empty = [];
2553
+ for (const f of ALERT_GROUPS) {
2554
+ const name = TEAM_GROUPS[f];
2555
+ if (!p.locs.get(t.locationId).groups.has(name)) continue;
2556
+ const another = [...people.values()].some(
2557
+ (q) => q.id !== uid && q.active && q.license === "base_manager" && q.locs.has(t.locationId) && q.locs.get(t.locationId).groups.has(name)
2558
+ );
2559
+ if (!another) empty.push(name);
2560
+ }
2561
+ if (empty.length) notes.push(`${t.name} has no Base Manager left in ${empty.join(", ")}; its alerts were not changed.`);
2562
+ }
2563
+ return notes;
2564
+ }
2565
+ /**
2566
+ * Everyone active at the customer's locations, with license, teams and lines.
2567
+ *
2568
+ * `license`: "base_user", "base_manager", "integration" or "other". A Base User has After Call on and
2569
+ * their own line mapped; a Base Manager has all three products, is on Management and is in the alert
2570
+ * groups of at least one team; an integration user is tagged as one; anyone else is "other", listed
2571
+ * so it can be corrected.
2572
+ */
2573
+ async listMembers(customer, options = {}) {
2574
+ await this.requireAdmin();
2575
+ const license = options.license ?? null;
2576
+ if (license !== null && !LICENSES.includes(license)) throw new InvalidRequestError(`license: one of ${JSON.stringify(LICENSES)}`);
2577
+ const cust = await this.resolve(customer);
2578
+ const lid = options.team !== void 0 && options.team !== null ? this.teamOf(cust, options.team).locationId : null;
2579
+ const out = [];
2580
+ for (const p of (await this.index(cust)).values()) {
2581
+ if (license !== null && p.license !== license) continue;
2582
+ if (lid !== null && !p.teams.includes(lid)) continue;
2583
+ out.push(this.member(p));
2584
+ }
2585
+ return out;
2586
+ }
2587
+ /** People by license and the number of teams (Management not counted). */
2588
+ async licenseReport(customer) {
2589
+ const cust = await this.resolve(customer);
2590
+ const members = await this.listMembers(cust);
2591
+ const by = { baseUser: [], baseManager: [], integration: [], other: [] };
2592
+ for (const m of members) {
2593
+ if (m.license === "base_user") by.baseUser.push(m);
2594
+ else if (m.license === "base_manager") by.baseManager.push(m);
2595
+ else if (m.license === "integration") by.integration.push(m);
2596
+ else by.other.push(m);
2597
+ }
2598
+ return {
2599
+ baseUser: by.baseUser.length,
2600
+ baseManager: by.baseManager.length,
2601
+ integration: by.integration.length,
2602
+ other: by.other.length,
2603
+ teams: cust.teams.length,
2604
+ members: by
2164
2605
  };
2165
- await step("pause_after_call_webhook", partial, async () => {
2166
- let hook = null;
2606
+ }
2607
+ // ------------------------------------------------------------------ people: low-level steps
2608
+ /**
2609
+ * Find or create the person (never emailing an invitation here) and make sure they are on
2610
+ * `locationIds`. Returns (id, created, company user).
2611
+ */
2612
+ async ensureUser(cust, person, locationIds) {
2613
+ const users = this.c.users;
2614
+ const found = await users.findUserByEmail(cust.companyId, person.email);
2615
+ if (found === null) {
2616
+ const body = {
2617
+ email: person.email,
2618
+ first_name: person.firstName,
2619
+ last_name: person.lastName,
2620
+ role: "frontline_user",
2621
+ location_ids: [...locationIds],
2622
+ send_invitation: false,
2623
+ auth_method: person.authMethod ?? "password"
2624
+ };
2625
+ if (person.phoneNumber) body.phone_number = person.phoneNumber;
2626
+ let row = unwrap(await users.createCompanyUser(cust.companyId, body)) ?? {};
2627
+ if (!row || typeof row !== "object" || !row.id) {
2628
+ const again = await users.findUserByEmail(cust.companyId, person.email);
2629
+ if (!again?.id) throw new InvalidRequestError("The user was not found after it was created");
2630
+ row = { ...again };
2631
+ }
2632
+ row.status ??= "invited";
2633
+ return [row.id, true, row];
2634
+ }
2635
+ const uid = found.id;
2636
+ if (found.status === "deactivated") await users.reactivateCompanyUser(cust.companyId, uid);
2637
+ const detail = unwrap(await users.getCompanyUser(cust.companyId, uid)) ?? {};
2638
+ if (detail.role !== "frontline_user") {
2639
+ throw new InvalidRequestError(`${person.email} has role ${detail.role}; licensed people are frontline users`);
2640
+ }
2641
+ await this.addLocations(cust, uid, locationIds, detail);
2642
+ return [uid, false, detail];
2643
+ }
2644
+ async addLocations(cust, uid, locationIds, detail) {
2645
+ const d = detail ?? unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2646
+ const have = (d.locations ?? []).map((x) => x.location_id);
2647
+ if (locationIds.some((lid) => !have.includes(lid))) {
2648
+ await this.c.users.updateCompanyUser(cust.companyId, uid, { location_ids: uniq([...have, ...locationIds]) });
2649
+ }
2650
+ }
2651
+ async removeLocations(cust, uid, locationIds) {
2652
+ const d = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2653
+ const have = (d.locations ?? []).map((x) => x.location_id);
2654
+ const drop = new Set(locationIds);
2655
+ const keep = have.filter((x) => !drop.has(x));
2656
+ if (keep.length !== have.length) await this.c.users.updateCompanyUser(cust.companyId, uid, { location_ids: keep });
2657
+ }
2658
+ async productsOn(locationId, uid, keys) {
2659
+ const row = unwrap(await this.c.users.getLocationUser(locationId, uid)) ?? {};
2660
+ const have = new Set(row.enabled_products ?? []);
2661
+ for (const key of keys) if (!have.has(key)) await this.c.products.enableUserProduct(locationId, uid, key);
2662
+ }
2663
+ async productsOff(locationId, uid, keys) {
2664
+ const row = unwrap(await this.c.users.getLocationUser(locationId, uid)) ?? {};
2665
+ const have = new Set(row.enabled_products ?? []);
2666
+ for (const key of keys) if (have.has(key)) await this.c.products.disableUserProduct(locationId, uid, key);
2667
+ }
2668
+ async joinGroups(locationId, uid, groupIds) {
2669
+ const want = groupIds.filter((g) => !!g);
2670
+ const current = await this.c.groups.userGroupIds(locationId, uid);
2671
+ if (want.some((g) => !current.includes(g))) {
2672
+ await this.c.groups.setUserGroupMembership(locationId, uid, { group_ids: uniq([...current, ...want]) });
2673
+ }
2674
+ }
2675
+ async leaveGroups(locationId, uid, groupIds) {
2676
+ const current = await this.c.groups.userGroupIds(locationId, uid);
2677
+ const drop = new Set(groupIds ?? []);
2678
+ const keep = groupIds === void 0 ? [] : current.filter((g) => !drop.has(g));
2679
+ if (keep.length !== current.length || keep.some((g, i) => g !== current[i])) {
2680
+ await this.c.groups.setUserGroupMembership(locationId, uid, { group_ids: keep });
2681
+ }
2682
+ }
2683
+ /** Alert email off for a person the helpers create. Someone who has signed in keeps their own choice. */
2684
+ async emailOff(locationId, uid, created, status) {
2685
+ if (!(created || status === "invited")) return;
2686
+ const prefs = await this.c.firstAlert.getAlertNotificationPreferences(locationId, uid) ?? {};
2687
+ if ((prefs.emailNotifications ?? {}).masterEnabled !== false) {
2688
+ await this.c.firstAlert.setAlertEmailPreferences(locationId, uid, { masterEnabled: false, alerts: [] });
2689
+ }
2690
+ }
2691
+ async setMappings(cust, uid, mappings) {
2692
+ try {
2693
+ await this.c.users.setUserNumberMappings(cust.companyId, uid, { mappings });
2694
+ } catch (exc) {
2695
+ if (exc instanceof ValidationError || exc instanceof ConflictError) throw new ExtensionMappingError(uid, exc);
2696
+ throw exc;
2697
+ }
2698
+ }
2699
+ /** Set (`replace`) or add to the person's numbers on one connector; other connectors are kept. */
2700
+ async map(cust, uid, connectorId, numbers, current, replace = true) {
2701
+ const cur = current ?? unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, uid));
2702
+ const have = numbersOf(cur, connectorId);
2703
+ const target = replace ? [...numbers] : uniq([...have, ...numbers]);
2704
+ if (deepEqual(target, have)) return;
2705
+ const others = cur.filter((m) => m.connector_id !== connectorId);
2706
+ await this.setMappings(cust, uid, mergeMappings(others, connectorId, target));
2707
+ }
2708
+ /** The last step: email the invitation to a person who has none yet. */
2709
+ async invite(cust, uid, invite) {
2710
+ if (!invite) return false;
2711
+ const detail = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2712
+ if (detail.status !== "invited" || detail.invited_at) return false;
2713
+ await this.c.users.resendInvitation(cust.companyId, uid);
2714
+ return true;
2715
+ }
2716
+ async faNumbers(team) {
2717
+ const cfg = unwrap(await this.c.firstAlert.getFirstAlertConfig(team.locationId)) ?? {};
2718
+ return numbersOf(cfg.connector_mappings ?? [], team.connectorId);
2719
+ }
2720
+ async ihNumbers(team) {
2721
+ const setup = unwrap(await this.c.insightsHub.getInsightsHubSetup(team.locationId)) ?? {};
2722
+ return numbersOf(setup.connector_mappings ?? [], team.connectorId);
2723
+ }
2724
+ /** A team line onto First Alert, Insights Hub and every holder of the team's lines. */
2725
+ async attachLine(cust, team, ln, people, exclude = []) {
2726
+ const cid = team.connectorId;
2727
+ if (!(await this.faNumbers(team)).includes(ln)) await this.c.firstAlert.addMonitoredNumbers(team.locationId, cid, [ln]);
2728
+ if (!(await this.ihNumbers(team)).includes(ln)) await this.c.insightsHub.addNumbers(team.locationId, cid, [ln]);
2729
+ for (const h of this.holders(team, people, exclude)) {
2730
+ if (!h.numbers(cid).includes(ln)) await this.map(cust, h.id, cid, [ln], h.mappings, false);
2731
+ }
2732
+ }
2733
+ /**
2734
+ * Take a team line off its holders, First Alert and Insights Hub, unless another Base User at the
2735
+ * team still holds it. Returns true when it was released.
2736
+ */
2737
+ async releaseLine(cust, team, ln, people, leaving) {
2738
+ if (!team.connectorId) return false;
2739
+ if ([...this.owners(team, people, [leaving]).values()].includes(ln)) return false;
2740
+ for (const h of this.holders(team, people, [leaving])) {
2741
+ const have = h.numbers(team.connectorId);
2742
+ if (have.includes(ln)) await this.map(cust, h.id, team.connectorId, have.filter((n) => n !== ln), h.mappings);
2743
+ }
2744
+ if ((await this.faNumbers(team)).includes(ln)) await this.c.firstAlert.removeMonitoredNumbers(team.locationId, team.connectorId, [ln]);
2745
+ if ((await this.ihNumbers(team)).includes(ln)) await this.c.insightsHub.removeNumbers(team.locationId, team.connectorId, [ln]);
2746
+ return true;
2747
+ }
2748
+ needConnector(team) {
2749
+ if (!team.connectorId) throw new InvalidRequestError(`${team.name} has no connector: attach one with setConnector`);
2750
+ return team.connectorId;
2751
+ }
2752
+ /** Management and each team: products, groups, alert email off, lines. Returns the lines held. */
2753
+ async managerSetup(cust, uid, teams, ln, companyReports, created, status, run) {
2754
+ const mgmt = cust.management;
2755
+ run.step = "products";
2756
+ for (const t of [...teams, mgmt]) await this.productsOn(t.locationId, uid, PRODUCT_KEYS);
2757
+ run.step = "groups";
2758
+ for (const t of teams) await this.joinGroups(t.locationId, uid, GROUP_FIELDS.map((f) => t.groups[f]));
2759
+ if (companyReports) await this.joinGroups(mgmt.locationId, uid, [mgmt.groups.weeklyReports]);
2760
+ run.step = "alert_email";
2761
+ for (const t of teams) await this.emailOff(t.locationId, uid, created, status);
2762
+ run.step = "lines";
2763
+ const people = await this.index(cust);
2764
+ const current = unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, uid));
2765
+ let mappings = current.map((m) => ({ ...m }));
2766
+ if (ln) {
2767
+ mappings = mergeMappings(
2768
+ mappings.filter((m) => m.connector_id !== mgmt.connectorId),
2769
+ this.needConnector(mgmt),
2770
+ uniq([...numbersOf(current, mgmt.connectorId), ln])
2771
+ );
2772
+ }
2773
+ for (const t of teams) {
2774
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [uid]));
2775
+ }
2776
+ if (!sameMappings(mappings, current)) await this.setMappings(cust, uid, mappings);
2777
+ return numbersOf(mappings);
2778
+ }
2779
+ // ------------------------------------------------------------------ people: helpers
2780
+ /**
2781
+ * Add a Base User: created without an invitation, After Call on, their line mapped on the team's
2782
+ * connector and added to the team's First Alert and Insights Hub lines and to every Base Manager and
2783
+ * integration user of the team, then the invitation (if `invite`). If the line cannot be mapped,
2784
+ * AccountError (cause ExtensionMappingError) is thrown and no invitation is sent.
2785
+ */
2786
+ async addBaseUser(customer, person, options) {
2787
+ await this.requireAdmin();
2788
+ const cust = await this.resolve(customer);
2789
+ const t = this.teamOf(cust, options.team);
2790
+ const ln = line(options.line);
2791
+ this.needConnector(t);
2792
+ await this.checkExisting(cust, person.email, "base_user");
2793
+ const result = newMember("", person.email, "base_user", [t.locationId], [ln]);
2794
+ const run = this.run(result);
2795
+ try {
2796
+ run.step = "monitor_all";
2797
+ await this.monitorAllOff(t.locationId);
2798
+ run.step = "user";
2799
+ const [uid, created, detail] = await this.ensureUser(cust, person, [t.locationId]);
2800
+ result.userId = uid;
2801
+ result.created = created;
2802
+ run.step = "products";
2803
+ await this.productsOn(t.locationId, uid, [AFTER_CALL]);
2804
+ run.step = "alert_email";
2805
+ await this.emailOff(t.locationId, uid, created, detail.status);
2806
+ run.step = "line";
2807
+ await this.map(cust, uid, t.connectorId, [ln]);
2808
+ run.step = "team_lines";
2809
+ await this.attachLine(cust, t, ln, await this.index(cust), [uid]);
2810
+ run.step = "invitation";
2811
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
2812
+ } catch (exc) {
2813
+ this.stop(run, exc);
2814
+ }
2815
+ return result;
2816
+ }
2817
+ /**
2818
+ * Add a Base Manager on each team and on Management: all three products; their own line at
2819
+ * Management (if `line`); every Base User line of each team; the three alert groups, Insights Hub
2820
+ * Access and Insights Hub Weekly Reports of each team (and the company-wide weekly reports group
2821
+ * with `companyReports: true`); alert email off. The invitation is sent last.
2822
+ */
2823
+ async addBaseManager(customer, person, options) {
2824
+ await this.requireAdmin();
2825
+ const cust = await this.resolve(customer);
2826
+ const teams = options?.teams;
2827
+ if (!Array.isArray(teams) || !teams.length) throw new InvalidRequestError("teams: a list of one or more teams");
2828
+ const ts = dedupeTeams(teams.map((x) => this.teamOf(cust, x)));
2829
+ if (cust.management === null) throw new InvalidRequestError("This customer has no Management location: run createCustomer again");
2830
+ const own = options.line !== void 0 && options.line !== null ? line(options.line) : null;
2831
+ if (own) this.needConnector(cust.management);
2832
+ await this.checkExisting(cust, person.email, "base_manager");
2833
+ const result = newMember("", person.email, "base_manager", ts.map((t) => t.locationId));
2834
+ const run = this.run(result);
2835
+ try {
2836
+ run.step = "monitor_all";
2837
+ for (const t of ts) await this.monitorAllOff(t.locationId);
2838
+ run.step = "user";
2839
+ const [uid, created, detail] = await this.ensureUser(cust, person, [...ts.map((t) => t.locationId), cust.management.locationId]);
2840
+ result.userId = uid;
2841
+ result.created = created;
2842
+ result.lines = await this.managerSetup(cust, uid, ts, own, !!options.companyReports, created, detail.status, run);
2843
+ run.step = "invitation";
2844
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
2845
+ } catch (exc) {
2846
+ this.stop(run, exc);
2847
+ }
2848
+ return result;
2849
+ }
2850
+ /**
2851
+ * Add the customer's integration (data-reading) user across every team: password sign-in, tagged
2852
+ * `department: "integration"`, all three products, the alert groups and Insights Hub Access, alert
2853
+ * email off, every team's lines. Later Base Users' lines are added to it. The company needs MFA off
2854
+ * (`CustomerSpec.mfaOff`) for it to sign in.
2855
+ */
2856
+ async addIntegrationUser(customer, person, options = {}) {
2857
+ await this.requireAdmin();
2858
+ if ((person.authMethod ?? "password") !== "password") {
2859
+ throw new InvalidRequestError('An integration user signs in with a password: set authMethod: "password"');
2860
+ }
2861
+ const cust = await this.resolve(customer);
2862
+ if (!cust.teams.length) throw new InvalidRequestError("This customer has no team");
2863
+ await this.checkExisting(cust, person.email, "integration");
2864
+ const result = newMember("", person.email, "integration", cust.teams.map((t) => t.locationId));
2865
+ const run = this.run(result);
2866
+ try {
2867
+ run.step = "user";
2868
+ const [uid, created] = await this.ensureUser(cust, person, cust.teams.map((t) => t.locationId));
2869
+ result.userId = uid;
2870
+ result.created = created;
2871
+ run.step = "tag";
2872
+ const detail = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
2873
+ if (!isIntegration(detail)) await this.c.users.updateCompanyUser(cust.companyId, uid, { department: INTEGRATION_DEPARTMENT });
2874
+ run.step = "products";
2875
+ for (const t of cust.teams) await this.productsOn(t.locationId, uid, PRODUCT_KEYS);
2876
+ run.step = "groups";
2877
+ for (const t of cust.teams) {
2878
+ await this.joinGroups(t.locationId, uid, [...ALERT_GROUPS, "insightsHubAccess"].map((f) => t.groups[f]));
2879
+ }
2880
+ run.step = "alert_email";
2881
+ for (const t of cust.teams) await this.emailOff(t.locationId, uid, created, detail.status);
2882
+ run.step = "lines";
2883
+ const people = await this.index(cust);
2884
+ const current = people.get(uid)?.mappings ?? [];
2885
+ let mappings = current.map((m) => ({ ...m }));
2886
+ for (const t of cust.teams) {
2887
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [uid]));
2888
+ }
2889
+ if (!sameMappings(mappings, current)) await this.setMappings(cust, uid, mappings);
2890
+ result.lines = numbersOf(mappings);
2891
+ run.step = "invitation";
2892
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
2893
+ } catch (exc) {
2894
+ this.stop(run, exc);
2895
+ }
2896
+ return result;
2897
+ }
2898
+ /**
2899
+ * Base User to Base Manager (`to: "base_manager"`): their own line moves to Management and they get
2900
+ * the products, team lines and groups of `teams` (default: their teams); teams they were on and that
2901
+ * are not in `teams` are left.
2902
+ * Base Manager to Base User (`to: "base_user"`): groups, team lines, the extra products and
2903
+ * Management are removed; they keep one team (`teams[0]`, default their first) and their own line
2904
+ * (`line`, default their Management line), which is added to that team's lists.
2905
+ *
2906
+ * Safe to run again, also after an AccountError: a person part-way through the change is recognised
2907
+ * and the change continues. Until it completes, `result.lines` and `result.teams` hold what the
2908
+ * person had before.
2909
+ */
2910
+ async changeLicense(customer, userId, to, options = {}) {
2911
+ await this.requireAdmin();
2912
+ if (to !== "base_user" && to !== "base_manager") throw new InvalidRequestError('to: "base_user" or "base_manager"');
2913
+ const cust = await this.resolve(customer);
2914
+ if (cust.management === null) throw new InvalidRequestError("This customer has no Management location: run createCustomer again");
2915
+ const [p, people] = await this.person(cust, userId);
2916
+ if (p.license !== "base_user" && p.license !== "base_manager" && p.license !== "other") {
2917
+ throw new InvalidRequestError(`User ${userId} is "${p.license}"; only Base Users and Base Managers change license`);
2918
+ }
2919
+ const ts = options.teams?.length ? dedupeTeams(options.teams.map((x) => this.teamOf(cust, x))) : cust.teams.filter((t) => p.teams.includes(t.locationId));
2920
+ if (!ts.length) throw new InvalidRequestError("teams: the person is on no team; pass teams");
2921
+ const result = this.member(p);
2922
+ const run = this.run(result);
2923
+ try {
2924
+ if (to === "base_manager") await this.toManager(cust, p, people, ts, options.line ?? null, run, result);
2925
+ else await this.toUser(cust, p, people, ts[0], options.line ?? null, run, result);
2926
+ } catch (exc) {
2927
+ this.stop(run, exc);
2928
+ }
2929
+ return result;
2930
+ }
2931
+ async toManager(cust, p, people, ts, lineArg, run, result) {
2932
+ const mgmt = cust.management;
2933
+ const stray = [];
2934
+ for (const t of cust.teams) {
2935
+ if (t.connectorId) {
2936
+ const lines = this.teamLines(t, people, [p.id]);
2937
+ for (const n of p.numbers(t.connectorId)) if (!lines.includes(n)) stray.push([t, n]);
2938
+ }
2939
+ }
2940
+ const mgNums = mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
2941
+ const own = lineArg !== null ? line(lineArg) : mgNums[0] ?? (stray.length ? stray[0][1] : null);
2942
+ if (own) this.needConnector(mgmt);
2943
+ const keepIds = new Set(ts.map((t) => t.locationId));
2944
+ const former = cust.teams.filter((t) => p.locs.has(t.locationId) && !keepIds.has(t.locationId));
2945
+ const notes = this.emptiedGroups(cust, people, p.id, former.map((t) => t.locationId));
2946
+ run.step = "locations";
2947
+ await this.addLocations(cust, p.id, [...ts.map((t) => t.locationId), mgmt.locationId]);
2948
+ run.step = "products";
2949
+ for (const t of [...ts, mgmt]) await this.productsOn(t.locationId, p.id, PRODUCT_KEYS);
2950
+ run.step = "groups";
2951
+ for (const t of ts) await this.joinGroups(t.locationId, p.id, GROUP_FIELDS.map((f) => t.groups[f]));
2952
+ run.step = "alert_email";
2953
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
2954
+ for (const t of ts) await this.emailOff(t.locationId, p.id, false, status);
2955
+ run.step = "monitor_all";
2956
+ for (const t of ts) await this.monitorAllOff(t.locationId);
2957
+ run.step = "release_line";
2958
+ for (const [t, n] of stray) await this.releaseLine(cust, t, n, people, p.id);
2959
+ run.step = "lines";
2960
+ let mappings = own ? mergeMappings([], mgmt.connectorId, [own]) : [];
2961
+ for (const t of ts) {
2962
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [p.id]));
2963
+ }
2964
+ if (!sameMappings(mappings, p.mappings)) await this.setMappings(cust, p.id, mappings);
2965
+ run.step = "former_teams";
2966
+ for (const t of former) await this.leaveGroups(t.locationId, p.id);
2967
+ await this.removeLocations(cust, p.id, former.map((t) => t.locationId));
2968
+ result.license = "base_manager";
2969
+ result.teams = ts.map((t) => t.locationId);
2970
+ result.lines = numbersOf(mappings);
2971
+ result.notes.push(...notes);
2972
+ }
2973
+ async toUser(cust, p, people, keep, lineArg, run, result) {
2974
+ const mgmt = cust.management;
2975
+ this.needConnector(keep);
2976
+ const mgNums = mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
2977
+ const lines = this.teamLines(keep, people, [p.id]);
2978
+ const mine = p.numbers(keep.connectorId).filter((n) => !lines.includes(n));
2979
+ const own = lineArg !== null ? line(lineArg) : mgNums[0] ?? mine[0] ?? null;
2980
+ if (!own) throw new InvalidRequestError("line: this manager has no own line at Management; pass line");
2981
+ const notes = this.emptiedGroups(cust, people, p.id, p.teams);
2982
+ const others = this.locationsOf(cust).filter((t) => t.locationId !== keep.locationId && p.locs.has(t.locationId)).map((t) => t.locationId);
2983
+ run.step = "groups";
2984
+ for (const t of this.locationsOf(cust)) if (p.locs.has(t.locationId)) await this.leaveGroups(t.locationId, p.id);
2985
+ run.step = "products";
2986
+ await this.productsOff(keep.locationId, p.id, [FIRST_ALERT, INSIGHTS_HUB]);
2987
+ await this.productsOn(keep.locationId, p.id, [AFTER_CALL]);
2988
+ run.step = "monitor_all";
2989
+ await this.monitorAllOff(keep.locationId);
2990
+ run.step = "lines";
2991
+ const target = mergeMappings([], keep.connectorId, [own]);
2992
+ if (!sameMappings(target, p.mappings)) await this.setMappings(cust, p.id, target);
2993
+ run.step = "team_lines";
2994
+ await this.attachLine(cust, keep, own, people, [p.id]);
2995
+ run.step = "locations";
2996
+ await this.addLocations(cust, p.id, [keep.locationId]);
2997
+ await this.removeLocations(cust, p.id, others);
2998
+ result.license = "base_user";
2999
+ result.teams = [keep.locationId];
3000
+ result.lines = [own];
3001
+ result.notes.push(...notes);
3002
+ }
3003
+ /**
3004
+ * Move a Base User (membership and line) to another team, or swap one of a Base Manager's teams for
3005
+ * another. Calls captured before the move stay with the old team (`Member.notes` says so). Safe to
3006
+ * run again, also after an AccountError: the move continues.
3007
+ */
3008
+ async moveUser(customer, userId, options) {
3009
+ await this.requireAdmin();
3010
+ const cust = await this.resolve(customer);
3011
+ if (!options || options.fromTeam === void 0 || options.toTeam === void 0) throw new InvalidRequestError("fromTeam and toTeam are required");
3012
+ const src = this.teamOf(cust, options.fromTeam);
3013
+ const dst = this.teamOf(cust, options.toTeam);
3014
+ if (src.locationId === dst.locationId) throw new InvalidRequestError("fromTeam and toTeam are the same team");
3015
+ const [p, people] = await this.person(cust, userId);
3016
+ const note = `Call history stays with ${src.name}: calls captured before the move remain there.`;
3017
+ const result = this.member(p);
3018
+ result.notes.push(note);
3019
+ if (!p.teams.includes(src.locationId) && p.teams.includes(dst.locationId)) return result;
3020
+ if (!p.teams.includes(src.locationId)) throw new InvalidRequestError(`User ${userId} is not on ${src.name}`);
3021
+ if (p.license === "integration") throw new InvalidRequestError(`User ${userId} is an integration user; it is on every team already`);
3022
+ const run = this.run(result);
3023
+ try {
3024
+ if (p.license === "base_manager") {
3025
+ await this.moveManager(cust, p, people, src, dst, run, result);
3026
+ } else {
3027
+ this.needConnector(dst);
3028
+ const nums = uniq([...src.connectorId ? p.numbers(src.connectorId) : [], ...p.numbers(dst.connectorId)]);
3029
+ if (nums.length !== 1) throw new InvalidRequestError("A Base User holds exactly one line; fix it with changeLine first");
3030
+ const ln = nums[0];
3031
+ run.step = "monitor_all";
3032
+ for (const t of [src, dst]) await this.monitorAllOff(t.locationId);
3033
+ run.step = "release_line";
3034
+ await this.releaseLine(cust, src, ln, people, p.id);
3035
+ run.step = "locations";
3036
+ await this.addLocations(cust, p.id, [dst.locationId]);
3037
+ run.step = "products";
3038
+ await this.productsOn(dst.locationId, p.id, [AFTER_CALL]);
3039
+ run.step = "alert_email";
3040
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
3041
+ await this.emailOff(dst.locationId, p.id, false, status);
3042
+ run.step = "line";
3043
+ const target = mergeMappings(p.mappings.filter((m) => m.connector_id !== src.connectorId), dst.connectorId, [ln]);
3044
+ if (!sameMappings(target, p.mappings)) await this.setMappings(cust, p.id, target);
3045
+ run.step = "team_lines";
3046
+ await this.attachLine(cust, dst, ln, await this.index(cust), [p.id]);
3047
+ run.step = "leave_team";
3048
+ await this.removeLocations(cust, p.id, [src.locationId]);
3049
+ result.teams = [dst.locationId];
3050
+ result.lines = [ln];
3051
+ }
3052
+ } catch (exc) {
3053
+ this.stop(run, exc);
3054
+ }
3055
+ return result;
3056
+ }
3057
+ async moveManager(cust, p, people, src, dst, run, result) {
3058
+ const notes = this.emptiedGroups(cust, people, p.id, [src.locationId]);
3059
+ run.step = "locations";
3060
+ await this.addLocations(cust, p.id, [dst.locationId]);
3061
+ run.step = "products";
3062
+ await this.productsOn(dst.locationId, p.id, PRODUCT_KEYS);
3063
+ run.step = "groups";
3064
+ await this.joinGroups(dst.locationId, p.id, GROUP_FIELDS.map((f) => dst.groups[f]));
3065
+ run.step = "alert_email";
3066
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
3067
+ await this.emailOff(dst.locationId, p.id, false, status);
3068
+ run.step = "monitor_all";
3069
+ for (const t of [src, dst]) await this.monitorAllOff(t.locationId);
3070
+ run.step = "lines";
3071
+ let mappings = p.mappings.filter((m) => m.connector_id !== src.connectorId).map((m) => ({ ...m }));
3072
+ if (dst.connectorId) mappings = mergeMappings(mappings, dst.connectorId, this.teamLines(dst, people, [p.id]));
3073
+ if (!sameMappings(mappings, p.mappings)) await this.setMappings(cust, p.id, mappings);
3074
+ run.step = "leave_team";
3075
+ if (p.locs.has(src.locationId)) await this.leaveGroups(src.locationId, p.id);
3076
+ await this.removeLocations(cust, p.id, [src.locationId]);
3077
+ result.teams = uniq([...p.teams.filter((x) => x !== src.locationId), dst.locationId]);
3078
+ result.lines = numbersOf(mappings);
3079
+ result.notes.push(...notes);
3080
+ }
3081
+ /**
3082
+ * Change a person's own line from `old` to `new`.
3083
+ *
3084
+ * A Base User: their mapping, and the team's First Alert and Insights Hub lists and holders, where
3085
+ * `old` is released only when no other Base User of the team still holds it. A Base Manager: their
3086
+ * own line at Management only; a team line belongs to the Base User who holds it, so `old` must be
3087
+ * the manager's own line.
3088
+ */
3089
+ async changeLine(customer, userId, oldLine, newLine) {
3090
+ await this.requireAdmin();
3091
+ const old = line(oldLine, "old");
3092
+ const nw = line(newLine, "new");
3093
+ const cust = await this.resolve(customer);
3094
+ const [p, people] = await this.person(cust, userId);
3095
+ const result = this.member(p);
3096
+ const mgmt = cust.management;
3097
+ if (p.license === "integration") throw new InvalidRequestError("An integration user holds every line; it has no line of its own");
3098
+ if (p.license === "base_manager") {
3099
+ const mine = mgmt && mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
3100
+ if (!mine.includes(old) && !mine.includes(nw)) {
3101
+ throw new InvalidRequestError(`${old} is not this manager's own line; a team line changes with the Base User who holds it`);
3102
+ }
3103
+ const run2 = this.run(result);
2167
3104
  try {
2168
- hook = (await c.webhooks.getAfterCallWebhook(loc)).data ?? null;
2169
- } catch (err) {
2170
- if (!(err instanceof NotFoundError)) throw err;
3105
+ run2.step = "line";
3106
+ if (mine.includes(old)) {
3107
+ await this.map(cust, p.id, mgmt.connectorId, uniq(mine.map((n) => n === old ? nw : n)), p.mappings);
3108
+ result.lines = result.lines.map((n) => n === old ? nw : n);
3109
+ }
3110
+ } catch (exc) {
3111
+ this.stop(run2, exc);
2171
3112
  }
2172
- if (hook?.webhook_url && hook.enabled !== false) {
2173
- await c.webhooks.saveAfterCallWebhook(loc, { webhook_url: hook.webhook_url, enabled: false });
2174
- result.webhookPaused = true;
3113
+ return result;
3114
+ }
3115
+ const team = cust.teams.find(
3116
+ (t) => t.connectorId && p.teams.includes(t.locationId) && (p.numbers(t.connectorId).includes(old) || p.numbers(t.connectorId).includes(nw))
3117
+ );
3118
+ if (team === void 0) throw new InvalidRequestError(`${old} is not one of this person's lines`);
3119
+ const cid = team.connectorId;
3120
+ const shared = [...this.owners(team, people, [p.id]).values()].includes(old);
3121
+ const run = this.run(result);
3122
+ const swap = (have) => {
3123
+ const out = shared ? [...have] : have.filter((n) => n !== old);
3124
+ return out.includes(nw) ? out : [...out, nw];
3125
+ };
3126
+ try {
3127
+ run.step = "monitor_all";
3128
+ await this.monitorAllOff(team.locationId);
3129
+ run.step = "line";
3130
+ const nums = p.numbers(cid);
3131
+ if (nums.includes(old)) {
3132
+ await this.map(cust, p.id, cid, uniq(nums.map((n) => n === old ? nw : n)), p.mappings);
3133
+ result.lines = uniq(result.lines.map((n) => n === old ? nw : n));
2175
3134
  }
2176
- });
2177
- await step("clear_first_alert_webhook", partial, async () => {
2178
- const cfg = (await c.firstAlert.getFirstAlertConfig(loc)).data;
2179
- if (cfg?.webhook_url) {
2180
- await c.firstAlert.setWebhookUrl(loc, null);
2181
- result.firstAlertWebhookCleared = true;
3135
+ run.step = "team_lines";
3136
+ for (const h of this.holders(team, people, [p.id])) {
3137
+ const have = h.numbers(cid);
3138
+ if (!deepEqual(swap(have), have)) await this.map(cust, h.id, cid, swap(have), h.mappings);
2182
3139
  }
2183
- });
2184
- await step("deactivate_connector", partial, async () => {
2185
- const conn = customer.connectorId ? (await c.connectors.getConnector(loc, customer.connectorId)).data ?? null : await this.bestConnector(loc);
2186
- if (conn?.id && conn.status !== "inactive" && conn.status !== "deactivating") {
2187
- try {
2188
- await c.connectors.deactivateConnector(loc, conn.id);
2189
- result.connectorDeactivated = true;
2190
- } catch (err) {
2191
- already(err);
3140
+ const targets = [
3141
+ [() => this.faNumbers(team), (n) => this.c.firstAlert.setMonitoredNumbers(team.locationId, cid, n)],
3142
+ [() => this.ihNumbers(team), (n) => this.c.insightsHub.setNumbers(team.locationId, cid, n)]
3143
+ ];
3144
+ for (const [getter, setter] of targets) {
3145
+ const have = await getter();
3146
+ if (!deepEqual(swap(have), have)) await setter(swap(have));
3147
+ }
3148
+ } catch (exc) {
3149
+ this.stop(run, exc);
3150
+ }
3151
+ return result;
3152
+ }
3153
+ /**
3154
+ * Take the person out of every group, release a Base User's line (unless `keepLines`, and only when
3155
+ * no other Base User of the team holds it), clear their lines, then deactivate them. Removing a Base
3156
+ * Manager or an integration user never takes a line off anyone else. `notes` names any team whose
3157
+ * alert groups are left with no Base Manager (its alerts are not changed).
3158
+ */
3159
+ async removeUser(customer, userId, options = {}) {
3160
+ await this.requireAdmin();
3161
+ const cust = await this.resolve(customer);
3162
+ const [p, people] = await this.person(cust, userId, true);
3163
+ if (!p.active) {
3164
+ p.mappings = unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, p.id));
3165
+ this.classify(cust, p);
3166
+ }
3167
+ const out = {
3168
+ userId,
3169
+ license: p.license,
3170
+ releasedLines: [],
3171
+ deactivated: false,
3172
+ notes: p.active ? this.emptiedGroups(cust, people, p.id, p.teams) : []
3173
+ };
3174
+ const run = this.run(out);
3175
+ try {
3176
+ run.step = "groups";
3177
+ for (const t of this.locationsOf(cust)) if (p.locs.has(t.locationId)) await this.leaveGroups(t.locationId, p.id);
3178
+ run.step = "release_lines";
3179
+ if (p.license === "base_user" && !options.keepLines) {
3180
+ for (const t of cust.teams) {
3181
+ if (p.teams.includes(t.locationId) && t.connectorId) {
3182
+ for (const n of p.numbers(t.connectorId)) {
3183
+ if (await this.releaseLine(cust, t, n, people, p.id)) out.releasedLines.push(n);
3184
+ }
3185
+ }
2192
3186
  }
2193
3187
  }
2194
- });
2195
- await step("deactivate_integration_users", partial, async () => {
2196
- for (const u of await this.listIntegrationUsers(customer)) {
3188
+ run.step = "lines";
3189
+ if (p.mappings.length) await this.setMappings(cust, p.id, []);
3190
+ run.step = "deactivate";
3191
+ if (p.active) {
2197
3192
  try {
2198
- await c.users.deactivateCompanyUser(customer.companyId, u.id);
2199
- result.integrationUsersDeactivated.push(u.id);
2200
- } catch (err) {
2201
- already(err);
3193
+ await this.c.users.deactivateCompanyUser(cust.companyId, p.id);
3194
+ out.deactivated = true;
3195
+ } catch (exc) {
3196
+ if (!(exc instanceof ConflictError)) throw exc;
2202
3197
  }
2203
3198
  }
2204
- });
2205
- if (options.deactivateCompany ?? true) {
2206
- await step("deactivate_company", partial, async () => {
2207
- try {
2208
- await c.companies.deactivateCompany(customer.companyId);
2209
- result.companyDeactivated = true;
2210
- } catch (err) {
2211
- already(err);
3199
+ } catch (exc) {
3200
+ this.stop(run, exc);
3201
+ }
3202
+ return out;
3203
+ }
3204
+ /**
3205
+ * Email invitations to people who have not signed in. Without `userIds`: everyone who was never
3206
+ * sent one, or whose invitation has expired. With `userIds`: re-send to those of them who have not
3207
+ * signed in. Returns the ids invited.
3208
+ */
3209
+ async sendInvitations(customer, options = {}) {
3210
+ await this.requireAdmin();
3211
+ const cust = await this.resolve(customer);
3212
+ const now = /* @__PURE__ */ new Date();
3213
+ const wanted = options.userIds ? new Set(options.userIds) : null;
3214
+ const sent = [];
3215
+ const run = this.run(sent);
3216
+ try {
3217
+ for (const p of (await this.index(cust)).values()) {
3218
+ if (p.status !== "invited") continue;
3219
+ if (wanted !== null) {
3220
+ if (!wanted.has(p.id)) continue;
3221
+ } else if (p.invitedAt && !expired(p.inviteExpiresAt, now)) {
3222
+ continue;
2212
3223
  }
2213
- });
3224
+ run.step = `invite:${p.id}`;
3225
+ await this.c.users.resendInvitation(cust.companyId, p.id);
3226
+ sent.push(p.id);
3227
+ }
3228
+ } catch (exc) {
3229
+ this.stop(run, exc);
2214
3230
  }
2215
- return result;
3231
+ return sent;
3232
+ }
3233
+ // ------------------------------------------------------------------ lines
3234
+ /**
3235
+ * Make the line lists match the people: every Base User's line is on their team's First Alert and
3236
+ * Insights Hub lists and on its holders; Base Managers and integration users hold exactly their
3237
+ * teams' lines on each team's connector; nothing else is listed. `dryRun: true` returns the changes
3238
+ * without making them.
3239
+ *
3240
+ * Anyone with After Call on and exactly one line on a team's connector owns that line, also when they
3241
+ * read back as "other" (listed under `other`): their line is never released.
3242
+ */
3243
+ async syncLines(customer, options = {}) {
3244
+ await this.requireAdmin();
3245
+ const cust = await this.resolve(customer);
3246
+ const people = await this.index(cust);
3247
+ const diff = { teams: {}, applied: false };
3248
+ const plans = [];
3249
+ for (const t of cust.teams) {
3250
+ if (!t.connectorId) continue;
3251
+ const owners = this.owners(t, people);
3252
+ const lines = uniq(owners.values());
3253
+ const fa = await this.faNumbers(t);
3254
+ const ih = await this.ihNumbers(t);
3255
+ const d = {
3256
+ team: t.name,
3257
+ lines,
3258
+ other: [...owners.keys()].filter((uid) => people.get(uid).license === "other"),
3259
+ firstAlert: { add: lines.filter((n) => !fa.includes(n)), remove: fa.filter((n) => !lines.includes(n)) },
3260
+ insightsHub: { add: lines.filter((n) => !ih.includes(n)), remove: ih.filter((n) => !lines.includes(n)) },
3261
+ holders: {}
3262
+ };
3263
+ for (const h of this.holders(t, people)) {
3264
+ const have = h.numbers(t.connectorId);
3265
+ const add = lines.filter((n) => !have.includes(n));
3266
+ const remove = have.filter((n) => !lines.includes(n));
3267
+ if (add.length || remove.length) d.holders[h.id] = { add, remove };
3268
+ }
3269
+ diff.teams[t.locationId] = d;
3270
+ plans.push([t, lines, d]);
3271
+ }
3272
+ if (options.dryRun) return diff;
3273
+ const run = this.run(diff);
3274
+ try {
3275
+ for (const [t, lines, d] of plans) {
3276
+ run.step = `sync:${t.name}`;
3277
+ await this.monitorAllOff(t.locationId);
3278
+ for (const uid of Object.keys(d.holders)) await this.map(cust, uid, t.connectorId, lines, people.get(uid).mappings);
3279
+ if (d.firstAlert.add.length || d.firstAlert.remove.length) await this.c.firstAlert.setMonitoredNumbers(t.locationId, t.connectorId, lines);
3280
+ if (d.insightsHub.add.length || d.insightsHub.remove.length) await this.c.insightsHub.setNumbers(t.locationId, t.connectorId, lines);
3281
+ }
3282
+ } catch (exc) {
3283
+ this.stop(run, exc);
3284
+ }
3285
+ diff.applied = true;
3286
+ return diff;
2216
3287
  }
3288
+ // ------------------------------------------------------------------ offboarding
2217
3289
  /**
2218
- * Recompute the union of end-user extensions (end users holding exactly one line) and push it to
2219
- * every manager, integration user, First Alert and Insights Hub. Managers and integration users end up with exactly
2220
- * these lines; any other number on their mapping is removed. `dryRun: true` returns the diff without writing.
3290
+ * Stop everything for a customer who leaves, at every team and at Management, in this order: pause
3291
+ * each After Call webhook (its address is kept; it can't be deleted), clear each First Alert webhook,
3292
+ * stop each connector (ends the phone-system subscription), deactivate the integration users, then
3293
+ * deactivate the company. Ask your Tresic contact about retention of the customer's data.
2221
3294
  */
2222
- async syncNumbers(ref, options = {}) {
3295
+ async offboardCustomer(customer, options = {}) {
3296
+ await this.requireAdmin();
3297
+ const cust = await this.resolve(customer);
2223
3298
  const c = this.c;
2224
- const customer = await this.resolve(ref);
2225
- const connectorId = this.requireConnector(customer);
2226
- const partial = {};
2227
- const lines = await step("read_frontline_numbers", partial, () => this.endUserLines(customer, connectorId));
2228
- const union = [...lines].sort();
2229
- const fa = await step(
2230
- "read_first_alert",
2231
- partial,
2232
- async () => numbersFor((await c.firstAlert.getFirstAlertConfig(customer.locationId)).data?.connector_mappings, connectorId)
2233
- );
2234
- const ih = await step(
2235
- "read_insights_hub",
2236
- partial,
2237
- async () => numbersFor(
2238
- (await c.insightsHub.getInsightsHubSetup(customer.locationId)).data?.attributes?.connector_mappings,
2239
- connectorId
2240
- )
2241
- );
2242
- const managers = [];
2243
- await step("read_managers", partial, async () => {
2244
- for (const m of await this.lineHolders(customer)) {
2245
- const cur = await c.users.userNumbers(customer.companyId, m.id, connectorId);
2246
- const target = union;
2247
- const d = diff(cur, target);
2248
- if (d.add.length || d.remove.length) managers.push({ userId: m.id, ...d });
3299
+ const out = {
3300
+ webhooksPaused: [],
3301
+ firstAlertWebhooksCleared: [],
3302
+ connectorsDeactivated: [],
3303
+ integrationUsersDeactivated: [],
3304
+ companyDeactivated: false
3305
+ };
3306
+ const run = this.run(out);
3307
+ try {
3308
+ const locs = this.locationsOf(cust);
3309
+ run.step = "webhooks";
3310
+ for (const t of locs) {
3311
+ const hook = await c.intelligence.getAfterCallWebhook(t.locationId) ?? {};
3312
+ if (hook.webhook_url && hook.enabled) {
3313
+ await c.intelligence.setAfterCallWebhook(t.locationId, hook.webhook_url, false);
3314
+ out.webhooksPaused.push(t.locationId);
3315
+ }
3316
+ if (await c.intelligence.getFirstAlertWebhook(t.locationId)) {
3317
+ await c.intelligence.setFirstAlertWebhook(t.locationId, null);
3318
+ out.firstAlertWebhooksCleared.push(t.locationId);
3319
+ }
2249
3320
  }
2250
- });
2251
- const result = {
2252
- dryRun: Boolean(options.dryRun),
2253
- lines: union,
2254
- managers,
2255
- firstAlert: diff(fa, union),
2256
- insightsHub: diff(ih, union)
3321
+ run.step = "connectors";
3322
+ for (const t of locs) {
3323
+ for (const row of await all(c.connectors.iterLocationConnectors(t.locationId))) {
3324
+ if (row.status === "inactive" || row.status === "deactivating") continue;
3325
+ try {
3326
+ await c.connectors.deactivateConnector(t.locationId, row.id);
3327
+ } catch (exc) {
3328
+ if (exc instanceof ConflictError) continue;
3329
+ throw exc;
3330
+ }
3331
+ out.connectorsDeactivated.push(row.id);
3332
+ }
3333
+ }
3334
+ run.step = "integration_users";
3335
+ for (const p of (await this.index(cust)).values()) {
3336
+ if (p.license !== "integration") continue;
3337
+ try {
3338
+ await c.users.deactivateCompanyUser(cust.companyId, p.id);
3339
+ } catch (exc) {
3340
+ if (exc instanceof ConflictError) continue;
3341
+ throw exc;
3342
+ }
3343
+ out.integrationUsersDeactivated.push(p.id);
3344
+ }
3345
+ run.step = "company";
3346
+ if (options.deactivateCompany ?? true) {
3347
+ const company = unwrap(await c.companies.getCompany(cust.companyId)) ?? {};
3348
+ if (company.is_active ?? true) {
3349
+ try {
3350
+ await c.companies.deactivateCompany(cust.companyId);
3351
+ out.companyDeactivated = true;
3352
+ } catch (exc) {
3353
+ if (!(exc instanceof ConflictError)) throw exc;
3354
+ }
3355
+ }
3356
+ }
3357
+ } catch (exc) {
3358
+ this.stop(run, exc);
3359
+ }
3360
+ return out;
3361
+ }
3362
+ };
3363
+ function unwrapMappings(body) {
3364
+ const d = body?.data;
3365
+ return Array.isArray(d) ? d : [];
3366
+ }
3367
+
3368
+ // src/webhooks.ts
3369
+ var MAX_EVENT_BYTES = 262144;
3370
+ function isUnknownEvent(e) {
3371
+ return e.kind === "unknown";
3372
+ }
3373
+ function parseAfterCallEvent(body, options = {}) {
3374
+ const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
3375
+ let obj = body;
3376
+ if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
3377
+ const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
3378
+ if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
3379
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
3380
+ try {
3381
+ obj = JSON.parse(text);
3382
+ } catch {
3383
+ throw new WebhookPayloadError("Body is not JSON.");
3384
+ }
3385
+ }
3386
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
3387
+ const o = obj;
3388
+ if (o.type !== "end_of_call_summary") {
3389
+ return {
3390
+ kind: "unknown",
3391
+ type: typeof o.type === "string" ? o.type : null,
3392
+ version: typeof o.version === "string" ? o.version : null,
3393
+ raw: o
2257
3394
  };
2258
- if (options.dryRun) return result;
2259
- await step("apply_managers", partial, async () => {
2260
- for (const m of managers) {
2261
- const cur = await c.users.userNumbers(customer.companyId, m.userId, connectorId);
2262
- await this.mapNumbers(customer, m.userId, [...cur.filter((n) => !m.remove.includes(n)), ...m.add]);
3395
+ }
3396
+ if (typeof o.version !== "string" || !o.version.startsWith("1.")) {
3397
+ throw new WebhookPayloadError("Unsupported event version.");
3398
+ }
3399
+ if (!o.call || typeof o.call !== "object" || typeof o.call.id !== "string" || !o.call.id) {
3400
+ throw new WebhookPayloadError("Event has no call.id.");
3401
+ }
3402
+ if (typeof o.location_id !== "string") throw new WebhookPayloadError("Event has no location_id.");
3403
+ const event = project(o, WEBHOOK_SHAPES.afterCallSummary);
3404
+ return { ...event, is_test: o.is_test === true };
3405
+ }
3406
+ var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
3407
+ var iso = (d) => d.toISOString().replace(/\.000Z$/, "Z");
3408
+ var EVENT_BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.FirstAlertEvent");
3409
+ function isFirstAlertEvent(v) {
3410
+ return v !== null && typeof v === "object" && v[EVENT_BRAND] === true;
3411
+ }
3412
+ var FirstAlertEvent = class {
3413
+ get [EVENT_BRAND]() {
3414
+ return true;
3415
+ }
3416
+ alertId;
3417
+ rule;
3418
+ locationId;
3419
+ callId;
3420
+ timestamp;
3421
+ isTest;
3422
+ constructor(f) {
3423
+ this.alertId = f.alertId;
3424
+ this.rule = f.rule ?? null;
3425
+ this.locationId = f.locationId ?? null;
3426
+ this.callId = f.callId ?? null;
3427
+ this.timestamp = f.timestamp ?? null;
3428
+ this.isTest = f.isTest ?? false;
3429
+ Object.defineProperty(this, "raw", { value: f.raw ?? {}, enumerable: false });
3430
+ }
3431
+ toString() {
3432
+ return `FirstAlertEvent(alertId='${this.alertId}', timestamp='${this.timestamp ? iso(this.timestamp) : null}')`;
3433
+ }
3434
+ toJSON() {
3435
+ return { alertId: this.alertId, timestamp: this.timestamp ? iso(this.timestamp) : null };
3436
+ }
3437
+ [INSPECT2]() {
3438
+ return this.toString();
3439
+ }
3440
+ };
3441
+ function firstStr(...values) {
3442
+ for (const v of values) if (typeof v === "string" && v.trim()) return v.trim();
3443
+ return null;
3444
+ }
3445
+ function lowerUuid(v) {
3446
+ return v !== null && isUuid(v) ? v.toLowerCase() : null;
3447
+ }
3448
+ function parseFirstAlertEvent(body, options = {}) {
3449
+ const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
3450
+ let obj = body;
3451
+ if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
3452
+ const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
3453
+ if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
3454
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body);
3455
+ try {
3456
+ obj = JSON.parse(text);
3457
+ } catch {
3458
+ throw new WebhookPayloadError("Body is not JSON.");
3459
+ }
3460
+ }
3461
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
3462
+ const data = obj;
3463
+ const sub = (k) => data[k] && typeof data[k] === "object" && !Array.isArray(data[k]) ? data[k] : {};
3464
+ const alert = sub("alert");
3465
+ const rule = sub("rule");
3466
+ const call = sub("call");
3467
+ const loc = sub("location");
3468
+ const alertId = lowerUuid(firstStr(data.alert_id, alert.id, data.id));
3469
+ if (alertId === null) throw new WebhookPayloadError("Event has no alert id.");
3470
+ const stamp = firstStr(data.timestamp, data.fired_at, data.created_at, alert.created_at);
3471
+ let when = null;
3472
+ if (stamp) {
3473
+ const t = new Date(stamp);
3474
+ when = Number.isNaN(t.getTime()) ? null : t;
3475
+ }
3476
+ return new FirstAlertEvent({
3477
+ alertId,
3478
+ rule: firstStr(data.rule_name, rule.name, typeof data.rule === "string" ? data.rule : null, data.alert_name, alert.rule_name, alert.name),
3479
+ locationId: lowerUuid(firstStr(data.location_id, loc.id, alert.location_id)),
3480
+ callId: lowerUuid(firstStr(data.call_id, call.id, alert.call_id)),
3481
+ timestamp: when,
3482
+ isTest: data.is_test === true,
3483
+ raw: { ...data }
3484
+ });
3485
+ }
3486
+ var MemoryDedupStore = class {
3487
+ constructor(maxSize = 1e4) {
3488
+ this.maxSize = maxSize;
3489
+ }
3490
+ maxSize;
3491
+ keys = /* @__PURE__ */ new Map();
3492
+ checkAndAdd(key) {
3493
+ if (this.keys.has(key)) {
3494
+ this.keys.delete(key);
3495
+ this.keys.set(key, true);
3496
+ return true;
3497
+ }
3498
+ this.keys.set(key, true);
3499
+ if (this.keys.size > this.maxSize) {
3500
+ const oldest = this.keys.keys().next().value;
3501
+ if (oldest !== void 0) this.keys.delete(oldest);
3502
+ }
3503
+ return false;
3504
+ }
3505
+ };
3506
+ var Deduplicator = class {
3507
+ store;
3508
+ constructor(options = {}) {
3509
+ this.store = options.store ?? new MemoryDedupStore(options.maxSize ?? 1e4);
3510
+ }
3511
+ /** True if this id was seen before. The first call for an id records it and returns false. */
3512
+ async isDuplicate(id) {
3513
+ return Boolean(await this.store.checkAndAdd(id));
3514
+ }
3515
+ /** @deprecated Use `isDuplicate` (same result). */
3516
+ seen(id) {
3517
+ return this.isDuplicate(id);
3518
+ }
3519
+ };
3520
+
3521
+ // src/conversations.ts
3522
+ var MAX_WINDOW_DAYS = 31;
3523
+ var MAX_LIMIT = 200;
3524
+ var MAX_HISTORY = 50;
3525
+ var PAGE = 100;
3526
+ var DAY_MS = 864e5;
3527
+ var INSPECT3 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
3528
+ var CALL_BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.CallBrief");
3529
+ var ALERT_BRAND = /* @__PURE__ */ Symbol.for("intelligence-cloud.AlertBrief");
3530
+ var brand = (v, b) => v !== null && typeof v === "object" && v[b] === true;
3531
+ var iso2 = (d) => d ? d.toISOString().replace(/\.000Z$/, "Z") : null;
3532
+ function maskNumber(number) {
3533
+ if (!number) return number;
3534
+ const digits = String(number).replace(/\D/g, "");
3535
+ return digits.length <= 4 ? number : "***" + digits.slice(-4);
3536
+ }
3537
+ var NUMBER_RUN = /\+?\d[\d\s().-]*\d/g;
3538
+ function maskName(name) {
3539
+ if (!name) return name;
3540
+ return name.replace(NUMBER_RUN, (m) => {
3541
+ const digits = m.replace(/\D/g, "");
3542
+ return digits.length >= 5 ? "***" + digits.slice(-4) : m;
3543
+ });
3544
+ }
3545
+ function parseTime(value) {
3546
+ if (typeof value !== "string" || !value) return null;
3547
+ const d = new Date(/T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(value) ? value + "Z" : value);
3548
+ return Number.isNaN(d.getTime()) ? null : d;
3549
+ }
3550
+ function localMidnight(y, m, d) {
3551
+ return new Date(y, m - 1, d, 0, 0, 0, 0);
3552
+ }
3553
+ var DATE_ONLY2 = /^(\d{4})-(\d{2})-(\d{2})$/;
3554
+ var RFC33392 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/i;
3555
+ function camelKey(k) {
3556
+ return k.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
3557
+ }
3558
+ function camelKeys(o) {
3559
+ const out = {};
3560
+ for (const [k, v] of Object.entries(o)) out[camelKey(k)] = v;
3561
+ return out;
3562
+ }
3563
+ var TaskBrief = class {
3564
+ id;
3565
+ title;
3566
+ status;
3567
+ dueDate;
3568
+ callId;
3569
+ description;
3570
+ constructor(f) {
3571
+ this.id = f.id;
3572
+ this.title = f.title ?? null;
3573
+ this.status = f.status ?? null;
3574
+ this.dueDate = f.dueDate ?? null;
3575
+ this.callId = f.callId ?? null;
3576
+ this.description = f.description ?? null;
3577
+ }
3578
+ toString() {
3579
+ return `TaskBrief(id='${this.id}', status='${this.status}', dueDate='${this.dueDate}')`;
3580
+ }
3581
+ [INSPECT3]() {
3582
+ return this.toString();
3583
+ }
3584
+ };
3585
+ var CallBrief = class {
3586
+ id = "";
3587
+ when = null;
3588
+ /** inbound, outbound, internal, missed, forwarded or unknown. */
3589
+ direction = null;
3590
+ status = null;
3591
+ durationSeconds = null;
3592
+ callerName = null;
3593
+ /** Last four digits unless the client has `maskNumbers: false`. */
3594
+ callerNumber = null;
3595
+ calleeName = null;
3596
+ calleeNumber = null;
3597
+ summary = null;
3598
+ /** From `brief()`; empty in list results. */
3599
+ keyPoints = [];
3600
+ /** From `brief()`; see `taskCount` in list results. */
3601
+ tasks = [];
3602
+ taskCount = null;
3603
+ sentiment = null;
3604
+ sentimentScore = null;
3605
+ topics = [];
3606
+ /** Names of the alerts the call raised (`brief()` only). */
3607
+ alerts = [];
3608
+ locationId = null;
3609
+ /** The call's page in the app (an id-only address). */
3610
+ link = null;
3611
+ constructor(f = {}) {
3612
+ Object.assign(this, f);
3613
+ }
3614
+ get [CALL_BRAND]() {
3615
+ return true;
3616
+ }
3617
+ toString() {
3618
+ return `CallBrief(id='${this.id}', when='${iso2(this.when)}')`;
3619
+ }
3620
+ [INSPECT3]() {
3621
+ return this.toString();
3622
+ }
3623
+ };
3624
+ var AlertBrief = class {
3625
+ id = "";
3626
+ callId = null;
3627
+ when = null;
3628
+ /** The alert (rule) names that fired. */
3629
+ alerts = [];
3630
+ callerName = null;
3631
+ callerNumber = null;
3632
+ calleeName = null;
3633
+ calleeNumber = null;
3634
+ summary = null;
3635
+ sentiment = null;
3636
+ sentimentScore = null;
3637
+ topics = [];
3638
+ /** Who holds the alert; the API does not publish it yet. */
3639
+ holder = null;
3640
+ /** Set by `alert()`. */
3641
+ call = null;
3642
+ /** The alert's page in the app (an id-only address). */
3643
+ link = null;
3644
+ constructor(f = {}) {
3645
+ Object.assign(this, f);
3646
+ }
3647
+ get [ALERT_BRAND]() {
3648
+ return true;
3649
+ }
3650
+ toString() {
3651
+ return `AlertBrief(id='${this.id}', when='${iso2(this.when)}')`;
3652
+ }
3653
+ [INSPECT3]() {
3654
+ return this.toString();
3655
+ }
3656
+ };
3657
+ var Conversations = class _Conversations {
3658
+ constructor(c) {
3659
+ this.c = c;
3660
+ }
3661
+ c;
3662
+ me_ = null;
3663
+ // ------------------------------------------------------------------ plumbing
3664
+ async requireUser() {
3665
+ if (this.me_ === null) this.me_ = unwrap2(await this.c.account.getMe()) ?? {};
3666
+ if (this.me_.role !== "frontline_user") throw new WrongLoginError(this.me_.role ?? null, "user");
3667
+ return this.me_;
3668
+ }
3669
+ mask(n) {
3670
+ return (this.c.maskNumbers ? maskNumber(n) : n) ?? null;
3671
+ }
3672
+ maskNm(n) {
3673
+ return (this.c.maskNumbers ? maskName(n) : n) ?? null;
3674
+ }
3675
+ link(kind, id) {
3676
+ if (!id) return null;
3677
+ const page = kind === "call" ? "after-call-copilot/calls" : "first-alert-copilot/alerts";
3678
+ return `${this.c.appUrl}/${page}/${encodeURIComponent(id)}`;
3679
+ }
3680
+ static limit(limit, top) {
3681
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > top) {
3682
+ throw new InvalidRequestError(`limit: 1 to ${top}`);
3683
+ }
3684
+ return limit;
3685
+ }
3686
+ static when(value, name) {
3687
+ if (typeof value === "string") {
3688
+ if (!RFC33392.test(value.trim())) throw new InvalidRequestError(`${name}: an RFC 3339 date-time with a time zone`);
3689
+ return new Date(value.trim());
3690
+ }
3691
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) throw new InvalidRequestError(`${name}: a Date or an RFC 3339 date-time`);
3692
+ return value;
3693
+ }
3694
+ /** (start, end). Default: today (local time), or the last `defaultDays` days. At most 31 days. */
3695
+ window(day, since, until, defaultDays) {
3696
+ const has = (v) => v !== void 0 && v !== null;
3697
+ if (has(day) && (has(since) || has(until))) throw new InvalidRequestError("Pass day, or since/until, not both");
3698
+ if (has(day)) {
3699
+ let y, m, d;
3700
+ if (typeof day === "string") {
3701
+ const mm = DATE_ONLY2.exec(day.trim());
3702
+ if (!mm) throw new InvalidRequestError("day: a date (YYYY-MM-DD) or a Date");
3703
+ [y, m, d] = [Number(mm[1]), Number(mm[2]), Number(mm[3])];
3704
+ } else if (day instanceof Date && !Number.isNaN(day.getTime())) {
3705
+ [y, m, d] = [day.getFullYear(), day.getMonth() + 1, day.getDate()];
3706
+ } else {
3707
+ throw new InvalidRequestError("day: a date (YYYY-MM-DD) or a Date");
2263
3708
  }
3709
+ const start2 = localMidnight(y, m, d);
3710
+ return [start2, new Date(localMidnight(y, m, d + 1).getTime() - 1e3)];
3711
+ }
3712
+ const end = has(until) ? _Conversations.when(until, "until") : /* @__PURE__ */ new Date();
3713
+ let start;
3714
+ if (has(since)) start = _Conversations.when(since, "since");
3715
+ else if (defaultDays) start = new Date(end.getTime() - defaultDays * DAY_MS);
3716
+ else start = localMidnight(end.getFullYear(), end.getMonth() + 1, end.getDate());
3717
+ if (end.getTime() <= start.getTime()) throw new InvalidRequestError("until must be after since");
3718
+ if (end.getTime() - start.getTime() > MAX_WINDOW_DAYS * DAY_MS) throw new InvalidRequestError(`The window is at most ${MAX_WINDOW_DAYS} days`);
3719
+ return [start, end];
3720
+ }
3721
+ async teamId(team) {
3722
+ if (team === void 0 || team === null) return null;
3723
+ if (typeof team === "object" && typeof team.locationId === "string") return team.locationId;
3724
+ if (typeof team === "string" && isUuid(team.trim())) return team.trim().toLowerCase();
3725
+ if (typeof team === "string") {
3726
+ for (const t of await this.teams()) if (t.name === team) return t.locationId;
3727
+ }
3728
+ throw new InvalidRequestError(`Unknown team "${String(team)}": use a TeamRef, its location id or its name`);
3729
+ }
3730
+ static searchTerm(phone, text) {
3731
+ if (phone !== void 0 && phone !== null && text !== void 0 && text !== null) {
3732
+ throw new InvalidRequestError("Pass number or search, not both: the API has one search field");
3733
+ }
3734
+ const term = phone ?? text;
3735
+ if (term === void 0 || term === null) return void 0;
3736
+ const t = String(term).trim();
3737
+ if (t.length < 2) throw new InvalidRequestError("search terms need at least 2 characters (shorter ones are ignored by the API)");
3738
+ return t;
3739
+ }
3740
+ async pages(fetch, limit) {
3741
+ const out = [];
3742
+ let cursor;
3743
+ while (out.length < limit) {
3744
+ const page = await fetch(Math.min(PAGE, limit - out.length), cursor);
3745
+ out.push(...page.items);
3746
+ if (!page.hasMore || !page.nextCursor) break;
3747
+ cursor = page.nextCursor;
3748
+ }
3749
+ return out.slice(0, limit);
3750
+ }
3751
+ briefFromRow(row) {
3752
+ return new CallBrief({
3753
+ id: row.id ?? "",
3754
+ when: parseTime(row.call_date),
3755
+ direction: row.call_type ?? null,
3756
+ status: row.status ?? null,
3757
+ durationSeconds: row.duration ?? null,
3758
+ callerName: this.maskNm(row.caller_name),
3759
+ callerNumber: this.mask(row.caller_number),
3760
+ calleeName: this.maskNm(row.callee_name),
3761
+ calleeNumber: this.mask(row.callee_number),
3762
+ summary: row.summary ?? null,
3763
+ taskCount: row.task_count ?? null,
3764
+ sentiment: row.sentiment ?? row.sentiment_label ?? null,
3765
+ sentimentScore: row.sentiment_score ?? null,
3766
+ locationId: row.location_id ?? null,
3767
+ link: this.link("call", row.id ?? "")
2264
3768
  });
2265
- if (result.firstAlert.add.length || result.firstAlert.remove.length) {
2266
- await step("apply_first_alert", partial, () => c.firstAlert.setMonitoredNumbers(customer.locationId, connectorId, union));
3769
+ }
3770
+ alertFromRow(row) {
3771
+ return new AlertBrief({
3772
+ id: row.id ?? "",
3773
+ callId: row.call_id ?? null,
3774
+ when: parseTime(row.call_date),
3775
+ alerts: [...row.keywords ?? []],
3776
+ callerName: this.maskNm(row.caller_name),
3777
+ callerNumber: this.mask(row.caller_number),
3778
+ calleeName: this.maskNm(row.callee_name),
3779
+ calleeNumber: this.mask(row.callee_number),
3780
+ summary: row.summary ?? null,
3781
+ sentiment: row.sentiment ?? row.sentiment_label ?? null,
3782
+ sentimentScore: row.sentiment_score ?? null,
3783
+ topics: [...row.topics ?? []],
3784
+ link: this.link("alert", row.id ?? "")
3785
+ });
3786
+ }
3787
+ static taskFromRow(row) {
3788
+ return new TaskBrief({
3789
+ id: row.id ?? "",
3790
+ title: row.title,
3791
+ status: row.status,
3792
+ dueDate: row.due_date,
3793
+ callId: row.call_id,
3794
+ description: row.description
3795
+ });
3796
+ }
3797
+ // ------------------------------------------------------------------ who
3798
+ /** Who is signed in, and their teams. (Their own lines are not readable with a user login yet.) */
3799
+ async me() {
3800
+ const me = await this.requireUser();
3801
+ const name = me.display_name || [me.first_name, me.last_name].filter(Boolean).join(" ") || null;
3802
+ return {
3803
+ userId: me.id ?? "",
3804
+ email: me.email ?? null,
3805
+ name,
3806
+ role: me.role ?? null,
3807
+ companyId: me.company_id ?? null,
3808
+ teams: await this.teams(),
3809
+ lines: null
3810
+ };
3811
+ }
3812
+ /** The teams (locations) this person can see. Management is listed with `kind: "management"`. */
3813
+ async teams() {
3814
+ await this.requireUser();
3815
+ const out = [];
3816
+ for await (const loc of this.c.account.iterVisibleLocations()) {
3817
+ const name = loc.location_name ?? "";
3818
+ out.push({ locationId: loc.id ?? "", name, kind: name.endsWith(" - Management") ? "management" : "team" });
2267
3819
  }
2268
- if (result.insightsHub.add.length || result.insightsHub.remove.length) {
2269
- await step("apply_insights_hub", partial, () => c.insightsHub.setNumbers(customer.locationId, connectorId, union));
3820
+ return out;
3821
+ }
3822
+ // ------------------------------------------------------------------ calls
3823
+ /**
3824
+ * Calls, newest first, as briefs. Default: today. The window is at most 31 days and `limit` at most
3825
+ * 200. `number` and `search` share the API's one search field: pass one or the other.
3826
+ */
3827
+ async calls(options = {}) {
3828
+ await this.requireUser();
3829
+ const limit = _Conversations.limit(options.limit ?? 50, MAX_LIMIT);
3830
+ const [start, end] = this.window(options.day, options.since, options.until);
3831
+ const term = _Conversations.searchTerm(options.number, options.search);
3832
+ const lid = await this.teamId(options.team);
3833
+ const rows = await this.pages(
3834
+ (n, cursor) => this.c.calls.listCalls({ dateFrom: start, dateTo: end, search: term, locationId: lid ?? void 0, limit: n, cursor }),
3835
+ limit
3836
+ );
3837
+ return rows.map((r) => this.briefFromRow(r));
3838
+ }
3839
+ /**
3840
+ * One call: when, direction, parties, summary, key points, tasks, sentiment, topics and the alerts
3841
+ * it raised. No transcript and no recording.
3842
+ */
3843
+ async brief(callId) {
3844
+ await this.requireUser();
3845
+ const data = unwrap2(await this.c.calls.getCall(callId)) ?? {};
3846
+ const b = this.briefFromRow(data);
3847
+ const analysis = data.analysis ?? {};
3848
+ const summ = analysis.summary ?? {};
3849
+ b.summary = b.summary ?? summ.text ?? null;
3850
+ b.keyPoints = [...summ.key_points ?? []];
3851
+ b.sentiment = b.sentiment ?? analysis.sentiment?.overall ?? null;
3852
+ b.topics = (analysis.topics ?? []).filter((t) => t && typeof t === "object" && t.name).map((t) => t.name);
3853
+ b.tasks = (data.tasks ?? []).map((t) => _Conversations.taskFromRow({ ...t, call_id: b.id }));
3854
+ b.taskCount = data.task_count ?? b.tasks.length;
3855
+ if (b.when !== null) {
3856
+ const t = b.when;
3857
+ const day0 = new Date(Date.UTC(t.getUTCFullYear(), t.getUTCMonth(), t.getUTCDate()));
3858
+ const page = await this.c.alerts.listAlerts({ dateFrom: day0, dateTo: new Date(day0.getTime() + DAY_MS - 1e3), limit: PAGE });
3859
+ const names = [];
3860
+ for (const a of page.items) {
3861
+ if (a.call_id === b.id) {
3862
+ for (const k of a.keywords ?? []) if (!names.includes(k)) names.push(k);
3863
+ }
3864
+ }
3865
+ b.alerts = names;
2270
3866
  }
2271
- return result;
3867
+ return b;
3868
+ }
3869
+ /** The transcript of one call: segments with `time`, `speaker`, `name` and `text`. */
3870
+ async transcript(callId) {
3871
+ await this.requireUser();
3872
+ const data = unwrap2(await this.c.calls.getCallTranscript(callId)) ?? {};
3873
+ return data.transcript ?? [];
3874
+ }
3875
+ /**
3876
+ * A link to the call's audio that expires, or null when the call has no recording. The SDK never
3877
+ * downloads the audio. Treat the link as a secret: never log or store it.
3878
+ */
3879
+ async recordingLink(callId) {
3880
+ await this.requireUser();
3881
+ const link = await this.c.intelligence.getRecordingUrl(callId);
3882
+ return link.url ? link : null;
3883
+ }
3884
+ /** Recent briefs for one caller (the last 31 days), for use before a callback. `limit` at most 50. */
3885
+ async callerHistory(number, options = {}) {
3886
+ await this.requireUser();
3887
+ const limit = _Conversations.limit(options.limit ?? 10, MAX_HISTORY);
3888
+ const term = _Conversations.searchTerm(number, null);
3889
+ const [start, end] = this.window(null, null, null, MAX_WINDOW_DAYS);
3890
+ const rows = await this.pages((n, cursor) => this.c.calls.listCalls({ dateFrom: start, dateTo: end, search: term, limit: n, cursor }), limit);
3891
+ return rows.map((r) => this.briefFromRow(r));
3892
+ }
3893
+ // ------------------------------------------------------------------ tasks and alerts
3894
+ /** Open tasks (up to 200), each with the id of the call it came from. `due`: only tasks due that day. */
3895
+ async openTasks(options = {}) {
3896
+ await this.requireUser();
3897
+ const lid = await this.teamId(options.team);
3898
+ const rows = await this.pages(
3899
+ (n, cursor) => this.c.tasks.listTasks({ status: "open", dueOn: options.due ?? void 0, locationId: lid ?? void 0, limit: n, cursor }),
3900
+ MAX_LIMIT
3901
+ );
3902
+ return rows.map((r) => _Conversations.taskFromRow(r));
3903
+ }
3904
+ /**
3905
+ * Alerts on this person's teams, newest first. Default: today; at most 31 days and 200 alerts.
3906
+ * `status` is refused: the API has no alert status filter yet.
3907
+ */
3908
+ async alerts(options = {}) {
3909
+ await this.requireUser();
3910
+ if (options.status !== void 0 && options.status !== null) {
3911
+ throw new InvalidRequestError("status: the API has no alert status filter yet");
3912
+ }
3913
+ const limit = _Conversations.limit(options.limit ?? 50, MAX_LIMIT);
3914
+ const [start, end] = this.window(null, options.since, options.until);
3915
+ const lid = await this.teamId(options.team);
3916
+ const rows = await this.pages(
3917
+ (n, cursor) => this.c.alerts.listAlerts({ dateFrom: start, dateTo: end, locationId: lid ?? void 0, limit: n, cursor }),
3918
+ limit
3919
+ );
3920
+ return rows.map((r) => this.alertFromRow(r));
3921
+ }
3922
+ /** One alert with its call brief, or null when this login cannot see it. */
3923
+ async alert(alertId) {
3924
+ await this.requireUser();
3925
+ const aid = String(alertId).trim().toLowerCase();
3926
+ const page = await this.c.alerts.listAlerts({ search: aid, limit: 10 });
3927
+ const row = page.items.find((a) => a.id === aid);
3928
+ if (row === void 0) return null;
3929
+ const out = this.alertFromRow(row);
3930
+ if (out.callId) out.call = await this.brief(out.callId);
3931
+ return out;
3932
+ }
3933
+ /**
3934
+ * For a manager: one team's counts, alerts, open tasks and briefs (up to 200) for a day or a window of
3935
+ * at most 31 days. Default: today.
3936
+ */
3937
+ async teamView(team, options = {}) {
3938
+ await this.requireUser();
3939
+ const lid = await this.teamId(team);
3940
+ if (lid === null) throw new InvalidRequestError("team is required");
3941
+ const [start, end] = this.window(options.day, options.since, options.until);
3942
+ const first = await this.c.calls.listCalls({ dateFrom: start, dateTo: end, locationId: lid, limit: PAGE });
3943
+ let rows = [...first.items];
3944
+ if (first.hasMore && first.nextCursor) {
3945
+ rows = rows.concat((await this.c.calls.listCalls({ dateFrom: start, dateTo: end, locationId: lid, limit: PAGE, cursor: first.nextCursor })).items);
3946
+ }
3947
+ const raw = first.raw ?? {};
3948
+ const summary = raw.data && typeof raw.data === "object" ? raw.data.summary ?? {} : {};
3949
+ const counts = {};
3950
+ for (const [k, v] of Object.entries(summary)) if (Number.isInteger(v)) counts[camelKey(k)] = v;
3951
+ const alerts = await this.pages((n, cursor) => this.c.alerts.listAlerts({ dateFrom: start, dateTo: end, locationId: lid, limit: n, cursor }), MAX_LIMIT);
3952
+ const tasks = await this.pages((n, cursor) => this.c.tasks.listTasks({ status: "open", locationId: lid, limit: n, cursor }), MAX_LIMIT);
3953
+ return {
3954
+ team: lid,
3955
+ since: start,
3956
+ until: end,
3957
+ counts,
3958
+ alerts: alerts.map((a) => this.alertFromRow(a)),
3959
+ openTasks: tasks.map((t) => _Conversations.taskFromRow(t)),
3960
+ briefs: rows.slice(0, MAX_LIMIT).map((r) => this.briefFromRow(r))
3961
+ };
3962
+ }
3963
+ /**
3964
+ * What customers are raising and which topics are rising. Default: the last 7 days; at most 31.
3965
+ * Needs Insights Hub access.
3966
+ */
3967
+ async topics(options = {}) {
3968
+ await this.requireUser();
3969
+ const [start, end] = this.window(null, options.since, options.until, 7);
3970
+ const lid = await this.teamId(options.team);
3971
+ const data = unwrap2(await this.c.insights.getInsightsDashboard({ start, end, locationId: lid ?? void 0 })) ?? {};
3972
+ const stats = data.stats ?? {};
3973
+ const rising = (data.trending_topics ?? []).filter((t) => (t.percentage_change ?? 0) > 0).map((t) => {
3974
+ const { trend_data: _drop, ...rest } = t;
3975
+ return camelKeys(rest);
3976
+ }).sort((a, b) => (b.percentageChange ?? 0) - (a.percentageChange ?? 0));
3977
+ return {
3978
+ since: start,
3979
+ until: end,
3980
+ calls: { total: stats.total_calls ?? 0, answered: stats.answered_calls ?? 0, unanswered: stats.unanswered_calls ?? 0 },
3981
+ topics: (data.topic_call_volumes ?? []).map((t) => camelKeys(t)),
3982
+ rising
3983
+ };
3984
+ }
3985
+ // ------------------------------------------------------------------ passing on
3986
+ /**
3987
+ * The id and its page in the app, for passing to another system in place of content. A string is
3988
+ * taken as a call id. The link uses the client's `appUrl` (default https://app.intelligence.cloud).
3989
+ */
3990
+ reference(callOrAlert) {
3991
+ let kind;
3992
+ let id;
3993
+ if (brand(callOrAlert, CALL_BRAND)) [kind, id] = ["call", callOrAlert.id];
3994
+ else if (brand(callOrAlert, ALERT_BRAND)) [kind, id] = ["alert", callOrAlert.id];
3995
+ else if (isFirstAlertEvent(callOrAlert)) [kind, id] = ["alert", callOrAlert.alertId];
3996
+ else if (typeof callOrAlert === "string" && callOrAlert.trim()) [kind, id] = ["call", callOrAlert.trim()];
3997
+ else throw new InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id");
3998
+ return { kind, id, link: this.link(kind, id) };
3999
+ }
4000
+ /** A typed First Alert event, beside `parseAfterCallEvent`. See `parseFirstAlertEvent`. */
4001
+ parseFirstAlertEvent(payload) {
4002
+ return parseFirstAlertEvent(payload);
2272
4003
  }
2273
4004
  };
4005
+ function unwrap2(body) {
4006
+ if (body && typeof body === "object" && "data" in body) {
4007
+ const d = body.data;
4008
+ if (d && typeof d === "object" && d.attributes && typeof d.attributes === "object") return d.attributes;
4009
+ return d;
4010
+ }
4011
+ return body;
4012
+ }
2274
4013
 
2275
4014
  // src/client.ts
2276
- function uniq(xs) {
4015
+ var RUNNING = ["active", "connected"];
4016
+ var DEFAULT_APP_URL = "https://app.intelligence.cloud";
4017
+ function checkAppUrl(appUrl) {
4018
+ let u;
4019
+ try {
4020
+ u = new URL(appUrl);
4021
+ } catch {
4022
+ throw new InvalidRequestError("appUrl must be an https:// URL.");
4023
+ }
4024
+ if (u.protocol !== "https:" || !u.hostname) throw new InvalidRequestError("appUrl must be an https:// URL.");
4025
+ return appUrl.replace(/\/+$/, "");
4026
+ }
4027
+ function uniq2(xs) {
2277
4028
  return [...new Set(xs)];
2278
4029
  }
2279
4030
  var Client = class {
@@ -2298,10 +4049,18 @@ var Client = class {
2298
4049
  webhooks;
2299
4050
  /** Conversation intelligence helpers (frontline credentials). */
2300
4051
  intelligence;
2301
- /** Base Intelligence Seat workflows (admin credentials). */
2302
- workflows;
4052
+ /** Create and maintain customers: teams, people, lines, alerts (administrator login). */
4053
+ accounts;
4054
+ /** A signed-in person's own calls, tasks and alerts, with careful defaults (user login). */
4055
+ conversations;
4056
+ /** Whether `conversations` masks caller numbers. */
4057
+ maskNumbers;
4058
+ /** The app's address for page links. */
4059
+ appUrl;
2303
4060
  constructor(options) {
2304
4061
  const c = this.core = new Core(options);
4062
+ this.maskNumbers = options.maskNumbers ?? true;
4063
+ this.appUrl = checkAppUrl(options.appUrl ?? DEFAULT_APP_URL);
2305
4064
  this.resellers = makeResellers(c);
2306
4065
  this.sso = makeSso(c);
2307
4066
  this.products = makeProducts(c);
@@ -2319,7 +4078,7 @@ var Client = class {
2319
4078
  /** Turn products on for a company, keeping the others (`enabled_products` is a full replacement). */
2320
4079
  addProducts: async (companyId, productKeys) => {
2321
4080
  const cur = await companyProducts(companyId);
2322
- const next = uniq([...cur, ...productKeys]);
4081
+ const next = uniq2([...cur, ...productKeys]);
2323
4082
  if (next.length === cur.length) return companies.getCompany(companyId);
2324
4083
  return companies.updateCompany(companyId, { enabled_products: next });
2325
4084
  },
@@ -2327,7 +4086,7 @@ var Client = class {
2327
4086
  removeProducts: async (companyId, productKeys) => {
2328
4087
  const cur = await companyProducts(companyId);
2329
4088
  const next = cur.filter((k) => !productKeys.includes(k));
2330
- if (next.length === 0) throw new FilterError("A company keeps at least one product; the API ignores an empty list.");
4089
+ if (next.length === 0) throw new InvalidRequestError("A company keeps at least one product; the API ignores an empty list.");
2331
4090
  if (next.length === cur.length) return companies.getCompany(companyId);
2332
4091
  return companies.updateCompany(companyId, { enabled_products: next });
2333
4092
  },
@@ -2357,7 +4116,7 @@ var Client = class {
2357
4116
  /** Turn products on for a location, keeping the others. They must be on for the company. */
2358
4117
  addProducts: async (companyId, locationId, productKeys) => {
2359
4118
  const cur = await locationProducts(companyId, locationId);
2360
- const next = uniq([...cur, ...productKeys]);
4119
+ const next = uniq2([...cur, ...productKeys]);
2361
4120
  if (next.length === cur.length) return locations.getLocation(companyId, locationId);
2362
4121
  return locations.updateLocation(companyId, locationId, { enabled_products: next });
2363
4122
  },
@@ -2381,7 +4140,7 @@ var Client = class {
2381
4140
  this.groups = {
2382
4141
  ...groups,
2383
4142
  /** Add members to a group (`member_ids` is a full replacement underneath). */
2384
- addMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, { member_ids: uniq([...await memberIds(locationId, groupId), ...userIds]) }),
4143
+ addMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, { member_ids: uniq2([...await memberIds(locationId, groupId), ...userIds]) }),
2385
4144
  removeMembers: async (locationId, groupId, userIds) => groups.updateUserGroup(locationId, groupId, {
2386
4145
  member_ids: (await memberIds(locationId, groupId)).filter((id) => !userIds.includes(id))
2387
4146
  }),
@@ -2389,7 +4148,7 @@ var Client = class {
2389
4148
  userGroupIds,
2390
4149
  /** Add a user to groups at a location (`group_ids` is a full replacement underneath). */
2391
4150
  addUserToGroups: async (locationId, userId, groupIds) => groups.setUserGroupMembership(locationId, userId, {
2392
- group_ids: uniq([...await userGroupIds(locationId, userId), ...groupIds])
4151
+ group_ids: uniq2([...await userGroupIds(locationId, userId), ...groupIds])
2393
4152
  }),
2394
4153
  /** Remove a user from some groups, or from every group when `groupIds` is omitted. */
2395
4154
  removeUserFromGroups: async (locationId, userId, groupIds) => groups.setUserGroupMembership(locationId, userId, {
@@ -2405,21 +4164,17 @@ var Client = class {
2405
4164
  };
2406
4165
  const connectors = makeConnectors(c);
2407
4166
  const waitForStatus = async (locationId, connectorId, final, o = {}) => {
2408
- const deadline = c.now() + (o.timeout ?? 600) * 1e3;
4167
+ const start = c.now();
4168
+ const deadline = start + (o.timeout ?? 600) * 1e3;
2409
4169
  for (; ; ) {
2410
4170
  const conn = (await connectors.getConnector(locationId, connectorId)).data ?? {};
2411
4171
  const st = conn.status ?? null;
2412
4172
  if (st === "error" && (o.raiseOnError ?? true) && !final.includes("error")) {
2413
- throw new ConnectorError(
2414
- `Connector is in error${conn.state_reason ? ` (${conn.state_reason})` : ""}.`,
2415
- conn.state_reason ?? null,
2416
- st,
2417
- conn
2418
- );
4173
+ throw new ConnectorError(conn);
2419
4174
  }
2420
4175
  if (st && final.includes(st)) return conn;
2421
4176
  if (c.now() >= deadline) {
2422
- throw new ConnectorError(`Connector did not settle in time (status ${st ?? "unknown"}).`, null, st, conn);
4177
+ throw new ConnectorTimeoutError(conn, (c.now() - start) / 1e3);
2423
4178
  }
2424
4179
  await c.sleep((o.checkInterval ?? 10) * 1e3);
2425
4180
  }
@@ -2432,17 +4187,17 @@ var Client = class {
2432
4187
  ...connectors,
2433
4188
  waitForStatus,
2434
4189
  /**
2435
- * Create a connector (202) and, by default, wait until it is `active`.
4190
+ * Create a connector (202) and, by default, wait until it is running (`active` or `connected`).
2436
4191
  * Throws `ConnectorError` with `stateReason` (e.g. `invalid_permissions`) when it ends in `error`.
2437
4192
  */
2438
- createConnector: async (locationId, body, o = {}) => settle(locationId, await connectors.createConnector(locationId, body), ["active"], o),
2439
- /** Update a connector; when it reconnects (202), wait until it is `active`. */
4193
+ createConnector: async (locationId, body, o = {}) => settle(locationId, await connectors.createConnector(locationId, body), [...RUNNING], o),
4194
+ /** Update a connector; when it reconnects (202), wait until it is running. */
2440
4195
  updateConnector: async (locationId, connectorId, body, o = {}) => {
2441
4196
  const r = await connectors.updateConnector(locationId, connectorId, body);
2442
- return r.data?.status === "connecting" ? settle(locationId, r, ["active"], o) : r;
4197
+ return r.data?.status === "connecting" ? settle(locationId, r, [...RUNNING], o) : r;
2443
4198
  },
2444
- /** Restart a connector and, by default, wait until it is `active` (ConnectorError on `error`). */
2445
- reactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.reactivateConnector(locationId, connectorId), ["active"], o),
4199
+ /** Restart a connector and, by default, wait until it is running, `active` or `connected` (ConnectorError on `error`). */
4200
+ reactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.reactivateConnector(locationId, connectorId), [...RUNNING], o),
2446
4201
  /** Stop a connector and, by default, wait until it is `inactive`. */
2447
4202
  deactivateConnector: async (locationId, connectorId, o = {}) => settle(locationId, await connectors.deactivateConnector(locationId, connectorId), ["inactive"], o, false),
2448
4203
  /** The connector with exactly this name at the location, or null. */
@@ -2482,7 +4237,7 @@ var Client = class {
2482
4237
  /** Set (null clears) the location alert webhook URL, keeping the monitored numbers. */
2483
4238
  setWebhookUrl: (locationId, url) => faSave(locationId, (cfg) => ({ webhook_url: url, connector_mappings: mergeMappings(cfg.connector_mappings, "") })),
2484
4239
  /** Route a rule to more groups (`group_ids` is a full replacement underneath). */
2485
- addRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, { group_ids: uniq([...await ruleGroupIds(locationId, ruleId), ...groupIds]) }),
4240
+ addRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, { group_ids: uniq2([...await ruleGroupIds(locationId, ruleId), ...groupIds]) }),
2486
4241
  removeRuleGroups: async (locationId, ruleId, groupIds) => firstAlert.updateAlertRule(locationId, ruleId, {
2487
4242
  group_ids: (await ruleGroupIds(locationId, ruleId)).filter((id) => !groupIds.includes(id))
2488
4243
  }),
@@ -2517,7 +4272,7 @@ var Client = class {
2517
4272
  const cur = await ihSetup(locationId);
2518
4273
  return insightsHub.saveInsightsHubSetup(locationId, {
2519
4274
  connector_mappings: mergeMappings(cur.connector_mappings, ""),
2520
- group_access: uniq([...cur.group_access ?? [], ...groupIds])
4275
+ group_access: uniq2([...cur.group_access ?? [], ...groupIds])
2521
4276
  });
2522
4277
  },
2523
4278
  removeGroups: async (locationId, groupIds) => insightsHub.updateInsightsHubSetup(locationId, {
@@ -2562,14 +4317,14 @@ var Client = class {
2562
4317
  /** The user with exactly this email, or null. */
2563
4318
  findUserByEmail,
2564
4319
  /** Assign the user to more locations (`location_ids` is a full replacement underneath). */
2565
- addLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, { location_ids: uniq([...await userLocationIds(companyId, userId), ...locationIds]) }),
4320
+ addLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, { location_ids: uniq2([...await userLocationIds(companyId, userId), ...locationIds]) }),
2566
4321
  removeLocations: async (companyId, userId, locationIds) => users.updateCompanyUser(companyId, userId, {
2567
4322
  location_ids: (await userLocationIds(companyId, userId)).filter((id) => !locationIds.includes(id))
2568
4323
  }),
2569
4324
  /** The numbers mapped to the user (for one connector, or all). */
2570
4325
  userNumbers: async (companyId, userId, connectorId) => {
2571
4326
  const cur = await currentMappings(companyId, userId);
2572
- return connectorId ? numbersFor(cur, connectorId) : uniq(cur.flatMap((m) => m.monitored_numbers ?? []));
4327
+ return connectorId ? numbersFor(cur, connectorId) : uniq2(cur.flatMap((m) => m.monitored_numbers ?? []));
2573
4328
  },
2574
4329
  /** Map more numbers to the user for one connector (read, merge, PUT). The connector must be `active`. */
2575
4330
  addNumbers: async (companyId, userId, connectorId, numbers) => users.setUserNumberMappings(companyId, userId, {
@@ -2592,7 +4347,8 @@ var Client = class {
2592
4347
  })
2593
4348
  };
2594
4349
  this.intelligence = new Intelligence(this, options.checkRole ?? true);
2595
- this.workflows = new Workflows(this);
4350
+ this.accounts = new Accounts(this);
4351
+ this.conversations = new Conversations(this);
2596
4352
  }
2597
4353
  // ================================================================ session
2598
4354
  /** Ends ALL sessions of this user (web app and other jobs too). The SDK never calls it on its own. */
@@ -2670,119 +4426,6 @@ var Client = class {
2670
4426
  testFirstAlertWebhook(locationId, url) {
2671
4427
  return this.intelligence.testFirstAlertWebhook(locationId, url);
2672
4428
  }
2673
- // ================================================================ workflow shortcuts
2674
- provisionSeatCustomer(...a) {
2675
- return this.workflows.provisionSeatCustomer(...a);
2676
- }
2677
- getSeatCustomer(...a) {
2678
- return this.workflows.getSeatCustomer(...a);
2679
- }
2680
- addFrontlineUser(...a) {
2681
- return this.workflows.addFrontlineUser(...a);
2682
- }
2683
- addManager(...a) {
2684
- return this.workflows.addManager(...a);
2685
- }
2686
- activateSeatAlerts(...a) {
2687
- return this.workflows.activateSeatAlerts(...a);
2688
- }
2689
- changeUserExtension(...a) {
2690
- return this.workflows.changeUserExtension(...a);
2691
- }
2692
- removeUser(...a) {
2693
- return this.workflows.removeUser(...a);
2694
- }
2695
- listFrontlineUsers(...a) {
2696
- return this.workflows.listFrontlineUsers(...a);
2697
- }
2698
- listManagers(...a) {
2699
- return this.workflows.listManagers(...a);
2700
- }
2701
- addIntegrationUser(...a) {
2702
- return this.workflows.addIntegrationUser(...a);
2703
- }
2704
- listIntegrationUsers(...a) {
2705
- return this.workflows.listIntegrationUsers(...a);
2706
- }
2707
- offboardCustomer(...a) {
2708
- return this.workflows.offboardCustomer(...a);
2709
- }
2710
- syncNumbers(...a) {
2711
- return this.workflows.syncNumbers(...a);
2712
- }
2713
- };
2714
-
2715
- // src/webhooks.ts
2716
- var MAX_EVENT_BYTES = 262144;
2717
- function isUnknownEvent(e) {
2718
- return e.kind === "unknown";
2719
- }
2720
- function parseAfterCallEvent(body, options = {}) {
2721
- const maxBytes = options.maxBytes ?? MAX_EVENT_BYTES;
2722
- let obj = body;
2723
- if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
2724
- const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
2725
- if (size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
2726
- const text = typeof body === "string" ? body : new TextDecoder().decode(body);
2727
- try {
2728
- obj = JSON.parse(text);
2729
- } catch {
2730
- throw new WebhookPayloadError("Body is not JSON.");
2731
- }
2732
- }
2733
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
2734
- const o = obj;
2735
- if (o.type !== "end_of_call_summary") {
2736
- return {
2737
- kind: "unknown",
2738
- type: typeof o.type === "string" ? o.type : null,
2739
- version: typeof o.version === "string" ? o.version : null,
2740
- raw: o
2741
- };
2742
- }
2743
- if (typeof o.version !== "string" || !o.version.startsWith("1.")) {
2744
- throw new WebhookPayloadError("Unsupported event version.");
2745
- }
2746
- if (!o.call || typeof o.call !== "object" || typeof o.call.id !== "string" || !o.call.id) {
2747
- throw new WebhookPayloadError("Event has no call.id.");
2748
- }
2749
- if (typeof o.location_id !== "string") throw new WebhookPayloadError("Event has no location_id.");
2750
- const event = project(o, WEBHOOK_SHAPES.afterCallSummary);
2751
- return { ...event, is_test: o.is_test === true };
2752
- }
2753
- var MemoryDedupStore = class {
2754
- constructor(maxSize = 1e4) {
2755
- this.maxSize = maxSize;
2756
- }
2757
- maxSize;
2758
- keys = /* @__PURE__ */ new Map();
2759
- checkAndAdd(key) {
2760
- if (this.keys.has(key)) {
2761
- this.keys.delete(key);
2762
- this.keys.set(key, true);
2763
- return true;
2764
- }
2765
- this.keys.set(key, true);
2766
- if (this.keys.size > this.maxSize) {
2767
- const oldest = this.keys.keys().next().value;
2768
- if (oldest !== void 0) this.keys.delete(oldest);
2769
- }
2770
- return false;
2771
- }
2772
- };
2773
- var Deduplicator = class {
2774
- store;
2775
- constructor(options = {}) {
2776
- this.store = options.store ?? new MemoryDedupStore(options.maxSize ?? 1e4);
2777
- }
2778
- /** True if this id was seen before. The first call for an id records it and returns false. */
2779
- async isDuplicate(id) {
2780
- return Boolean(await this.store.checkAndAdd(id));
2781
- }
2782
- /** @deprecated Use `isDuplicate` (same result). */
2783
- seen(id) {
2784
- return this.isDuplicate(id);
2785
- }
2786
4429
  };
2787
4430
 
2788
- export { ALL_PRODUCTS, ALWAYS_REMOVED_FIELDS, ApiError, AuthError, CUSTOMER_THREAT_RULE, Client, ConflictError, ConnectorError, DEFAULT_BASE_URL, Deduplicator, EXTENSION_CONFLICT_MESSAGE, ExtensionMappingError, FileTokenStore, FilterError, FrontlineRequiredError, INSIGHTS_HUB_ACCESS_GROUP, INTEGRATION_DEPARTMENT, Intelligence, IntelligenceCloudError, MANAGER_ALERTS_GROUP, MAX_EVENT_BYTES, MAX_LOCATION_IDS, MAX_NUMBERS, MAX_RETRY_AFTER_MS, MemoryDedupStore, MemoryTokenStore, MfaRequiredError, NotFoundError, PasswordExpiredError, PayloadTooLargeError, RateLimitError, SDK_VERSION, THREAT_PHRASES_MISSING, UPSET_CUSTOMER_RULE, ValidationError, WebhookPayloadError, WorkflowError, Workflows, alertNumber, companyNameConflictMessage, customerThreatRule, digitsOnly, isFrontline, isIntegration, isManager, isUnknownEvent, parseAfterCallEvent, toRfc3339, upsetCustomerRule };
4431
+ export { ALWAYS_REMOVED_FIELDS, AccountError, Accounts, AlertBrief, ApiError, AuthError, CallBrief, Client, ConflictError, ConnectorError, ConnectorSpec, ConnectorTimeoutError, Conversations, DEFAULT_APP_URL, DEFAULT_BASE_URL, Deduplicator, EXTENSION_CONFLICT_MESSAGE, ExtensionMappingError, FileTokenStore, FilterError, FirstAlertEvent, FrontlineRequiredError, Intelligence, IntelligenceCloudError, InvalidRequestError, LICENSES, MAX_EVENT_BYTES, MAX_HISTORY, MAX_LIMIT, MAX_LOCATION_IDS, MAX_NUMBERS, MAX_RETRY_AFTER_MS, MAX_WINDOW_DAYS, MemoryDedupStore, MemoryTokenStore, MfaRequiredError, NotFoundError, PRODUCT_KEYS, PasswordExpiredError, PayloadTooLargeError, RUNNING, RateLimitError, RecordingLink, SDK_VERSION, TaskBrief, ValidationError, WebhookPayloadError, WrongLoginError, alertNumber, digitsOnly, isUnknownEvent, maskName, maskNumber, parseAfterCallEvent, parseFirstAlertEvent, toRfc3339 };