# Messages Backend

## Purpose

`messages` is the per-organization store of broadcast/announcement messages (subject, body,
channel, audience). It is a generic-CRUD slice assembled from the shared factories; the backend
is the source of truth for message records. This is the generic-CRUD slice for the `messages`
table; the higher-level parent-messaging workflow is documented separately in `communications.md`.

## Slice Files (by layer)

- Route: `src/routes/messages.ts` — `createCrudRouter(controller, { permission: 'messages' })`.
- Controller: `src/api/controllers/messages.controller.ts` — `createCrudController(service, { csvFields })`.
- Service (BLL): `src/services/messages.ts` — `createCrudService(DbApi, { notFoundCode: 'messagesNotFound' })`.
- Repository (DAL): `src/db/api/messages.ts` (`MessagesDBApi`) — entity-specific
  `create`/`bulkImport`/`update`/`findBy`/`findAll`; `remove`/`deleteByIds`/`findAllAutocomplete`
  delegate to `db/api/shared/repository.ts`.
- Model: `src/db/models/messages.ts`.
- Shared used: CRUD factories (`services/shared/crud-service.ts`,
  `api/controllers/shared/crud-controller.ts`, `api/http/crud-router.ts`), repository helpers
  (`db/api/shared/repository.ts`), `shared/constants/pagination.ts` (`resolvePagination`),
  `db/api/file.ts` (`replaceRelationFiles` for the `attachments` relation).

## API

The standard generic-CRUD surface (all under `/api/messages`, JWT + `${METHOD}_MESSAGES`
permission, all `200`) — see `backend-architecture.md` for the shared contract:

- `POST /` — body `{ data }`, returns `true`.
- `POST /bulk-import` — multipart CSV file, returns `true`.
- `PUT /:id` — body `{ data, id }` (the service reads the id from the **body**, not the path
  param), returns `true`.
- `DELETE /:id` — returns `true`.
- `POST /deleteByIds` — body `{ data: string[] }`, returns `true`.
- `GET /` — query filters, returns `{ rows, count }`; `?filetype=csv` streams a CSV of `csvFields`.
- `GET /count` — returns `{ rows: [], count }`.
- `GET /autocomplete` — `?query&limit&offset`, returns `[{ id, label }]` where `label` is
  `subject`.
- `GET /:id` — returns the record with eager associations (see Data Contract).

`csvFields`: `id`, `subject`, `body`, `sent_at`.

## Access Rules

- JWT required; the whole router is guarded by `checkCrudPermissions('messages')`, deriving
  `READ_MESSAGES` / `CREATE_MESSAGES` / `UPDATE_MESSAGES` / `DELETE_MESSAGES` per HTTP method.
- Access is granted by role permission or per-user `custom_permissions` (see `permissions.md`).

## Tenant Scope

- `findAll` scopes `where.organizationId` to `currentUser.organizationId`; a `globalAccess`
  role clears the org filter (sees all tenants).
- `create` assigns the organization from `currentUser.organizationId`; `update` only reassigns
  organization for `globalAccess` users (otherwise it stays the caller's org).

## Data Contract

Model columns (`paranoid`, soft-delete via `deletedAt`):

- `id` (UUID PK), `subject`, `body` (TEXT, nullable).
- `channel` — ENUM `in_app` | `email` | `sms`.
- `audience` — ENUM `all_org` | `campus` | `class` | `staff` | `students` | `guardians` | `custom`.
- `sent_at` — DATE.
- `status` — ENUM `draft` | `scheduled` | `sent` | `failed`.
- `importHash` (unique), `campusId`, `organizationId`, `sent_byId`, `createdById`, `updatedById`,
  timestamps.

Associations: `belongsTo` organization, campus, sent_by (users), createdBy/updatedBy (users);
`hasMany` `message_recipients_message` (message_recipients); `hasMany` file as `attachments`
(scoped relation). `findBy`/`GET /:id` eager-load `message_recipients_message`, organization,
campus, sent_by, attachments in a single `Promise.all`.

List filters (`MessagesFilter`): `id`, `subject`, `body`, `sent_atRange`, `channel`, `audience`,
`status`, `campus` (id or name, `|`-separated), `sent_by` (id or firstName, `|`-separated),
`organization`, `createdAtRange`, plus `field`/`sort` ordering and `limit`/`page` pagination.

## Behavior / Notes

- `create`/`bulkImport`/`update` manage the `attachments` file relation via
  `FileDBApi.replaceRelationFiles`.
- `bulkImport` offsets `createdAt` per row by `BULK_IMPORT_TIMESTAMP_STEP_MS` to preserve order.
- List pagination uses the shared `resolvePagination` defaults (page size 10, capped at 100).
- Note: `MessagesFilter` accepts an `active` flag the model has no column for; it is currently
  inert (kept for source accuracy).

## Tests

None yet.

## Related

- Generic-CRUD contract: `backend-architecture.md`; parent-messaging workflow:
  `communications.md`; related slices: `message_recipients`, `campuses`, `file.md`,
  `permissions.md`.
