Skip to main content

stmo_cli/
models.rs

1#![allow(clippy::missing_errors_doc)]
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5fn deserialize_null_as_empty_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
6where
7    T: Deserialize<'de>,
8    D: Deserializer<'de>,
9{
10    Ok(Option::deserialize(deserializer)?.unwrap_or_default())
11}
12
13#[derive(Debug, Serialize, Deserialize, Clone)]
14pub struct Query {
15    pub id: u64,
16    pub name: String,
17    pub description: Option<String>,
18    #[serde(rename = "query")]
19    pub sql: String,
20    pub data_source_id: u64,
21    #[serde(default)]
22    pub user: Option<QueryUser>,
23    pub schedule: Option<Schedule>,
24    pub options: QueryOptions,
25    #[serde(default)]
26    pub visualizations: Vec<Visualization>,
27    pub tags: Option<Vec<String>>,
28    pub is_archived: bool,
29    pub is_draft: bool,
30    pub updated_at: String,
31    pub created_at: String,
32}
33
34#[derive(Debug, Serialize, Clone)]
35pub struct CreateQuery {
36    pub name: String,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub description: Option<String>,
39    #[serde(rename = "query")]
40    pub sql: String,
41    pub data_source_id: u64,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub schedule: Option<Schedule>,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub options: Option<QueryOptions>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub tags: Option<Vec<String>>,
48    pub is_archived: bool,
49    pub is_draft: bool,
50}
51
52#[derive(Debug, Serialize, Deserialize, Clone)]
53pub struct QueryUser {
54    pub id: u64,
55    pub name: String,
56    pub email: String,
57}
58
59#[derive(Debug, Serialize, Deserialize, Clone)]
60pub struct QueryOptions {
61    #[serde(default)]
62    pub parameters: Vec<Parameter>,
63}
64
65#[derive(Debug, Serialize, Deserialize, Clone)]
66pub struct Parameter {
67    pub name: String,
68    pub title: String,
69    #[serde(rename = "type")]
70    pub param_type: String,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub value: Option<serde_json::Value>,
73    #[serde(rename = "enumOptions", skip_serializing_if = "Option::is_none")]
74    pub enum_options: Option<String>,
75    #[serde(rename = "queryId", skip_serializing_if = "Option::is_none")]
76    pub query_id: Option<u64>,
77    #[serde(rename = "multiValuesOptions", skip_serializing_if = "Option::is_none")]
78    pub multi_values_options: Option<MultiValuesOptions>,
79}
80
81#[derive(Debug, Serialize, Deserialize, Clone)]
82pub struct MultiValuesOptions {
83    #[serde(rename = "prefix", skip_serializing_if = "Option::is_none")]
84    pub prefix: Option<String>,
85    #[serde(rename = "suffix", skip_serializing_if = "Option::is_none")]
86    pub suffix: Option<String>,
87    #[serde(rename = "separator", skip_serializing_if = "Option::is_none")]
88    pub separator: Option<String>,
89    #[serde(rename = "quoteCharacter", skip_serializing_if = "Option::is_none")]
90    pub quote_character: Option<String>,
91}
92
93#[derive(Debug, Serialize, Deserialize, Clone)]
94pub struct Schedule {
95    pub interval: Option<u64>,
96    pub time: Option<String>,
97    pub day_of_week: Option<String>,
98    pub until: Option<String>,
99}
100
101#[derive(Debug, Serialize, Deserialize, Clone)]
102pub struct Visualization {
103    pub id: u64,
104    pub name: String,
105    #[serde(rename = "type")]
106    pub viz_type: String,
107    pub options: serde_json::Value,
108    pub description: Option<String>,
109}
110
111#[derive(Debug, Serialize, Clone)]
112pub struct CreateVisualization {
113    pub query_id: u64,
114    pub name: String,
115    #[serde(rename = "type")]
116    pub viz_type: String,
117    pub options: serde_json::Value,
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub description: Option<String>,
120}
121
122#[derive(Debug, Serialize, Deserialize)]
123pub struct QueriesResponse {
124    pub results: Vec<Query>,
125    pub count: u64,
126    pub page: u64,
127    pub page_size: u64,
128}
129
130#[derive(Debug, Serialize, Deserialize)]
131pub struct QueryMetadata {
132    pub id: u64,
133    pub name: String,
134    pub description: Option<String>,
135    pub data_source_id: u64,
136    #[serde(default)]
137    pub user_id: Option<u64>,
138    pub schedule: Option<Schedule>,
139    pub options: QueryOptions,
140    pub visualizations: Vec<Visualization>,
141    pub tags: Option<Vec<String>>,
142}
143
144#[derive(Debug, Serialize, Deserialize, Clone)]
145pub struct User {
146    pub id: u64,
147    pub name: String,
148    pub email: String,
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub profile_image_url: Option<String>,
151}
152
153#[derive(Debug, Serialize, Deserialize, Clone)]
154pub struct DataSource {
155    pub id: u64,
156    pub name: String,
157    #[serde(rename = "type")]
158    pub ds_type: String,
159    pub syntax: Option<String>,
160    pub description: Option<String>,
161    pub paused: u8,
162    pub pause_reason: Option<String>,
163    pub view_only: bool,
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub queue_name: Option<String>,
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub scheduled_queue_name: Option<String>,
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub groups: Option<serde_json::Value>,
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub options: Option<serde_json::Value>,
172}
173
174#[derive(Debug, Serialize, Deserialize)]
175pub struct DataSourceSchema {
176    pub schema: Vec<SchemaTable>,
177}
178
179#[derive(Debug, Serialize, Deserialize)]
180pub struct SchemaTable {
181    pub name: String,
182    pub columns: Vec<SchemaColumn>,
183}
184
185#[derive(Debug, Serialize, Deserialize)]
186pub struct SchemaColumn {
187    pub name: String,
188    #[serde(rename = "type")]
189    pub column_type: String,
190}
191
192#[derive(Debug, Serialize, Deserialize)]
193pub struct RefreshRequest {
194    pub max_age: u64,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub parameters: Option<std::collections::HashMap<String, serde_json::Value>>,
197}
198
199#[derive(Debug, Serialize, Deserialize)]
200pub struct JobResponse {
201    pub job: Job,
202}
203
204#[derive(Debug, Serialize, Deserialize)]
205pub struct Job {
206    pub id: String,
207    pub status: u8,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub query_result_id: Option<u64>,
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub error: Option<String>,
212}
213
214#[derive(Debug, Serialize, Deserialize)]
215pub struct QueryResultResponse {
216    pub query_result: QueryResult,
217}
218
219#[derive(Debug, Serialize, Deserialize)]
220pub struct QueryResult {
221    pub id: u64,
222    pub data: QueryResultData,
223    pub runtime: f64,
224    pub retrieved_at: String,
225}
226
227#[derive(Debug, Serialize, Deserialize)]
228pub struct QueryResultData {
229    pub columns: Vec<Column>,
230    pub rows: Vec<serde_json::Value>,
231}
232
233#[derive(Debug, Serialize, Deserialize)]
234pub struct Column {
235    pub name: String,
236    #[serde(rename = "type")]
237    pub type_name: String,
238    #[serde(skip_serializing_if = "Option::is_none")]
239    pub friendly_name: Option<String>,
240}
241
242#[derive(Debug, Clone, Copy)]
243pub enum JobStatus {
244    Pending = 1,
245    Started = 2,
246    Success = 3,
247    Failure = 4,
248    Cancelled = 5,
249}
250
251impl JobStatus {
252    pub fn from_u8(status: u8) -> anyhow::Result<Self> {
253        match status {
254            1 => Ok(Self::Pending),
255            2 => Ok(Self::Started),
256            3 => Ok(Self::Success),
257            4 => Ok(Self::Failure),
258            5 => Ok(Self::Cancelled),
259            _ => Err(anyhow::anyhow!("Invalid job status: {status}")),
260        }
261    }
262}
263
264#[derive(Debug, Serialize, Deserialize)]
265pub struct Dashboard {
266    pub id: u64,
267    pub name: String,
268    pub slug: String,
269    pub user_id: u64,
270    pub is_archived: bool,
271    pub is_draft: bool,
272    #[serde(rename = "dashboard_filters_enabled")]
273    pub filters_enabled: bool,
274    pub tags: Vec<String>,
275    #[serde(default, deserialize_with = "deserialize_null_as_empty_vec")]
276    pub widgets: Vec<Widget>,
277}
278
279#[derive(Debug, Serialize)]
280pub struct CreateDashboard {
281    pub name: String,
282}
283
284#[derive(Debug, Serialize, Deserialize)]
285pub struct Widget {
286    pub id: u64,
287    pub dashboard_id: u64,
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub visualization_id: Option<u64>,
290    #[serde(skip_serializing_if = "Option::is_none")]
291    pub visualization: Option<WidgetVisualization>,
292    #[serde(default)]
293    pub text: String,
294    pub options: WidgetOptions,
295}
296
297#[derive(Debug, Serialize, Deserialize)]
298pub struct WidgetVisualization {
299    pub id: u64,
300    pub name: String,
301    pub query: VisualizationQuery,
302}
303
304#[derive(Debug, Serialize, Deserialize)]
305pub struct VisualizationQuery {
306    pub id: u64,
307    pub name: String,
308}
309
310#[derive(Debug, Serialize, Deserialize, Clone)]
311pub struct WidgetOptions {
312    pub position: WidgetPosition,
313    #[serde(default, skip_serializing_if = "Option::is_none", rename = "parameterMappings")]
314    pub parameter_mappings: Option<serde_json::Value>,
315}
316
317#[derive(Debug, Serialize, Deserialize, Clone)]
318pub struct WidgetPosition {
319    pub col: u32,
320    pub row: u32,
321    #[serde(rename = "sizeX")]
322    pub size_x: u32,
323    #[serde(rename = "sizeY")]
324    pub size_y: u32,
325}
326
327#[derive(Debug, Serialize, Deserialize)]
328pub struct DashboardMetadata {
329    pub id: u64,
330    pub name: String,
331    pub slug: String,
332    pub user_id: u64,
333    pub is_draft: bool,
334    pub is_archived: bool,
335    #[serde(rename = "dashboard_filters_enabled")]
336    pub filters_enabled: bool,
337    pub tags: Vec<String>,
338    pub widgets: Vec<WidgetMetadata>,
339}
340
341#[derive(Debug, Serialize, Deserialize)]
342pub struct WidgetMetadata {
343    pub id: u64,
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub visualization_id: Option<u64>,
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub query_id: Option<u64>,
348    #[serde(skip_serializing_if = "Option::is_none")]
349    pub visualization_name: Option<String>,
350    #[serde(default, skip_serializing_if = "String::is_empty")]
351    pub text: String,
352    pub options: WidgetOptions,
353}
354
355#[derive(Debug, Deserialize)]
356pub struct DashboardsResponse {
357    pub results: Vec<DashboardSummary>,
358    pub count: u64,
359}
360
361#[derive(Debug, Deserialize)]
362pub struct DashboardSummary {
363    #[allow(dead_code)]
364    pub id: u64,
365    pub name: String,
366    #[allow(dead_code)]
367    pub slug: String,
368    pub is_draft: bool,
369    pub is_archived: bool,
370}
371
372#[derive(Debug, Serialize)]
373pub struct CreateWidget {
374    pub dashboard_id: u64,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub visualization_id: Option<u64>,
377    #[serde(default, skip_serializing_if = "String::is_empty")]
378    pub text: String,
379    pub options: WidgetOptions,
380}
381
382#[cfg(test)]
383#[allow(clippy::missing_errors_doc)]
384#[allow(clippy::unnecessary_literal_unwrap)]
385mod tests {
386    use super::*;
387
388    #[test]
389    fn test_job_status_from_u8_valid() {
390        assert!(matches!(JobStatus::from_u8(1).unwrap(), JobStatus::Pending));
391        assert!(matches!(JobStatus::from_u8(2).unwrap(), JobStatus::Started));
392        assert!(matches!(JobStatus::from_u8(3).unwrap(), JobStatus::Success));
393        assert!(matches!(JobStatus::from_u8(4).unwrap(), JobStatus::Failure));
394        assert!(matches!(JobStatus::from_u8(5).unwrap(), JobStatus::Cancelled));
395    }
396
397    #[test]
398    fn test_job_status_from_u8_invalid() {
399        assert!(JobStatus::from_u8(0).is_err());
400        assert!(JobStatus::from_u8(6).is_err());
401        assert!(JobStatus::from_u8(255).is_err());
402
403        let err = JobStatus::from_u8(10).unwrap_err();
404        assert!(err.to_string().contains("Invalid job status"));
405    }
406
407    #[test]
408    fn test_query_serialization() {
409        let query = Query {
410            id: 1,
411            name: "Test Query".to_string(),
412            description: None,
413            sql: "SELECT * FROM table".to_string(),
414            data_source_id: 63,
415            user: None,
416            schedule: None,
417            options: QueryOptions { parameters: vec![] },
418            visualizations: vec![],
419            tags: None,
420            is_archived: false,
421            is_draft: false,
422            updated_at: "2026-01-21".to_string(),
423            created_at: "2026-01-21".to_string(),
424        };
425
426        let json = serde_json::to_string(&query).unwrap();
427        assert!(json.contains("\"query\":"));
428        assert!(json.contains("SELECT * FROM table"));
429    }
430
431    #[test]
432    fn test_query_metadata_deserialization() {
433        let yaml = r"
434id: 100064
435name: Test Query
436description: null
437data_source_id: 63
438user_id: 530
439schedule: null
440options:
441  parameters:
442    - name: project
443      title: project
444      type: enum
445      value:
446        - try
447      enumOptions: |
448        try
449        autoland
450visualizations: []
451tags:
452  - bug 1840828
453";
454
455        let metadata: QueryMetadata = serde_yaml::from_str(yaml).unwrap();
456        assert_eq!(metadata.id, 100_064);
457        assert_eq!(metadata.name, "Test Query");
458        assert_eq!(metadata.data_source_id, 63);
459        assert_eq!(metadata.options.parameters.len(), 1);
460        assert_eq!(metadata.options.parameters[0].name, "project");
461    }
462
463    #[test]
464    fn test_datasource_deserialization() {
465        let json = r#"{
466            "id": 63,
467            "name": "Test DB",
468            "type": "bigquery",
469            "description": null,
470            "syntax": "sql",
471            "paused": 0,
472            "pause_reason": null,
473            "view_only": false,
474            "queue_name": "queries",
475            "scheduled_queue_name": "scheduled_queries",
476            "groups": {},
477            "options": {}
478        }"#;
479
480        let ds: DataSource = serde_json::from_str(json).unwrap();
481        assert_eq!(ds.id, 63);
482        assert_eq!(ds.name, "Test DB");
483        assert_eq!(ds.ds_type, "bigquery");
484        assert_eq!(ds.syntax, Some("sql".to_string()));
485        assert_eq!(ds.description, None);
486        assert_eq!(ds.paused, 0);
487        assert!(!ds.view_only);
488        assert_eq!(ds.queue_name, Some("queries".to_string()));
489    }
490
491    #[test]
492    fn test_datasource_with_nulls() {
493        let json = r#"{
494            "id": 10,
495            "name": "Minimal DB",
496            "type": "pg",
497            "description": "Test description",
498            "syntax": null,
499            "paused": 1,
500            "pause_reason": "Maintenance",
501            "view_only": true,
502            "queue_name": null,
503            "scheduled_queue_name": null,
504            "groups": null,
505            "options": null
506        }"#;
507
508        let ds: DataSource = serde_json::from_str(json).unwrap();
509        assert_eq!(ds.id, 10);
510        assert_eq!(ds.name, "Minimal DB");
511        assert_eq!(ds.ds_type, "pg");
512        assert_eq!(ds.description, Some("Test description".to_string()));
513        assert_eq!(ds.syntax, None);
514        assert_eq!(ds.paused, 1);
515        assert_eq!(ds.pause_reason, Some("Maintenance".to_string()));
516        assert!(ds.view_only);
517        assert_eq!(ds.queue_name, None);
518    }
519
520    #[test]
521    fn test_datasource_schema_deserialization() {
522        let json = r#"{
523            "schema": [
524                {
525                    "name": "table1",
526                    "columns": [
527                        {"name": "col1", "type": "STRING"},
528                        {"name": "col2", "type": "INTEGER"}
529                    ]
530                },
531                {
532                    "name": "table2",
533                    "columns": [{"name": "id", "type": "INTEGER"}]
534                }
535            ]
536        }"#;
537
538        let schema: DataSourceSchema = serde_json::from_str(json).unwrap();
539        assert_eq!(schema.schema.len(), 2);
540        assert_eq!(schema.schema[0].name, "table1");
541        assert_eq!(schema.schema[0].columns.len(), 2);
542        assert_eq!(schema.schema[0].columns[0].name, "col1");
543        assert_eq!(schema.schema[0].columns[0].column_type, "STRING");
544        assert_eq!(schema.schema[1].name, "table2");
545        assert_eq!(schema.schema[1].columns.len(), 1);
546    }
547
548    #[test]
549    fn test_schema_table_structure() {
550        let json = r#"{
551            "name": "users",
552            "columns": [
553                {"name": "id", "type": "INTEGER"},
554                {"name": "name", "type": "STRING"},
555                {"name": "email", "type": "STRING"}
556            ]
557        }"#;
558
559        let table: SchemaTable = serde_json::from_str(json).unwrap();
560        assert_eq!(table.name, "users");
561        assert_eq!(table.columns.len(), 3);
562        assert_eq!(table.columns[0].name, "id");
563        assert_eq!(table.columns[0].column_type, "INTEGER");
564        assert_eq!(table.columns[1].name, "name");
565        assert_eq!(table.columns[1].column_type, "STRING");
566        assert_eq!(table.columns[2].name, "email");
567        assert_eq!(table.columns[2].column_type, "STRING");
568    }
569
570    #[test]
571    fn test_datasource_serialization() {
572        let ds = DataSource {
573            id: 123,
574            name: "My DB".to_string(),
575            ds_type: "mysql".to_string(),
576            syntax: Some("sql".to_string()),
577            description: Some("Test".to_string()),
578            paused: 0,
579            pause_reason: None,
580            view_only: false,
581            queue_name: Some("queries".to_string()),
582            scheduled_queue_name: None,
583            groups: None,
584            options: None,
585        };
586
587        let json = serde_json::to_string(&ds).unwrap();
588        assert!(json.contains("\"id\":123"));
589        assert!(json.contains("\"name\":\"My DB\""));
590        assert!(json.contains("\"type\":\"mysql\""));
591        assert!(json.contains("\"syntax\":\"sql\""));
592    }
593
594    #[test]
595    fn test_dashboard_deserialization() {
596        let json = r#"{
597            "id": 2570,
598            "name": "Test Dashboard",
599            "slug": "test-dashboard",
600            "user_id": 530,
601            "is_archived": false,
602            "is_draft": false,
603            "dashboard_filters_enabled": true,
604            "tags": ["tag1", "tag2"],
605            "widgets": []
606        }"#;
607
608        let dashboard: Dashboard = serde_json::from_str(json).unwrap();
609        assert_eq!(dashboard.id, 2570);
610        assert_eq!(dashboard.name, "Test Dashboard");
611        assert_eq!(dashboard.slug, "test-dashboard");
612        assert_eq!(dashboard.user_id, 530);
613        assert!(!dashboard.is_archived);
614        assert!(!dashboard.is_draft);
615        assert!(dashboard.filters_enabled);
616        assert_eq!(dashboard.tags, vec!["tag1", "tag2"]);
617        assert_eq!(dashboard.widgets.len(), 0);
618    }
619
620    #[test]
621    fn test_dashboard_with_widgets() {
622        let json = r##"{
623            "id": 2570,
624            "name": "Test Dashboard",
625            "slug": "test-dashboard",
626            "user_id": 530,
627            "is_archived": false,
628            "is_draft": false,
629            "dashboard_filters_enabled": false,
630            "tags": [],
631            "widgets": [
632                {
633                    "id": 75035,
634                    "dashboard_id": 2570,
635                    "text": "# Test Widget",
636                    "options": {
637                        "position": {
638                            "col": 0,
639                            "row": 0,
640                            "sizeX": 6,
641                            "sizeY": 2
642                        }
643                    }
644                },
645                {
646                    "id": 75029,
647                    "dashboard_id": 2570,
648                    "visualization_id": 279588,
649                    "visualization": {
650                        "id": 279588,
651                        "name": "Total MAU",
652                        "query": {
653                            "id": 114049,
654                            "name": "MAU Query"
655                        }
656                    },
657                    "text": "",
658                    "options": {
659                        "position": {
660                            "col": 3,
661                            "row": 2,
662                            "sizeX": 3,
663                            "sizeY": 8
664                        },
665                        "parameterMappings": {
666                            "channel": {
667                                "name": "channel",
668                                "type": "dashboard-level"
669                            }
670                        }
671                    }
672                }
673            ]
674        }"##;
675
676        let dashboard: Dashboard = serde_json::from_str(json).unwrap();
677        assert_eq!(dashboard.widgets.len(), 2);
678        assert_eq!(dashboard.widgets[0].id, 75035);
679        assert_eq!(dashboard.widgets[0].text, "# Test Widget");
680        assert!(dashboard.widgets[0].visualization_id.is_none());
681        assert_eq!(dashboard.widgets[1].id, 75029);
682        assert_eq!(dashboard.widgets[1].visualization_id, Some(279_588));
683        let viz = dashboard.widgets[1].visualization.as_ref().unwrap();
684        assert_eq!(viz.id, 279_588);
685        assert_eq!(viz.query.id, 114_049);
686    }
687
688    #[test]
689    fn test_widget_position_serde() {
690        let json = r#"{
691            "col": 3,
692            "row": 5,
693            "sizeX": 6,
694            "sizeY": 4
695        }"#;
696
697        let position: WidgetPosition = serde_json::from_str(json).unwrap();
698        assert_eq!(position.col, 3);
699        assert_eq!(position.row, 5);
700        assert_eq!(position.size_x, 6);
701        assert_eq!(position.size_y, 4);
702
703        let serialized = serde_json::to_string(&position).unwrap();
704        assert!(serialized.contains("\"sizeX\":6"));
705        assert!(serialized.contains("\"sizeY\":4"));
706    }
707
708    #[test]
709    fn test_dashboard_metadata_yaml() {
710        let yaml = r"
711id: 2570
712name: Test Dashboard
713slug: test-dashboard
714user_id: 530
715is_draft: false
716is_archived: false
717dashboard_filters_enabled: true
718tags:
719  - tag1
720  - tag2
721widgets:
722  - id: 75035
723    visualization_id: null
724    query_id: null
725    visualization_name: null
726    text: '# Test Widget'
727    options:
728      position:
729        col: 0
730        row: 0
731        sizeX: 6
732        sizeY: 2
733      parameter_mappings: null
734";
735
736        let metadata: DashboardMetadata = serde_yaml::from_str(yaml).unwrap();
737        assert_eq!(metadata.id, 2570);
738        assert_eq!(metadata.name, "Test Dashboard");
739        assert_eq!(metadata.slug, "test-dashboard");
740        assert_eq!(metadata.user_id, 530);
741        assert!(!metadata.is_draft);
742        assert!(!metadata.is_archived);
743        assert!(metadata.filters_enabled);
744        assert_eq!(metadata.tags, vec!["tag1", "tag2"]);
745        assert_eq!(metadata.widgets.len(), 1);
746        assert_eq!(metadata.widgets[0].id, 75035);
747        assert_eq!(metadata.widgets[0].text, "# Test Widget");
748    }
749
750    #[test]
751    fn test_widget_metadata_text_widget() {
752        let yaml = r"
753id: 75035
754visualization_id: null
755query_id: null
756visualization_name: null
757text: '## Section Header'
758options:
759  position:
760    col: 0
761    row: 0
762    sizeX: 6
763    sizeY: 2
764  parameter_mappings: null
765";
766
767        let widget: WidgetMetadata = serde_yaml::from_str(yaml).unwrap();
768        assert_eq!(widget.id, 75035);
769        assert!(widget.visualization_id.is_none());
770        assert!(widget.query_id.is_none());
771        assert!(widget.visualization_name.is_none());
772        assert_eq!(widget.text, "## Section Header");
773        assert_eq!(widget.options.position.col, 0);
774        assert_eq!(widget.options.position.size_x, 6);
775    }
776
777    #[test]
778    fn test_widget_metadata_viz_widget() {
779        let yaml = r"
780id: 75029
781visualization_id: 279588
782query_id: 114049
783visualization_name: Total MAU
784text: ''
785options:
786  position:
787    col: 3
788    row: 2
789    sizeX: 3
790    sizeY: 8
791  parameterMappings:
792    channel:
793      name: channel
794      type: dashboard-level
795";
796
797        let widget: WidgetMetadata = serde_yaml::from_str(yaml).unwrap();
798        assert_eq!(widget.id, 75029);
799        assert_eq!(widget.visualization_id, Some(279_588));
800        assert_eq!(widget.query_id, Some(114_049));
801        assert_eq!(widget.visualization_name, Some("Total MAU".to_string()));
802        assert_eq!(widget.text, "");
803        assert!(widget.options.parameter_mappings.is_some());
804    }
805
806    #[test]
807    fn test_create_widget_serialization() {
808        let widget = CreateWidget {
809            dashboard_id: 2570,
810            visualization_id: Some(279_588),
811            text: String::new(),
812            options: WidgetOptions {
813                position: WidgetPosition {
814                    col: 0,
815                    row: 0,
816                    size_x: 3,
817                    size_y: 2,
818                },
819                parameter_mappings: None,
820            },
821        };
822
823        let json = serde_json::to_string(&widget).unwrap();
824        assert!(json.contains("\"dashboard_id\":2570"));
825        assert!(json.contains("\"visualization_id\":279588"));
826        assert!(json.contains("\"sizeX\":3"));
827        assert!(json.contains("\"sizeY\":2"));
828    }
829
830    #[test]
831    fn test_dashboards_response() {
832        let json = r#"{
833            "results": [
834                {
835                    "id": 2570,
836                    "name": "Dashboard 1",
837                    "slug": "dashboard-1",
838                    "is_draft": false,
839                    "is_archived": false
840                },
841                {
842                    "id": 2558,
843                    "name": "Dashboard 2",
844                    "slug": "dashboard-2",
845                    "is_draft": true,
846                    "is_archived": false
847                }
848            ],
849            "count": 2
850        }"#;
851
852        let response: DashboardsResponse = serde_json::from_str(json).unwrap();
853        assert_eq!(response.results.len(), 2);
854        assert_eq!(response.count, 2);
855        assert_eq!(response.results[0].id, 2570);
856        assert_eq!(response.results[0].name, "Dashboard 1");
857        assert_eq!(response.results[0].slug, "dashboard-1");
858        assert!(!response.results[0].is_draft);
859        assert!(!response.results[0].is_archived);
860        assert_eq!(response.results[1].id, 2558);
861        assert_eq!(response.results[1].slug, "dashboard-2");
862        assert!(response.results[1].is_draft);
863    }
864}