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

# Audit Trail

> Track all system activity and data changes for compliance and security

## Overview

The **Audit Trail** automatically logs all significant actions performed in your organization, providing a complete history of who did what, when, and whether it succeeded or failed.

<Note>
  **Permission required**: `audit_logs:read` (ANY scope)

  Audit logs are automatically created for all CREATE, UPDATE, DELETE, and CONFIGURE operations. Read-only operations (READ, VIEW, SEARCH) are excluded to reduce clutter.
</Note>

***

## API Endpoint

**Get audit logs:**

```http theme={null}
GET /audit-logs?page=1&limit=20&sortBy=createdAt&sortOrder=desc
Headers:
  x-organization-id: {organizationId}
```

**Query parameters:**

| Parameter      | Type              | Required | Default     | Description                                                            |
| -------------- | ----------------- | -------- | ----------- | ---------------------------------------------------------------------- |
| `actorType`    | enum              | No       | -           | Filter by actor: `organization_admin`, `organization_user`             |
| `resourceType` | enum              | No       | -           | Filter by resource (see resource types below)                          |
| `actionType`   | enum              | No       | -           | Filter by action: `CREATE`, `UPDATE`, `DELETE`, `DEFAULT`, `CONFIGURE` |
| `startDate`    | string (ISO date) | No       | -           | Filter logs from this date                                             |
| `endDate`      | string (ISO date) | No       | -           | Filter logs to this date                                               |
| `search`       | string            | No       | -           | Search in actor name and description                                   |
| `page`         | number            | No       | 1           | Page number for pagination                                             |
| `limit`        | number            | No       | 20          | Records per page (max recommended: 100)                                |
| `sortBy`       | enum              | No       | `createdAt` | Sort by: `createdAt`, `actorName`, `actionType`, `resourceType`        |
| `sortOrder`    | enum              | No       | `desc`      | Sort order: `asc`, `desc`                                              |

**Resource types:**

| Value               | Description                     |
| ------------------- | ------------------------------- |
| `ORGANIZATION`      | Organization settings           |
| `ORGANIZATION_USER` | Members/users                   |
| `SAVINGS`           | Deposits and withdrawals        |
| `LOAN`              | Loan creation and modifications |
| `LOAN_INSTALLMENT`  | Loan installment changes        |
| `LOAN_PAYMENT`      | Loan payment recording          |
| `EXPENSE`           | Expense recording               |
| `ASSET`             | Fixed asset management          |
| `TRANSACTION`       | General transactions            |
| `UPLOAD`            | File uploads                    |
| `CONFIG`            | Configuration changes           |

**Example request:**

```bash theme={null}
curl -X GET "/audit-logs?actorType=organization_admin&actionType=DELETE&page=1&limit=20" \
  -H "x-organization-id: org-abc123" \
  -H "Authorization: Bearer {token}"
```

***

## Response Structure

```json theme={null}
{
  "message": "Audit logs retrieved successfully",
  "data": [
    {
      "id": "log-123",
      "actorName": "John Doe",
      "actorType": "organization_admin",
      "actionType": "CREATE",
      "resourceType": "LOAN",
      "description": "Created loan for Jane Smith - 500,000 RWF",
      "metadata": {
        "status": "success",
        "memberName": "Jane Smith",
        "amount": 500000,
        "term": 12,
        "interestRate": 10
      },
      "createdAt": "2026-06-10T14:32:15.000Z"
    },
    {
      "id": "log-124",
      "actorName": "Sarah Lee",
      "actorType": "organization_user",
      "actionType": "CREATE",
      "resourceType": "SAVINGS",
      "description": "Recorded deposit for Peter Kalisa - 20,000 RWF",
      "metadata": {
        "status": "success",
        "memberName": "Peter Kalisa",
        "amount": 20000,
        "paymentMethod": "Cash"
      },
      "createdAt": "2026-06-10T09:15:22.000Z"
    },
    {
      "id": "log-125",
      "actorName": "Mark Johnson",
      "actorType": "organization_admin",
      "actionType": "DELETE",
      "resourceType": "EXPENSE",
      "description": "Attempted to delete expense",
      "metadata": {
        "status": "failed"
      },
      "createdAt": "2026-06-10T16:45:33.000Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "totalCount": 523,
    "totalPages": 27,
    "hasNextPage": true,
    "hasPreviousPage": false
  }
}
```

**Response fields:**

