# Assessments Backend

## Purpose

`assessments` is the per-organization catalog of student assessments (quizzes, homework, exams,
etc.) attached to a class subject. It is a generic-CRUD slice assembled from the shared factories;
the backend is the source of truth for these records.

## Slice Files (by layer)

- Route: `src/routes/assessments.ts` — `createCrudRouter(controller, { permission: 'assessments' })`.
- Controller: `src/api/controllers/assessments.controller.ts` — `createCrudController(service, { csvFields })`.
- Service (BLL): `src/services/assessments.ts` — `createCrudService(DbApi, { notFoundCode: 'assessmentsNotFound' })`.
- Repository (DAL): `src/db/api/assessments.ts` (`AssessmentsDBApi`) — entity-specific
  `create`/`bulkImport`/`update`/`findBy`/`findAll`; `remove`/`deleteByIds`/`findAllAutocomplete`
  delegate to `db/api/shared/repository.ts`.
- Model: `src/db/models/assessments.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/assessments`, JWT + `${METHOD}_ASSESSMENTS`
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**), 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 `name`.
- `GET /:id` — returns the record with eager associations (see Data Contract).

`csvFields`: `id`, `name`, `instructions`, `max_score`, `assigned_at`, `due_at`.

## Access Rules

- JWT required; the whole router is guarded by `checkCrudPermissions('assessments')`, deriving
  `READ_ASSESSMENTS` / `CREATE_ASSESSMENTS` / `UPDATE_ASSESSMENTS` / `DELETE_ASSESSMENTS` 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), `name`, `instructions` (TEXT, nullable).
- `assessment_type` — ENUM `quiz` | `homework` | `project` | `midterm` | `final` | `other`.
- `status` — ENUM `draft` | `published` | `closed`.
- `assigned_at`, `due_at` — DATE, nullable.
- `max_score` — DECIMAL (nullable).
- `importHash` (unique), `organizationId`, `class_subjectId`, `createdById`, `updatedById`,
  timestamps.

Associations: `belongsTo` organization, class_subject (class_subjects), createdBy/updatedBy
(users); `hasMany` `assessment_results_assessment` (assessment_results); `hasMany` file as
`attachments` (scoped relation). `findBy`/`GET /:id` eager-load `assessment_results_assessment`,
`organization`, `class_subject`, and `attachments` in a single `Promise.all`.

List filters (`AssessmentsFilter`): `id`, `name`, `instructions`, `calendarStart`+`calendarEnd`
(matches rows whose `assigned_at` or `due_at` falls between the two), `assigned_atRange`,
`due_atRange`, `max_scoreRange`, `active`, `assessment_type`, `status`, `class_subject` (id or
`status` text, `|`-separated, applied as an `include` where-clause), `organization`
(`|`-separated ids), `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: `AssessmentsFilter` accepts an `active` flag the model has no column for; it is
  currently inert (kept for source accuracy).
- Note: the `class_subject` filter matches against the related class_subjects' `status` field
  for the text branch (kept for source accuracy).

## Tests

None yet.

## Related

- Generic-CRUD contract: `backend-architecture.md`; related slices: `assessment_results`,
  `class_subjects`, `organizations`, `file.md`, `permissions.md`.
