use crate::{ book::{release, CancelReason}, validation::identifier, }; use anyhow::{ensure, Result}; use rusqlite::{params, Transaction}; use serde_json::{json, Map, Value}; pub(crate) fn by_id(tx: &Transaction, account: &str, orders: &[i64]) -> Result { identifier(account)?; ensure!( (1..=3000).contains(&orders.len()), "cancel_orders requires 1 to 3000 order IDs" ); let mut stmt = tx.prepare( "WITH requested AS ( SELECT value AS id, MIN(key) AS ordinal FROM json_each(?1) GROUP BY value ) SELECT r.id,o.status FROM requested r LEFT JOIN orders o ON o.seq=r.id AND o.account=?2 ORDER BY r.ordinal", )?; // Capture the candidate set before touching orders via the same connection. let selected = stmt .query_map(params![serde_json::to_string(orders)?, account], |r| { Ok((r.get::<_, i64>(0)?, r.get::<_, Option>(1)?)) })? .collect::>>()?; let mut canceled = Vec::new(); let mut not_canceled = Map::new(); for (order, status) in selected { match status.as_deref() { Some("live") => { release(tx, order, account, CancelReason::Cancelled)?; canceled.push(order); } other => { let reason = other.map_or_else(|| "order not found".to_owned(), |s| format!("order is {s}")); not_canceled.insert(order.to_string(), json!(reason)); } } } Ok(json!({"canceled":canceled,"not_canceled":not_canceled})) } pub(crate) fn in_scope( tx: &Transaction, account: &str, market: Option<&str>, outcome: Option<&str>, ) -> Result { identifier(account)?; if let Some(market) = market { identifier(market)?; } if let Some(outcome) = outcome { ensure!( market.is_some() && matches!(outcome, "YES" | "NO"), "invalid cancellation scope" ); } let mut stmt = tx.prepare( "SELECT seq FROM orders WHERE account=?1 AND status='live' AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3) ORDER BY seq", )?; let canceled = stmt .query_map(params![account, market, outcome], |r| r.get::<_, i64>(0))? .collect::>>()?; for order in &canceled { release(tx, *order, account, CancelReason::Cancelled)?; } Ok(json!({"canceled":canceled,"not_canceled":{}})) }