| Field          | Type                  | Description                                                            |
| -------------- | --------------------- | ---------------------------------------------------------------------- |
| `id`           | string                | Audit log ID                                                           |
| `actorName`    | string                | Name of person who performed action                                    |
| `actorType`    | enum                  | Actor type: `organization_admin`, `organization_user`                  |
| `actionType`   | enum                  | Action performed: `CREATE`, `UPDATE`, `DELETE`, `DEFAULT`, `CONFIGURE` |
| `resourceType` | enum                  | Type of resource affected                                              |
| `description`  | string                | Human-readable description of action                                   |
| `metadata`     | object                | Additional details including `status` (success/failed)                 |
| `createdAt`    | string (ISO datetime) | When action occurred                                                   |

**Pagination fields:**

| Field             | Type    | Description                        |
| ----------------- | ------- | ---------------------------------- |
| `page`            | number  | Current page number                |
| `limit`           | number  | Records per page                   |
| `totalCount`      | number  | Total audit logs matching filters  |
| `totalPages`      | number  | Total pages available              |
| `hasNextPage`     | boolean | More pages available after current |
| `hasPreviousPage` | boolean | Pages available before current     |

***

## What Gets Logged

**Automatically logged:**

**CREATE operations:**

* ✅ New loan creation
* ✅ New deposit recording
* ✅ New expense recording
* ✅ New asset addition
* ✅ New member registration
* ✅ New invitation sent

**UPDATE operations:**

* ✅ Loan modifications
* ✅ Member information changes
* ✅ Configuration updates
* ✅ Role assignments

**DELETE operations:**

* ✅ Expense deletion
* ✅ Asset disposal
* ✅ Member deactivation

**CONFIGURE operations:**

* ✅ Organization settings changes
* ✅ Permission modifications
* ✅ System configuration updates

**NOT logged (to reduce clutter):**

* ❌ READ operations (viewing pages, reports)
* ❌ VIEW operations (browsing data)
* ❌ SEARCH operations (searching records)
* ❌ System admin actions (excluded from organization audit trail)

***

## Filtering Audit Logs

### Filter by Actor Type

**Organization Admins only:**

```bash theme={null}
GET /audit-logs?actorType=organization_admin
```

Shows actions by administrators with elevated permissions.

**Organization Users only:**

```bash theme={null}
GET /audit-logs?actorType=organization_user
```

Shows actions by regular members/staff.

***

### Filter by Resource Type

**Loan-related activities:**

```bash theme={null}
GET /audit-logs?resourceType=LOAN
```

**Savings deposits/withdrawals:**

```bash theme={null}
GET /audit-logs?resourceType=SAVINGS
```

**Member changes:**

```bash theme={null}
GET /audit-logs?resourceType=ORGANIZATION_USER
```

***

### Filter by Action Type

**Only creations:**

```bash theme={null}
GET /audit-logs?actionType=CREATE
```

**Only deletions (sensitive):**

```bash theme={null}
GET /audit-logs?actionType=DELETE
```

**Configuration changes:**

```bash theme={null}
GET /audit-logs?actionType=CONFIGURE
```

***

### Filter by Date Range

**Last 7 days:**

```bash theme={null}
GET /audit-logs?startDate=2026-06-05&endDate=2026-06-12
```

**Specific month:**

```bash theme={null}
GET /audit-logs?startDate=2026-06-01&endDate=2026-06-30
```

***

### Search by Keywords

**Find actions by specific user:**

```bash theme={null}
GET /audit-logs?search=John%20Doe
```

**Find specific transaction descriptions:**

```bash theme={null}
GET /audit-logs?search=Jane%20Smith
```

Search looks in both `actorName` and `description` fields (case-insensitive).

***

### Combine Filters

**Deletions by admins in last month:**

```bash theme={null}
GET /audit-logs?actorType=organization_admin&actionType=DELETE&startDate=2026-05-01&endDate=2026-05-31
```

**Failed loan operations:**

```bash theme={null}
GET /audit-logs?resourceType=LOAN&search=failed
```

***

## Pagination

**Default**: 20 records per page

**Navigate pages:**

```bash theme={null}
# Page 1
GET /audit-logs?page=1&limit=20

# Page 2
GET /audit-logs?page=2&limit=20

# Custom page size (50 records)
GET /audit-logs?page=1&limit=50
```

**Use pagination object:**

```json theme={null}
{
  "pagination": {
    "page": 2,
    "limit": 20,
    "totalCount": 523,
    "totalPages": 27,
    "hasNextPage": true,
    "hasPreviousPage": true
  }
}
```

**Navigation logic:**

