@intelligence-cloud/sdk 0.2.0 → 0.3.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,9 +1,15 @@
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", "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" } };
2
+ var OPERATIONS = { "login": { "method": "POST", "path": "/auth/login", "tag": "Authentication", "role": "frontline_user", "query": [], "pathParams": [], "headers": [], "hasBody": true, "bodyRequired": true, "body": { "required": ["email", "password"], "properties": { "email": { "type": "string", "format": "email" }, "password": { "type": "string", "format": "password" } } }, "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, "body": { "required": ["refresh_token"], "properties": { "refresh_token": { "type": "string" } } }, "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, "body": null, "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, "body": null, "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, "body": { "required": [], "properties": { "display_name": { "type": "string" }, "primary_accent_color": { "type": "string" }, "secondary_accent_color": { "type": "string" }, "support_email": { "type": "string", "format": "email" }, "support_portal_url": { "type": "string", "format": "uri" }, "privacy_policy_url": { "type": "string", "format": "uri" }, "terms_of_service_url": { "type": "string", "format": "uri" }, "copyright_text": { "type": "string" } } }, "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, "body": null, "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, "body": { "required": ["smtp_host", "smtp_port", "sender_name", "sender_email"], "properties": { "smtp_host": { "type": "string" }, "smtp_port": { "type": "integer" }, "smtp_username": { "type": "string" }, "smtp_password": { "type": "string", "format": "password" }, "sender_name": { "type": "string" }, "sender_email": { "type": "string", "format": "email" } } }, "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, "body": null, "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, "body": null, "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, "body": { "required": ["company_name", "primary_admin_contact_name", "primary_admin_contact_email", "primary_admin_contact_phone"], "properties": { "company_name": { "type": "string" }, "company_code": { "type": "string" }, "primary_admin_contact_name": { "type": "string" }, "primary_admin_contact_email": { "type": "string", "format": "email" }, "primary_admin_contact_phone": { "type": "string" }, "enabled_products": { "type": "array", "items": { "type": "string", "enum": ["after-call-copilot", "first-alert-copilot", "insights-hub"] } } } }, "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, "body": null, "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, "body": null, "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, "body": { "required": [], "properties": { "company_name": { "type": "string" }, "company_code": { "type": "string" }, "primary_admin_contact_name": { "type": "string" }, "primary_admin_contact_email": { "type": "string", "format": "email" }, "primary_admin_contact_phone": { "type": "string" }, "enabled_products": { "type": "array", "items": { "type": "string", "enum": ["after-call-copilot", "first-alert-copilot", "insights-hub"] } }, "vertical": { "type": "string" }, "address": { "type": "string" }, "mfa_enforced": { "type": "boolean" } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": [], "properties": { "display_name": { "type": "string" }, "primary_accent_color": { "type": "string" }, "secondary_accent_color": { "type": "string" }, "support_email": { "type": "string", "format": "email" }, "privacy_policy_url": { "type": "string", "format": "uri" }, "terms_of_service_url": { "type": "string", "format": "uri" }, "copyright_text": { "type": "string" } } }, "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, "body": null, "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, "body": { "required": ["domain"], "properties": { "domain": { "type": "string" } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["type", "display_name", "issuer", "well_known_endpoint", "client_id", "acknowledgement"], "properties": { "type": { "type": "string" }, "display_name": { "type": "string" }, "issuer": { "type": "string" }, "well_known_endpoint": { "type": "string", "format": "uri" }, "client_id": { "type": "string" }, "client_auth_method": { "type": "string", "enum": ["client_secret", "none"] }, "client_secret": { "type": "string", "format": "password" }, "secret_expires_at": { "type": "string", "format": "date-time" }, "acknowledgement": { "type": "string", "enum": ["true", "yes", "acknowledged", "1"] } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["location_name", "street", "city", "state", "country", "zipcode", "vertical_id"], "properties": { "location_name": { "type": "string" }, "street": { "type": "string" }, "city": { "type": "string" }, "state": { "type": "string" }, "country": { "type": "string" }, "zipcode": { "type": "string" }, "vertical_id": { "type": "string", "format": "uuid" }, "enabled_products": { "type": "array", "items": { "type": "string", "enum": ["after-call-copilot", "first-alert-copilot", "insights-hub"] } } } }, "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, "body": null, "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, "body": { "required": [], "properties": { "location_name": { "type": "string" }, "street": { "type": "string" }, "city": { "type": "string" }, "state": { "type": "string" }, "country": { "type": "string" }, "zipcode": { "type": "string" }, "vertical_id": { "type": "string", "format": "uuid" }, "enabled_products": { "type": "array", "items": { "type": "string", "enum": ["after-call-copilot", "first-alert-copilot", "insights-hub"] } } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["group_name"], "properties": { "group_name": { "type": "string" }, "member_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": { "required": [], "properties": { "group_name": { "type": "string" }, "member_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": null, "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, "body": { "required": ["group_ids"], "properties": { "group_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": { "required": ["type", "config"], "properties": { "type": { "type": "string", "enum": ["netsapiens"] }, "config": { "type": "object" }, "connector_id": { "type": "string", "format": "uuid" } } }, "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, "body": null, "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, "body": { "required": ["name", "type", "config"], "properties": { "name": { "type": "string" }, "type": { "type": "string", "enum": ["netsapiens"] }, "config": { "type": "object" } } }, "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, "body": null, "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, "body": { "required": [], "properties": { "name": { "type": "string" }, "config": { "type": "object" } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["name", "priority", "triggers"], "properties": { "name": { "type": "string" }, "priority": { "type": "string", "enum": ["critical", "high", "medium", "low"] }, "match_logic": { "type": "string", "enum": ["any", "all"] }, "enabled": { "type": "boolean" }, "triggers": { "type": "array", "items": { "type": "object" } }, "group_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": { "required": [], "properties": { "name": { "type": "string" }, "priority": { "type": "string", "enum": ["critical", "high", "medium", "low"] }, "match_logic": { "type": "string", "enum": ["any", "all"] }, "enabled": { "type": "boolean" }, "triggers": { "type": "array", "items": { "type": "object" } }, "group_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["connector_mappings"], "properties": { "webhook_url": { "type": ["string", "null"], "format": "uri" }, "connector_mappings": { "type": "array", "items": { "type": "object" } } } }, "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, "body": { "required": ["url"], "properties": { "url": { "type": "string", "format": "uri" } } }, "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, "body": null, "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, "body": { "required": ["masterEnabled"], "properties": { "masterEnabled": { "type": "boolean" }, "alerts": { "type": "array", "items": { "type": "object" } } } }, "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, "body": { "required": ["enabled", "frequency", "sendTime", "timezone"], "properties": { "enabled": { "type": "boolean" }, "frequency": { "type": "string", "enum": ["daily", "weekly", "both", "never"] }, "sendTime": { "type": "string" }, "timezone": { "type": "string" }, "timeFormat": { "type": "string", "enum": ["12h", "24h"] } } }, "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, "body": null, "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, "body": { "required": ["connector_mappings", "group_access"], "properties": { "connector_mappings": { "type": "array", "items": { "type": "object" } }, "group_access": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": { "required": [], "properties": { "connector_mappings": { "type": "array", "items": { "type": "object" } }, "group_access": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": { "required": ["monitor_all_numbers"], "properties": { "monitor_all_numbers": { "type": "boolean" } } }, "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, "body": null, "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, "body": null, "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, "body": { "required": ["email", "first_name", "last_name", "role"], "properties": { "email": { "type": "string", "format": "email" }, "first_name": { "type": "string" }, "last_name": { "type": "string" }, "phone_number": { "type": "string" }, "role": { "type": "string", "enum": ["customer_admin", "frontline_user"] }, "location_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } }, "send_invitation": { "type": "boolean" }, "auth_method": { "type": "string", "enum": ["password", "sso"] } } }, "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, "body": null, "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, "body": { "required": [], "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, "phone_number": { "type": "string" }, "department": { "type": "string" }, "role": { "type": "string", "enum": ["customer_admin", "frontline_user"] }, "location_ids": { "type": "array", "items": { "type": "string", "format": "uuid" } } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["mappings"], "properties": { "mappings": { "type": "array", "items": { "type": "object" } } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": [], "properties": { "eoc_enabled": { "type": "boolean" }, "eod_enabled": { "type": "boolean" }, "eod_time": { "type": "string" }, "eod_timezone": { "type": "string" }, "digest_frequency": { "type": "string", "enum": ["daily", "weekly", "both", "never"] }, "digest_time_format": { "type": "string", "enum": ["12h", "24h"] }, "connector_mappings": { "type": "array", "items": { "type": "object" } } } }, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": null, "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, "body": { "required": ["webhook_url"], "properties": { "webhook_url": { "type": "string", "format": "uri" }, "enabled": { "type": "boolean" } } }, "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, "body": null, "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
6
+ var brandOf = (name) => /* @__PURE__ */ Symbol.for(`intelligence-cloud.error.${name}`);
6
7
  var IntelligenceCloudError = class extends Error {
8
+ static [Symbol.hasInstance](value) {
9
+ if (value === null || typeof value !== "object") return false;
10
+ if (value[brandOf(this.name)] === true) return true;
11
+ return Function.prototype[Symbol.hasInstance].call(this, value);
12
+ }
7
13
  constructor(message, options) {
8
14
  super(message, options);
9
15
  this.name = new.target.name;
@@ -43,6 +49,18 @@ var PasswordExpiredError = class extends AuthError {
43
49
  super(200, "password_expired", "The password has expired. Change it in the app, then sign in again.");
44
50
  }
45
51
  };
52
+ var NetworkError = class extends ApiError {
53
+ kind;
54
+ requestSent;
55
+ constructor(kind, detail, requestSent = true) {
56
+ const code = kind === "timeout" ? "timeout" : "network_error";
57
+ super(0, code, apiErrorText(0, code, null, `the request did not complete (${detail})`), {
58
+ serverMessage: "The request did not complete."
59
+ });
60
+ this.kind = kind;
61
+ this.requestSent = requestSent;
62
+ }
63
+ };
46
64
  var NotFoundError = class extends ApiError {
47
65
  };
48
66
  var ConflictError = class extends ApiError {
@@ -83,24 +101,13 @@ var ConnectorError = class extends IntelligenceCloudError {
83
101
  this.statusMessage = typeof c.status_message === "string" ? c.status_message : null;
84
102
  }
85
103
  };
86
- var ConnectorTimeoutError = class extends IntelligenceCloudError {
87
- connector;
88
- status;
104
+ var ConnectorTimeoutError = class extends ConnectorError {
105
+ waited;
89
106
  constructor(connector, waitedSeconds) {
107
+ super(connector);
90
108
  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`);
93
- this.connector = connector;
94
- this.status = status;
95
- }
96
- };
97
- var FrontlineRequiredError = class extends IntelligenceCloudError {
98
- role;
99
- constructor(role) {
100
- super(
101
- `This login has role "${role ?? "unknown"}". Conversation data endpoints return empty lists to admin logins: sign in with a frontline integration user.`
102
- );
103
- this.role = role;
109
+ this.message = `Connector ${typeof c.id === "string" ? c.id : "unknown"} still "${this.status ?? "unknown"}" after ${Math.round(waitedSeconds)} s`;
110
+ this.waited = waitedSeconds;
104
111
  }
105
112
  };
106
113
  var AccountError = class extends IntelligenceCloudError {
@@ -112,6 +119,21 @@ var AccountError = class extends IntelligenceCloudError {
112
119
  this.step = step;
113
120
  this.result = result;
114
121
  }
122
+ /**
123
+ * The first error of `type` in the cause chain (`cause`, its `cause` ...), or undefined. A line another
124
+ * location holds arrives as AccountError, then ExtensionMappingError, then ConflictError:
125
+ * `err.find(ConflictError)` returns the ConflictError.
126
+ */
127
+ find(type) {
128
+ const seen = /* @__PURE__ */ new Set();
129
+ let err = this.cause;
130
+ while (err !== void 0 && err !== null && !seen.has(err)) {
131
+ seen.add(err);
132
+ if (err instanceof type) return err;
133
+ err = typeof err === "object" ? err.cause : void 0;
134
+ }
135
+ return void 0;
136
+ }
115
137
  };
116
138
  var WrongLoginError = class extends IntelligenceCloudError {
117
139
  role;
@@ -124,6 +146,12 @@ var WrongLoginError = class extends IntelligenceCloudError {
124
146
  this.needed = needed;
125
147
  }
126
148
  };
149
+ var FrontlineRequiredError = class extends WrongLoginError {
150
+ constructor(role) {
151
+ super(role, "user");
152
+ this.message = `This login has role "${role ?? "unknown"}". Conversation data (calls, alerts, tasks, insights) needs a frontline_user login; admin logins get empty lists.`;
153
+ }
154
+ };
127
155
  var ExtensionMappingError = class extends IntelligenceCloudError {
128
156
  userId;
129
157
  constructor(userId, cause) {
@@ -139,6 +167,29 @@ var WebhookPayloadError = class extends IntelligenceCloudError {
139
167
  var PayloadTooLargeError = class extends WebhookPayloadError {
140
168
  };
141
169
  var EXTENSION_CONFLICT_MESSAGE = "Extension is already monitored at another location.";
170
+ for (const cls of [
171
+ IntelligenceCloudError,
172
+ ApiError,
173
+ AuthError,
174
+ MfaRequiredError,
175
+ PasswordExpiredError,
176
+ NotFoundError,
177
+ ConflictError,
178
+ ValidationError,
179
+ RateLimitError,
180
+ NetworkError,
181
+ InvalidRequestError,
182
+ ConnectorError,
183
+ ConnectorTimeoutError,
184
+ AccountError,
185
+ WrongLoginError,
186
+ FrontlineRequiredError,
187
+ ExtensionMappingError,
188
+ WebhookPayloadError,
189
+ PayloadTooLargeError
190
+ ]) {
191
+ Object.defineProperty(cls.prototype, brandOf(cls.name), { value: true, enumerable: false });
192
+ }
142
193
 
143
194
  // src/filters.ts
144
195
  var RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/i;
@@ -269,6 +320,100 @@ function buildQuery(operationId, rules, options) {
269
320
  return out;
270
321
  }
271
322
 
323
+ // src/util.ts
324
+ async function uuid4() {
325
+ const c = globalThis.crypto;
326
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
327
+ let bytes;
328
+ if (c && typeof c.getRandomValues === "function") {
329
+ bytes = c.getRandomValues(new Uint8Array(16));
330
+ } else {
331
+ const nodeCrypto = await import('crypto');
332
+ bytes = new Uint8Array(nodeCrypto.randomBytes(16));
333
+ }
334
+ bytes[6] = bytes[6] & 15 | 64;
335
+ bytes[8] = bytes[8] & 63 | 128;
336
+ const h = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
337
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
338
+ }
339
+ function numbersFor(mappings, connectorId) {
340
+ const out = [];
341
+ for (const m of mappings ?? []) if (m.connector_id === connectorId) out.push(...m.monitored_numbers ?? []);
342
+ return [...new Set(out)];
343
+ }
344
+ function mergeMappings(current, connectorId, add = [], remove = []) {
345
+ const byConnector = /* @__PURE__ */ new Map();
346
+ for (const m of current ?? []) {
347
+ if (!m.connector_id) continue;
348
+ const list3 = byConnector.get(m.connector_id) ?? [];
349
+ list3.push(...m.monitored_numbers ?? []);
350
+ byConnector.set(m.connector_id, list3);
351
+ }
352
+ const drop = new Set(remove);
353
+ const mine = (byConnector.get(connectorId) ?? []).filter((n) => !drop.has(n));
354
+ for (const n of add) if (!mine.includes(n)) mine.push(n);
355
+ byConnector.set(connectorId, mine);
356
+ const out = [];
357
+ for (const [connector_id, nums] of byConnector) {
358
+ const uniq3 = [...new Set(nums)];
359
+ if (uniq3.length) out.push({ connector_id, monitored_numbers: uniq3 });
360
+ }
361
+ return out;
362
+ }
363
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
364
+ function isUuid(value) {
365
+ return typeof value === "string" && UUID_RE.test(value);
366
+ }
367
+ function pathArg(value, name = "id") {
368
+ if (typeof value !== "string" || value === "" || value === "." || value === ".." || [...value].length > 128 || // code points, not UTF-16 units
369
+ /[\/\\?#%\s\u0000-\u001f\u007f-\u009f\ufeff]/.test(value)) {
370
+ throw new InvalidRequestError(`${name}: an id of at most 128 characters without "/", "?", "#", "%", whitespace (also at the ends: nothing is trimmed), control characters, and not "." or ".."`);
371
+ }
372
+ return value;
373
+ }
374
+
375
+ // src/bodycheck.ts
376
+ var typeOk = (t, v) => {
377
+ switch (t) {
378
+ case "string":
379
+ return typeof v === "string";
380
+ case "integer":
381
+ return typeof v === "number" && Number.isInteger(v);
382
+ case "number":
383
+ return typeof v === "number" && Number.isFinite(v);
384
+ case "boolean":
385
+ return typeof v === "boolean";
386
+ case "array":
387
+ return Array.isArray(v);
388
+ case "object":
389
+ return v !== null && typeof v === "object" && !Array.isArray(v);
390
+ default:
391
+ return true;
392
+ }
393
+ };
394
+ function problem(rule, value, items = false) {
395
+ if (!rule) return null;
396
+ const types = rule.type === void 0 ? [] : typeof rule.type === "string" ? [rule.type] : [...rule.type];
397
+ if (value === null) return !types.length || types.includes("null") ? null : "must not be null";
398
+ if (types.length && !types.some((t) => t !== "null" && typeOk(t, value))) return `must be ${types.filter((t) => t !== "null").join(" or ")}`;
399
+ if (items && Array.isArray(value) && rule.items) {
400
+ for (const v of value) {
401
+ const p = problem(rule.items, v);
402
+ if (p) return `an item ${p}`;
403
+ }
404
+ }
405
+ return null;
406
+ }
407
+ function checkBody(operationId, rule, body) {
408
+ if (!rule || body === void 0 || body === null) return;
409
+ if (typeof body !== "object" || Array.isArray(body)) throw new InvalidRequestError(`${operationId}: the body must be an object`);
410
+ for (const [name, value] of Object.entries(body)) {
411
+ if (value === void 0) continue;
412
+ const p = problem(rule.properties[name], value, true);
413
+ if (p) throw new InvalidRequestError(`${operationId}: ${name} ${p}`);
414
+ }
415
+ }
416
+
272
417
  // src/projection.ts
273
418
  function project(value, shape) {
274
419
  if (shape === null || shape === void 0 || shape === "*") return value;
@@ -403,10 +548,45 @@ var FileTokenStore = class {
403
548
 
404
549
  // src/core.ts
405
550
  var DEFAULT_BASE_URL = "https://app.intelligence.cloud/api/v1";
406
- var SDK_VERSION = "0.2.0";
551
+ var SDK_VERSION = "0.3.0";
407
552
  var SUPPRESS_ERROR_TEXT = /* @__PURE__ */ new Set(["testConnector", "testAfterCallWebhook", "testFirstAlertWebhook"]);
408
553
  var NUMBER_MAPPING_OPS = /* @__PURE__ */ new Set(["setUserNumberMappings", "updateUserAfterCallSettings"]);
409
554
  var LOGIN_RATE_LIMIT_WAIT_S = 60;
555
+ var DEFAULT_DEADLINE_S = 120;
556
+ var RETRY_METHODS = /* @__PURE__ */ new Set(["GET", "PUT", "PATCH", "DELETE"]);
557
+ var NOT_SENT_ERRNO = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NODATA", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "ETIMEDOUT"]);
558
+ var NOT_SENT_ALWAYS = /* @__PURE__ */ new Set([
559
+ "UND_ERR_CONNECT_TIMEOUT",
560
+ "ERR_INVALID_URL",
561
+ "ERR_INVALID_PROTOCOL",
562
+ "ERR_UNSUPPORTED_PROTOCOL",
563
+ "CERT_HAS_EXPIRED",
564
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
565
+ "SELF_SIGNED_CERT_IN_CHAIN",
566
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
567
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
568
+ "ERR_TLS_CERT_ALTNAME_INVALID",
569
+ "CERT_NOT_YET_VALID"
570
+ ]);
571
+ var TIMEOUT_CODES = /* @__PURE__ */ new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "ETIMEDOUT"]);
572
+ function failureEntries(err, out = [], depth = 0) {
573
+ if (!err || typeof err !== "object" || depth > 6) return out;
574
+ const e = err;
575
+ const children = Array.isArray(e.errors) && e.errors.length > 0;
576
+ if (typeof e.code === "string" && !children) out.push({ code: e.code, syscall: typeof e.syscall === "string" ? e.syscall : void 0 });
577
+ if (children) for (const x of e.errors) failureEntries(x, out, depth + 1);
578
+ if (e.cause) failureEntries(e.cause, out, depth + 1);
579
+ return out;
580
+ }
581
+ var neverLeft = (f) => NOT_SENT_ALWAYS.has(f.code) || NOT_SENT_ERRNO.has(f.code) && (f.syscall === "connect" || f.syscall === "getaddrinfo");
582
+ function classifyFetchFailure(err, aborted = false) {
583
+ const entries = failureEntries(err);
584
+ const codes = entries.map((f) => f.code);
585
+ const name = err && typeof err === "object" ? String(err.name ?? "Error") : "Error";
586
+ const timeout = aborted || name === "AbortError" || name === "TimeoutError" || codes.some((c) => TIMEOUT_CODES.has(c));
587
+ const sent = !(entries.length > 0 && entries.every(neverLeft));
588
+ return { kind: timeout ? "timeout" : "transport", sent, detail: codes[0] ?? (aborted ? "timed out" : name) };
589
+ }
410
590
  var RENEW_MARGIN_MS = 3e4;
411
591
  var MAX_RETRY_AFTER_MS = 6e4;
412
592
  var ALWAYS_PROJECT = /* @__PURE__ */ new Set([
@@ -449,6 +629,9 @@ var Core = class {
449
629
  random;
450
630
  now;
451
631
  renewing = null;
632
+ clock;
633
+ deadlineMs;
634
+ spentRefresh = /* @__PURE__ */ new Set();
452
635
  /** Write requests (anything but GET) attempted by this client. Account helpers use it to tell a clean stop from a partial one. */
453
636
  writes = 0;
454
637
  constructor(opts) {
@@ -459,7 +642,13 @@ var Core = class {
459
642
  this.email = opts.email;
460
643
  this.password = opts.password;
461
644
  this.store = opts.tokenStore ?? new MemoryTokenStore();
462
- this.timeoutMs = (opts.timeout ?? 30) * 1e3;
645
+ const timeout = opts.timeout ?? 30;
646
+ const deadline = opts.deadline ?? DEFAULT_DEADLINE_S;
647
+ if (typeof timeout !== "number" || !(timeout > 0)) throw new InvalidRequestError("timeout: a number of seconds above 0");
648
+ if (typeof deadline !== "number" || !(deadline > 0)) throw new InvalidRequestError("deadline: a number of seconds above 0");
649
+ this.timeoutMs = timeout * 1e3;
650
+ this.deadlineMs = deadline * 1e3;
651
+ this.clock = opts.clock ?? (() => performance.now());
463
652
  this.maxRetries = opts.maxRetries ?? 3;
464
653
  this.loginWaitS = opts.loginRateLimitWait ?? LOGIN_RATE_LIMIT_WAIT_S;
465
654
  this.keepUnknown = opts.keepUnknownFields ?? false;
@@ -477,13 +666,15 @@ var Core = class {
477
666
  const op = OPERATIONS[operationId];
478
667
  const query = buildQuery(operationId, op.query, opts.query ?? {});
479
668
  const url = this.url(op, pathArgs, query);
669
+ if (op.hasBody) checkBody(operationId, op.body, opts.body);
480
670
  if (op.method !== "GET") this.writes++;
481
671
  const res = await this.send(op.method, url, {
482
672
  body: op.hasBody ? opts.body ?? {} : void 0,
483
673
  headers: opts.headers,
484
674
  idempotencyKey: opts.idempotencyKey,
485
675
  auth: true,
486
- operationId
676
+ operationId,
677
+ budget: this.newBudget()
487
678
  });
488
679
  if (res.status < 200 || res.status >= 300) throw this.toError(res, operationId, op.hasBody ? opts.body : void 0);
489
680
  if (res.status === 204 || res.text === "") return void 0;
@@ -525,7 +716,7 @@ var Core = class {
525
716
  async logout() {
526
717
  const t = await this.store.get();
527
718
  if (t && t.accessToken) {
528
- const res = await this.send("POST", `${this.baseUrl}/auth/logout`, { auth: true, operationId: "logout", body: {} });
719
+ const res = await this.send("POST", `${this.baseUrl}/auth/logout`, { auth: true, operationId: "logout", body: {}, budget: this.newBudget() });
529
720
  if (res.status >= 300 && res.status !== 401) throw this.toError(res, "logout");
530
721
  }
531
722
  await this.store.set(null);
@@ -534,11 +725,31 @@ var Core = class {
534
725
  async close() {
535
726
  await this.store.set(null);
536
727
  }
728
+ // -------------------------------------------------------------- the deadline
729
+ newBudget() {
730
+ return { at: this.clock() + this.deadlineMs };
731
+ }
732
+ remainingS(b) {
733
+ return (b.at - this.clock()) / 1e3;
734
+ }
735
+ /** Sleep `seconds` if the deadline leaves room; otherwise return false without sleeping. */
736
+ async wait(b, seconds) {
737
+ if (seconds > this.remainingS(b)) return false;
738
+ await this.sleep(seconds * 1e3);
739
+ return true;
740
+ }
741
+ /** Seconds to wait before the next try, or null when Retry-After asks for more than 60 seconds. */
742
+ backoff(attempt, retryAfter) {
743
+ const w = parseRetryAfter(retryAfter);
744
+ if (w !== null) return w > MAX_RETRY_AFTER_MS / 1e3 ? null : w;
745
+ const base = Math.min(8, 0.5 * 2 ** attempt);
746
+ return base + this.random() * (base / 2);
747
+ }
537
748
  // -------------------------------------------------------------- auth
538
- async accessToken() {
749
+ async accessToken(b) {
539
750
  const t = await this.store.get();
540
- if (!t || !t.accessToken) return (await this.renew(null)).accessToken;
541
- if (t.expiresAt - this.now() < RENEW_MARGIN_MS) return (await this.renew(t.accessToken)).accessToken;
751
+ if (!t || !t.accessToken) return (await this.renew(null, b)).accessToken;
752
+ if (t.expiresAt - this.now() < RENEW_MARGIN_MS) return (await this.renew(t.accessToken, b)).accessToken;
542
753
  return t.accessToken;
543
754
  }
544
755
  /**
@@ -546,26 +757,26 @@ var Core = class {
546
757
  * `failed` is the access token that was rejected (null = none yet); if another caller has
547
758
  * already replaced it, the new tokens are reused.
548
759
  */
549
- renew(failed) {
760
+ renew(failed, b) {
550
761
  if (this.renewing) return this.renewing;
551
762
  const work = async () => {
552
763
  const cur = await this.store.get();
553
764
  if (cur && cur.accessToken && cur.accessToken !== failed && cur.expiresAt - this.now() >= RENEW_MARGIN_MS) {
554
765
  return cur;
555
766
  }
556
- if (cur && cur.refreshToken) {
767
+ if (cur && cur.refreshToken && !this.spentRefresh.has(cur.refreshToken)) {
557
768
  const spent = cur.refreshToken;
558
769
  await this.store.set({ ...cur, refreshToken: "" });
559
770
  let fresh;
560
771
  try {
561
- fresh = await this.refreshWith(spent);
772
+ fresh = await this.refreshWith(spent, b);
562
773
  } catch (err) {
563
774
  if (err instanceof RateLimitError) await this.store.set(cur);
564
775
  throw err;
565
776
  }
566
777
  if (fresh) return fresh;
567
778
  }
568
- return await this.login();
779
+ return await this.login(b);
569
780
  };
570
781
  this.renewing = (async () => {
571
782
  try {
@@ -577,48 +788,70 @@ var Core = class {
577
788
  return this.renewing;
578
789
  }
579
790
  /**
580
- * Swap a refresh token for a new pair. On 429 the same token is tried again after a wait (it was
581
- * not used); a sign-in is never attempted for a rate-limited refresh. Returns null when the token
582
- * is refused (spent, expired or revoked), so the caller signs in again.
791
+ * Swap a refresh token for a new pair. A refresh token is used once, and sending a used one ends every
792
+ * session of the login. It is sent again only after a 429 (the server did not use it) or after a
793
+ * failure where the request provably never left this machine. After a 5xx, a failure after the
794
+ * request left, or an unreadable answer it is never sent again: this returns null and the caller
795
+ * signs in instead.
583
796
  */
584
- async refreshWith(refreshToken) {
585
- for (let attempt = 0; ; attempt++) {
586
- const res = await this.send("POST", `${this.baseUrl}/auth/refresh`, {
587
- body: { refresh_token: refreshToken },
588
- auth: false,
589
- operationId: "refresh",
590
- noRetry: true
591
- });
592
- if (res.status === 429) {
593
- const ra = retryAfterMs(res.headers);
594
- if (attempt >= this.maxRetries || ra !== null && ra > MAX_RETRY_AFTER_MS) throw this.toError(res, "refresh");
595
- await this.sleep(this.backoff(attempt + 1, ra));
596
- continue;
797
+ async refreshWith(refreshToken, b) {
798
+ let attempt = 0;
799
+ let res;
800
+ for (; ; ) {
801
+ try {
802
+ res = await this.send("POST", `${this.baseUrl}/auth/refresh`, {
803
+ body: { refresh_token: refreshToken },
804
+ auth: false,
805
+ operationId: "refresh",
806
+ budget: b,
807
+ retry429: false,
808
+ retryFailures: true,
809
+ onlyUnsent: true
810
+ });
811
+ } catch (err) {
812
+ if (!(err instanceof NetworkError)) throw err;
813
+ res = null;
597
814
  }
598
- if (res.status !== 200) return null;
599
- return this.saveTokens(res.json);
815
+ if (res === null || res.status !== 429) break;
816
+ const wait = this.backoff(attempt, res.headers.get("retry-after"));
817
+ if (attempt >= this.maxRetries || wait === null || !await this.wait(b, wait)) throw this.toError(res, "refresh");
818
+ attempt++;
819
+ }
820
+ this.spentRefresh.add(refreshToken);
821
+ if (res && res.status === 200) {
822
+ const j = res.json;
823
+ if (j && typeof j.access_token === "string" && typeof j.refresh_token === "string") return this.saveTokens(j);
600
824
  }
825
+ return null;
601
826
  }
602
- async login() {
827
+ async login(b) {
603
828
  let waited = false;
829
+ let res;
604
830
  for (; ; ) {
605
- const res = await this.send("POST", `${this.baseUrl}/auth/login`, {
831
+ res = await this.send("POST", `${this.baseUrl}/auth/login`, {
606
832
  body: { email: this.email, password: this.password },
607
833
  auth: false,
608
834
  operationId: "login",
609
- noRetry: true
835
+ budget: b,
836
+ retry429: false,
837
+ retryFailures: true,
838
+ networkUnsentOnly: true
610
839
  });
611
840
  if (res.status === 429 && !waited && this.loginWaitS > 0) {
612
- waited = true;
613
- await this.sleep(this.loginWaitS * 1e3);
614
- continue;
841
+ const ra = retryAfterMs(res.headers);
842
+ if (ra === null || ra / 1e3 <= this.loginWaitS) {
843
+ waited = true;
844
+ if (!await this.wait(b, ra !== null ? ra / 1e3 : this.loginWaitS)) break;
845
+ continue;
846
+ }
615
847
  }
616
- if (res.status !== 200) throw this.toError(res, "login");
617
- const body = res.json;
618
- if (body && body.status === "mfa_required") throw new MfaRequiredError();
619
- if (body && body.password_expired === true) throw new PasswordExpiredError();
620
- return this.saveTokens(body);
848
+ break;
621
849
  }
850
+ if (res.status !== 200) throw this.toError(res, "login");
851
+ const body = res.json;
852
+ if (body && body.status === "mfa_required") throw new MfaRequiredError();
853
+ if (body && body.password_expired === true) throw new PasswordExpiredError();
854
+ return this.saveTokens(body);
622
855
  }
623
856
  async saveTokens(body) {
624
857
  const b = body ?? {};
@@ -637,19 +870,25 @@ var Core = class {
637
870
  url(op, pathArgs, query) {
638
871
  let i = 0;
639
872
  const path = op.path.replace(/\{([^}]+)\}/g, (_, name) => {
640
- const v = pathArgs[i++];
641
- if (typeof v !== "string" || v.trim() === "") {
642
- throw new TypeError(`Missing path parameter "${name}".`);
643
- }
644
- return encodeURIComponent(v);
873
+ return encodeURIComponent(pathArg(pathArgs[i++], `path parameter "${name}"`));
645
874
  });
646
875
  const qs = new URLSearchParams(query).toString();
647
876
  return `${this.baseUrl}${path}${qs ? `?${qs}` : ""}`;
648
877
  }
878
+ /**
879
+ * Send with the retry policy (README "Retries"). Network failures and 5xx are retried up to
880
+ * `maxRetries` with backoff for idempotent requests (reads, updates, deletes, user create with its
881
+ * idempotency key) and for sign-in and token renewal (`retryFailures`; renewal retries a network
882
+ * failure only when the request never left, `onlyUnsent`, so a refresh token is never sent twice).
883
+ * 429 honours Retry-After up to 60 seconds; a longer one is returned at once. The deadline caps the
884
+ * whole call, sign-in and renewal included.
885
+ */
649
886
  async send(method, url, o) {
887
+ let idempotent = RETRY_METHODS.has(method) || Boolean(o.idempotencyKey);
888
+ if (o.retryFailures !== void 0) idempotent = o.retryFailures;
889
+ const retry429 = o.retry429 ?? true;
650
890
  let attempt = 0;
651
- let authRetried = false;
652
- const safeToRepeat = method !== "POST" || Boolean(o.idempotencyKey);
891
+ let refreshed = false;
653
892
  for (; ; ) {
654
893
  const headers = {
655
894
  Accept: "application/json",
@@ -661,50 +900,64 @@ var Core = class {
661
900
  if (attempt > 0 && o.idempotencyKey) headers["Accept-Encoding"] = "identity";
662
901
  let token = null;
663
902
  if (o.auth) {
664
- token = await this.accessToken();
903
+ token = await this.accessToken(o.budget);
665
904
  headers.Authorization = `Bearer ${token}`;
666
905
  }
667
906
  let res;
668
907
  try {
669
- res = await this.fetchOnce(method, url, headers, o.body);
908
+ res = await this.fetchOnce(method, url, headers, o.body, o.budget);
670
909
  } catch (err) {
671
- if (!o.noRetry && safeToRepeat && attempt < this.maxRetries) {
910
+ if (err instanceof NetworkError && err.kind !== "decoding" && idempotent && attempt < this.maxRetries && !((o.onlyUnsent || o.networkUnsentOnly) && err.requestSent)) {
911
+ if (!await this.wait(o.budget, this.backoff(attempt, null) ?? 0)) {
912
+ throw new NetworkError("timeout", "deadline reached", err.requestSent);
913
+ }
672
914
  attempt++;
673
- await this.sleep(this.backoff(attempt, null));
674
915
  continue;
675
916
  }
676
917
  throw err;
677
918
  }
678
- if (res.status === 401 && o.auth && !authRetried) {
679
- authRetried = true;
680
- await this.renew(token);
919
+ if (res.status === 401 && o.auth && !refreshed) {
920
+ refreshed = true;
921
+ await this.renew(token, o.budget);
681
922
  continue;
682
923
  }
683
- if (!o.noRetry && attempt < this.maxRetries) {
684
- const retriable = res.status === 429 || res.status >= 500 && safeToRepeat;
685
- const ra = retryAfterMs(res.headers);
686
- if (retriable && (ra === null || ra <= MAX_RETRY_AFTER_MS)) {
687
- attempt++;
688
- await this.sleep(this.backoff(attempt, ra));
689
- continue;
690
- }
924
+ const retryable = res.status === 429 && retry429 || res.status >= 500 && idempotent && !o.onlyUnsent;
925
+ if (retryable && attempt < this.maxRetries) {
926
+ const wait = this.backoff(attempt, res.headers?.get?.("retry-after"));
927
+ if (wait === null || !await this.wait(o.budget, wait)) return res;
928
+ attempt++;
929
+ continue;
691
930
  }
692
931
  return res;
693
932
  }
694
933
  }
695
- async fetchOnce(method, url, headers, body) {
934
+ async fetchOnce(method, url, headers, body, budget) {
935
+ const remaining = this.remainingS(budget);
936
+ if (remaining < 5e-3) throw new NetworkError("timeout", "deadline reached", false);
696
937
  const ctrl = new AbortController();
697
- const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
938
+ const timer = setTimeout(() => ctrl.abort(), Math.min(this.timeoutMs, remaining * 1e3));
939
+ let r;
698
940
  try {
699
- const r = await this.fetchImpl(url, {
700
- method,
701
- headers,
702
- body: body === void 0 ? void 0 : JSON.stringify(body),
703
- signal: ctrl.signal,
704
- redirect: "manual",
705
- cache: "no-store"
706
- });
707
- const text = await r.text();
941
+ try {
942
+ r = await this.fetchImpl(url, {
943
+ method,
944
+ headers,
945
+ body: body === void 0 ? void 0 : JSON.stringify(body),
946
+ signal: ctrl.signal,
947
+ redirect: "manual",
948
+ cache: "no-store"
949
+ });
950
+ } catch (err) {
951
+ const f = classifyFetchFailure(err, ctrl.signal.aborted);
952
+ throw new NetworkError(f.kind, f.detail, f.sent);
953
+ }
954
+ let text;
955
+ try {
956
+ text = await r.text();
957
+ } catch (err) {
958
+ const f = classifyFetchFailure(err, ctrl.signal.aborted);
959
+ throw new NetworkError(f.kind === "timeout" ? "timeout" : "decoding", f.detail, true);
960
+ }
708
961
  let json = null;
709
962
  if (text) {
710
963
  try {
@@ -714,20 +967,10 @@ var Core = class {
714
967
  }
715
968
  }
716
969
  return { status: r.status, headers: r.headers, json, text };
717
- } catch (err) {
718
- const aborted = err?.name === "AbortError";
719
- throw new ApiError(0, aborted ? "timeout" : "network_error", aborted ? "Request timed out." : "Network error.", {
720
- cause: err
721
- });
722
970
  } finally {
723
971
  clearTimeout(timer);
724
972
  }
725
973
  }
726
- backoff(attempt, retryAfter) {
727
- const base = Math.min(8e3, 500 * 2 ** (attempt - 1));
728
- const jittered = base / 2 + this.random() * (base / 2);
729
- return Math.max(jittered, retryAfter ?? 0);
730
- }
731
974
  // -------------------------------------------------------------- errors
732
975
  toError(res, operationId, requestBody) {
733
976
  const { code, message: serverText, requestId, hint } = normaliseErrorBody(res);
@@ -813,13 +1056,13 @@ function normaliseErrorBody(res) {
813
1056
  function str(v) {
814
1057
  return typeof v === "string" && v !== "" ? v : null;
815
1058
  }
1059
+ function parseRetryAfter(value) {
1060
+ if (typeof value !== "string" || !/^[0-9]{1,9}(\.[0-9]+)?$/.test(value)) return null;
1061
+ return Number(value);
1062
+ }
816
1063
  function retryAfterMs(h) {
817
- const v = h?.get?.("retry-after");
818
- if (!v) return null;
819
- const n = Number(v);
820
- if (Number.isFinite(n)) return Math.max(0, n * 1e3);
821
- const t = Date.parse(v);
822
- return Number.isFinite(t) ? Math.max(0, t - Date.now()) : null;
1064
+ const s = parseRetryAfter(h?.get?.("retry-after"));
1065
+ return s === null ? null : s * 1e3;
823
1066
  }
824
1067
  function secondsOrNull(ms) {
825
1068
  return ms === null ? null : Math.round(ms / 1e3);
@@ -1224,6 +1467,17 @@ var Intelligence = class {
1224
1467
  }
1225
1468
  return this.roleCheck;
1226
1469
  }
1470
+ /** Checks a query against the operation's published filters, before the role check or any request. */
1471
+ check(operationId, query) {
1472
+ for (const key of ["search", "keyword", "topic"]) {
1473
+ const v = query[key];
1474
+ if (typeof v === "string" && v.length > 200) throw new InvalidRequestError(`${key}: at most 200 characters`);
1475
+ }
1476
+ if (Array.isArray(query.numbers) && query.numbers.some((n) => typeof n === "string" && n.length > 200)) {
1477
+ throw new InvalidRequestError("numbers: at most 200 characters each");
1478
+ }
1479
+ buildQuery(operationId, OPERATIONS[operationId].query, query);
1480
+ }
1227
1481
  async frontline() {
1228
1482
  if (this.checkRole) await this.requireFrontline();
1229
1483
  }
@@ -1250,6 +1504,7 @@ var Intelligence = class {
1250
1504
  /** One page of calls, newest first, with totals for the whole filter in `summary`. */
1251
1505
  async searchCalls(filters = {}) {
1252
1506
  const q = this.callQuery(filters);
1507
+ this.check("listCalls", q);
1253
1508
  await this.frontline();
1254
1509
  const page = await this.c.calls.listCalls(q);
1255
1510
  return { ...page, summary: page.raw.data?.summary ?? {} };
@@ -1258,16 +1513,19 @@ var Intelligence = class {
1258
1513
  async *iterCalls(filters = {}) {
1259
1514
  const { maxItems, ...f } = filters;
1260
1515
  const q = this.callQuery(f);
1516
+ this.check("listCalls", q);
1261
1517
  await this.frontline();
1262
1518
  yield* this.c.calls.iterCalls({ ...q, maxItems });
1263
1519
  }
1264
1520
  /** Full detail of one call. NotFoundError when the call is outside this login's view. */
1265
1521
  async getCall(callId) {
1522
+ pathArg(callId, "callId");
1266
1523
  await this.frontline();
1267
1524
  return (await this.c.calls.getCall(callId)).data ?? {};
1268
1525
  }
1269
1526
  /** Transcript lines in order ("Speaker 1" … "Speaker N"; `name` when known). */
1270
1527
  async getTranscript(callId) {
1528
+ pathArg(callId, "callId");
1271
1529
  await this.frontline();
1272
1530
  return (await this.c.calls.getCallTranscript(callId)).data?.transcript ?? [];
1273
1531
  }
@@ -1279,6 +1537,7 @@ var Intelligence = class {
1279
1537
  * no recording.
1280
1538
  */
1281
1539
  async getRecordingUrl(callId) {
1540
+ pathArg(callId, "callId");
1282
1541
  const call = await this.getCall(callId);
1283
1542
  const v = call.vcon;
1284
1543
  return new RecordingLink(v?.recording_url ?? null, v?.recording_url_expires_at ?? null);
@@ -1303,12 +1562,14 @@ var Intelligence = class {
1303
1562
  /** One page of First Alert hits, newest first. `total` counts every match. */
1304
1563
  async searchAlerts(filters = {}) {
1305
1564
  const q = this.alertQuery(filters);
1565
+ this.check("listAlerts", q);
1306
1566
  await this.frontline();
1307
1567
  return this.c.alerts.listAlerts(q);
1308
1568
  }
1309
1569
  async *iterAlerts(filters = {}) {
1310
1570
  const { maxItems, ...f } = filters;
1311
1571
  const q = this.alertQuery(f);
1572
+ this.check("listAlerts", q);
1312
1573
  await this.frontline();
1313
1574
  yield* this.c.alerts.iterAlerts({ ...q, maxItems });
1314
1575
  }
@@ -1317,6 +1578,7 @@ var Intelligence = class {
1317
1578
  * Returns null when the alert is not visible. With `withCall: true` the call detail is added as `call`.
1318
1579
  */
1319
1580
  async getAlert(alertId, options = {}) {
1581
+ if (typeof alertId !== "string") throw new InvalidRequestError("alertId must be a UUID.");
1320
1582
  const id = alertId.trim().toLowerCase();
1321
1583
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) {
1322
1584
  throw new InvalidRequestError("alertId must be a UUID.");
@@ -1330,6 +1592,7 @@ var Intelligence = class {
1330
1592
  /** Alert totals for a window (default: 00:00 UTC seven days ago until now). */
1331
1593
  async getAlertsDashboard(filters = {}) {
1332
1594
  only(filters, ["dateFrom", "dateTo", "locationIds", "companyId"], "getAlertsDashboard");
1595
+ this.check("getAlertsDashboard", renameLocationIds(filters));
1333
1596
  await this.frontline();
1334
1597
  return (await this.c.alerts.getAlertsDashboard(renameLocationIds(filters))).data ?? {};
1335
1598
  }
@@ -1337,6 +1600,7 @@ var Intelligence = class {
1337
1600
  /** One page of follow-up tasks, newest first. No default date window. */
1338
1601
  async listTasks(filters = {}) {
1339
1602
  only(filters, TASK_FILTERS, "listTasks");
1603
+ this.check("listTasks", renameLocationIds(filters));
1340
1604
  await this.frontline();
1341
1605
  const page = await this.c.tasks.listTasks(renameLocationIds(filters));
1342
1606
  return { ...page, summary: page.raw.summary ?? {} };
@@ -1344,6 +1608,7 @@ var Intelligence = class {
1344
1608
  async *iterTasks(filters = {}) {
1345
1609
  const { maxItems, ...f } = filters;
1346
1610
  only(f, TASK_FILTERS, "iterTasks");
1611
+ this.check("listTasks", renameLocationIds(f));
1347
1612
  await this.frontline();
1348
1613
  yield* this.c.tasks.iterTasks({ ...renameLocationIds(f), maxItems });
1349
1614
  }
@@ -1351,18 +1616,23 @@ var Intelligence = class {
1351
1616
  /** Insights Hub dashboard for a window. `start` and `end` are required. */
1352
1617
  async getInsightsDashboard(filters) {
1353
1618
  only(filters, ["start", "end", "trendingLimit", "locationIds", "companyId"], "getInsightsDashboard");
1619
+ this.check("getInsightsDashboard", renameLocationIds(filters));
1354
1620
  await this.frontline();
1355
1621
  return (await this.c.insights.getInsightsDashboard(renameLocationIds(filters))).data ?? {};
1356
1622
  }
1357
1623
  /** One page of calls for a topic slug (from the dashboard's `topic_call_volumes`). */
1358
1624
  async listTopicCalls(slug, filters = {}) {
1625
+ pathArg(slug, "slug");
1359
1626
  only(filters, TOPIC_FILTERS, "listTopicCalls");
1627
+ this.check("listTopicCalls", renameLocationIds(filters));
1360
1628
  await this.frontline();
1361
1629
  return this.c.insights.listTopicCalls(slug, renameLocationIds(filters));
1362
1630
  }
1363
1631
  async *iterTopicCalls(slug, filters = {}) {
1364
1632
  const { maxItems, ...f } = filters;
1633
+ pathArg(slug, "slug");
1365
1634
  only(f, TOPIC_FILTERS, "iterTopicCalls");
1635
+ this.check("listTopicCalls", renameLocationIds(f));
1366
1636
  await this.frontline();
1367
1637
  yield* this.c.insights.iterTopicCalls(slug, { ...renameLocationIds(f), maxItems });
1368
1638
  }
@@ -1376,7 +1646,8 @@ var Intelligence = class {
1376
1646
  * whatever users' number mappings say. `enabled: false` pauses it (there is no delete).
1377
1647
  */
1378
1648
  async setAfterCallWebhook(locationId, url, enabled = true) {
1379
- if (!/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1649
+ pathArg(locationId, "locationId");
1650
+ if (typeof url !== "string" || !/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1380
1651
  const r = await this.c.webhooks.saveAfterCallWebhook(locationId, { webhook_url: url, enabled });
1381
1652
  return r.data ?? {};
1382
1653
  }
@@ -1394,7 +1665,8 @@ var Intelligence = class {
1394
1665
  * configuration PUT would otherwise clear the monitored numbers.
1395
1666
  */
1396
1667
  async setFirstAlertWebhook(locationId, url) {
1397
- if (url !== null && !/^https:\/\//i.test(url)) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1668
+ pathArg(locationId, "locationId");
1669
+ if (url !== null && (typeof url !== "string" || !/^https:\/\//i.test(url))) throw new InvalidRequestError("The webhook URL must use HTTPS.");
1398
1670
  return (await this.c.firstAlert.setWebhookUrl(locationId, url)).data ?? {};
1399
1671
  }
1400
1672
  /** Send a test request to `url` (default: the saved URL). Returns only success and your endpoint's status. */
@@ -1406,51 +1678,6 @@ var Intelligence = class {
1406
1678
  }
1407
1679
  };
1408
1680
 
1409
- // src/util.ts
1410
- async function uuid4() {
1411
- const c = globalThis.crypto;
1412
- if (c && typeof c.randomUUID === "function") return c.randomUUID();
1413
- let bytes;
1414
- if (c && typeof c.getRandomValues === "function") {
1415
- bytes = c.getRandomValues(new Uint8Array(16));
1416
- } else {
1417
- const nodeCrypto = await import('crypto');
1418
- bytes = new Uint8Array(nodeCrypto.randomBytes(16));
1419
- }
1420
- bytes[6] = bytes[6] & 15 | 64;
1421
- bytes[8] = bytes[8] & 63 | 128;
1422
- const h = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
1423
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
1424
- }
1425
- function numbersFor(mappings, connectorId) {
1426
- const out = [];
1427
- for (const m of mappings ?? []) if (m.connector_id === connectorId) out.push(...m.monitored_numbers ?? []);
1428
- return [...new Set(out)];
1429
- }
1430
- function mergeMappings(current, connectorId, add = [], remove = []) {
1431
- const byConnector = /* @__PURE__ */ new Map();
1432
- for (const m of current ?? []) {
1433
- if (!m.connector_id) continue;
1434
- const list2 = byConnector.get(m.connector_id) ?? [];
1435
- list2.push(...m.monitored_numbers ?? []);
1436
- byConnector.set(m.connector_id, list2);
1437
- }
1438
- const drop = new Set(remove);
1439
- const mine = (byConnector.get(connectorId) ?? []).filter((n) => !drop.has(n));
1440
- for (const n of add) if (!mine.includes(n)) mine.push(n);
1441
- byConnector.set(connectorId, mine);
1442
- const out = [];
1443
- for (const [connector_id, nums] of byConnector) {
1444
- const uniq3 = [...new Set(nums)];
1445
- if (uniq3.length) out.push({ connector_id, monitored_numbers: uniq3 });
1446
- }
1447
- return out;
1448
- }
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
1681
  // src/secrets.ts
1455
1682
  var SECRET_WORDS = ["key", "secret", "token", "password", "passwd", "pwd", "credential", "auth"];
1456
1683
  var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
@@ -1623,10 +1850,12 @@ async function all(gen) {
1623
1850
  for await (const x of gen) out.push(x);
1624
1851
  return out;
1625
1852
  }
1853
+ var LINE_RE = /^\+?[0-9*#]{1,32}$/;
1626
1854
  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;
1855
+ if (typeof value !== "string" || !LINE_RE.test(value)) {
1856
+ throw new InvalidRequestError(`${name}: an extension or number of 1 to 32 digits, * or # (an optional leading +), with no spaces or other characters`);
1857
+ }
1858
+ return value;
1630
1859
  }
1631
1860
  function numbersOf(mappings, connectorId) {
1632
1861
  const out = [];
@@ -1648,8 +1877,25 @@ function sameMappings(a, b) {
1648
1877
  };
1649
1878
  return deepEqual(norm(a), norm(b));
1650
1879
  }
1880
+ function str2(value, name, required = true, max = 200) {
1881
+ if ((value === void 0 || value === null) && !required) return null;
1882
+ if (typeof value !== "string") throw new InvalidRequestError(`${name}: a string${required ? "" : " or null"}`);
1883
+ const v = value.trim();
1884
+ if (required && !v) throw new InvalidRequestError(`${name} is required`);
1885
+ if (v.length > max) throw new InvalidRequestError(`${name}: at most ${max} characters`);
1886
+ return v;
1887
+ }
1888
+ function list2(value, name) {
1889
+ if (value === void 0 || value === null || typeof value === "string" || typeof value[Symbol.iterator] !== "function") {
1890
+ throw new InvalidRequestError(`${name}: a list`);
1891
+ }
1892
+ return [...value];
1893
+ }
1894
+ function bool(value, name) {
1895
+ if (value !== void 0 && typeof value !== "boolean") throw new InvalidRequestError(`${name}: true or false`);
1896
+ }
1651
1897
  function checkSetting(key, s) {
1652
- if (s === null || s === void 0) return;
1898
+ if (s === null || s === void 0) return null;
1653
1899
  if (typeof s !== "object") throw new InvalidRequestError(`alerts.${key} must be an AlertSetting`);
1654
1900
  if (s.sentimentBelow !== void 0 && s.sentimentBelow !== null) {
1655
1901
  const lvl = s.sentimentBelow;
@@ -1657,24 +1903,72 @@ function checkSetting(key, s) {
1657
1903
  throw new InvalidRequestError(`alerts.${key}.sentimentBelow: a whole number from -100 to -1`);
1658
1904
  }
1659
1905
  }
1906
+ let phrases = null;
1660
1907
  if (s.phrases !== void 0 && s.phrases !== null) {
1661
1908
  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())) {
1909
+ phrases = list2(s.phrases, `alerts.${key}.phrases`);
1910
+ if (!phrases.every((p) => typeof p === "string")) throw new InvalidRequestError(`alerts.${key}.phrases must be a list of strings`);
1911
+ if (!phrases.some((p) => p.trim())) {
1666
1912
  throw new InvalidRequestError(`alerts.${key}.phrases is empty; pass null to keep the current phrases`);
1667
1913
  }
1668
1914
  }
1915
+ return { phrases, sentimentBelow: s.sentimentBelow ?? null };
1669
1916
  }
1670
1917
  function checkAlerts(alerts) {
1671
- if (alerts === null || alerts === void 0) return;
1918
+ if (alerts === null || alerts === void 0) return null;
1672
1919
  if (typeof alerts !== "object") throw new InvalidRequestError("alerts must be an AlertSettings");
1673
- for (const key of RULE_FIELDS) checkSetting(key, alerts[key]);
1920
+ const out = {};
1921
+ for (const key of RULE_FIELDS) out[key] = checkSetting(key, alerts[key]);
1922
+ return out;
1923
+ }
1924
+ function checkConnectorLocal(cs, required = false) {
1925
+ if (cs === null || cs === void 0) {
1926
+ if (required) throw new InvalidRequestError("A connector is required: pass a ConnectorSpec");
1927
+ return;
1928
+ }
1929
+ if (!isConnectorSpec(cs)) throw new InvalidRequestError("connector must be a ConnectorSpec");
1930
+ str2(cs.type, "connector.type");
1931
+ str2(cs.name, "connector.name", false);
1932
+ if (typeof cs.timeout !== "number" || !(cs.timeout >= 0)) throw new InvalidRequestError("connector.timeout: a number of seconds");
1933
+ }
1934
+ var isCustomerObject = (v) => v !== null && typeof v === "object" && "companyId" in v;
1935
+ var isTeamObject = (v) => v !== null && typeof v === "object" && typeof v.locationId === "string";
1936
+ function checkCustomerRef(customer) {
1937
+ if (isCustomerObject(customer)) {
1938
+ pathArg(customer.companyId, "customer.companyId");
1939
+ for (const t of [...customer.management ? [customer.management] : [], ...Array.isArray(customer.teams) ? customer.teams : []]) {
1940
+ if (!isTeamObject(t)) throw new InvalidRequestError("customer: every team needs a string locationId");
1941
+ pathArg(t.locationId, "team.locationId");
1942
+ }
1943
+ return;
1944
+ }
1945
+ if (typeof customer !== "string") throw new InvalidRequestError("customer: a Customer or a company id");
1946
+ pathArg(customer, "customer");
1947
+ }
1948
+ function checkTeamRef(team, required = true) {
1949
+ if ((team === void 0 || team === null) && !required) return;
1950
+ if (isTeamObject(team)) return;
1951
+ if (typeof team !== "string" || !team.trim() || team.length > 200) throw new InvalidRequestError("team: a Team, its location id or its name");
1952
+ }
1953
+ function checkPerson(person) {
1954
+ if (!person || typeof person !== "object") throw new InvalidRequestError("person must be a PersonSpec");
1955
+ const p = person;
1956
+ if (!str2(p.email, "person.email").includes("@")) throw new InvalidRequestError("person.email: an email address");
1957
+ str2(p.firstName, "person.firstName");
1958
+ str2(p.lastName, "person.lastName");
1959
+ str2(p.phoneNumber, "person.phoneNumber", false);
1960
+ if (p.authMethod !== void 0 && p.authMethod !== "password" && p.authMethod !== "sso") {
1961
+ throw new InvalidRequestError('person.authMethod: "password" or "sso"');
1962
+ }
1674
1963
  }
1964
+ function checkTeamSpec(team) {
1965
+ if (!team || typeof team !== "object" || isTeamObject(team)) throw new InvalidRequestError("team must be a TeamSpec");
1966
+ for (const f of ["name", "street", "city", "state", "country", "zipcode", "vertical"]) str2(team[f], `team.${f}`);
1967
+ }
1968
+ var checkUserId = (id) => void pathArg(id, "userId");
1675
1969
  function cleanPhrases(phrases) {
1676
1970
  if (phrases === null || phrases === void 0) return null;
1677
- return uniq(phrases.filter((p) => p && p.trim()).map((p) => p.trim()));
1971
+ return uniq([...phrases].filter((p) => p && p.trim()).map((p) => p.trim()));
1678
1972
  }
1679
1973
  function ruleSettings(rule) {
1680
1974
  let phrases = null;
@@ -1772,44 +2066,28 @@ var Accounts = class _Accounts {
1772
2066
  constructor(c) {
1773
2067
  this.c = c;
1774
2068
  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
- }
1806
2069
  }
1807
2070
  c;
1808
2071
  me = null;
1809
2072
  verticals = null;
1810
- connectorTypes = null;
2073
+ /** Teams whose groups and rules were read in the current helper call: a live listing is not repeated for them. */
2074
+ readNow = /* @__PURE__ */ new WeakSet();
2075
+ lastIndex = null;
1811
2076
  rawConnectors;
1812
2077
  tail = Promise.resolve();
2078
+ /**
2079
+ * Runs `fn` after every earlier writing helper of this client has finished (lists are read, merged and
2080
+ * written back, so two helpers at once would lose each other's lines). A failed helper does not fail the
2081
+ * next one. Arguments are checked before a helper gets here, so a bad argument is refused at once.
2082
+ */
2083
+ exclusive(fn) {
2084
+ const run = this.tail.then(fn, fn);
2085
+ this.tail = run.then(
2086
+ () => void 0,
2087
+ () => void 0
2088
+ );
2089
+ return run;
2090
+ }
1813
2091
  // ------------------------------------------------------------------ plumbing
1814
2092
  async requireAdmin() {
1815
2093
  if (this.me === null) this.me = unwrap(await this.c.account.getMe()) ?? {};
@@ -1825,10 +2103,66 @@ var Accounts = class _Accounts {
1825
2103
  if (exc instanceof AccountError || this.c.core.writes === run.start) throw exc;
1826
2104
  throw new AccountError(run.step, run.result, exc);
1827
2105
  }
2106
+ /**
2107
+ * The customer to work on. A company id is read live. A Customer object may be stale (a team added or
2108
+ * stopped elsewhere): one cheap live read, the company's location list, is compared with the object's
2109
+ * teams and Management by id and active state; if anything differs the full layout is read again and the
2110
+ * object is updated in place. A Customer that carries a location that is not in its company is refused.
2111
+ */
1828
2112
  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");
2113
+ if (typeof customer === "string" && customer !== "") return this.getCustomer(customer);
2114
+ if (!customer || typeof customer !== "object") throw new InvalidRequestError("customer: a Customer or a company id");
2115
+ for (const t of this.locationsOf(customer)) this.readNow.delete(t);
2116
+ let locs;
2117
+ try {
2118
+ locs = await all(this.c.locations.iterCompanyLocations(customer.companyId));
2119
+ } catch (exc) {
2120
+ if (exc instanceof NotFoundError) throw new InvalidRequestError("This Customer's company is not visible to this login");
2121
+ throw exc;
2122
+ }
2123
+ const known = new Set(locs.map((l) => l.id));
2124
+ const active = new Set(locs.filter((l) => l.is_active ?? true).map((l) => l.id));
2125
+ const mine = this.locationsOf(customer).map((t) => t.locationId);
2126
+ if (mine.some((id) => !known.has(id))) {
2127
+ throw new InvalidRequestError("The Customer carries a location that is not in its company: read it again with getCustomer");
2128
+ }
2129
+ if (mine.length !== active.size || !mine.every((id) => active.has(id))) {
2130
+ const fresh = await this.getCustomer(customer.companyId);
2131
+ const byId = new Map(this.locationsOf(customer).map((t) => [t.locationId, t]));
2132
+ const keep = (t) => {
2133
+ const old = byId.get(t.locationId);
2134
+ const kept = old ? Object.assign(old, t) : t;
2135
+ this.readNow.add(kept);
2136
+ return kept;
2137
+ };
2138
+ customer.management = fresh.management ? keep(fresh.management) : null;
2139
+ customer.teams.splice(0, customer.teams.length, ...fresh.teams.map(keep));
2140
+ customer.pending = fresh.pending;
2141
+ customer.ssoDomainId = fresh.ssoDomainId;
2142
+ customer.ssoTxtRecord = fresh.ssoTxtRecord;
2143
+ }
2144
+ customer.refreshedAt = /* @__PURE__ */ new Date();
2145
+ return customer;
2146
+ }
2147
+ /**
2148
+ * Group and rule ids of these teams from a live listing made now, never from the object (a company id
2149
+ * included: the layout read does not list groups and rules again). A group in `need` that is missing is
2150
+ * refused before any write.
2151
+ */
2152
+ async live(teams, need = []) {
2153
+ for (const t of teams) {
2154
+ if (!this.readNow.has(t)) {
2155
+ const [groups, rules] = await this.readGroupsRules(t.locationId);
2156
+ Object.assign(t.groups, groups);
2157
+ Object.assign(t.rules, rules);
2158
+ this.readNow.add(t);
2159
+ }
2160
+ const wanted = t.kind === "team" ? need : need.filter((f) => f === "weeklyReports");
2161
+ const missing = wanted.filter((f) => t.groups[f] === null).map((f) => TEAM_GROUPS[f]);
2162
+ if (missing.length) {
2163
+ throw new InvalidRequestError(`${t.name}: group ${missing.join(", ")} is missing; run createCustomer (or addTeam) again to restore the layout`);
2164
+ }
2165
+ }
1832
2166
  }
1833
2167
  teamOf(cust, team) {
1834
2168
  if (typeof team === "object" && team !== null) {
@@ -1852,18 +2186,9 @@ var Accounts = class _Accounts {
1852
2186
  for (const v of this.verticals) if (vertical === v.key || vertical === v.name) return v.id;
1853
2187
  throw new InvalidRequestError(`Unknown vertical "${vertical}": use an id or key from listVerticals()`);
1854
2188
  }
2189
+ /** The local checks only: the type's value is the platform's to judge (any type is passed through, no list read first). */
1855
2190
  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)}`);
1866
- }
2191
+ checkConnectorLocal(cs, required);
1867
2192
  }
1868
2193
  // ------------------------------------------------------------------ reading the layout
1869
2194
  /**
@@ -1872,6 +2197,7 @@ var Accounts = class _Accounts {
1872
2197
  * what is missing listed in `pending`.
1873
2198
  */
1874
2199
  async getCustomer(companyId) {
2200
+ checkCustomerRef(companyId);
1875
2201
  await this.requireAdmin();
1876
2202
  const c = this.c;
1877
2203
  const company = unwrap(await c.companies.getCompany(companyId)) ?? {};
@@ -1884,7 +2210,7 @@ var Accounts = class _Accounts {
1884
2210
  const [b1, b2] = key(b);
1885
2211
  return a1 < b1 ? -1 : a1 > b1 ? 1 : a2 < b2 ? -1 : a2 > b2 ? 1 : 0;
1886
2212
  });
1887
- const cust = { companyId, management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [] };
2213
+ const cust = { companyId, management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [], refreshedAt: null };
1888
2214
  for (const loc of locs) {
1889
2215
  const kind = loc.location_name === mgmtName ? "management" : "team";
1890
2216
  const team = await this.readTeam(loc.id, loc.location_name ?? "", kind);
@@ -1892,6 +2218,7 @@ var Accounts = class _Accounts {
1892
2218
  else cust.teams.push(team);
1893
2219
  }
1894
2220
  cust.pending = this.pendingOf(cust);
2221
+ cust.refreshedAt = /* @__PURE__ */ new Date();
1895
2222
  for (const dom of rowsOf(await c.sso.listCompanyDomains(companyId))) {
1896
2223
  cust.ssoDomainId = dom.id ?? null;
1897
2224
  const ver = dom.verification ?? {};
@@ -1901,16 +2228,24 @@ var Accounts = class _Accounts {
1901
2228
  return cust;
1902
2229
  }
1903
2230
  async readTeam(locationId, name, kind) {
1904
- const c = this.c;
1905
2231
  const team = newTeam(locationId, name, kind);
2232
+ const [groups, rules] = await this.readGroupsRules(locationId);
2233
+ Object.assign(team.groups, groups);
2234
+ Object.assign(team.rules, rules);
2235
+ await this.readConnector(team);
2236
+ this.readNow.add(team);
2237
+ return team;
2238
+ }
2239
+ async readGroupsRules(locationId) {
2240
+ const c = this.c;
2241
+ const probe = newTeam(locationId, "", "team");
1906
2242
  const byName = /* @__PURE__ */ new Map();
1907
2243
  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;
2244
+ for (const f of GROUP_FIELDS) probe.groups[f] = byName.get(TEAM_GROUPS[f]) ?? null;
1909
2245
  const rules = /* @__PURE__ */ new Map();
1910
2246
  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;
2247
+ for (const key of RULE_FIELDS) probe.rules[key] = rules.get(RULES[key].name) ?? null;
2248
+ return [probe.groups, probe.rules];
1914
2249
  }
1915
2250
  async readConnector(team) {
1916
2251
  const conns = (await all(this.c.connectors.iterLocationConnectors(team.locationId))).sort((a, b) => rank(a.status) - rank(b.status));
@@ -1948,90 +2283,100 @@ var Accounts = class _Accounts {
1948
2283
  * `companyId` and pass it on later runs: a company is never adopted by its name alone.
1949
2284
  */
1950
2285
  async createCustomer(spec) {
1951
- const me = await this.requireAdmin();
1952
2286
  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)");
2287
+ if (!spec || typeof spec !== "object") throw new InvalidRequestError("spec must be a CustomerSpec");
2288
+ str2(spec.companyName, "companyName");
2289
+ checkPerson(spec.admin);
2290
+ str2(spec.admin.phoneNumber, "admin.phoneNumber");
2291
+ checkTeamSpec(spec.team);
2292
+ const alerts = checkAlerts(spec.alerts);
2293
+ checkConnectorLocal(spec.connector);
2294
+ for (const f of ["resellerId", "companyCode", "companyId", "ssoDomain"]) str2(spec[f], f, false);
2295
+ bool(spec.mfaOff, "mfaOff");
2296
+ bool(spec.reactivate, "reactivate");
1959
2297
  const mgmtName = spec.companyName + MANAGEMENT_SUFFIX;
1960
2298
  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)`);
2299
+ return this.exclusive(async () => {
2300
+ const me = await this.requireAdmin();
2301
+ await this.checkConnector(spec.connector);
2302
+ const resellerId = spec.resellerId || me.reseller_id;
2303
+ if (!resellerId) throw new InvalidRequestError("resellerId is required (this login has none)");
2304
+ await this.verticalId(spec.team.vertical);
2305
+ const result = { companyId: "", management: null, teams: [], pending: [], ssoDomainId: null, ssoTxtRecord: null, created: [], existing: [], refreshedAt: null };
2306
+ const failures = [];
2307
+ const run = this.run(result);
2308
+ try {
2309
+ run.step = "company";
2310
+ let company = await this.findCompany(resellerId, spec);
2311
+ if (company === null) {
2312
+ const body = {
2313
+ company_name: spec.companyName,
2314
+ primary_admin_contact_name: `${spec.admin.firstName} ${spec.admin.lastName}`.trim(),
2315
+ primary_admin_contact_email: spec.admin.email,
2316
+ primary_admin_contact_phone: spec.admin.phoneNumber,
2317
+ enabled_products: [...PRODUCT_KEYS]
2318
+ };
2319
+ if (spec.companyCode) body.company_code = spec.companyCode;
2320
+ company = unwrap(await c.companies.createCompany(resellerId, body));
2321
+ result.created.push("company");
2322
+ } else {
2323
+ result.existing.push("company");
2324
+ if (!(company.is_active ?? true)) {
2325
+ if (!spec.reactivate) {
2326
+ throw new InvalidRequestError(`Company "${spec.companyName}" exists but is inactive (set reactivate: true to reactivate it)`);
2327
+ }
2328
+ await c.companies.reactivateCompany(company.id);
1984
2329
  }
1985
- await c.companies.reactivateCompany(company.id);
1986
2330
  }
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, {});
2331
+ const companyId = result.companyId = company.id;
2332
+ run.step = "mfa";
2333
+ if (spec.mfaOff) {
2334
+ const current2 = unwrap(await c.companies.getCompany(companyId)) ?? {};
2335
+ if (current2.mfa_enforced) {
2336
+ await c.companies.updateCompany(companyId, { mfa_enforced: false });
2337
+ if ((unwrap(await c.companies.getCompany(companyId)) ?? {}).mfa_enforced) {
2338
+ const text = "MFA is still on for the company after the update";
2339
+ throw new ApiError(200, null, text, {});
2340
+ }
1997
2341
  }
1998
2342
  }
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);
2343
+ run.step = "sso";
2344
+ if (spec.ssoDomain) await this.ensureDomain(companyId, spec.ssoDomain, result);
2345
+ run.step = "products";
2346
+ const current = unwrap(await c.companies.getCompany(companyId)) ?? {};
2347
+ const have = current.enabled_products ?? [];
2348
+ if (!PRODUCT_KEYS.every((k) => have.includes(k))) await c.companies.addProducts(companyId, [...PRODUCT_KEYS]);
2349
+ run.step = "locations";
2350
+ const team = await this.ensureLocation(companyId, spec.team.name, spec.team, "team", !!spec.reactivate, result);
2351
+ const mgmt = await this.ensureLocation(companyId, mgmtName, spec.team, "management", !!spec.reactivate, result);
2352
+ result.teams = [team];
2353
+ result.management = mgmt;
2354
+ run.step = "connectors";
2355
+ if (spec.connector) {
2356
+ for (const t of [team, mgmt]) {
2357
+ const failure = await this.ensureConnector(t, spec.connector, result);
2358
+ if (failure) failures.push(failure);
2359
+ }
2360
+ } else {
2361
+ await this.readConnector(team);
2362
+ await this.readConnector(mgmt);
2016
2363
  }
2017
- } else {
2018
- await this.readConnector(team);
2019
- await this.readConnector(mgmt);
2364
+ run.step = "groups";
2365
+ await this.ensureGroups(team, result);
2366
+ await this.ensureGroups(mgmt, result);
2367
+ run.step = "rules";
2368
+ await this.ensureRules(team, this.settingsFrom(alerts), result);
2369
+ run.step = "insights_hub";
2370
+ await this.ensureInsightsHub(team);
2371
+ await this.monitorAllOff(mgmt.locationId);
2372
+ result.pending = this.pendingOf(result);
2373
+ result.refreshedAt = /* @__PURE__ */ new Date();
2374
+ } catch (exc) {
2375
+ this.stop(run, exc);
2020
2376
  }
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);
2032
- }
2033
- raiseConnectorFailure(failures, result);
2034
- return result;
2377
+ raiseConnectorFailure(failures, result);
2378
+ return result;
2379
+ });
2035
2380
  }
2036
2381
  /**
2037
2382
  * `spec.companyId`, or the one company with this exact name whose primary contact email is
@@ -2214,18 +2559,42 @@ var Accounts = class _Accounts {
2214
2559
  const label = `connector:${team.name}`;
2215
2560
  if (found !== null) {
2216
2561
  const unchanged = _Accounts.unchanged(found, name, config);
2217
- if ([...RUNNING, "connecting"].includes(found.status) && unchanged) {
2562
+ if (RUNNING.includes(found.status) && unchanged) {
2218
2563
  result?.existing.push(label);
2219
2564
  this.setConn(team, found);
2220
2565
  return null;
2221
2566
  }
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") {
2567
+ if (found.status === "connecting" && unchanged) {
2568
+ result?.existing.push(label);
2569
+ try {
2570
+ let settled;
2571
+ try {
2572
+ settled = await conns.waitForStatus(team.locationId, found.id, [...RUNNING, "error"], { timeout: cs.timeout, raiseOnError: false });
2573
+ } catch (exc) {
2574
+ if (!(exc instanceof ConnectorTimeoutError)) throw exc;
2575
+ settled = { status: "connecting" };
2576
+ }
2577
+ if (!RUNNING.includes(settled.status)) {
2578
+ await conns.deactivateConnector(team.locationId, found.id, { timeout: cs.timeout });
2579
+ settled = unwrap(await conns.reactivateConnector(team.locationId, found.id, { timeout: cs.timeout })) ?? {};
2580
+ }
2581
+ this.setConn(team, settled);
2582
+ return null;
2583
+ } catch (exc) {
2584
+ if (exc instanceof ConnectorError || exc instanceof ConnectorTimeoutError) {
2585
+ this.setConn(team, exc.connector ?? {});
2586
+ return exc;
2587
+ }
2588
+ throw exc;
2589
+ }
2590
+ }
2591
+ }
2592
+ let conn;
2593
+ try {
2594
+ if (found !== null) {
2595
+ if (result) result.existing.push(label, label + ":updated");
2596
+ await this.rawConnectors.updateConnector(team.locationId, found.id, { name, config });
2597
+ if (found.status === "inactive") {
2229
2598
  conn = unwrap(await conns.reactivateConnector(team.locationId, found.id, { timeout: cs.timeout }));
2230
2599
  } else {
2231
2600
  conn = await conns.waitForStatus(team.locationId, found.id, [...RUNNING, "error"], { timeout: cs.timeout, raiseOnError: false });
@@ -2261,52 +2630,58 @@ var Accounts = class _Accounts {
2261
2630
  * and Insights Hub setup. The rules are created switched off.
2262
2631
  */
2263
2632
  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];
2633
+ checkCustomerRef(customer);
2634
+ checkTeamSpec(team);
2635
+ checkConnectorLocal(connector, true);
2636
+ const alerts = checkAlerts(options?.alerts);
2637
+ bool(options?.reactivate, "reactivate");
2638
+ return this.exclusive(async () => {
2639
+ await this.requireAdmin();
2640
+ await this.checkConnector(connector, true);
2641
+ const cust = await this.resolve(customer);
2642
+ if (cust.management !== null && team.name === cust.management.name) {
2643
+ throw new InvalidRequestError("That name is the Management location; name the team differently");
2644
+ }
2645
+ await this.verticalId(team.vertical);
2646
+ const settings = this.settingsFrom(alerts);
2647
+ const first = cust.teams.find((t) => t.name !== team.name);
2648
+ if (first !== void 0) await this.live([first]);
2649
+ const made = newTeam("", team.name);
2650
+ let failure = null;
2651
+ const run = this.run(made);
2652
+ try {
2653
+ run.step = "copy_alerts";
2654
+ if (first !== void 0) {
2655
+ for (const key of RULE_FIELDS) {
2656
+ const d = RULES[key];
2657
+ const rid = first.rules[key];
2658
+ if (rid === null) continue;
2659
+ const [phr, lvl] = ruleSettings(unwrap(await this.c.firstAlert.getAlertRule(first.locationId, rid)) ?? {});
2660
+ const [givenPhr, givenLvl] = settings[key];
2661
+ settings[key] = [givenPhr !== null ? givenPhr : d.hasPhrases ? phr : null, givenLvl !== null ? givenLvl : lvl];
2662
+ }
2288
2663
  }
2664
+ run.step = "location";
2665
+ const loc = await this.ensureLocation(cust.companyId, team.name, team, "team", !!options?.reactivate, cust);
2666
+ made.locationId = loc.locationId;
2667
+ run.step = "connector";
2668
+ failure = await this.ensureConnector(made, connector, cust);
2669
+ run.step = "groups";
2670
+ await this.ensureGroups(made, cust);
2671
+ run.step = "rules";
2672
+ await this.ensureRules(made, settings, cust);
2673
+ run.step = "insights_hub";
2674
+ await this.ensureInsightsHub(made);
2675
+ const existing = cust.teams.findIndex((t) => t.locationId === made.locationId);
2676
+ if (existing < 0) cust.teams.push(made);
2677
+ else cust.teams[existing] = made;
2678
+ cust.pending = this.pendingOf(cust);
2679
+ } catch (exc) {
2680
+ this.stop(run, exc);
2289
2681
  }
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;
2682
+ raiseConnectorFailure(failure ? [failure] : [], made);
2683
+ return made;
2684
+ });
2310
2685
  }
2311
2686
  /**
2312
2687
  * Create or update the three rules' phrases and sentiment levels on one team or on every team.
@@ -2315,24 +2690,33 @@ var Accounts = class _Accounts {
2315
2690
  * ids of the rules created or changed.
2316
2691
  */
2317
2692
  async setAlerts(customer, alerts, options = {}) {
2318
- await this.requireAdmin();
2319
- checkAlerts(alerts);
2693
+ checkCustomerRef(customer);
2694
+ checkTeamRef(options?.team, false);
2320
2695
  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));
2330
- }
2331
- cust.pending = this.pendingOf(cust);
2332
- } catch (exc) {
2333
- this.stop(run, exc);
2696
+ const checked = checkAlerts(alerts);
2697
+ if (RULE_FIELDS.every((k) => checked[k] === null || checked[k] === void 0)) {
2698
+ throw new InvalidRequestError("alerts sets nothing: give at least one AlertSetting");
2334
2699
  }
2335
- return changed;
2700
+ if (isCustomerObject(customer) && options?.team !== void 0 && options.team !== null) this.teamOf(customer, options.team);
2701
+ return this.exclusive(async () => {
2702
+ await this.requireAdmin();
2703
+ const cust = await this.resolve(customer);
2704
+ const teams = this.teamsOf(cust, options?.team);
2705
+ await this.live(teams, ALERT_GROUPS);
2706
+ const settings = this.settingsFrom(checked);
2707
+ const changed = [];
2708
+ const run = this.run(changed);
2709
+ try {
2710
+ for (const t of teams) {
2711
+ run.step = `rules:${t.name}`;
2712
+ changed.push(...await this.ensureRules(t, settings, null));
2713
+ }
2714
+ cust.pending = this.pendingOf(cust);
2715
+ } catch (exc) {
2716
+ this.stop(run, exc);
2717
+ }
2718
+ return changed;
2719
+ });
2336
2720
  }
2337
2721
  /**
2338
2722
  * Attach a phone system to a customer created without one: the named team, or the first team and
@@ -2340,84 +2724,97 @@ var Accounts = class _Accounts {
2340
2724
  * Returns the teams it attached.
2341
2725
  */
2342
2726
  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;
2727
+ checkCustomerRef(customer);
2728
+ checkTeamRef(options?.team, false);
2729
+ checkConnectorLocal(connector, true);
2730
+ if (isCustomerObject(customer) && options?.team !== void 0 && options.team !== null) this.teamOf(customer, options.team);
2731
+ return this.exclusive(async () => {
2732
+ await this.requireAdmin();
2733
+ await this.checkConnector(connector, true);
2734
+ const cust = await this.resolve(customer);
2735
+ let targets;
2736
+ if (options?.team !== void 0 && options.team !== null) {
2737
+ targets = [this.teamOf(cust, options.team)];
2738
+ } else {
2739
+ if (!cust.teams.length) throw new InvalidRequestError("This customer has no team");
2740
+ targets = [cust.teams[0], ...cust.management ? [cust.management] : []];
2365
2741
  }
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);
2742
+ const todo = [];
2743
+ for (const t of targets) {
2744
+ const name = connector.name || `${t.name} phone system`;
2745
+ const found = await this.findConnector(t.locationId, connector, name);
2746
+ const active = (await all(this.c.connectors.iterLocationConnectors(t.locationId))).filter((x) => RUNNING.includes(x.status));
2747
+ const same = found !== null && RUNNING.includes(found.status) && Object.entries(plainConfig(connector.config)).every(
2748
+ ([k, v]) => !(k in (found.config ?? {})) || isSecretName(k) || deepEqual(found.config[k], v)
2749
+ );
2750
+ if (active.length && !same) throw new InvalidRequestError(`${t.name} already has an active connector`);
2751
+ if (same) {
2752
+ this.setConn(t, found);
2753
+ continue;
2754
+ }
2755
+ todo.push(t);
2375
2756
  }
2376
- } catch (exc) {
2377
- this.stop(run, exc);
2378
- }
2379
- raiseConnectorFailure(failures, targets);
2380
- return targets;
2757
+ const run = this.run(targets);
2758
+ const failures = [];
2759
+ try {
2760
+ for (const t of todo) {
2761
+ run.step = `connector:${t.name}`;
2762
+ const failure = await this.ensureConnector(t, connector, cust);
2763
+ if (failure) failures.push(failure);
2764
+ }
2765
+ } catch (exc) {
2766
+ this.stop(run, exc);
2767
+ }
2768
+ raiseConnectorFailure(failures, targets);
2769
+ return targets;
2770
+ });
2381
2771
  }
2382
2772
  /**
2383
2773
  * Switch the rules on for every team. A team does not need a manager: its alerts then show in the app
2384
2774
  * only, and the team is listed under `noManager` with the alert groups that have none.
2385
2775
  */
2386
2776
  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));
2777
+ checkCustomerRef(customer);
2778
+ checkTeamRef(options?.team, false);
2779
+ if (isCustomerObject(customer) && options?.team !== void 0 && options.team !== null) this.teamOf(customer, options.team);
2780
+ return this.exclusive(async () => {
2781
+ await this.requireAdmin();
2782
+ const cust = await this.resolve(customer);
2783
+ const out = { switchedOn: [], noManager: [] };
2784
+ const people = await this.index(cust);
2785
+ const managers = new Set([...people.values()].filter((p) => p.license === "base_manager").map((p) => p.id));
2786
+ const run = this.run(out);
2787
+ try {
2788
+ const wanted = this.teamsOf(cust, options?.team);
2789
+ await this.live(wanted);
2790
+ for (const t of wanted) {
2791
+ run.step = `activate:${t.name}`;
2792
+ const missing = [];
2793
+ for (const f of ALERT_GROUPS) {
2794
+ const gid = t.groups[f];
2795
+ let members = /* @__PURE__ */ new Set();
2796
+ if (gid) {
2797
+ const grp = unwrap(await this.c.groups.getUserGroup(t.locationId, gid)) ?? {};
2798
+ members = new Set((grp.members ?? []).map((m) => m.id));
2799
+ }
2800
+ if (![...members].some((m) => managers.has(m))) missing.push(TEAM_GROUPS[f]);
2403
2801
  }
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);
2802
+ if (missing.length) out.noManager.push({ locationId: t.locationId, team: t.name, missing });
2803
+ for (const key of RULE_FIELDS) {
2804
+ const rid = t.rules[key];
2805
+ if (!rid) continue;
2806
+ const rule = unwrap(await this.c.firstAlert.getAlertRule(t.locationId, rid)) ?? {};
2807
+ if (!rule.enabled) {
2808
+ await this.c.firstAlert.updateAlertRule(t.locationId, rid, { enabled: true });
2809
+ out.switchedOn.push(rid);
2810
+ }
2414
2811
  }
2415
2812
  }
2813
+ } catch (exc) {
2814
+ this.stop(run, exc);
2416
2815
  }
2417
- } catch (exc) {
2418
- this.stop(run, exc);
2419
- }
2420
- return out;
2816
+ return out;
2817
+ });
2421
2818
  }
