npm package: @haykal/audit-client
Description: Domain client package for the **Audit** domain.
Latest version: 1.0.0

# @haykal/audit-client

Domain client package for the **Audit** domain.

Provides React Query hooks for audit trail management, including paginated audit log listings, entity-specific history, user activity tracking, and aggregate statistics.

## Installation

This package is already part of the Haykal monorepo. To use it in your app:

```typescript
import {
  useAuditLogs,
  useAuditStats,
  useEntityAuditTrail,
  useUserAuditLogs,
  initMutator,
} from '@haykal/audit-client';
```

## Initialization

Initialize the mutator at app startup (after setting up HaykalClient):

```typescript
import { HaykalClient } from '@haykal/core-client';
import { initMutator } from '@haykal/audit-client';

// Initialize HaykalClient
const client = new HaykalClient({ baseURL: '/api' });

// Connect the audit client to HaykalClient
initMutator(client.axios);
```

## Custom Hooks

### `useAuditLogs(options)`

Fetch paginated audit logs with optional filtering.

```typescript
function AuditLogsList() {
  const { data, total, isLoading, refetch } = useAuditLogs({
    action: 'CREATE',
    entityType: 'User',
    limit: 50,
    offset: 0,
  });

  if (isLoading) return <Spinner />;

  return (
    <div>
      <h2>Audit Logs ({total} total)</h2>
      {data.map((log) => (
        <AuditLogEntry key={log.id} log={log} />
      ))}
    </div>
  );
}
```

**Options:**

- `action?: string` - Filter by action type (CREATE, UPDATE, DELETE, etc.)
- `entityType?: string` - Filter by entity type (User, Order, etc.)
- `userId?: string` - Filter by user ID
- `tenantId?: string` - Filter by tenant ID
- `search?: string` - Full-text search on description
- `dateFrom?: string` - Filter from date (ISO 8601)
- `dateTo?: string` - Filter to date (ISO 8601)
- `limit?: number` - Items per page (default: 20)
- `offset?: number` - Pagination offset (default: 0)
- `enabled?: boolean` - Whether to enable the query (default: true)

### `useAuditStats(options)`

Fetch aggregate audit statistics (counts per action type).

```typescript
function AuditStatsWidget() {
  const { stats, isLoading } = useAuditStats({ tenantId: 'tenant-123' });

  if (isLoading) return <Spinner />;

  return (
    <div>
      <h3>Audit Activity</h3>
      {stats.map((stat) => (
        <div key={stat.action}>
          {stat.action}: {stat.count}
        </div>
      ))}
    </div>
  );
}
```

**Options:**

- `tenantId?: string` - Filter by tenant ID
- `enabled?: boolean` - Whether to enable the query (default: true)

### `useEntityAuditTrail(options)`

Fetch the complete audit history for a specific entity.

```typescript
function UserActivityTab({ userId }: { userId: string }) {
  const { data, total, isLoading } = useEntityAuditTrail({
    entityType: 'User',
    entityId: userId,
    limit: 100,
  });

  if (isLoading) return <Spinner />;

  return (
    <div>
      <h3>Activity History ({total} events)</h3>
      <Timeline>
        {data.map((log) => (
          <TimelineItem key={log.id} log={log} />
        ))}
      </Timeline>
    </div>
  );
}
```

**Options:**

- `entityType: string` - Entity type (required)
- `entityId: string` - Entity ID (required)
- `limit?: number` - Items per page (default: 50)
- `offset?: number` - Pagination offset (default: 0)
- `enabled?: boolean` - Whether to enable the query (default: true)

### `useUserAuditLogs(options)`

Fetch all audit logs for a specific user (all actions performed by the user).

```typescript
function UserActivityPage({ userId }: { userId: string }) {
  const { data, total, isLoading } = useUserAuditLogs({
    userId,
    limit: 100,
  });

  if (isLoading) return <Spinner />;

  return (
    <div>
      <h3>User Activity ({total} actions)</h3>
      {data.map((log) => (
        <AuditLogCard key={log.id} log={log} />
      ))}
    </div>
  );
}
```

**Options:**

- `userId: string` - User ID (required)
- `limit?: number` - Items per page (default: 50)
- `offset?: number` - Pagination offset (default: 0)
- `enabled?: boolean` - Whether to enable the query (default: true)

## Generating the Client

Regenerate the client hooks from the latest OpenAPI spec:

```bash
# Make sure the backend is running on localhost:8080
nx run audit-client:generate
```

This generates React Query hooks and TypeScript types from the audit backend's OpenAPI spec.

## Generated Hooks

In addition to the custom hooks above, you can also use the generated hooks directly:

- `useAuditControllerList` - Raw generated hook for listing audit logs
- `useAuditControllerGetStats` - Raw generated hook for statistics
- `useAuditControllerGetEntityHistory` - Raw generated hook for entity history
- `useAuditControllerGetUserAuditLogs` - Raw generated hook for user activity

The custom hooks provide a friendlier API with better TypeScript support.