> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zappway.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Access Groups

> Control who can access what inside your ZappWay organization. Access Groups let you define permission sets and assign them to team members — enabling role-based access control without managing individual permissions.

> **What you will learn:**
> This page explains how Access Groups work, how to create and configure groups, how to assign members, and how to use the permission model to control access to ZappWay features.

***

## 🔢 Table of Contents

1. [Overview](#1-overview)
2. [How Access Groups Work](#2-how-access-groups-work)
3. [Endpoint Reference](#3-endpoint-reference)
4. [Managing Groups](#4-managing-groups)
5. [Managing Members](#5-managing-members)
6. [System Groups](#6-system-groups)
7. [Permission Audit](#7-permission-audit)
8. [Response Format](#8-response-format)
9. [Best Practices](#9-best-practices)
10. [Troubleshooting](#10-troubleshooting)

***

## 1. Overview

### What are Access Groups?

Access Groups are **collections of permissions** that you assign to team members. Instead of managing individual permissions per person, you:

1. **Create a group** (e.g., "Sales Team", "Support Manager")
2. **Define its permissions** (e.g., read conversations, manage contacts)
3. **Assign members** to the group

All members of a group inherit its permissions automatically.

### Key Benefits

* **Simplified management** — Change permissions for an entire team at once
* **Role-based access** — Match your organization structure to platform access
* **Auditable** — Every group change is recorded in the permission audit log
* **Scalable** — Works for teams of 2 to 2000+

***

## 2. How Access Groups Work

### Permission Model

ZappWay uses a **permission-based access model** with granular permissions such as:

| Permission            | What it grants                    |
| --------------------- | --------------------------------- |
| `conversations.read`  | View conversations                |
| `conversations.write` | Reply to and manage conversations |
| `agents.read`         | View AI Employees                 |
| `agents.write`        | Create and edit AI Employees      |
| `contacts.read`       | View contacts                     |
| `contacts.write`      | Create and edit contacts          |
| `groups.read`         | View access groups                |
| `groups.manage`       | Create, edit, and delete groups   |
| `team.invite`         | Invite new team members           |
| `team.change_group`   | Move members between groups       |
| `billing.read`        | View billing information          |
| `billing.manage`      | Manage subscription and payments  |

### Group Assignment Flow

```
Organization Admin
       ↓
Creates Access Group (with permissions)
       ↓
Invites team member OR changes existing member's group
       ↓
Team member inherits all group permissions
       ↓
Member can access features matching their permissions
```

***

## 3. Endpoint Reference

| Method   | Endpoint                          | Description                                | Auth                                                  |
| -------- | --------------------------------- | ------------------------------------------ | ----------------------------------------------------- |
| `GET`    | `/api/access-groups`              | List all access groups in the organization | `groups.read` OR `team.invite` OR `team.change_group` |
| `POST`   | `/api/access-groups`              | Create a new access group                  | `groups.manage`                                       |
| `GET`    | `/api/access-groups/[id]`         | Get a specific access group                | `groups.read`                                         |
| `PATCH`  | `/api/access-groups/[id]`         | Update an access group                     | `groups.manage`                                       |
| `DELETE` | `/api/access-groups/[id]`         | Delete an access group                     | `groups.manage`                                       |
| `GET`    | `/api/access-groups/[id]/members` | List members of a group                    | `groups.manage`                                       |
| `PATCH`  | `/api/access-groups/[id]/members` | Assign members to a group                  | `groups.manage`                                       |
| `DELETE` | `/api/access-groups/[id]/members` | Reset (remove) members from a group        | `groups.manage`                                       |

***

## 4. Managing Groups

### List Access Groups

```bash theme={null}
GET /api/access-groups
```

Returns all access groups in the current organization, including system-managed groups.

**Response:**

```json theme={null}
[
  {
    "id": "grp_abc123",
    "organizationId": "org_xyz",
    "key": "sales_team",
    "name": "Sales Team",
    "description": "Access for sales representatives",
    "isSystem": false,
    "permissions": ["conversations.read", "conversations.write", "contacts.read", "contacts.write"],
    "memberCount": 5,
    "createdAt": "2025-01-10T08:00:00.000Z",
    "updatedAt": "2025-01-15T14:00:00.000Z"
  },
  {
    "id": "grp_sys_admin",
    "key": "admin",
    "name": "Administrator",
    "isSystem": true,
    "permissions": ["*"],
    "memberCount": 2
  }
]
```

### Create an Access Group

```bash theme={null}
POST /api/access-groups
Content-Type: application/json
```

**Request Body:**

| Field         | Type       | Required | Description                                     |
| ------------- | ---------- | -------- | ----------------------------------------------- |
| `name`        | `string`   | ✅        | Display name of the group                       |
| `key`         | `string`   | ❌        | Machine-readable key (auto-generated from name) |
| `description` | `string`   | ❌        | Description of the group's purpose              |
| `permissions` | `string[]` | ✅        | Array of permission strings to grant            |

**Example:**

```json theme={null}
{
  "name": "Support Team",
  "description": "Frontline support agents — can read and reply to conversations",
  "permissions": [
    "conversations.read",
    "conversations.write",
    "contacts.read",
    "agents.read"
  ]
}
```

**cURL:**

```bash theme={null}
curl -X POST "https://your-domain.com/api/access-groups" \
  -H "Content-Type: application/json" \
  -H "Cookie: next-auth.session-token=YOUR_SESSION_TOKEN" \
  -d '{
    "name": "Support Team",
    "permissions": ["conversations.read", "conversations.write", "contacts.read"]
  }'
```

**TypeScript:**

```ts theme={null}
const response = await fetch('/api/access-groups', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'Support Team',
    description: 'Frontline support agents',
    permissions: ['conversations.read', 'conversations.write', 'contacts.read'],
  }),
});

const group = await response.json();
```

> Every `POST` and `DELETE` on access groups is recorded in the **permission audit log** automatically.

### Update an Access Group

```bash theme={null}
PATCH /api/access-groups/{groupId}
Content-Type: application/json
```

All fields are optional. Only provided fields are updated.

**Example — add a permission:**

```json theme={null}
{
  "permissions": [
    "conversations.read",
    "conversations.write",
    "contacts.read",
    "contacts.write"
  ]
}
```

> Updating `permissions` replaces the entire permission set. Always include all desired permissions in the update, not just the additions.

### Delete an Access Group

```bash theme={null}
DELETE /api/access-groups/{groupId}
```

> ⚠️ **System groups cannot be deleted.** Attempting to delete a system group (`isSystem: true`) returns `403 Forbidden`.

***

## 5. Managing Members

### List Members of a Group

```bash theme={null}
GET /api/access-groups/{groupId}/members
```

**Response:**

```json theme={null}
[
  {
    "id": "mem_abc",
    "userId": "user_123",
    "name": "Jane Smith",
    "email": "jane@company.com",
    "role": "member",
    "joinedAt": "2025-01-12T10:00:00.000Z"
  }
]
```

### Assign Members to a Group

```bash theme={null}
PATCH /api/access-groups/{groupId}/members
Content-Type: application/json
```

**Request Body:**

| Field           | Type       | Required | Description                                 |
| --------------- | ---------- | -------- | ------------------------------------------- |
| `membershipIds` | `string[]` | ✅        | Array of membership IDs to add to the group |

**Example:**

```json theme={null}
{
  "membershipIds": ["mem_abc123", "mem_def456"]
}
```

### Remove Members from a Group

```bash theme={null}
DELETE /api/access-groups/{groupId}/members
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "membershipIds": ["mem_abc123"]
}
```

***

## 6. System Groups

ZappWay automatically creates **system-managed access groups** for every organization:

| Group Key | Name          | Description                         |
| --------- | ------------- | ----------------------------------- |
| `admin`   | Administrator | Full access to all features         |
| `member`  | Member        | Default access for new team members |
| `viewer`  | Viewer        | Read-only access                    |

**System group rules:**

* System groups **cannot be deleted**
* System group permissions **cannot be modified** (managed by ZappWay)
* Every new team member is assigned to `member` by default unless you specify otherwise during invitation

***

## 7. Permission Audit

Every group creation, update, deletion, and member assignment is automatically recorded in the **permission audit log**. The audit record includes:

* Who made the change (user)
* What changed (action: `create`, `update`, `delete`)
* What resource was affected (access group ID, key)
* Outcome (success/failure)
* Metadata (group key, whether it's a system group)

You can export audit logs via the organization settings.

***

## 8. Response Format

### Status Codes

| Status | Meaning                                                         |
| ------ | --------------------------------------------------------------- |
| `200`  | Request successful                                              |
| `201`  | Group created                                                   |
| `400`  | Invalid request body                                            |
| `401`  | Not authenticated                                               |
| `403`  | Insufficient permissions or attempting to modify a system group |
| `404`  | Access group not found in organization                          |
| `500`  | Internal server error                                           |

***

## 9. Best Practices

### Design Your Group Structure First

Before creating groups, map your organization structure:

```
Organization
├── Administrator (system group — full access)
├── Team Lead (custom — can invite + change groups)
├── Sales Representative (custom — conversations + contacts)
├── Support Agent (custom — conversations read/write)
└── Viewer (system group — read only)
```

### Permission Assignments

✅ **Do:**

* Follow the **principle of least privilege** — grant only the permissions each role actually needs
* Create role-based groups that match real job functions
* Review permissions quarterly and remove unnecessary ones

❌ **Avoid:**

* Creating one group with all permissions for non-admin users
* Duplicating the `admin` system group behavior in custom groups
* Giving `billing.manage` to non-financial team members

### Managing Members at Scale

* Assign members to groups **during invitation** rather than after (cleaner workflow)
* Use `PATCH /members` to do bulk reassignments when reorganizing teams
* Review group membership after team members change roles

***

## 10. Troubleshooting

| Problem                                 | Possible Cause                                                  | Solution                                                                 |
| --------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `403 Forbidden` on group operations     | Not enough permissions                                          | You need `groups.manage` permission                                      |
| Cannot delete system group              | The group has `isSystem: true`                                  | System groups cannot be deleted; contact support if you need changes     |
| Member not inheriting group permissions | Cache delay                                                     | Wait a few seconds and refresh; session permissions update on next login |
| Wrong permissions after group update    | `permissions` update replaces the full set                      | Always include all desired permissions in the update payload             |
| Member listed but no access             | Member is in multiple groups; another group may restrict access | Check all group memberships for the affected user                        |