2422
2819
  // ------------------------------------------------------------------ people: reading
2423
2820
  /** Everyone at the customer's locations, with products and groups per location, lines and license. */
@@ -2448,8 +2845,14 @@ var Accounts = class _Accounts {
2448
2845
  if (p.active) p.mappings = unwrapMappings(await c.users.getUserNumberMappings(cust.companyId, p.id));
2449
2846
  this.classify(cust, p);
2450
2847
  }
2848
+ this.lastIndex = people;
2451
2849
  return people;
2452
2850
  }
2851
+ /** All of the person's teams as the latest read saw them. */
2852
+ currentTeams(uid, fallback) {
2853
+ const p = this.lastIndex?.get(uid);
2854
+ return p ? [...p.teams] : fallback;
2855
+ }
2453
2856
  classify(cust, p) {
2454
2857
  const teamIds = cust.teams.map((t) => t.locationId);
2455
2858
  const mgmt = cust.management ? cust.management.locationId : null;
@@ -2571,11 +2974,16 @@ var Accounts = class _Accounts {
2571
2974
  * so it can be corrected.
2572
2975
  */
2573
2976
  async listMembers(customer, options = {}) {
2574
- await this.requireAdmin();
2575
- const license = options.license ?? null;
2977
+ checkCustomerRef(customer);
2978
+ checkTeamRef(options?.team, false);
2979
+ const license = options?.license ?? null;
2576
2980
  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;
2981
+ if (isCustomerObject(customer) && options?.team !== void 0 && options.team !== null) this.teamOf(customer, options.team);
2982
+ await this.requireAdmin();
2983
+ return this.membersOf(await this.resolve(customer), license, options?.team);
2984
+ }
2985
+ async membersOf(cust, license, team) {
2986
+ const lid = team !== void 0 && team !== null ? this.teamOf(cust, team).locationId : null;
2579
2987
  const out = [];
2580
2988
  for (const p of (await this.index(cust)).values()) {
2581
2989
  if (license !== null && p.license !== license) continue;
@@ -2586,8 +2994,10 @@ var Accounts = class _Accounts {
2586
2994
  }
2587
2995
  /** People by license and the number of teams (Management not counted). */
2588
2996
  async licenseReport(customer) {
2997
+ checkCustomerRef(customer);
2998
+ await this.requireAdmin();
2589
2999
  const cust = await this.resolve(customer);
2590
- const members = await this.listMembers(cust);
3000
+ const members = await this.membersOf(cust, null);
2591
3001
  const by = { baseUser: [], baseManager: [], integration: [], other: [] };
2592
3002
  for (const m of members) {
2593
3003
  if (m.license === "base_user") by.baseUser.push(m);
@@ -2784,35 +3194,43 @@ var Accounts = class _Accounts {
2784
3194
  * AccountError (cause ExtensionMappingError) is thrown and no invitation is sent.
2785
3195
  */
2786
3196
  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;
3197
+ checkCustomerRef(customer);
3198
+ checkPerson(person);
3199
+ checkTeamRef(options?.team);
3200
+ const ln = line(options?.line);
3201
+ bool(options?.invite, "invite");
3202
+ if (isCustomerObject(customer)) this.teamOf(customer, options.team);
3203
+ return this.exclusive(async () => {
3204
+ await this.requireAdmin();
3205
+ const cust = await this.resolve(customer);
3206
+ const t = this.teamOf(cust, options.team);
3207
+ this.needConnector(t);
3208
+ await this.checkExisting(cust, person.email, "base_user");
3209
+ const result = newMember("", person.email, "base_user", [t.locationId], [ln]);
3210
+ const run = this.run(result);
3211
+ try {
3212
+ run.step = "monitor_all";
3213
+ await this.monitorAllOff(t.locationId);
3214
+ run.step = "user";
3215
+ const [uid, created, detail] = await this.ensureUser(cust, person, [t.locationId]);
3216
+ result.userId = uid;
3217
+ result.created = created;
3218
+ run.step = "products";
3219
+ await this.productsOn(t.locationId, uid, [AFTER_CALL]);
3220
+ run.step = "alert_email";
3221
+ await this.emailOff(t.locationId, uid, created, detail.status);
3222
+ run.step = "line";
3223
+ await this.map(cust, uid, t.connectorId, [ln]);
3224
+ run.step = "team_lines";
3225
+ await this.attachLine(cust, t, ln, await this.index(cust), [uid]);
3226
+ run.step = "invitation";
3227
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
3228
+ result.teams = this.currentTeams(uid, result.teams);
3229
+ } catch (exc) {
3230
+ this.stop(run, exc);
3231
+ }
3232
+ return result;
3233
+ });
2816
3234
  }
2817
3235
  /**
2818
3236
  * Add a Base Manager on each team and on Management: all three products; their own line at
@@ -2821,31 +3239,42 @@ var Accounts = class _Accounts {
2821
3239
  * with `companyReports: true`); alert email off. The invitation is sent last.
2822
3240
  */
2823
3241
  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");
3242
+ checkCustomerRef(customer);
3243
+ checkPerson(person);
3244
+ const teams = list2(options?.teams, "teams");
3245
+ if (!teams.length) throw new InvalidRequestError("teams: a list of one or more teams");
3246
+ for (const x of teams) checkTeamRef(x);
2830
3247
  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;
3248
+ bool(options.invite, "invite");
3249
+ bool(options.companyReports, "companyReports");
3250
+ if (isCustomerObject(customer)) for (const x of teams) this.teamOf(customer, x);
3251
+ return this.exclusive(async () => {
3252
+ await this.requireAdmin();
3253
+ const cust = await this.resolve(customer);
3254
+ const ts = dedupeTeams(teams.map((x) => this.teamOf(cust, x)));
3255
+ await this.live(ts, GROUP_FIELDS);
3256
+ if (options.companyReports && cust.management) await this.live([cust.management], ["weeklyReports"]);
3257
+ if (cust.management === null) throw new InvalidRequestError("This customer has no Management location: run createCustomer again");
3258
+ if (own) this.needConnector(cust.management);
3259
+ await this.checkExisting(cust, person.email, "base_manager");
3260
+ const result = newMember("", person.email, "base_manager", ts.map((t) => t.locationId));
3261
+ const run = this.run(result);
3262
+ try {
3263
+ run.step = "monitor_all";
3264
+ for (const t of ts) await this.monitorAllOff(t.locationId);
3265
+ run.step = "user";
3266
+ const [uid, created, detail] = await this.ensureUser(cust, person, [...ts.map((t) => t.locationId), cust.management.locationId]);
3267
+ result.userId = uid;
3268
+ result.created = created;
3269
+ result.lines = await this.managerSetup(cust, uid, ts, own, !!options.companyReports, created, detail.status, run);
3270
+ result.teams = this.currentTeams(uid, result.teams);
3271
+ run.step = "invitation";
3272
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
3273
+ } catch (exc) {
3274
+ this.stop(run, exc);
3275
+ }
3276
+ return result;
3277
+ });
2849
3278
  }
2850
3279
  /**
2851
3280
  * Add the customer's integration (data-reading) user across every team: password sign-in, tagged
@@ -2854,46 +3283,52 @@ var Accounts = class _Accounts {
2854
3283
  * (`CustomerSpec.mfaOff`) for it to sign in.
2855
3284
  */
2856
3285
  async addIntegrationUser(customer, person, options = {}) {
2857
- await this.requireAdmin();
3286
+ checkCustomerRef(customer);
3287
+ checkPerson(person);
2858
3288
  if ((person.authMethod ?? "password") !== "password") {
2859
3289
  throw new InvalidRequestError('An integration user signs in with a password: set authMethod: "password"');
2860
3290
  }
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]));
3291
+ bool(options?.invite, "invite");
3292
+ return this.exclusive(async () => {
3293
+ await this.requireAdmin();
3294
+ const cust = await this.resolve(customer);
3295
+ if (!cust.teams.length) throw new InvalidRequestError("This customer has no team");
3296
+ await this.live(cust.teams, [...ALERT_GROUPS, "insightsHubAccess"]);
3297
+ await this.checkExisting(cust, person.email, "integration");
3298
+ const result = newMember("", person.email, "integration", cust.teams.map((t) => t.locationId));
3299
+ const run = this.run(result);
3300
+ try {
3301
+ run.step = "user";
3302
+ const [uid, created] = await this.ensureUser(cust, person, cust.teams.map((t) => t.locationId));
3303
+ result.userId = uid;
3304
+ result.created = created;
3305
+ run.step = "tag";
3306
+ const detail = unwrap(await this.c.users.getCompanyUser(cust.companyId, uid)) ?? {};
3307
+ if (!isIntegration(detail)) await this.c.users.updateCompanyUser(cust.companyId, uid, { department: INTEGRATION_DEPARTMENT });
3308
+ run.step = "products";
3309
+ for (const t of cust.teams) await this.productsOn(t.locationId, uid, PRODUCT_KEYS);
3310
+ run.step = "groups";
3311
+ for (const t of cust.teams) {
3312
+ await this.joinGroups(t.locationId, uid, [...ALERT_GROUPS, "insightsHubAccess"].map((f) => t.groups[f]));
3313
+ }
3314
+ run.step = "alert_email";
3315
+ for (const t of cust.teams) await this.emailOff(t.locationId, uid, created, detail.status);
3316
+ run.step = "lines";
3317
+ const people = await this.index(cust);
3318
+ const current = people.get(uid)?.mappings ?? [];
3319
+ let mappings = current.map((m) => ({ ...m }));
3320
+ for (const t of cust.teams) {
3321
+ if (t.connectorId) mappings = mergeMappings(mappings, t.connectorId, this.teamLines(t, people, [uid]));
3322
+ }
3323
+ if (!sameMappings(mappings, current)) await this.setMappings(cust, uid, mappings);
3324
+ result.lines = numbersOf(mappings);
3325
+ run.step = "invitation";
3326
+ result.invited = await this.invite(cust, uid, options.invite ?? true);
3327
+ } catch (exc) {
3328
+ this.stop(run, exc);
2888
3329
  }
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;
3330
+ return result;
3331
+ });
2897
3332
  }
2898
3333
  /**
2899
3334
  * Base User to Base Manager (`to: "base_manager"`): their own line moves to Management and they get
@@ -2908,28 +3343,41 @@ var Accounts = class _Accounts {
2908
3343
  * person had before.
2909
3344
  */
2910
3345
  async changeLicense(customer, userId, to, options = {}) {
2911
- await this.requireAdmin();
3346
+ checkCustomerRef(customer);
3347
+ checkUserId(userId);
2912
3348
  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);
3349
+ let teamList = null;
3350
+ if (options?.teams !== void 0 && options.teams !== null) {
3351
+ teamList = list2(options.teams, "teams");
3352
+ if (!teamList.length) throw new InvalidRequestError("teams: a list of one or more teams");
3353
+ for (const x of teamList) checkTeamRef(x);
3354
+ if (isCustomerObject(customer)) for (const x of teamList) this.teamOf(customer, x);
2928
3355
  }
2929
- return result;
3356
+ if (options?.line !== void 0 && options.line !== null) line(options.line);
3357
+ return this.exclusive(async () => {
3358
+ await this.requireAdmin();
3359
+ const cust = await this.resolve(customer);
3360
+ if (cust.management === null) throw new InvalidRequestError("This customer has no Management location: run createCustomer again");
3361
+ const [p, people] = await this.person(cust, userId);
3362
+ if (p.license !== "base_user" && p.license !== "base_manager" && p.license !== "other") {
3363
+ throw new InvalidRequestError(`User ${userId} is "${p.license}"; only Base Users and Base Managers change license`);
3364
+ }
3365
+ const ts = teamList?.length ? dedupeTeams(teamList.map((x) => this.teamOf(cust, x))) : cust.teams.filter((t) => p.teams.includes(t.locationId));
3366
+ if (!ts.length) throw new InvalidRequestError("teams: the person is on no team; pass teams");
3367
+ const result = this.member(p);
3368
+ const run = this.run(result);
3369
+ try {
3370
+ if (to === "base_manager") await this.toManager(cust, p, people, ts, options.line ?? null, run, result);
3371
+ else await this.toUser(cust, p, people, ts[0], options.line ?? null, run, result);
3372
+ } catch (exc) {
3373
+ this.stop(run, exc);
3374
+ }
3375
+ return result;
3376
+ });
2930
3377
  }
2931
3378
  async toManager(cust, p, people, ts, lineArg, run, result) {
2932
3379
  const mgmt = cust.management;
3380
+ await this.live(ts, GROUP_FIELDS);
2933
3381
  const stray = [];
2934
3382
  for (const t of cust.teams) {
2935
3383
  if (t.connectorId) {
@@ -3006,55 +3454,66 @@ var Accounts = class _Accounts {
3006
3454
  * run again, also after an AccountError: the move continues.
3007
3455
  */
3008
3456
  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);
3457
+ checkCustomerRef(customer);
3458
+ checkUserId(userId);
3459
+ checkTeamRef(options?.fromTeam);
3460
+ checkTeamRef(options?.toTeam);
3461
+ const idOf = (t) => isTeamObject(t) ? t.locationId : t;
3462
+ if (idOf(options.fromTeam) === idOf(options.toTeam)) throw new InvalidRequestError("fromTeam and toTeam are the same team");
3463
+ if (isCustomerObject(customer) && this.teamOf(customer, options.fromTeam).locationId === this.teamOf(customer, options.toTeam).locationId) {
3464
+ throw new InvalidRequestError("fromTeam and toTeam are the same team");
3054
3465
  }
3055
- return result;
3466
+ return this.exclusive(async () => {
3467
+ await this.requireAdmin();
3468
+ const cust = await this.resolve(customer);
3469
+ const src = this.teamOf(cust, options.fromTeam);
3470
+ const dst = this.teamOf(cust, options.toTeam);
3471
+ if (src.locationId === dst.locationId) throw new InvalidRequestError("fromTeam and toTeam are the same team");
3472
+ const [p, people] = await this.person(cust, userId);
3473
+ const note = `Call history stays with ${src.name}: calls captured before the move remain there.`;
3474
+ const result = this.member(p);
3475
+ result.notes.push(note);
3476
+ if (!p.teams.includes(src.locationId) && p.teams.includes(dst.locationId)) return result;
3477
+ if (!p.teams.includes(src.locationId)) throw new InvalidRequestError(`User ${userId} is not on ${src.name}`);
3478
+ if (p.license === "integration") throw new InvalidRequestError(`User ${userId} is an integration user; it is on every team already`);
3479
+ const run = this.run(result);
3480
+ try {
3481
+ if (p.license === "base_manager") {
3482
+ await this.moveManager(cust, p, people, src, dst, run, result);
3483
+ } else {
3484
+ this.needConnector(dst);
3485
+ const nums = uniq([...src.connectorId ? p.numbers(src.connectorId) : [], ...p.numbers(dst.connectorId)]);
3486
+ if (nums.length !== 1) throw new InvalidRequestError("A Base User holds exactly one line; fix it with changeLine first");
3487
+ const ln = nums[0];
3488
+ run.step = "monitor_all";
3489
+ for (const t of [src, dst]) await this.monitorAllOff(t.locationId);
3490
+ run.step = "release_line";
3491
+ await this.releaseLine(cust, src, ln, people, p.id);
3492
+ run.step = "locations";
3493
+ await this.addLocations(cust, p.id, [dst.locationId]);
3494
+ run.step = "products";
3495
+ await this.productsOn(dst.locationId, p.id, [AFTER_CALL]);
3496
+ run.step = "alert_email";
3497
+ const status = (unwrap(await this.c.users.getCompanyUser(cust.companyId, p.id)) ?? {}).status;
3498
+ await this.emailOff(dst.locationId, p.id, false, status);
3499
+ run.step = "line";
3500
+ const target = mergeMappings(p.mappings.filter((m) => m.connector_id !== src.connectorId), dst.connectorId, [ln]);
3501
+ if (!sameMappings(target, p.mappings)) await this.setMappings(cust, p.id, target);
3502
+ run.step = "team_lines";
3503
+ await this.attachLine(cust, dst, ln, await this.index(cust), [p.id]);
3504
+ run.step = "leave_team";
3505
+ await this.removeLocations(cust, p.id, [src.locationId]);
3506
+ result.teams = [dst.locationId];
3507
+ result.lines = [ln];
3508
+ }
3509
+ } catch (exc) {
3510
+ this.stop(run, exc);
3511
+ }
3512
+ return result;
3513
+ });
3056
3514
  }
3057
3515
  async moveManager(cust, p, people, src, dst, run, result) {
3516
+ await this.live([dst], GROUP_FIELDS);
3058
3517
  const notes = this.emptiedGroups(cust, people, p.id, [src.locationId]);
3059
3518
  run.step = "locations";
3060
3519
  await this.addLocations(cust, p.id, [dst.locationId]);
@@ -3087,68 +3546,73 @@ var Accounts = class _Accounts {
3087
3546
  * the manager's own line.
3088
3547
  */
3089
3548
  async changeLine(customer, userId, oldLine, newLine) {
3090
- await this.requireAdmin();
3549
+ checkCustomerRef(customer);
3550
+ checkUserId(userId);
3091
3551
  const old = line(oldLine, "old");
3092
3552
  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`);
3553
+ if (old === nw) throw new InvalidRequestError("old and new are the same line");
3554
+ return this.exclusive(async () => {
3555
+ await this.requireAdmin();
3556
+ const cust = await this.resolve(customer);
3557
+ const [p, people] = await this.person(cust, userId);
3558
+ const result = this.member(p);
3559
+ const mgmt = cust.management;
3560
+ if (p.license === "integration") throw new InvalidRequestError("An integration user holds every line; it has no line of its own");
3561
+ if (p.license === "base_manager") {
3562
+ const mine = mgmt && mgmt.connectorId ? p.numbers(mgmt.connectorId) : [];
3563
+ if (!mine.includes(old) && !mine.includes(nw)) {
3564
+ throw new InvalidRequestError(`${old} is not this manager's own line; a team line changes with the Base User who holds it`);
3565
+ }
3566
+ const run2 = this.run(result);
3567
+ try {
3568
+ run2.step = "line";
3569
+ if (mine.includes(old)) {
3570
+ await this.map(cust, p.id, mgmt.connectorId, uniq(mine.map((n) => n === old ? nw : n)), p.mappings);
3571
+ result.lines = result.lines.map((n) => n === old ? nw : n);
3572
+ }
3573
+ } catch (exc) {
3574
+ this.stop(run2, exc);
3575
+ }
3576
+ return result;
3102
3577
  }
3103
- const run2 = this.run(result);
3578
+ const team = cust.teams.find(
3579
+ (t) => t.connectorId && p.teams.includes(t.locationId) && (p.numbers(t.connectorId).includes(old) || p.numbers(t.connectorId).includes(nw))
3580
+ );
3581
+ if (team === void 0) throw new InvalidRequestError(`${old} is not one of this person's lines`);
3582
+ const cid = team.connectorId;
3583
+ const shared = [...this.owners(team, people, [p.id]).values()].includes(old);
3584
+ const run = this.run(result);
3585
+ const swap = (have) => {
3586
+ const out = shared ? [...have] : have.filter((n) => n !== old);
3587
+ return out.includes(nw) ? out : [...out, nw];
3588
+ };
3104
3589
  try {
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);
3590
+ run.step = "monitor_all";
3591
+ await this.monitorAllOff(team.locationId);
3592
+ run.step = "line";
3593
+ const nums = p.numbers(cid);
3594
+ if (nums.includes(old)) {
3595
+ await this.map(cust, p.id, cid, uniq(nums.map((n) => n === old ? nw : n)), p.mappings);
3596
+ result.lines = uniq(result.lines.map((n) => n === old ? nw : n));
3597
+ }
3598
+ run.step = "team_lines";
3599
+ for (const h of this.holders(team, people, [p.id])) {
3600
+ const have = h.numbers(cid);
3601
+ if (!deepEqual(swap(have), have)) await this.map(cust, h.id, cid, swap(have), h.mappings);
3602
+ }
3603
+ const targets = [
3604
+ [() => this.faNumbers(team), (n) => this.c.firstAlert.setMonitoredNumbers(team.locationId, cid, n)],
3605
+ [() => this.ihNumbers(team), (n) => this.c.insightsHub.setNumbers(team.locationId, cid, n)]
3606
+ ];
3607
+ for (const [getter, setter] of targets) {
3608
+ const have = await getter();
3609
+ if (!deepEqual(swap(have), have)) await setter(swap(have));
3109
3610
  }
3110
3611
  } catch (exc) {
3111
- this.stop(run2, exc);
3612
+ this.stop(run, exc);
3112
3613
  }
3113
3614
  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));
3134
- }
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);
3139
- }
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;
3615
+ });
3152
3616
  }
