1use serde::{Deserialize, Serialize};
11
12pub use byob_types::routine::{MAX_ID_CHARS, MAX_ROUTINES, Missed, Report, Routine, RunCause, RunRecord, RunStatus, Tell, Trigger, id_ok};
13
14use crate::ClientMsg;
15
16pub const CAP_ROUTINES: &str = "routines";
18
19#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
21pub struct RoutineView {
22 pub routine: Routine,
23 #[serde(default, skip_serializing_if = "Vec::is_empty")]
26 pub schedule: Vec<String>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub next_run: Option<i64>,
30 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub runs_per_month: Option<u32>,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub last_run: Option<RunRecord>,
36}
37
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum RoutineEventKind {
42 #[default]
44 Reported,
45 Waiting,
47 Failed,
49 #[serde(other)]
51 Other,
52}
53
54pub(crate) fn check_sizes(msg: &ClientMsg) -> Result<(), String> {
56 let id = |s: &str| if id_ok(s) { Ok(()) } else { Err(format!("{:?} isn't a routine id", s.chars().take(80).collect::<String>())) };
57 match msg {
58 ClientMsg::SaveRoutine { routine } => routine.clone().validated().map(|_| ()),
59 ClientMsg::DeleteRoutine { id: i }
60 | ClientMsg::RunRoutine { id: i }
61 | ClientMsg::SetRoutineEnabled { id: i, .. }
62 | ClientMsg::ListRoutineRuns { id: i } => id(i),
63 _ => Ok(()),
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70 use crate::ServerMsg;
71
72 fn loom() -> Routine {
73 Routine {
74 id: "loom".into(),
75 name: "Loom deals".into(),
76 instructions: "Find deals on a new floor loom.".into(),
77 when: vec![Trigger::Schedule { rule: "FREQ=DAILY".into(), at: "08:00".into(), zone: Some("Europe/Berlin".into()), start: None }],
78 ..Routine::default()
79 }
80 }
81
82 #[test]
83 fn routine_messages_round_trip_and_are_checked() {
84 let msgs = vec![
85 ClientMsg::SaveRoutine { routine: loom() },
86 ClientMsg::SaveRoutine { routine: Routine { id: String::new(), ..loom() } },
87 ClientMsg::DeleteRoutine { id: "loom".into() },
88 ClientMsg::RunRoutine { id: "loom".into() },
89 ClientMsg::SetRoutineEnabled { id: "loom".into(), enabled: false },
90 ClientMsg::ListRoutineRuns { id: "loom".into() },
91 ];
92 for m in msgs {
93 assert!(m.check_sizes().is_ok(), "{}", m.to_json());
94 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
95 }
96 assert!(ClientMsg::RunRoutine { id: "../x".into() }.check_sizes().is_err());
97 assert!(ClientMsg::SaveRoutine { routine: Routine { instructions: "x".repeat(9000), ..loom() } }.check_sizes().is_err());
98 let server = vec![
99 ServerMsg::Routines {
100 items: vec![RoutineView {
101 routine: loom(),
102 schedule: vec!["Every day at 8:00 AM".into()],
103 next_run: Some(5),
104 runs_per_month: Some(30),
105 last_run: None,
106 }],
107 },
108 ServerMsg::RoutineRuns {
109 routine: "loom".into(),
110 runs: vec![RunRecord { chat: Some("c".into()), status: RunStatus::Reported, ..RunRecord::default() }],
111 },
112 ServerMsg::RoutineEvent {
113 routine: "loom".into(),
114 name: "Loom deals".into(),
115 chat: Some("c".into()),
116 kind: RoutineEventKind::Reported,
117 title: "Schacht Wolf Pup, 20% off".into(),
118 body: "At The Woolery until Sunday.".into(),
119 },
120 ];
121 for m in server {
122 let json = serde_json::to_string(&m).unwrap();
123 assert_eq!(ServerMsg::from_json(&json).unwrap(), m, "{json}");
124 }
125 let e = ServerMsg::from_json(r#"{"type":"routine_event","routine":"r","name":"R","kind":"exploded","title":"t"}"#).unwrap();
127 assert!(matches!(e, ServerMsg::RoutineEvent { kind: RoutineEventKind::Other, .. }));
128 }
129}