# UML Sequence Diagram: Scheduling, Prescheduling, and Swap

Package flow: `api.views.admin.schedule_request`, `api.views.admin.preschedule_request`, `api.views.admin.swap`, `backend.kafka`, `kafka_consumer.tt_response`, `api.utils`, `node`.

## Flow Description

1. The frontend posts activity ids and an optional `socket_id` to `schedule-request`, `preschedule-request`, or `swap`.
2. The view validates activity/resource ids and builds a Kafka request with `session_id`, `activities`, optional slot, and method-specific fields.
3. `send_request()` adds `request_id`, sets the Kafka `method` header, produces to the request topic, and inserts `KafkaLog`.
4. The scheduler service responds on the response topic with the same `request_id`.
5. `kafka_consumer.tt_response` updates `KafkaLog`, writes schedule results into `TtActivity` and join/resource-map tables, syncs Redis, and sends websocket notifications through the Node bridge.
6. `node/broadcast.js` emits the event to the matching Socket.IO `socket_id`.

```mermaid
sequenceDiagram
autonumber
participant FE as Frontend
participant View as ScheduleRequest or PrescheduleRequest or Swap
participant Kafka as backend.kafka.send_request
participant KLog as KafkaLog
participant RequestTopic as Kafka request topic
participant Scheduler as Scheduler service
participant ResponseTopic as Kafka response topic
participant Worker as kafka_consumer.tt_response
participant DB as TtActivity and relation models
participant Redis as Redis JSON cache
participant Node as node/broadcast.js

FE->>View: POST activity ids, optional slot/resources, socket_id
View->>View: validate request and load settings/activity data
View->>Kafka: send_request(topic, payload, socket_id, method)
Kafka->>RequestTopic: produce request JSON and method header
Kafka->>KLog: insert_request(request_id, topic, payload, socket_id)
View-->>FE: immediate success envelope
RequestTopic->>Scheduler: consume request
Scheduler->>ResponseTopic: publish response with request_id
ResponseTopic->>Worker: poll message
Worker->>KLog: update_response(topic, response, headers)
Worker->>DB: update schedule, staff/location assignments, variants, resource maps
Worker->>Redis: bulk_sync_to_redis(update/delete payload)
Worker->>Node: POST endpoint with socket_id and response data
Node-->>FE: Socket.IO event
```

