npm package: @haykal/user-management-backend
Description: > User CRUD, bulk operations, import/export, and statistics — the canonical owner of the `UserEntity` shared across auth and other domains.
Latest version: 1.0.0

# @haykal/user-management-backend

> User CRUD, bulk operations, import/export, and statistics — the canonical owner of the `UserEntity` shared across auth and other domains.

## Installation

```bash
pnpm add @haykal/user-management-backend
```

## Configuration

### `forRoot()` Options

```typescript
import { UserManagementModule } from '@haykal/user-management-backend';

@Module({
  imports: [
    UserManagementModule.forRoot({
      // Currently no required config options
      // Extensible for future settings (e.g., maxPageSize)
    }),
  ],
})
export class AppModule {}
```

The `UserManagementConfig` interface is an extensible placeholder — no fields are required.

## Key Exports

| Export                     | Type          | Description                                                |
| -------------------------- | ------------- | ---------------------------------------------------------- |
| `UserManagementModule`     | NestJS Module | Main module with `forRoot()` / `forRootAsync()`            |
| `USER_MANAGEMENT_CONFIG`   | Symbol        | Inject the config object                                   |
| `UsersService`             | Service       | User CRUD, bulk ops, import/export, statistics             |
| `UsersRepository`          | Repository    | Data access layer for `UserEntity`                         |
| `UserEntity`               | Entity        | Canonical user entity (shared with `@haykal/auth-backend`) |
| `USER_MANAGEMENT_ENTITIES` | Array         | `[UserEntity]` for migration discovery                     |

### DTOs

| DTO               | Description                                     |
| ----------------- | ----------------------------------------------- |
| `CreateUserDto`   | Create a new user (email, password, name, etc.) |
| `UpdateUserDto`   | Partial update (all fields optional)            |
| `UserResponseDto` | Serialized user response                        |

### Domain Errors

| Error                    | Code                                  | Status | Description                |
| ------------------------ | ------------------------------------- | ------ | -------------------------- |
| `UserNotFoundError`      | `USER_MANAGEMENT_USER_NOT_FOUND`      | 404    | User not found by ID       |
| `UserAlreadyExistsError` | `USER_MANAGEMENT_USER_ALREADY_EXISTS` | 409    | Duplicate email            |
| `UserInactiveError`      | `USER_MANAGEMENT_USER_INACTIVE`       | 422    | Operating on inactive user |

### Domain Events

| Event                  | Payload                            |
| ---------------------- | ---------------------------------- |
| `UserCreatedEvent`     | `userId`, `email`, `createdBy`     |
| `UserUpdatedEvent`     | `userId`, `changes`, `updatedBy`   |
| `UserDeletedEvent`     | `userId`, `deletedBy`              |
| `UserActivatedEvent`   | `userId`, `activatedBy`            |
| `UserDeactivatedEvent` | `userId`, `deactivatedBy`          |
| `UserSuspendedEvent`   | `userId`, `reason`, `suspendedBy`  |
| `UserBulkActionEvent`  | `action`, `userIds`, `performedBy` |

## API Endpoints

All endpoints require JWT authentication. Base path: `/api/users`.

| Method   | Path                     | Description                                  |
| -------- | ------------------------ | -------------------------------------------- |
| `POST`   | `/users`                 | Create a new user                            |
| `GET`    | `/users`                 | List users (paginated, filterable, sortable) |
| `GET`    | `/users/:id`             | Get a user by ID                             |
| `PATCH`  | `/users/:id`             | Update a user                                |
| `DELETE` | `/users/:id`             | Soft-delete a user                           |
| `GET`    | `/users/stats`           | Get user statistics                          |
| `GET`    | `/users/export`          | Export users to CSV or JSON                  |
| `POST`   | `/users/import`          | Import users from CSV (multipart upload)     |
| `POST`   | `/users/bulk/activate`   | Activate multiple users                      |
| `POST`   | `/users/bulk/deactivate` | Deactivate multiple users                    |
| `POST`   | `/users/bulk/delete`     | Soft-delete multiple users                   |

## Usage Examples

### Injecting the Service

```typescript
import { UsersService } from '@haykal/user-management-backend';

@Injectable()
export class MyService {
  constructor(private readonly usersService: UsersService) {}

  async findActiveUsers(query: QueryOptionsDto) {
    return this.usersService.findAll(query);
  }
}
```

### Listening to User Events

```typescript
import { OnDomainEvent } from '@haykal/core-backend';
import { UserCreatedEvent } from '@haykal/user-management-backend';

@OnDomainEvent(UserCreatedEvent)
async onUserCreated(event: UserCreatedEvent) {
  // Create default profile, assign default role, etc.
}
```

## Entity: `UserEntity`

Table: `users`

| Field             | Type           | Description                 |
| ----------------- | -------------- | --------------------------- |
| `id`              | `uuid`         | Primary key                 |
| `email`           | `varchar(255)` | Unique, indexed             |
| `passwordHash`    | `varchar(255)` | Nullable (shared with auth) |
| `name`            | `varchar(255)` | Display name                |
| `firstName`       | `varchar(100)` | First name                  |
| `lastName`        | `varchar(100)` | Last name                   |
| `phoneNumber`     | `varchar(20)`  | Phone number                |
| `avatarUrl`       | `varchar(512)` | Avatar URL                  |
| `isActive`        | `boolean`      | Default: `true`             |
| `isEmailVerified` | `boolean`      | Default: `false`            |
| `lastLoginAt`     | `timestamptz`  | Last login timestamp        |
| `deletedAt`       | `timestamptz`  | Soft delete timestamp       |

## Related Packages

- `@haykal/user-management-client` — React Query hooks for user management
- `@haykal/auth-backend` — Uses `UserEntity` for authentication
- `@haykal/profile-management-backend` — Extended user profiles
- `@haykal/rbac-backend` — Role and permission assignments

## Further Reading

- [API Reference](../../../docs/api-reference.md) — Full endpoint listing
- [Architecture Overview](../../../docs/architecture.md) — System design and module composition
- [Backend Style Guide](../../../docs/backend-styleguide.md) — Coding conventions