3153
3617
  /**
3154
3618
  * Take the person out of every group, release a Base User's line (unless `keepLines`, and only when
@@ -3157,49 +3621,54 @@ var Accounts = class _Accounts {
3157
3621
  * alert groups are left with no Base Manager (its alerts are not changed).
3158
3622
  */
3159
3623
  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);
3624
+ checkCustomerRef(customer);
3625
+ checkUserId(userId);
3626
+ bool(options?.keepLines, "keepLines");
3627
+ return this.exclusive(async () => {
3628
+ await this.requireAdmin();
3629
+ const cust = await this.resolve(customer);
3630
+ const [p, people] = await this.person(cust, userId, true);
3631
+ if (!p.active) {
3632
+ p.mappings = unwrapMappings(await this.c.users.getUserNumberMappings(cust.companyId, p.id));
3633
+ this.classify(cust, p);
3634
+ }
3635
+ const out = {
3636
+ userId,
3637
+ license: p.license,
3638
+ releasedLines: [],
3639
+ deactivated: false,
3640
+ notes: p.active ? this.emptiedGroups(cust, people, p.id, p.teams) : []
3641
+ };
3642
+ const run = this.run(out);
3643
+ try {
3644
+ run.step = "groups";
3645
+ for (const t of this.locationsOf(cust)) if (p.locs.has(t.locationId)) await this.leaveGroups(t.locationId, p.id);
3646
+ run.step = "release_lines";
3647
+ if (p.license === "base_user" && !options.keepLines) {
3648
+ for (const t of cust.teams) {
3649
+ if (p.teams.includes(t.locationId) && t.connectorId) {
3650
+ for (const n of p.numbers(t.connectorId)) {
3651
+ if (await this.releaseLine(cust, t, n, people, p.id)) out.releasedLines.push(n);
3652
+ }
3184
3653
  }
3185
3654
  }
3186
3655
  }
3187
- }
3188
- run.step = "lines";
3189
- if (p.mappings.length) await this.setMappings(cust, p.id, []);
3190
- run.step = "deactivate";
3191
- if (p.active) {
3192
- try {
3193
- await this.c.users.deactivateCompanyUser(cust.companyId, p.id);
3194
- out.deactivated = true;
3195
- } catch (exc) {
3196
- if (!(exc instanceof ConflictError)) throw exc;
3656
+ run.step = "lines";
3657
+ if (p.mappings.length) await this.setMappings(cust, p.id, []);
3658
+ run.step = "deactivate";
3659
+ if (p.active) {
3660
+ try {
3661
+ await this.c.users.deactivateCompanyUser(cust.companyId, p.id);
3662
+ out.deactivated = true;
3663
+ } catch (exc) {
3664
+ if (!(exc instanceof ConflictError)) throw exc;
3665
+ }
3197
3666
  }
3667
+ } catch (exc) {
3668
+ this.stop(run, exc);
3198
3669
  }
3199
- } catch (exc) {
3200
- this.stop(run, exc);
3201
- }
3202
- return out;
3670
+ return out;
3671
+ });
3203
3672
  }