* If `hasNextPage = true`: Request `page + 1`
* If `hasPreviousPage = true`: Request `page - 1`

***

## Sorting

**Most recent first (default):**

```bash theme={null}
GET /audit-logs?sortBy=createdAt&sortOrder=desc
```

**Oldest first:**

```bash theme={null}
GET /audit-logs?sortBy=createdAt&sortOrder=asc
```

**Sort by actor name (alphabetical):**

```bash theme={null}
GET /audit-logs?sortBy=actorName&sortOrder=asc
```

**Sort by action type:**

```bash theme={null}
GET /audit-logs?sortBy=actionType&sortOrder=asc
```

**Sort by resource type:**

```bash theme={null}
GET /audit-logs?sortBy=resourceType&sortOrder=asc
```

***

## Status Detection

**Success vs Failed:**

Backend determines status from HTTP response code:

* **Status = 'success'**: HTTP 200-299 (successful operation)
* **Status = 'failed'**: HTTP 400+ (error occurred)

**Checking status:**

```json theme={null}
{
  "metadata": {
    "status": "success"
  }
}
```

**Failed operation example:**

```json theme={null}
{
  "actionType": "DELETE",
  "resourceType": "EXPENSE",
  "description": "Attempted to delete expense",
  "metadata": {
    "status": "failed"
  }
}
```

**Use case**: Find all failed operations to identify issues:

```bash theme={null}
GET /audit-logs?search=failed
```

***

## Use Cases

### Compliance & Audit

**Annual audit review:**

```bash theme={null}
GET /audit-logs?startDate=2025-01-01&endDate=2025-12-31&limit=100
```

Export and provide to auditors as evidence of:

* All financial transactions
* Proper authorization
* Change tracking

***

### Security Monitoring

**Track deletions (sensitive operations):**

```bash theme={null}
GET /audit-logs?actionType=DELETE
```

**Monitor admin actions:**

```bash theme={null}
GET /audit-logs?actorType=organization_admin
```

**Detect unauthorized access attempts:**

* Failed operations may indicate permission issues
* Unusual patterns (many failed attempts) warrant investigation

***

### Troubleshooting

**Find who made erroneous entry:**

```bash theme={null}
GET /audit-logs?resourceType=LOAN&search=Jane%20Smith&startDate=2026-06-01
```

Review sequence of events to understand what happened.

**Track when incorrect change occurred:**

```bash theme={null}
GET /audit-logs?resourceType=SAVINGS&sortBy=createdAt&sortOrder=asc
```

Sort chronologically to see timeline of changes.

***

### Training & Quality Control

**Review new user actions:**

```bash theme={null}
GET /audit-logs?search=Mark%20Johnson
```

See how new staff members are using the system.

**Identify common mistakes:**

```bash theme={null}
GET /audit-logs?search=failed
```

Failed operations reveal training needs or confusing workflows.

***

## Example Scenarios

### Scenario 1: Investigating Loan Error

**Problem**: Member claims loan amount was recorded incorrectly

**Investigation:**

```bash theme={null}
# Find all loan actions for this member
GET /audit-logs?resourceType=LOAN&search=Jane%20Smith
```

**Response shows:**

```json theme={null}
{
  "actorName": "John Doe",
  "actionType": "CREATE",
  "resourceType": "LOAN",
  "description": "Created loan for Jane Smith - 500,000 RWF",
  "metadata": {
    "status": "success",
    "amount": 500000,
    "term": 12
  },
  "createdAt": "2026-06-10T14:32:15.000Z"
}
```

**Conclusion**: Loan was created correctly by John Doe on June 10. Amount matches records.

***

### Scenario 2: Monthly Security Review

**Goal**: Check for unusual admin activity in June

**API call:**

```bash theme={null}
GET /audit-logs?actorType=organization_admin&startDate=2026-06-01&endDate=2026-06-30&actionType=DELETE
```

**Review deletions:**

* Are deletions authorized?
* Are deletion counts normal?
* Any suspicious patterns?

***

### Scenario 3: Audit Trail Export

**Goal**: Provide audit evidence for external audit

**API calls:**

```bash theme={null}
# Get all financial operations for year
GET /audit-logs?resourceType=LOAN&startDate=2025-01-01&endDate=2025-12-31&limit=100
GET /audit-logs?resourceType=SAVINGS&startDate=2025-01-01&endDate=2025-12-31&limit=100
GET /audit-logs?resourceType=EXPENSE&startDate=2025-01-01&endDate=2025-12-31&limit=100
```

