| 1 | use chrono::{DateTime, Utc}; |
| 2 | use rusqlite::{Row, params}; |
| 3 | use serde_json::json; |
| 4 | |
| 5 | use crate::attachment_images::{PROPOSAL_OWNER, delete_images, load_images, replace_images}; |
| 6 | use crate::error::Result; |
| 7 | use crate::models::{AgentProposalMention, AgentProposalRecord, AgentReactionRecord}; |
| 8 | use crate::store::Store; |
| 9 | use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis}; |
| 10 | |
| 11 | const PENDING_STATE: &str = "pending"; |
| 12 | |
| 13 | const PROPOSAL_COLUMNS: &str = "id, conversation_id, reply_to_message_id, text, agent, session_id, created_at, state, resolved_at, mentions"; |
| 14 | |
| 15 | const REACTION_COLUMNS: &str = |
| 16 | "id, conversation_id, message_id, emoji, agent, session_id, created_at, state, resolved_at"; |
| 17 | |
| 18 | impl Store { |
| 19 | pub fn insert_agent_proposal(&self, proposal: &AgentProposalRecord) -> Result<()> { |
| 20 | let mut connection = self.lock()?; |
| 21 | let transaction = connection.transaction()?; |
| 22 | transaction.execute( |
| 23 | &format!( |
| 24 | "INSERT INTO agent_proposals ({PROPOSAL_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)" |
| 25 | ), |
| 26 | params![ |
| 27 | proposal.id, |
| 28 | proposal.conversation_id, |
| 29 | proposal.reply_to_message_id, |
| 30 | proposal.text, |
| 31 | proposal.agent, |
| 32 | proposal.session_id, |
| 33 | to_millis(proposal.created_at), |
| 34 | proposal.state, |
| 35 | optional_to_millis(proposal.resolved_at), |
| 36 | mentions_json(&proposal.mentions), |
| 37 | ], |
| 38 | )?; |
| 39 | replace_images(&transaction, PROPOSAL_OWNER, &proposal.id, &proposal.images)?; |
| 40 | Ok(transaction.commit()?) |
| 41 | } |
| 42 | |
| 43 | pub fn set_agent_proposal_state( |
| 44 | &self, |
| 45 | proposal_id: &str, |
| 46 | state: &str, |
| 47 | resolved_at: Option<DateTime<Utc>>, |
| 48 | ) -> Result<bool> { |
| 49 | let mut connection = self.lock()?; |
| 50 | let transaction = connection.transaction()?; |
| 51 | let changed = transaction.execute( |
| 52 | "UPDATE agent_proposals SET state = ?2, resolved_at = ?3 WHERE id = ?1", |
| 53 | params![proposal_id, state, optional_to_millis(resolved_at)], |
| 54 | )?; |
| 55 | if state != PENDING_STATE { |
| 56 | delete_images(&transaction, PROPOSAL_OWNER, proposal_id)?; |
| 57 | } |
| 58 | transaction.commit()?; |
| 59 | Ok(changed > 0) |
| 60 | } |
| 61 | |
| 62 | /// Oldest first. |
| 63 | pub fn pending_agent_proposals(&self) -> Result<Vec<AgentProposalRecord>> { |
| 64 | let connection = self.read()?; |
| 65 | let mut statement = connection.prepare_cached(&format!( |
| 66 | "SELECT {PROPOSAL_COLUMNS} FROM agent_proposals WHERE state = ?1 |
| 67 | ORDER BY created_at ASC, id ASC" |
| 68 | ))?; |
| 69 | let mut proposals = statement |
| 70 | .query_map([PENDING_STATE], proposal_from_row)? |
| 71 | .collect::<rusqlite::Result<Vec<_>>>()?; |
| 72 | for proposal in &mut proposals { |
| 73 | proposal.images = load_images(&connection, PROPOSAL_OWNER, &proposal.id)?; |
| 74 | } |
| 75 | Ok(proposals) |
| 76 | } |
| 77 | |
| 78 | pub fn sweep_agent_proposal_images(&self) -> Result<usize> { |
| 79 | let connection = self.lock()?; |
| 80 | let removed = connection.execute( |
| 81 | "DELETE FROM attachment_images WHERE owner_kind = ?1 |
| 82 | AND owner_id NOT IN (SELECT id FROM agent_proposals WHERE state = ?2)", |
| 83 | params![PROPOSAL_OWNER, PENDING_STATE], |
| 84 | )?; |
| 85 | Ok(removed) |
| 86 | } |
| 87 | |
| 88 | pub fn agent_proposal_image_count(&self, proposal_id: &str) -> Result<usize> { |
| 89 | let connection = self.read()?; |
| 90 | let count: i64 = connection.query_row( |
| 91 | "SELECT COUNT(*) FROM attachment_images WHERE owner_kind = ?1 AND owner_id = ?2", |
| 92 | params![PROPOSAL_OWNER, proposal_id], |
| 93 | |row| row.get(0), |
| 94 | )?; |
| 95 | Ok(count as usize) |
| 96 | } |
| 97 | |
| 98 | pub fn insert_agent_reaction(&self, reaction: &AgentReactionRecord) -> Result<()> { |
| 99 | let connection = self.lock()?; |
| 100 | connection.execute( |
| 101 | &format!( |
| 102 | "INSERT INTO agent_reaction_proposals ({REACTION_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)" |
| 103 | ), |
| 104 | params![ |
| 105 | reaction.id, |
| 106 | reaction.conversation_id, |
| 107 | reaction.message_id, |
| 108 | reaction.emoji, |
| 109 | reaction.agent, |
| 110 | reaction.session_id, |
| 111 | to_millis(reaction.created_at), |
| 112 | reaction.state, |
| 113 | optional_to_millis(reaction.resolved_at), |
| 114 | ], |
| 115 | )?; |
| 116 | Ok(()) |
| 117 | } |
| 118 | |
| 119 | pub fn set_agent_reaction_state( |
| 120 | &self, |
| 121 | reaction_id: &str, |
| 122 | state: &str, |
| 123 | resolved_at: Option<DateTime<Utc>>, |
| 124 | ) -> Result<bool> { |
| 125 | let connection = self.lock()?; |
| 126 | let changed = connection.execute( |
| 127 | "UPDATE agent_reaction_proposals SET state = ?2, resolved_at = ?3 WHERE id = ?1", |
| 128 | params![reaction_id, state, optional_to_millis(resolved_at)], |
| 129 | )?; |
| 130 | Ok(changed > 0) |
| 131 | } |
| 132 | |
| 133 | /// Oldest first. |
| 134 | pub fn pending_agent_reactions(&self) -> Result<Vec<AgentReactionRecord>> { |
| 135 | let connection = self.read()?; |
| 136 | let mut statement = connection.prepare_cached(&format!( |
| 137 | "SELECT {REACTION_COLUMNS} FROM agent_reaction_proposals WHERE state = ?1 |
| 138 | ORDER BY created_at ASC, id ASC" |
| 139 | ))?; |
| 140 | let reactions = statement |
| 141 | .query_map([PENDING_STATE], reaction_from_row)? |
| 142 | .collect::<rusqlite::Result<_>>()?; |
| 143 | Ok(reactions) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | fn mentions_json(mentions: &[AgentProposalMention]) -> String { |
| 148 | json!( |
| 149 | mentions |
| 150 | .iter() |
| 151 | .map(|mention| json!({"user_id": mention.user_id, "name": mention.name})) |
| 152 | .collect::<Vec<_>>() |
| 153 | ) |
| 154 | .to_string() |
| 155 | } |
| 156 | |
| 157 | fn mentions_from_json(text: &str) -> Vec<AgentProposalMention> { |
| 158 | let Ok(serde_json::Value::Array(entries)) = serde_json::from_str(text) else { |
| 159 | return Vec::new(); |
| 160 | }; |
| 161 | entries |
| 162 | .iter() |
| 163 | .filter_map(|entry| { |
| 164 | Some(AgentProposalMention { |
| 165 | user_id: entry.get("user_id")?.as_str()?.to_owned(), |
| 166 | name: entry.get("name")?.as_str()?.to_owned(), |
| 167 | }) |
| 168 | }) |
| 169 | .collect() |
| 170 | } |
| 171 | |
| 172 | fn proposal_from_row(row: &Row<'_>) -> rusqlite::Result<AgentProposalRecord> { |
| 173 | let mentions: String = row.get(9)?; |
| 174 | Ok(AgentProposalRecord { |
| 175 | id: row.get(0)?, |
| 176 | conversation_id: row.get(1)?, |
| 177 | reply_to_message_id: row.get(2)?, |
| 178 | text: row.get(3)?, |
| 179 | mentions: mentions_from_json(&mentions), |
| 180 | images: Vec::new(), |
| 181 | agent: row.get(4)?, |
| 182 | session_id: row.get(5)?, |
| 183 | created_at: from_millis(row.get(6)?), |
| 184 | state: row.get(7)?, |
| 185 | resolved_at: optional_from_millis(row.get(8)?), |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | fn reaction_from_row(row: &Row<'_>) -> rusqlite::Result<AgentReactionRecord> { |
| 190 | Ok(AgentReactionRecord { |
| 191 | id: row.get(0)?, |
| 192 | conversation_id: row.get(1)?, |
| 193 | message_id: row.get(2)?, |
| 194 | emoji: row.get(3)?, |
| 195 | agent: row.get(4)?, |
| 196 | session_id: row.get(5)?, |
| 197 | created_at: from_millis(row.get(6)?), |
| 198 | state: row.get(7)?, |
| 199 | resolved_at: optional_from_millis(row.get(8)?), |
| 200 | }) |
| 201 | } |