3204
3673
  /**
3205
3674
  * Email invitations to people who have not signed in. Without `userIds`: everyone who was never
@@ -3207,28 +3676,36 @@ var Accounts = class _Accounts {
3207
3676
  * signed in. Returns the ids invited.
3208
3677
  */
3209
3678
  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;
3679
+ checkCustomerRef(customer);
3680
+ let ids = null;
3681
+ if (options?.userIds !== void 0 && options.userIds !== null) {
3682
+ ids = list2(options.userIds, "userIds");
3683
+ for (const u of ids) checkUserId(u);
3684
+ }
3685
+ return this.exclusive(async () => {
3686
+ await this.requireAdmin();
3687
+ const cust = await this.resolve(customer);
3688
+ const now = /* @__PURE__ */ new Date();
3689
+ const wanted = ids ? new Set(ids) : null;
3690
+ const sent = [];
3691
+ const run = this.run(sent);
3692
+ try {
3693
+ for (const p of (await this.index(cust)).values()) {
3694
+ if (p.status !== "invited") continue;
3695
+ if (wanted !== null) {
3696
+ if (!wanted.has(p.id)) continue;
3697
+ } else if (p.invitedAt && !expired(p.inviteExpiresAt, now)) {
3698
+ continue;
3699
+ }
3700
+ run.step = `invite:${p.id}`;
3701
+ await this.c.users.resendInvitation(cust.companyId, p.id);
3702
+ sent.push(p.id);
3223
3703
  }
3224
- run.step = `invite:${p.id}`;
3225
- await this.c.users.resendInvitation(cust.companyId, p.id);
3226
- sent.push(p.id);
3704
+ } catch (exc) {
3705
+ this.stop(run, exc);
3227
3706
  }
3228
- } catch (exc) {
3229
- this.stop(run, exc);
3230
- }
3231
- return sent;
3707
+ return sent;
3708
+ });
3232
3709
  }
