cal_core/
queue.rs

1// File: cal-core/src/queue.rs
2
3use serde::{Deserialize, Serialize};
4use std::collections::VecDeque;
5use crate::conversation::Contact;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct QueueGroup {
9    pub name: String,
10    #[serde(rename = "type")]
11    pub queue_type: Option<String>,
12    pub device_id: String,
13    pub account_id: String,
14    pub entries: VecDeque<Entry>,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct Entry {
19    pub call_sid: String,
20    pub from: String,
21    pub priority: i32,
22    pub timestamp: i64,
23    pub contact: Option<Contact>,
24}
25
26impl QueueGroup {
27    pub fn new(name: String, queue_type: Option<String>, device_id: String, account_id: String) -> Self {
28        Self {
29            name,
30            queue_type,
31            device_id,
32            account_id,
33            entries: VecDeque::new(),
34        }
35    }
36
37    pub fn get_type(&self) -> String {
38        self.queue_type.clone().unwrap_or_else(|| "callable-queue".to_string())
39    }
40
41    pub fn add(&mut self, call_sid: String, from: String, priority: i32, contact: Option<Contact>) -> Entry {
42        let entry = Entry {
43            call_sid: call_sid.clone(),
44            from,
45            priority,
46            timestamp: chrono::Utc::now().timestamp_millis(),
47            contact,
48        };
49        self.entries.push_back(entry.clone());
50        entry
51    }
52
53    pub fn remove(&mut self, call_sid: &str) {
54        self.entries.retain(|entry| entry.call_sid != call_sid);
55    }
56
57    pub fn pop(&mut self) -> Option<Entry> {
58        self.entries.pop_front()
59    }
60
61    pub fn pop_by_priority(&mut self) -> Option<Entry> {
62        if self.entries.is_empty() {
63            return None;
64        }
65
66        // Find the index of the entry with the minimum prioritized timestamp
67        let min_index = self.entries
68            .iter()
69            .enumerate()
70            .min_by_key(|(_, entry)| entry.get_prioritized_timestamp())
71            .map(|(index, _)| index)?;
72
73        // Remove and return the entry at that index
74        self.entries.remove(min_index)
75    }
76}
77
78impl Entry {
79    pub fn get_prioritized_timestamp(&self) -> i64 {
80        // Lower priority number = higher priority (1 is highest)
81        // Multiply by -1 to reverse the order so lower numbers come first
82        self.timestamp * (self.priority as i64) * -1
83    }
84}