| 1 | use chrono::{DateTime, Utc}; |
| 2 | use rusqlite::{Row, params}; |
| 3 | |
| 4 | use crate::error::Result; |
| 5 | use crate::models::AgentProposalRecord; |
| 6 | use crate::store::Store; |
| 7 | use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis}; |
| 8 | |
| 9 | const PENDING_STATE: &str = "pending"; |
| 10 | |
| 11 | const PROPOSAL_COLUMNS: &str = "id, conversation_id, reply_to_message_id, text, agent, session_id, created_at, state, resolved_at"; |
| 12 | |
| 13 | impl Store { |
| 14 | pub fn insert_agent_proposal(&self, proposal: &AgentProposalRecord) -> Result<()> { |
| 15 | let connection = self.lock()?; |
| 16 | connection.execute( |
| 17 | &format!( |
| 18 | "INSERT INTO agent_proposals ({PROPOSAL_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)" |
| 19 | ), |
| 20 | params![ |
| 21 | proposal.id, |
| 22 | proposal.conversation_id, |
| 23 | proposal.reply_to_message_id, |
| 24 | proposal.text, |
| 25 | proposal.agent, |
| 26 | proposal.session_id, |
| 27 | to_millis(proposal.created_at), |
| 28 | proposal.state, |
| 29 | optional_to_millis(proposal.resolved_at), |
| 30 | ], |
| 31 | )?; |
| 32 | Ok(()) |
| 33 | } |
| 34 | |
| 35 | pub fn set_agent_proposal_state( |
| 36 | &self, |
| 37 | proposal_id: &str, |
| 38 | state: &str, |
| 39 | resolved_at: Option<DateTime<Utc>>, |
| 40 | ) -> Result<bool> { |
| 41 | let connection = self.lock()?; |
| 42 | let changed = connection.execute( |
| 43 | "UPDATE agent_proposals SET state = ?2, resolved_at = ?3 WHERE id = ?1", |
| 44 | params![proposal_id, state, optional_to_millis(resolved_at)], |
| 45 | )?; |
| 46 | Ok(changed > 0) |
| 47 | } |
| 48 | |
| 49 | /// Oldest first. |
| 50 | pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> { |
| 51 | let connection = self.lock()?; |
| 52 | let mut statement = connection.prepare_cached(&format!( |
| 53 | "SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?1 |
| 54 | ORDER BY created_at ASC, id ASC" |
| 55 | ))?; |
| 56 | let proposals = statement |
| 57 | .query_map([PENDING_STATE], proposal_from_row)? |
| 58 | .collect::<rusqlite::Result<_>>()?; |
| 59 | Ok(proposals) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | fn proposal_from_row(row: &Row<'_>) -> rusqlite::Result<AgentProposalRecord> { |
| 64 | Ok(AgentProposalRecord { |
| 65 | id: row.get(0)?, |
| 66 | conversation_id: row.get(1)?, |
| 67 | reply_to_message_id: row.get(2)?, |
| 68 | text: row.get(3)?, |
| 69 | agent: row.get(4)?, |
| 70 | session_id: row.get(5)?, |
| 71 | created_at: from_millis(row.get(6)?), |
| 72 | state: row.get(7)?, |
| 73 | resolved_at: optional_from_millis(row.get(8)?), |
| 74 | }) |
| 75 | } |