3233
3710
  // ------------------------------------------------------------------ lines
3234
3711
  /**
@@ -3241,49 +3718,53 @@ var Accounts = class _Accounts {
3241
3718
  * read back as "other" (listed under `other`): their line is never released.
3242
3719
  */
3243
3720
  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 };
3721
+ checkCustomerRef(customer);
3722
+ bool(options?.dryRun, "dryRun");
3723
+ return this.exclusive(async () => {
3724
+ await this.requireAdmin();
3725
+ const cust = await this.resolve(customer);
3726
+ const people = await this.index(cust);
3727
+ const diff = { teams: {}, applied: false };
3728
+ const plans = [];
3729
+ for (const t of cust.teams) {
3730
+ if (!t.connectorId) continue;
3731
+ const owners = this.owners(t, people);
3732
+ const lines = uniq(owners.values());
3733
+ const fa = await this.faNumbers(t);
3734
+ const ih = await this.ihNumbers(t);
3735
+ const d = {
3736
+ team: t.name,
3737
+ lines,
3738
+ other: [...owners.keys()].filter((uid) => people.get(uid).license === "other"),
3739
+ firstAlert: { add: lines.filter((n) => !fa.includes(n)), remove: fa.filter((n) => !lines.includes(n)) },
3740
+ insightsHub: { add: lines.filter((n) => !ih.includes(n)), remove: ih.filter((n) => !lines.includes(n)) },
3741
+ holders: {}
3742
+ };
3743
+ for (const h of this.holders(t, people)) {
3744
+ const have = h.numbers(t.connectorId);
3745
+ const add = lines.filter((n) => !have.includes(n));
3746
+ const remove = have.filter((n) => !lines.includes(n));
3747
+ if (add.length || remove.length) d.holders[h.id] = { add, remove };
3748
+ }
3749
+ diff.teams[t.locationId] = d;
3750
+ plans.push([t, lines, d]);
3268
3751
  }
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);
3752
+ if (options.dryRun) return diff;
3753
+ const run = this.run(diff);
3754
+ try {
3755
+ for (const [t, lines, d] of plans) {
3756
+ run.step = `sync:${t.name}`;
3757
+ await this.monitorAllOff(t.locationId);
3758
+ for (const uid of Object.keys(d.holders)) await this.map(cust, uid, t.connectorId, lines, people.get(uid).mappings);
3759
+ if (d.firstAlert.add.length || d.firstAlert.remove.length) await this.c.firstAlert.setMonitoredNumbers(t.locationId, t.connectorId, lines);
3760
+ if (d.insightsHub.add.length || d.insightsHub.remove.length) await this.c.insightsHub.setNumbers(t.locationId, t.connectorId, lines);
3761
+ }
3762
+ } catch (exc) {
3763
+ this.stop(run, exc);
3281
3764
  }
3282
- } catch (exc) {
3283
- this.stop(run, exc);
3284
- }
3285
- diff.applied = true;
3286
- return diff;
3765
+ diff.applied = true;
3766
+ return diff;
3767
+ });
3287
3768
  }