**Process:**

1. Paginate through all results
2. Export to spreadsheet or PDF
3. Provide to auditors as supporting documentation

***

## Audit Log Retention

**Storage**: Audit logs are permanently stored in the database and cannot be deleted by users.

**Why permanent?**

* Compliance requirements (may need 7+ years)
* Legal evidence
* Fraud investigation
* Historical analysis

**Access**: Retrievable via API with pagination (20 records per page default)

**Performance**: Large organizations with thousands of logs should use specific filters rather than retrieving all logs.

***

## Best Practices

<Note>
  **Effective audit trail management:**

  **Regular monitoring:**

  * ✅ Review audit logs weekly for unusual activity
  * ✅ Check failed operations (may indicate issues)
  * ✅ Monitor DELETE actions (sensitive)
  * ✅ Track admin actions (elevated permissions)

  **Filtering:**

  * ✅ Use date filters to narrow down to specific periods
  * ✅ Filter by resourceType when investigating specific area
  * ✅ Search by actor name to track specific user's actions
  * ✅ Combine filters for precise results

  **Investigation:**

  * ✅ Sort chronologically (sortBy=createdAt) to see timeline
  * ✅ Check metadata for additional context
  * ✅ Cross-reference with actual records (loans, deposits, etc.)
  * ✅ Document findings

  **Compliance:**

  * ✅ Export audit logs for external audits
  * ✅ Keep copies of audit exports with financial reports
  * ✅ Review audit logs before period closing
  * ✅ Demonstrate access controls to auditors

  **Pagination:**

  * ✅ Use appropriate page size (20-50 for UI, 100 for exports)
  * ✅ Check `hasNextPage` before requesting more
  * ✅ Don't request all logs at once (use filters)
</Note>

***

## Limitations

**Cannot delete audit logs**: Logs are permanent and immutable. This ensures audit trail integrity but means:

* No way to remove incorrect/test logs
* Logs accumulate over time
* Use filters to find relevant logs in large datasets

**Read-only operations not logged**: To reduce clutter:

* Viewing reports not logged
* Browsing pages not logged
* Search queries not logged

**System admin actions excluded**: Organization audit trail only shows:

* organization\_admin actions
* organization\_user actions
* System admin actions excluded (different audit trail)

**Pagination required**: Cannot retrieve all logs in single request for large organizations:

* Default: 20 records per page
* Use filters to reduce result set
* Paginate through results as needed

***

## Troubleshooting

**Q: Can't see audit logs**

A: Requires `audit_logs:read` permission with ANY scope. Contact administrator to grant permission.

***

**Q: Too many logs to review**

A: Use filters to narrow down:

```bash theme={null}
# Example: Only loan deletions in June
GET /audit-logs?resourceType=LOAN&actionType=DELETE&startDate=2026-06-01&endDate=2026-06-30
```

***

**Q: Log description unclear**

A: Check `metadata` field for additional details:

```json theme={null}
{
  "description": "Created loan for Jane Smith",
  "metadata": {
    "amount": 500000,
    "term": 12,
    "interestRate": 10,
    "memberName": "Jane Smith"
  }
}
```

Cross-reference with actual record (loan, deposit, etc.) using date/time.

***

**Q: Can't find specific action**

A: Verify:

* Is action CREATE/UPDATE/DELETE/CONFIGURE? (READ/VIEW not logged)
* Is actor organization user/admin? (system\_admin excluded)
* Check date range is correct
* Try broader search terms

***

**Q: Want to export audit logs**

A: Paginate through results and save to CSV/Excel:

```typescript theme={null}
let page = 1;
let hasMore = true;
const allLogs = [];

while (hasMore) {
  const response = await fetch(`/audit-logs?page=${page}&limit=100`);
  const data = await response.json();

  allLogs.push(...data.data);
  hasMore = data.pagination.hasNextPage;
  page++;
}

// Convert allLogs to CSV or Excel
```

***

## Related Topics

<CardGroup cols={2}>
  <Card title="Permissions" icon="shield" href="/tontines/reference/permissions-matrix">
    Understanding access control
  </Card>

  <Card title="Journal Entries" icon="book-open" href="/tontines/general-ledger/viewing-journal-entries">
    View financial transaction details
  </Card>

  <Card title="Period Closing" icon="lock" href="/tontines/advanced/period-closing">
    Review audit trail before closing
  </Card>

  <Card title="Organization Settings" icon="gear" href="/tontines/settings/organization-settings">
    Configure organization
  </Card>
</CardGroup>
