add chat function

#
This commit is contained in:
Bartal Læarsson
2026-06-12 17:47:14 +01:00
commit 385727b09d
12 changed files with 2776 additions and 0 deletions
+208
View File
@@ -0,0 +1,208 @@
use axum::{
extract::{Path, State, Form},
response::Html,
};
use chrono::Utc;
use std::sync::Arc;
use uuid::Uuid;
use crate::{
models::{ChatSession, Message, MessageSender, SendMessageForm, NewSessionForm, SessionStatus},
state::AppState,
};
fn render_message(msg: &Message) -> String {
let (bubble_class, label) = match msg.sender {
MessageSender::Customer => ("msg-customer", "You"),
MessageSender::Agent => ("msg-agent", "Support"),
MessageSender::System => ("msg-system", ""),
};
if msg.sender == MessageSender::System {
format!(
"<div class=\"msg-system-wrap\"><span class=\"msg-system-text\">{}</span></div>",
html_escape(&msg.content)
)
} else {
let time = msg.timestamp.format("%H:%M").to_string();
format!(
"<div class=\"msg-wrap {bclass}-wrap\">\
<div class=\"{bclass}\">\
<span class=\"msg-label\">{label}</span>\
<p class=\"msg-text\">{content}</p>\
<span class=\"msg-time\">{time}</span>\
</div>\
</div>",
bclass = bubble_class,
content = html_escape(&msg.content),
)
}
}
fn html_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}
/// GET /messages/:session_id
pub async fn get_messages(
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
) -> Html<String> {
let Some(session) = state.sessions.get(&session_id) else {
return Html("<p class='error'>Session not found.</p>".to_string());
};
let html: String = session.messages.iter().map(render_message).collect();
Html(html)
}
/// POST /send/:session_id — customer sends a message
pub async fn send_message(
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
Form(form): Form<SendMessageForm>,
) -> Html<String> {
let content = form.content.trim().to_string();
if content.is_empty() {
return Html(String::new());
}
let msg = Message {
id: Uuid::new_v4().to_string(),
session_id: session_id.clone(),
sender: MessageSender::Customer,
content,
timestamp: Utc::now(),
};
let rendered = render_message(&msg);
if let Some(mut session) = state.sessions.get_mut(&session_id) {
session.messages.push(msg);
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
let _ = state.agent_notifier.send(session_id.clone());
}
Html(rendered)
}
/// POST /agent/send/:session_id — agent sends a message
pub async fn agent_send_message(
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
Form(form): Form<SendMessageForm>,
) -> Html<String> {
let content = form.content.trim().to_string();
if content.is_empty() {
return Html(String::new());
}
let msg = Message {
id: Uuid::new_v4().to_string(),
session_id: session_id.clone(),
sender: MessageSender::Agent,
content,
timestamp: Utc::now(),
};
let rendered = render_message(&msg);
if let Some(mut session) = state.sessions.get_mut(&session_id) {
session.messages.push(msg);
session.status = SessionStatus::Active;
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
}
Html(rendered)
}
/// GET /sessions — session list for agent dashboard
pub async fn get_sessions(
State(state): State<Arc<AppState>>,
) -> Html<String> {
let mut sessions: Vec<_> = state.sessions
.iter()
.filter(|s| s.status != SessionStatus::Closed)
.map(|s| (s.id.clone(), s.customer_name.clone(), s.status.clone(), s.messages.len()))
.collect();
sessions.sort_by(|a, b| a.0.cmp(&b.0));
if sessions.is_empty() {
return Html("<p class=\"no-sessions\">No active conversations yet.</p>".to_string());
}
let mut html = String::new();
for (id, name, status, count) in &sessions {
let status_class = match status {
SessionStatus::Waiting => "status-waiting",
SessionStatus::Active => "status-active",
SessionStatus::Closed => "status-closed",
};
let status_label = match status {
SessionStatus::Waiting => "Waiting",
SessionStatus::Active => "Active",
SessionStatus::Closed => "Closed",
};
let short_id = &id[..8];
let escaped_name = html_escape(name);
html.push_str(&format!(
"<button class=\"session-item\" \
hx-get=\"/messages/{id}\" \
hx-target=\"#agent-messages\" \
hx-swap=\"innerHTML\" \
onclick=\"document.querySelectorAll('.session-item').forEach(function(b){{b.classList.remove('selected')}}); this.classList.add('selected'); setActiveSession('{id}', '{escaped_name}')\">\
<span class=\"session-name\">{escaped_name}</span>\
<span class=\"session-meta\">\
<span class=\"session-badge {status_class}\">{status_label}</span>\
<span class=\"session-count\">{count} msgs</span>\
</span>\
<span class=\"session-id\">#{short_id}</span>\
</button>"
));
}
Html(html)
}
/// POST /sessions/new — start a new customer session
pub async fn new_session(
State(state): State<Arc<AppState>>,
Form(form): Form<NewSessionForm>,
) -> Html<String> {
let name = form.name.trim().to_string();
let name = if name.is_empty() { "Anonymous".to_string() } else { name };
let session_id = Uuid::new_v4().to_string();
let short = session_id[..8].to_string();
let session = ChatSession::new(session_id.clone(), name.clone());
state.sessions.insert(session_id.clone(), session);
state.get_or_create_notifier(&session_id);
let _ = state.agent_notifier.send(session_id.clone());
// The response swaps out #start-form and fills #chat-container via OOB
let html = format!(
"<div id=\"chat-container\" style=\"display:flex;flex-direction:column\" hx-swap-oob=\"true\">\
<div id=\"chat-header\">\
<span class=\"chat-status-dot active\"></span>\
<span>Support Chat</span>\
<span class=\"chat-session-id\">Session #{short}</span>\
</div>\
<div id=\"messages\" \
hx-get=\"/messages/{session_id}\" \
hx-trigger=\"load, every 2s\" \
hx-swap=\"innerHTML\">\
</div>\
<div id=\"typing-indicator\" class=\"htmx-indicator\">\
<span class=\"typing-dot\"></span><span class=\"typing-dot\"></span><span class=\"typing-dot\"></span>\
</div>\
<form id=\"chat-form\" \
hx-post=\"/send/{session_id}\" \
hx-target=\"#messages\" \
hx-swap=\"beforeend\" \
hx-on=\"htmx:afterRequest: this.reset(); scrollMessages()\">\
<input type=\"text\" name=\"content\" placeholder=\"Type your message...\" autocomplete=\"off\" required />\
<button type=\"submit\">Send</button>\
</form>\
</div>\
<script>document.getElementById('start-form').style.display='none'; window.__sessionId='{session_id}';</script>"
);
Html(html)
}