3288
3769
  // ------------------------------------------------------------------ offboarding
3289
3770
  /**
@@ -3293,71 +3774,75 @@ var Accounts = class _Accounts {
3293
3774
  * deactivate the company. Ask your Tresic contact about retention of the customer's data.
3294
3775
  */
3295
3776
  async offboardCustomer(customer, options = {}) {
3296
- await this.requireAdmin();
3297
- const cust = await this.resolve(customer);
3298
- const c = this.c;
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);
3777
+ checkCustomerRef(customer);
3778
+ bool(options?.deactivateCompany, "deactivateCompany");
3779
+ return this.exclusive(async () => {
3780
+ await this.requireAdmin();
3781
+ const cust = await this.resolve(customer);
3782
+ const c = this.c;
3783
+ const out = {
3784
+ webhooksPaused: [],
3785
+ firstAlertWebhooksCleared: [],
3786
+ connectorsDeactivated: [],
3787
+ integrationUsersDeactivated: [],
3788
+ companyDeactivated: false
3789
+ };
3790
+ const run = this.run(out);
3791
+ try {
3792
+ const locs = this.locationsOf(cust);
3793
+ run.step = "webhooks";
3794
+ for (const t of locs) {
3795
+ const hook = await c.intelligence.getAfterCallWebhook(t.locationId) ?? {};
3796
+ if (hook.webhook_url && hook.enabled) {
3797
+ await c.intelligence.setAfterCallWebhook(t.locationId, hook.webhook_url, false);
3798
+ out.webhooksPaused.push(t.locationId);
3799
+ }
3800
+ if (await c.intelligence.getFirstAlertWebhook(t.locationId)) {
3801
+ await c.intelligence.setFirstAlertWebhook(t.locationId, null);
3802
+ out.firstAlertWebhooksCleared.push(t.locationId);
3803
+ }
3315
3804
  }
3316
- if (await c.intelligence.getFirstAlertWebhook(t.locationId)) {
3317
- await c.intelligence.setFirstAlertWebhook(t.locationId, null);
3318
- out.firstAlertWebhooksCleared.push(t.locationId);
3805
+ run.step = "connectors";
3806
+ for (const t of locs) {
3807
+ for (const row of await all(c.connectors.iterLocationConnectors(t.locationId))) {
3808
+ if (row.status === "inactive" || row.status === "deactivating") continue;
3809
+ try {
3810
+ await c.connectors.deactivateConnector(t.locationId, row.id);
3811
+ } catch (exc) {
3812
+ if (exc instanceof ConflictError) continue;
3813
+ throw exc;
3814
+ }
3815
+ out.connectorsDeactivated.push(row.id);
3816
+ }
3319
3817
  }
3320
- }
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;
3818
+ run.step = "integration_users";
3819
+ for (const p of (await this.index(cust)).values()) {
3820
+ if (p.license !== "integration") continue;
3325
3821
  try {
3326
- await c.connectors.deactivateConnector(t.locationId, row.id);
3822
+ await c.users.deactivateCompanyUser(cust.companyId, p.id);
3327
3823
  } catch (exc) {
3328
3824
  if (exc instanceof ConflictError) continue;
3329
3825
  throw exc;
3330
3826
  }
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;
3827
+ out.integrationUsersDeactivated.push(p.id);
3342
3828
  }
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;
3829
+ run.step = "company";
3830
+ if (options.deactivateCompany ?? true) {
3831
+ const company = unwrap(await c.companies.getCompany(cust.companyId)) ?? {};
3832
+ if (company.is_active ?? true) {
3833
+ try {
3834
+ await c.companies.deactivateCompany(cust.companyId);
3835
+ out.companyDeactivated = true;
3836
+ } catch (exc) {
3837
+ if (!(exc instanceof ConflictError)) throw exc;
3838
+ }
3354
3839
  }
3355
3840
  }
3841
+ } catch (exc) {
3842
+ this.stop(run, exc);
3356
3843
  }
3357
- } catch (exc) {
3358
- this.stop(run, exc);
3359
- }
3360
- return out;
3844
+ return out;
3845
+ });
3361
3846
  }
3362
3847
  };
3363
3848
  function unwrapMappings(body) {
@@ -3371,20 +3856,7 @@ function isUnknownEvent(e) {
3371
3856
  return e.kind === "unknown";
3372
3857
  }
3373
3858
  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;
3859
+ const o = loadBody(body, options.maxBytes ?? MAX_EVENT_BYTES);
3388
3860
  if (o.type !== "end_of_call_summary") {
3389
3861
  return {
3390
3862
  kind: "unknown",
@@ -3393,15 +3865,40 @@ function parseAfterCallEvent(body, options = {}) {
3393
3865
  raw: o
3394
3866
  };
3395
3867
  }
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.");
3868
+ const data = projectEvent(o, WEBHOOK_SHAPES.afterCallSummary);
3869
+ const need = (obj, key, ok, where) => {
3870
+ if (!(key in obj)) throw new WebhookPayloadError(`${where}.${key} is missing.`);
3871
+ if (!ok(obj[key])) throw new WebhookPayloadError(`${where}.${key} has the wrong type.`);
3872
+ return obj[key];
3873
+ };
3874
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
3875
+ const isStr = (v) => typeof v === "string";
3876
+ const call = need(data, "call", isObj, "event");
3877
+ need(data, "location", isObj, "event");
3878
+ need(call, "call_date", isStr, "call");
3879
+ need(data, "version", isStr, "event");
3880
+ need(data, "is_test", (v) => typeof v === "boolean", "event");
3881
+ need(data, "location_id", isStr, "event");
3882
+ need(data, "timestamp", isStr, "event");
3883
+ const plain = (v, where) => {
3884
+ if (typeof v !== "string" || !ID_RE.test(v)) throw new WebhookPayloadError(`${where} is not a plain id (letters, digits, "-" and "_", at most 128).`);
3885
+ };
3886
+ plain(call.id ?? need(call, "id", isStr, "call"), "call.id");
3887
+ plain(data.location_id, "location_id");
3888
+ need(call, "call_type", isStr, "call");
3889
+ need(call, "duration_seconds", (v) => typeof v === "number" && Number.isInteger(v), "call");
3890
+ return data;
3891
+ }
3892
+ function projectEvent(value, shape) {
3893
+ if (shape === null || shape === void 0 || shape === "*" || shape === "v") return value;
3894
+ if (value === null || typeof value !== "object") return value;
3895
+ if ("a" in shape) return Array.isArray(value) ? value.map((v) => projectEvent(v, shape.a)) : value;
3896
+ if (Array.isArray(value)) return value;
3897
+ const out = {};
3898
+ for (const [k, sub] of Object.entries(shape.o)) {
3899
+ if (Object.prototype.hasOwnProperty.call(value, k)) out[k] = projectEvent(value[k], sub);
3401
3900
  }
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 };
3901
+ return out;
3405
3902
  }
3406
3903
  var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
3407
3904
  var iso = (d) => d.toISOString().replace(/\.000Z$/, "Z");
@@ -3438,35 +3935,123 @@ var FirstAlertEvent = class {
3438
3935
  return this.toString();
3439
3936
  }
3440
3937
  };
3938
+ var ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
3441
3939
  function firstStr(...values) {
3442
3940
  for (const v of values) if (typeof v === "string" && v.trim()) return v.trim();
3443
3941
  return null;
3444
3942
  }
3445
- function lowerUuid(v) {
3446
- return v !== null && isUuid(v) ? v.toLowerCase() : null;
3943
+ function plainId(v) {
3944
+ return v !== null && ID_RE.test(v) ? v : null;
3447
3945
  }
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);
3946
+ var wellFormed = (t) => {
3947
+ const w = t;
3948
+ if (typeof w.isWellFormed === "function") return w.isWellFormed();
3949
+ for (let i = 0; i < t.length; i++) {
3950
+ const c = t.charCodeAt(i);
3951
+ if (c >= 55296 && c <= 56319) {
3952
+ const n = t.charCodeAt(i + 1);
3953
+ if (!(n >= 56320 && n <= 57343)) return false;
3954
+ i++;
3955
+ } else if (c >= 56320 && c <= 57343) return false;
3956
+ }
3957
+ return true;
3958
+ };
3959
+ var MAX_DEPTH = 64;
3960
+ function assertNoRepeatedKeys(text) {
3961
+ const stack = [];
3962
+ let i = 0;
3963
+ while (i < text.length) {
3964
+ const ch = text[i];
3965
+ if (ch === '"') {
3966
+ let j = i + 1;
3967
+ while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
3968
+ const top = stack[stack.length - 1];
3969
+ if (top && top !== "array" && top.expectKey) {
3970
+ const key = JSON.parse(text.slice(i, j + 1));
3971
+ if (top.keys.has(key)) throw new WebhookPayloadError("Body repeats a key inside one object.");
3972
+ top.keys.add(key);
3973
+ top.expectKey = false;
3974
+ }
3975
+ i = j + 1;
3976
+ continue;
3977
+ }
3978
+ if (ch === "{" || ch === "[") {
3979
+ if (stack.length >= MAX_DEPTH) throw new WebhookPayloadError(`Body is nested more than ${MAX_DEPTH} levels deep.`);
3980
+ stack.push(ch === "{" ? { keys: /* @__PURE__ */ new Set(), expectKey: true } : "array");
3981
+ } else if (ch === "}" || ch === "]") stack.pop();
3982
+ else if (ch === ",") {
3983
+ const top = stack[stack.length - 1];
3984
+ if (top && top !== "array") top.expectKey = true;
3985
+ }
3986
+ i++;
3987
+ }
3988
+ }
3989
+ function assertCleanValue(v, depth = 0) {
3990
+ if (depth > MAX_DEPTH) throw new WebhookPayloadError(`Body is nested more than ${MAX_DEPTH} levels deep.`);
3991
+ if (typeof v === "string") {
3992
+ if (!wellFormed(v)) throw new WebhookPayloadError("Body holds a lone surrogate (not valid Unicode).");
3993
+ } else if (typeof v === "number") {
3994
+ if (!Number.isFinite(v)) throw new WebhookPayloadError("Body holds a number that is not finite.");
3995
+ } else if (Array.isArray(v)) {
3996
+ for (const x of v) assertCleanValue(x, depth + 1);
3997
+ } else if (v !== null && typeof v === "object") {
3998
+ for (const [k, x] of Object.entries(v)) {
3999
+ if (!wellFormed(k)) throw new WebhookPayloadError("Body holds a lone surrogate (not valid Unicode).");
4000
+ assertCleanValue(x, depth + 1);
4001
+ }
4002
+ }
4003
+ }
4004
+ function parseIJson(input) {
4005
+ let text;
4006
+ if (typeof input === "string") {
4007
+ if (!wellFormed(input)) throw new WebhookPayloadError("Body holds a lone surrogate (not valid Unicode).");
4008
+ text = input;
4009
+ } else {
3455
4010
  try {
3456
- obj = JSON.parse(text);
4011
+ text = new TextDecoder("utf-8", { fatal: true }).decode(input);
3457
4012
  } catch {
3458
- throw new WebhookPayloadError("Body is not JSON.");
4013
+ throw new WebhookPayloadError("Body is not valid UTF-8.");
3459
4014
  }
3460
4015
  }
4016
+ if (text.charCodeAt(0) === 65279) text = text.slice(1);
4017
+ try {
4018
+ assertNoRepeatedKeys(text);
4019
+ } catch (e) {
4020
+ if (e instanceof WebhookPayloadError) throw e;
4021
+ throw new WebhookPayloadError("Body is not JSON.");
4022
+ }
4023
+ let value;
4024
+ try {
4025
+ value = JSON.parse(text);
4026
+ } catch {
4027
+ throw new WebhookPayloadError("Body is not JSON.");
4028
+ }
4029
+ assertCleanValue(value);
4030
+ return value;
4031
+ }
4032
+ function loadBody(body, maxBytes) {
4033
+ let obj = body;
4034
+ if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer) {
4035
+ const size = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.byteLength;
4036
+ if (maxBytes && size > maxBytes) throw new PayloadTooLargeError(`Body is larger than ${maxBytes} bytes.`);
4037
+ obj = parseIJson(body);
4038
+ }
3461
4039
  if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new WebhookPayloadError("Body is not a JSON object.");
3462
- const data = obj;
4040
+ assertCleanValue(obj);
4041
+ return obj;
4042
+ }
4043
+ function parseFirstAlertEvent(body, options = {}) {
4044
+ const data = loadBody(body, options.maxBytes ?? MAX_EVENT_BYTES);
3463
4045
  const sub = (k) => data[k] && typeof data[k] === "object" && !Array.isArray(data[k]) ? data[k] : {};
3464
4046
  const alert = sub("alert");
3465
4047
  const rule = sub("rule");
3466
4048
  const call = sub("call");
3467
4049
  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.");
4050
+ const rawId = "alert_id" in data ? data.alert_id : "id" in alert ? alert.id : data.id;
4051
+ const alertId = typeof rawId === "string" ? rawId : null;
4052
+ if (!alertId || !ID_RE.test(alertId)) {
4053
+ throw new WebhookPayloadError("Event has no valid alert id (letters, digits, '-' and '_', at most 128).");
4054
+ }
3470
4055
  const stamp = firstStr(data.timestamp, data.fired_at, data.created_at, alert.created_at);
3471
4056
  let when = null;
3472
4057
  if (stamp) {
@@ -3476,45 +4061,159 @@ function parseFirstAlertEvent(body, options = {}) {
3476
4061
  return new FirstAlertEvent({
3477
4062
  alertId,
3478
4063
  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)),
4064
+ locationId: plainId(firstStr(data.location_id, loc.id, alert.location_id)),
4065
+ callId: plainId(firstStr(data.call_id, call.id, alert.call_id)),
3481
4066
  timestamp: when,
3482
4067
  isTest: data.is_test === true,
3483
4068
  raw: { ...data }
3484
4069
  });
3485
4070
  }
4071
+ function canonicalJson(v) {
4072
+ if (v === null) return "null";
4073
+ switch (typeof v) {
4074
+ case "boolean":
4075
+ return v ? "true" : "false";
4076
+ case "number":
4077
+ if (!Number.isFinite(v)) throw new WebhookPayloadError("A number that is not finite cannot be hashed.");
4078
+ return JSON.stringify(v);
4079
+ case "string":
4080
+ if (!wellFormed(v)) throw new WebhookPayloadError("A lone surrogate cannot be hashed.");
4081
+ return JSON.stringify(v);
4082
+ case "object": {
4083
+ if (Array.isArray(v)) return "[" + v.map((x) => canonicalJson(x === void 0 ? null : x)).join(",") + "]";
4084
+ const o = v;
4085
+ const keys = Object.keys(o).filter((k) => o[k] !== void 0).sort();
4086
+ return "{" + keys.map((k) => canonicalJson(k) + ":" + canonicalJson(o[k])).join(",") + "}";
4087
+ }
4088
+ default:
4089
+ throw new WebhookPayloadError("A value that is not JSON cannot be hashed.");
4090
+ }
4091
+ }
4092
+ async function sha256Hex(text) {
4093
+ const data = new TextEncoder().encode(text);
4094
+ const subtle = globalThis.crypto?.subtle;
4095
+ if (subtle) {
4096
+ const buf = await subtle.digest("SHA-256", data);
4097
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
4098
+ }
4099
+ const nodeCrypto = await import('crypto');
4100
+ return nodeCrypto.createHash("sha256").update(data).digest("hex");
4101
+ }
4102
+ function asEvent(item) {
4103
+ if (isFirstAlertEvent(item)) return { kind: "first_alert", event: item };
4104
+ if (item && typeof item === "object" && item.kind === "unknown" && "raw" in item) {
4105
+ const u = item;
4106
+ return { kind: "unknown", type: u.type, raw: u.raw };
4107
+ }
4108
+ const body = loadBody(item, MAX_EVENT_BYTES);
4109
+ const ev = parseAfterCallEvent(body);
4110
+ if (isUnknownEvent(ev)) {
4111
+ try {
4112
+ return { kind: "first_alert", event: parseFirstAlertEvent(body) };
4113
+ } catch (e) {
4114
+ if (e instanceof WebhookPayloadError && !Object.prototype.hasOwnProperty.call(body, "alert_id")) return { kind: "unknown", type: ev.type, raw: ev.raw };
4115
+ throw e;
4116
+ }
4117
+ }
4118
+ return { kind: "after_call", event: ev };
4119
+ }
4120
+ function upsertKey(event) {
4121
+ const ev = asEvent(event);
4122
+ if (ev.kind === "after_call") return ev.event.call.id;
4123
+ if (ev.kind === "first_alert") return ev.event.alertId;
4124
+ throw new WebhookPayloadError("Not an After Call or First Alert event.");
4125
+ }
4126
+ var RFC33392 = /^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}:\d{2}:\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})$/;
4127
+ function stampOf(value) {
4128
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : [value.getTime(), "000"];
4129
+ if (typeof value !== "string") return null;
4130
+ const m = RFC33392.exec(value.trim());
4131
+ if (!m) return null;
4132
+ const frac = (m[3] ?? "").padEnd(3, "0");
4133
+ const t = (/* @__PURE__ */ new Date(`${m[1]}T${m[2]}.${frac.slice(0, 3)}${m[4].toUpperCase()}`)).getTime();
4134
+ return Number.isNaN(t) ? null : [t, frac.slice(3).padEnd(3, "0")];
4135
+ }
4136
+ function eventTime(value) {
4137
+ if (value === null || value === void 0) return null;
4138
+ if (value instanceof Date) return stampOf(value);
4139
+ if (typeof value === "string" && !value.replace(/^[\ufeff \t\r\n]+/, "").startsWith("{")) return stampOf(value);
4140
+ let ev;
4141
+ try {
4142
+ ev = asEvent(value);
4143
+ } catch {
4144
+ return null;
4145
+ }
4146
+ if (ev.kind === "after_call") return stampOf(ev.event.timestamp);
4147
+ if (ev.kind === "first_alert") return stampOf(ev.event.timestamp);
4148
+ return null;
4149
+ }
4150
+ function isOlder(event, stored) {
4151
+ const a = eventTime(event);
4152
+ const b = eventTime(stored);
4153
+ if (a === null || b === null) return false;
4154
+ return a[0] < b[0] || a[0] === b[0] && a[1] < b[1];
4155
+ }
4156
+ async function deliveryKey(event) {
4157
+ if (typeof event === "string" && !event.replace(/^[\ufeff \t\r\n]+/, "").startsWith("{")) {
4158
+ throw new InvalidRequestError(
4159
+ "seen(event) and remember(event) take the event, its parsed body or the raw request body, not an id: an id alone cannot tell newer data apart"
4160
+ );
4161
+ }
4162
+ const ev = asEvent(event);
4163
+ if (ev.kind === "after_call") {
4164
+ const e = ev.event;
4165
+ return `${e.type}:${e.location_id}:${e.call.id}:${await sha256Hex(canonicalJson(e))}`;
4166
+ }
4167
+ if (ev.kind === "first_alert") return `first_alert:${ev.event.alertId}:${await sha256Hex(canonicalJson(ev.event.raw))}`;
4168
+ return `${typeof ev.type === "string" ? ev.type : "unknown"}:${await sha256Hex(canonicalJson(ev.raw))}`;
4169
+ }
3486
4170
  var MemoryDedupStore = class {
3487
4171
  constructor(maxSize = 1e4) {
3488
4172
  this.maxSize = maxSize;
3489
4173
  }
3490
4174
  maxSize;
3491
4175
  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
- }
4176
+ has(key) {
4177
+ if (!this.keys.has(key)) return false;
4178
+ this.keys.delete(key);
4179
+ this.keys.set(key, true);
4180
+ return true;
4181
+ }
4182
+ add(key) {
4183
+ this.keys.delete(key);
3498
4184
  this.keys.set(key, true);
3499
4185
  if (this.keys.size > this.maxSize) {
3500
4186
  const oldest = this.keys.keys().next().value;
3501
4187
  if (oldest !== void 0) this.keys.delete(oldest);
3502
4188
  }
3503
- return false;
3504
4189
  }
3505
4190
  };
4191
+ function present(event) {
4192
+ if (event === void 0 || event === null || event === "" || event instanceof Uint8Array && event.byteLength === 0) {
4193
+ throw new InvalidRequestError("an event is required");
4194
+ }
4195
+ return event;
4196
+ }
3506
4197
  var Deduplicator = class {
3507
4198
  store;
3508
4199
  constructor(options = {}) {
3509
4200
  this.store = options.store ?? new MemoryDedupStore(options.maxSize ?? 1e4);
3510
4201
  }
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));
4202
+ /** True when this exact delivery was remembered before. Records nothing. */
4203
+ async seen(event) {
4204
+ return Boolean(await this.store.has(await deliveryKey(present(event))));
4205
+ }
4206
+ /** Record this delivery. Call it after your durable write succeeded. */
4207
+ async remember(event) {
4208
+ await this.store.add(await deliveryKey(present(event)));
3514
4209
  }
3515
- /** @deprecated Use `isDuplicate` (same result). */
3516
- seen(id) {
3517
- return this.isDuplicate(id);
4210
+ /** The call id (After Call) or alert id (First Alert) to store the delivery under. */
4211
+ static upsertKey(event) {
4212
+ return upsertKey(event);
4213
+ }
4214
+ /** The call id (After Call) or alert id (First Alert) to store the delivery under. */
4215
+ upsertKey(event) {
4216
+ return upsertKey(event);
3518
4217
  }
3519
4218
  };
3520
4219
 
@@ -3551,7 +4250,7 @@ function localMidnight(y, m, d) {
3551
4250
  return new Date(y, m - 1, d, 0, 0, 0, 0);
3552
4251
  }
3553
4252
  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;
4253
+ var RFC33393 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/i;
3555
4254
  function camelKey(k) {
3556
4255
  return k.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
3557
4256
  }
@@ -3654,6 +4353,24 @@ var AlertBrief = class {
3654
4353
  return this.toString();
3655
4354
  }
3656
4355
  };
4356
+ var idArg = (value, name) => pathArg(value, name);
4357
+ function checkTeam(team) {
4358
+ if (team === void 0 || team === null) return;
4359
+ if (typeof team === "object" && typeof team.locationId === "string") return;
4360
+ if (typeof team !== "string" || !team.trim() || team.length > 200) throw new InvalidRequestError("team: a TeamRef, a location id or a team name");
4361
+ }
4362
+ function checkDue(due) {
4363
+ if (due === void 0 || due === null) return;
4364
+ if (due instanceof Date && !Number.isNaN(due.getTime())) return;
4365
+ if (typeof due === "string") {
4366
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(due);
4367
+ if (m) {
4368
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
4369
+ if (d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3])) return;
4370
+ }
4371
+ }
4372
+ throw new InvalidRequestError("due: a date (YYYY-MM-DD)");
4373
+ }
3657
4374
  var Conversations = class _Conversations {
3658
4375
  constructor(c) {
3659
4376
  this.c = c;
@@ -3673,7 +4390,7 @@ var Conversations = class _Conversations {
3673
4390
  return (this.c.maskNumbers ? maskName(n) : n) ?? null;
3674
4391
  }
3675
4392
  link(kind, id) {
3676
- if (!id) return null;
4393
+ if (typeof id !== "string" || !ID_RE.test(id)) return null;
3677
4394
  const page = kind === "call" ? "after-call-copilot/calls" : "first-alert-copilot/alerts";
3678
4395
  return `${this.c.appUrl}/${page}/${encodeURIComponent(id)}`;
3679
4396
  }
@@ -3685,13 +4402,13 @@ var Conversations = class _Conversations {
3685
4402
  }
3686
4403
  static when(value, name) {
3687
4404
  if (typeof value === "string") {
3688
- if (!RFC33392.test(value.trim())) throw new InvalidRequestError(`${name}: an RFC 3339 date-time with a time zone`);
4405
+ if (!RFC33393.test(value.trim())) throw new InvalidRequestError(`${name}: an RFC 3339 date-time with a time zone`);
3689
4406
  return new Date(value.trim());
3690
4407
  }
3691
4408
  if (!(value instanceof Date) || Number.isNaN(value.getTime())) throw new InvalidRequestError(`${name}: a Date or an RFC 3339 date-time`);
3692
4409
  return value;
3693
4410
  }
3694
- /** (start, end). Default: today (local time), or the last `defaultDays` days. At most 31 days. */
4411
+ /** @internal (start, end). Default: today (local time), or the last `defaultDays` days. At most 31 days. */
3695
4412
  window(day, since, until, defaultDays) {
3696
4413
  const has = (v) => v !== void 0 && v !== null;
3697
4414
  if (has(day) && (has(since) || has(until))) throw new InvalidRequestError("Pass day, or since/until, not both");
@@ -3733,7 +4450,9 @@ var Conversations = class _Conversations {
3733
4450
  }
3734
4451
  const term = phone ?? text;
3735
4452
  if (term === void 0 || term === null) return void 0;
3736
- const t = String(term).trim();
4453
+ if (typeof term !== "string") throw new InvalidRequestError("number and search: a string");
4454
+ const t = term.trim();
4455
+ if (t.length > 200) throw new InvalidRequestError("number and search: at most 200 characters");
3737
4456
  if (t.length < 2) throw new InvalidRequestError("search terms need at least 2 characters (shorter ones are ignored by the API)");
3738
4457
  return t;
3739
4458
  }
@@ -3809,7 +4528,10 @@ var Conversations = class _Conversations {
3809
4528
  lines: null
3810
4529
  };
3811
4530
  }
3812
- /** The teams (locations) this person can see. Management is listed with `kind: "management"`. */
4531
+ /**
4532
+ * The teams (locations) this person can see: those with `kind === "team"` first, in name order, then Management
4533
+ * (`kind === "management"`) last. Pick "my team" by `kind === "team"`.
4534
+ */
3813
4535
  async teams() {
3814
4536
  await this.requireUser();
3815
4537
  const out = [];
@@ -3817,7 +4539,8 @@ var Conversations = class _Conversations {
3817
4539
  const name = loc.location_name ?? "";
3818
4540
  out.push({ locationId: loc.id ?? "", name, kind: name.endsWith(" - Management") ? "management" : "team" });
3819
4541
  }
3820
- return out;
4542
+ const rank2 = (t) => t.kind === "team" ? 0 : 1;
4543
+ return out.sort((a, b) => rank2(a) - rank2(b) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
3821
4544
  }
3822
4545
  // ------------------------------------------------------------------ calls
3823
4546
  /**
@@ -3825,11 +4548,12 @@ var Conversations = class _Conversations {
3825
4548
  * 200. `number` and `search` share the API's one search field: pass one or the other.
3826
4549
  */
3827
4550
  async calls(options = {}) {
4551
+ const limit = _Conversations.limit(options?.limit ?? 50, MAX_LIMIT);
4552
+ const [start, end] = this.window(options?.day, options?.since, options?.until);
4553
+ const term = _Conversations.searchTerm(options?.number, options?.search);
4554
+ checkTeam(options?.team);
3828
4555
  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);
4556
+ const lid = await this.teamId(options?.team);
3833
4557
  const rows = await this.pages(
3834
4558
  (n, cursor) => this.c.calls.listCalls({ dateFrom: start, dateTo: end, search: term, locationId: lid ?? void 0, limit: n, cursor }),
3835
4559
  limit
@@ -3841,6 +4565,7 @@ var Conversations = class _Conversations {
3841
4565
  * it raised. No transcript and no recording.
3842
4566
  */
3843
4567
  async brief(callId) {
4568
+ callId = idArg(callId, "callId");
3844
4569
  await this.requireUser();
3845
4570
  const data = unwrap2(await this.c.calls.getCall(callId)) ?? {};
3846
4571
  const b = this.briefFromRow(data);
@@ -3868,6 +4593,7 @@ var Conversations = class _Conversations {
3868
4593
  }
3869
4594
  /** The transcript of one call: segments with `time`, `speaker`, `name` and `text`. */
3870
4595
  async transcript(callId) {
4596
+ callId = idArg(callId, "callId");
3871
4597
  await this.requireUser();
3872
4598
  const data = unwrap2(await this.c.calls.getCallTranscript(callId)) ?? {};
3873
4599
  return data.transcript ?? [];
@@ -3877,26 +4603,30 @@ var Conversations = class _Conversations {
3877
4603
  * downloads the audio. Treat the link as a secret: never log or store it.
3878
4604
  */
3879
4605
  async recordingLink(callId) {
4606
+ callId = idArg(callId, "callId");
3880
4607
  await this.requireUser();
3881
4608
  const link = await this.c.intelligence.getRecordingUrl(callId);
3882
4609
  return link.url ? link : null;
3883
4610
  }
3884
4611
  /** Recent briefs for one caller (the last 31 days), for use before a callback. `limit` at most 50. */
3885
4612
  async callerHistory(number, options = {}) {
3886
- await this.requireUser();
3887
- const limit = _Conversations.limit(options.limit ?? 10, MAX_HISTORY);
4613
+ const limit = _Conversations.limit(options?.limit ?? 10, MAX_HISTORY);
4614
+ if (typeof number !== "string" || !number.trim()) throw new InvalidRequestError("number: a non-empty string");
3888
4615
  const term = _Conversations.searchTerm(number, null);
3889
4616
  const [start, end] = this.window(null, null, null, MAX_WINDOW_DAYS);
4617
+ await this.requireUser();
3890
4618
  const rows = await this.pages((n, cursor) => this.c.calls.listCalls({ dateFrom: start, dateTo: end, search: term, limit: n, cursor }), limit);
3891
4619
  return rows.map((r) => this.briefFromRow(r));
3892
4620
  }
3893
4621
  // ------------------------------------------------------------------ tasks and alerts
3894
4622
  /** Open tasks (up to 200), each with the id of the call it came from. `due`: only tasks due that day. */
3895
4623
  async openTasks(options = {}) {
4624
+ checkDue(options?.due);
4625
+ checkTeam(options?.team);
3896
4626
  await this.requireUser();
3897
- const lid = await this.teamId(options.team);
4627
+ const lid = await this.teamId(options?.team);
3898
4628
  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 }),
4629
+ (n, cursor) => this.c.tasks.listTasks({ status: "open", dueOn: options?.due ?? void 0, locationId: lid ?? void 0, limit: n, cursor }),
3900
4630
  MAX_LIMIT
3901
4631
  );
3902
4632
  return rows.map((r) => _Conversations.taskFromRow(r));
@@ -3906,13 +4636,14 @@ var Conversations = class _Conversations {
3906
4636
  * `status` is refused: the API has no alert status filter yet.
3907
4637
  */
3908
4638
  async alerts(options = {}) {
3909
- await this.requireUser();
3910
- if (options.status !== void 0 && options.status !== null) {
4639
+ if (options?.status !== void 0 && options.status !== null) {
3911
4640
  throw new InvalidRequestError("status: the API has no alert status filter yet");
3912
4641
  }
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);
4642
+ const limit = _Conversations.limit(options?.limit ?? 50, MAX_LIMIT);
4643
+ const [start, end] = this.window(null, options?.since, options?.until);
4644
+ checkTeam(options?.team);
4645
+ await this.requireUser();
4646
+ const lid = await this.teamId(options?.team);
3916
4647
  const rows = await this.pages(
3917
4648
  (n, cursor) => this.c.alerts.listAlerts({ dateFrom: start, dateTo: end, locationId: lid ?? void 0, limit: n, cursor }),
3918
4649
  limit
@@ -3921,8 +4652,8 @@ var Conversations = class _Conversations {
3921
4652
  }
3922
4653
  /** One alert with its call brief, or null when this login cannot see it. */
3923
4654
  async alert(alertId) {
4655
+ const aid = idArg(alertId, "alertId").toLowerCase();
3924
4656
  await this.requireUser();
3925
- const aid = String(alertId).trim().toLowerCase();
3926
4657
  const page = await this.c.alerts.listAlerts({ search: aid, limit: 10 });
3927
4658
  const row = page.items.find((a) => a.id === aid);
3928
4659
  if (row === void 0) return null;
@@ -3935,10 +4666,11 @@ var Conversations = class _Conversations {
3935
4666
  * at most 31 days. Default: today.
3936
4667
  */
3937
4668
  async teamView(team, options = {}) {
4669
+ if (team === void 0 || team === null) throw new InvalidRequestError("team is required");
4670
+ checkTeam(team);
4671
+ const [start, end] = this.window(options?.day, options?.since, options?.until);
3938
4672
  await this.requireUser();
3939
4673
  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
4674
  const first = await this.c.calls.listCalls({ dateFrom: start, dateTo: end, locationId: lid, limit: PAGE });
3943
4675
  let rows = [...first.items];
3944
4676
  if (first.hasMore && first.nextCursor) {
@@ -3965,9 +4697,10 @@ var Conversations = class _Conversations {
3965
4697
  * Needs Insights Hub access.
3966
4698
  */
3967
4699
  async topics(options = {}) {
4700
+ const [start, end] = this.window(null, options?.since, options?.until, 7);
4701
+ checkTeam(options?.team);
3968
4702
  await this.requireUser();
3969
- const [start, end] = this.window(null, options.since, options.until, 7);
3970
- const lid = await this.teamId(options.team);
4703
+ const lid = await this.teamId(options?.team);
3971
4704
  const data = unwrap2(await this.c.insights.getInsightsDashboard({ start, end, locationId: lid ?? void 0 })) ?? {};
3972
4705
  const stats = data.stats ?? {};
3973
4706
  const rising = (data.trending_topics ?? []).filter((t) => (t.percentage_change ?? 0) > 0).map((t) => {
@@ -3993,8 +4726,9 @@ var Conversations = class _Conversations {
3993
4726
  if (brand(callOrAlert, CALL_BRAND)) [kind, id] = ["call", callOrAlert.id];
3994
4727
  else if (brand(callOrAlert, ALERT_BRAND)) [kind, id] = ["alert", callOrAlert.id];
3995
4728
  else if (isFirstAlertEvent(callOrAlert)) [kind, id] = ["alert", callOrAlert.alertId];
3996
- else if (typeof callOrAlert === "string" && callOrAlert.trim()) [kind, id] = ["call", callOrAlert.trim()];
4729
+ else if (typeof callOrAlert === "string" && callOrAlert !== "") [kind, id] = ["call", callOrAlert];
3997
4730
  else throw new InvalidRequestError("reference: a CallBrief, an AlertBrief, a FirstAlertEvent or a call id");
4731
+ if (typeof id !== "string" || !ID_RE.test(id)) throw new InvalidRequestError("reference: an id of letters, digits, '-' and '_' (at most 128)");
3998
4732
  return { kind, id, link: this.link(kind, id) };
3999
4733
  }
4000
4734
  /** A typed First Alert event, beside `parseAfterCallEvent`. See `parseFirstAlertEvent`. */
@@ -4165,7 +4899,9 @@ var Client = class {
4165
4899
  const connectors = makeConnectors(c);
4166
4900
  const waitForStatus = async (locationId, connectorId, final, o = {}) => {
4167
4901
  const start = c.now();
4168
- const deadline = start + (o.timeout ?? 600) * 1e3;
4902
+ const timeout = o.timeout ?? 600;
4903
+ const interval = o.checkInterval ?? 10;
4904
+ let checks = 0;
4169
4905
  for (; ; ) {
4170
4906
  const conn = (await connectors.getConnector(locationId, connectorId)).data ?? {};
4171
4907
  const st = conn.status ?? null;
@@ -4173,10 +4909,10 @@ var Client = class {
4173
4909
  throw new ConnectorError(conn);
4174
4910
  }
4175
4911
  if (st && final.includes(st)) return conn;
4176
- if (c.now() >= deadline) {
4177
- throw new ConnectorTimeoutError(conn, (c.now() - start) / 1e3);
4178
- }
4179
- await c.sleep((o.checkInterval ?? 10) * 1e3);
4912
+ const waited = Math.max((c.now() - start) / 1e3, checks * interval);
4913
+ if (waited >= timeout) throw new ConnectorTimeoutError(conn, waited);
4914
+ await c.sleep(interval * 1e3);
4915
+ checks++;
4180
4916
  }
4181
4917
  };
4182
4918
  const settle = async (locationId, first, final, o, raiseOnError = true) => {
@@ -4428,4 +5164,4 @@ var Client = class {
4428
5164
  }
4429
5165
  };
4430
5166
 
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 };
5167
+ 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, NetworkError, NotFoundError, PRODUCT_KEYS, PasswordExpiredError, PayloadTooLargeError, RUNNING, RateLimitError, RecordingLink, SDK_VERSION, TaskBrief, ValidationError, WebhookPayloadError, WrongLoginError, alertNumber, digitsOnly, isOlder, isUnknownEvent, maskName, maskNumber, parseAfterCallEvent, parseFirstAlertEvent, toRfc3339, upsertKey };