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    pub text: String,
378    pub width: u32,
379    pub options: WidgetOptions,
380}
381
382#[must_use]
383pub fn build_dashboard_level_parameter_mappings(parameters: &[Parameter]) -> serde_json::Value {
384    let mut mappings = serde_json::Map::new();
385    for param in parameters {
386        mappings.insert(param.name.clone(), serde_json::json!({
387            "mapTo": param.name,
388            "name": param.name,
389            "title": "",
390            "type": "dashboard-level",
391            "value": null,
392        }));
393    }
394    serde_json::Value::Object(mappings)
395}
396
397#[cfg(test)]
398#[allow(clippy::missing_errors_doc)]
399#[allow(clippy::unnecessary_literal_unwrap)]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn test_job_status_from_u8_valid() {
405        assert!(matches!(JobStatus::from_u8(1).unwrap(), JobStatus::Pending));
406        assert!(matches!(JobStatus::from_u8(2).unwrap(), JobStatus::Started));
407        assert!(matches!(JobStatus::from_u8(3).unwrap(), JobStatus::Success));
408        assert!(matches!(JobStatus::from_u8(4).unwrap(), JobStatus::Failure));
409        assert!(matches!(JobStatus::from_u8(5).unwrap(), JobStatus::Cancelled));
410    }
411
412    #[test]
413    fn test_job_status_from_u8_invalid() {
414        assert!(JobStatus::from_u8(0).is_err());
415        assert!(JobStatus::from_u8(6).is_err());
416        assert!(JobStatus::from_u8(255).is_err());
417
418        let err = JobStatus::from_u8(10).unwrap_err();
419        assert!(err.to_string().contains("Invalid job status"));
420    }
421
422    #[test]
423    fn test_query_serialization() {
424        let query = Query {
425            id: 1,
426            name: "Test Query".to_string(),
427            description: None,
428            sql: "SELECT * FROM table".to_string(),
429            data_source_id: 63,
430            user: None,
431            schedule: None,
432            options: QueryOptions { parameters: vec![] },
433            visualizations: vec![],
434            tags: None,
435            is_archived: false,
436            is_draft: false,
437            updated_at: "2026-01-21".to_string(),
438            created_at: "2026-01-21".to_string(),
439        };
440
441        let json = serde_json::to_string(&query).unwrap();
442        assert!(json.contains("\"query\":"));
443        assert!(json.contains("SELECT * FROM table"));
444    }
445
446    #[test]
447    fn test_query_metadata_deserialization() {
448        let yaml = r"
449id: 100064
450name: Test Query
451description: null
452data_source_id: 63
453user_id: 530
454schedule: null
455options:
456  parameters:
457    - name: project
458      title: project
459      type: enum
460      value:
461        - try
462      enumOptions: |
463        try
464        autoland
465visualizations: []
466tags:
467  - bug 1840828
468";
469
470        let metadata: QueryMetadata = serde_yaml::from_str(yaml).unwrap();
471        assert_eq!(metadata.id, 100_064);
472        assert_eq!(metadata.name, "Test Query");
473        assert_eq!(metadata.data_source_id, 63);
474        assert_eq!(metadata.options.parameters.len(), 1);
475        assert_eq!(metadata.options.parameters[0].name, "project");
476    }
477
478    #[test]
479    fn test_datasource_deserialization() {
480        let json = r#"{
481            "id": 63,
482            "name": "Test DB",
483            "type": "bigquery",
484            "description": null,
485            "syntax": "sql",
486            "paused": 0,
487            "pause_reason": null,
488            "view_only": false,
489            "queue_name": "queries",
490            "scheduled_queue_name": "scheduled_queries",
491            "groups": {},
492            "options": {}
493        }"#;
494
495        let ds: DataSource = serde_json::from_str(json).unwrap();
496        assert_eq!(ds.id, 63);
497        assert_eq!(ds.name, "Test DB");
498        assert_eq!(ds.ds_type, "bigquery");
499        assert_eq!(ds.syntax, Some("sql".to_string()));
500        assert_eq!(ds.description, None);
501        assert_eq!(ds.paused, 0);
502        assert!(!ds.view_only);
503        assert_eq!(ds.queue_name, Some("queries".to_string()));
504    }
505
506    #[test]
507    fn test_datasource_with_nulls() {
508        let json = r#"{
509            "id": 10,
510            "name": "Minimal DB",
511            "type": "pg",
512            "description": "Test description",
513            "syntax": null,
514            "paused": 1,
515            "pause_reason": "Maintenance",
516            "view_only": true,
517            "queue_name": null,
518            "scheduled_queue_name": null,
519            "groups": null,
520            "options": null
521        }"#;
522
523        let ds: DataSource = serde_json::from_str(json).unwrap();
524        assert_eq!(ds.id, 10);
525        assert_eq!(ds.name, "Minimal DB");
526        assert_eq!(ds.ds_type, "pg");
527        assert_eq!(ds.description, Some("Test description".to_string()));
528        assert_eq!(ds.syntax, None);
529        assert_eq!(ds.paused, 1);
530        assert_eq!(ds.pause_reason, Some("Maintenance".to_string()));
531        assert!(ds.view_only);
532        assert_eq!(ds.queue_name, None);
533    }
534
535    #[test]
536    fn test_datasource_schema_deserialization() {
537        let json = r#"{
538            "schema": [
539                {
540                    "name": "table1",
541                    "columns": [
542                        {"name": "col1", "type": "STRING"},
543                        {"name": "col2", "type": "INTEGER"}
544                    ]
545                },
546                {
547                    "name": "table2",
548                    "columns": [{"name": "id", "type": "INTEGER"}]
549                }
550            ]
551        }"#;
552
553        let schema: DataSourceSchema = serde_json::from_str(json).unwrap();
554        assert_eq!(schema.schema.len(), 2);
555        assert_eq!(schema.schema[0].name, "table1");
556        assert_eq!(schema.schema[0].columns.len(), 2);
557        assert_eq!(schema.schema[0].columns[0].name, "col1");
558        assert_eq!(schema.schema[0].columns[0].column_type, "STRING");
559        assert_eq!(schema.schema[1].name, "table2");
560        assert_eq!(schema.schema[1].columns.len(), 1);
561    }
562
563    #[test]
564    fn test_schema_table_structure() {
565        let json = r#"{
566            "name": "users",
567            "columns": [
568                {"name": "id", "type": "INTEGER"},
569                {"name": "name", "type": "STRING"},
570                {"name": "email", "type": "STRING"}
571            ]
572        }"#;
573
574        let table: SchemaTable = serde_json::from_str(json).unwrap();
575        assert_eq!(table.name, "users");
576        assert_eq!(table.columns.len(), 3);
577        assert_eq!(table.columns[0].name, "id");
578        assert_eq!(table.columns[0].column_type, "INTEGER");
579        assert_eq!(table.columns[1].name, "name");
580        assert_eq!(table.columns[1].column_type, "STRING");
581        assert_eq!(table.columns[2].name, "email");
582        assert_eq!(table.columns[2].column_type, "STRING");
583    }
584
585    #[test]
586    fn test_datasource_serialization() {
587        let ds = DataSource {
588            id: 123,
589            name: "My DB".to_string(),
590            ds_type: "mysql".to_string(),
591            syntax: Some("sql".to_string()),
592            description: Some("Test".to_string()),
593            paused: 0,
594            pause_reason: None,
595            view_only: false,
596            queue_name: Some("queries".to_string()),
597            scheduled_queue_name: None,
598            groups: None,
599            options: None,
600        };
601
602        let json = serde_json::to_string(&ds).unwrap();
603        assert!(json.contains("\"id\":123"));
604        assert!(json.contains("\"name\":\"My DB\""));
605        assert!(json.contains("\"type\":\"mysql\""));
606        assert!(json.contains("\"syntax\":\"sql\""));
607    }
608
609    #[test]
610    fn test_dashboard_deserialization() {
611        let json = r#"{
612            "id": 2570,
613            "name": "Test Dashboard",
614            "slug": "test-dashboard",
615            "user_id": 530,
616            "is_archived": false,
617            "is_draft": false,
618            "dashboard_filters_enabled": true,
619            "tags": ["tag1", "tag2"],
620            "widgets": []
621        }"#;
622
623        let dashboard: Dashboard = serde_json::from_str(json).unwrap();
624        assert_eq!(dashboard.id, 2570);
625        assert_eq!(dashboard.name, "Test Dashboard");
626        assert_eq!(dashboard.slug, "test-dashboard");
627        assert_eq!(dashboard.user_id, 530);
628        assert!(!dashboard.is_archived);
629        assert!(!dashboard.is_draft);
630        assert!(dashboard.filters_enabled);
631        assert_eq!(dashboard.tags, vec!["tag1", "tag2"]);
632        assert_eq!(dashboard.widgets.len(), 0);
633    }
634
635    #[test]
636    fn test_dashboard_with_widgets() {
637        let json = r##"{
638            "id": 2570,
639            "name": "Test Dashboard",
640            "slug": "test-dashboard",
641            "user_id": 530,
642            "is_archived": false,
643            "is_draft": false,
644            "dashboard_filters_enabled": false,
645            "tags": [],
646            "widgets": [
647                {
648                    "id": 75035,
649                    "dashboard_id": 2570,
650                    "text": "# Test Widget",
651                    "options": {
652                        "position": {
653                            "col": 0,
654                            "row": 0,
655                            "sizeX": 6,
656                            "sizeY": 2
657                        }
658                    }
659                },
660                {
661                    "id": 75029,
662                    "dashboard_id": 2570,
663                    "visualization_id": 279588,
664                    "visualization": {
665                        "id": 279588,
666                        "name": "Total MAU",
667                        "query": {
668                            "id": 114049,
669                            "name": "MAU Query"
670                        }
671                    },
672                    "text": "",
673                    "options": {
674                        "position": {
675                            "col": 3,
676                            "row": 2,
677                            "sizeX": 3,
678                            "sizeY": 8
679                        },
680                        "parameterMappings": {
681                            "channel": {
682                                "name": "channel",
683                                "type": "dashboard-level"
684                            }
685                        }
686                    }
687                }
688            ]
689        }"##;
690
691        let dashboard: Dashboard = serde_json::from_str(json).unwrap();
692        assert_eq!(dashboard.widgets.len(), 2);
693        assert_eq!(dashboard.widgets[0].id, 75035);
694        assert_eq!(dashboard.widgets[0].text, "# Test Widget");
695        assert!(dashboard.widgets[0].visualization_id.is_none());
696        assert_eq!(dashboard.widgets[1].id, 75029);
697        assert_eq!(dashboard.widgets[1].visualization_id, Some(279_588));
698        let viz = dashboard.widgets[1].visualization.as_ref().unwrap();
699        assert_eq!(viz.id, 279_588);
700        assert_eq!(viz.query.id, 114_049);
701    }
702
703    #[test]
704    fn test_widget_position_serde() {
705        let json = r#"{
706            "col": 3,
707            "row": 5,
708            "sizeX": 6,
709            "sizeY": 4
710        }"#;
711
712        let position: WidgetPosition = serde_json::from_str(json).unwrap();
713        assert_eq!(position.col, 3);
714        assert_eq!(position.row, 5);
715        assert_eq!(position.size_x, 6);
716        assert_eq!(position.size_y, 4);
717
718        let serialized = serde_json::to_string(&position).unwrap();
719        assert!(serialized.contains("\"sizeX\":6"));
720        assert!(serialized.contains("\"sizeY\":4"));
721    }
722
723    #[test]
724    fn test_dashboard_metadata_yaml() {
725        let yaml = r"
726id: 2570
727name: Test Dashboard
728slug: test-dashboard
729user_id: 530
730is_draft: false
731is_archived: false
732dashboard_filters_enabled: true
733tags:
734  - tag1
735  - tag2
736widgets:
737  - id: 75035
738    visualization_id: null
739    query_id: null
740    visualization_name: null
741    text: '# Test Widget'
742    options:
743      position:
744        col: 0
745        row: 0
746        sizeX: 6
747        sizeY: 2
748      parameter_mappings: null
749";
750
751        let metadata: DashboardMetadata = serde_yaml::from_str(yaml).unwrap();
752        assert_eq!(metadata.id, 2570);
753        assert_eq!(metadata.name, "Test Dashboard");
754        assert_eq!(metadata.slug, "test-dashboard");
755        assert_eq!(metadata.user_id, 530);
756        assert!(!metadata.is_draft);
757        assert!(!metadata.is_archived);
758        assert!(metadata.filters_enabled);
759        assert_eq!(metadata.tags, vec!["tag1", "tag2"]);
760        assert_eq!(metadata.widgets.len(), 1);
761        assert_eq!(metadata.widgets[0].id, 75035);
762        assert_eq!(metadata.widgets[0].text, "# Test Widget");
763    }
764
765    #[test]
766    fn test_widget_metadata_text_widget() {
767        let yaml = r"
768id: 75035
769visualization_id: null
770query_id: null
771visualization_name: null
772text: '## Section Header'
773options:
774  position:
775    col: 0
776    row: 0
777    sizeX: 6
778    sizeY: 2
779  parameter_mappings: null
780";
781
782        let widget: WidgetMetadata = serde_yaml::from_str(yaml).unwrap();
783        assert_eq!(widget.id, 75035);
784        assert!(widget.visualization_id.is_none());
785        assert!(widget.query_id.is_none());
786        assert!(widget.visualization_name.is_none());
787        assert_eq!(widget.text, "## Section Header");
788        assert_eq!(widget.options.position.col, 0);
789        assert_eq!(widget.options.position.size_x, 6);
790    }
791
792    #[test]
793    fn test_widget_metadata_viz_widget() {
794        let yaml = r"
795id: 75029
796visualization_id: 279588
797query_id: 114049
798visualization_name: Total MAU
799text: ''
800options:
801  position:
802    col: 3
803    row: 2
804    sizeX: 3
805    sizeY: 8
806  parameterMappings:
807    channel:
808      name: channel
809      type: dashboard-level
810";
811
812        let widget: WidgetMetadata = serde_yaml::from_str(yaml).unwrap();
813        assert_eq!(widget.id, 75029);
814        assert_eq!(widget.visualization_id, Some(279_588));
815        assert_eq!(widget.query_id, Some(114_049));
816        assert_eq!(widget.visualization_name, Some("Total MAU".to_string()));
817        assert_eq!(widget.text, "");
818        assert!(widget.options.parameter_mappings.is_some());
819    }
820
821    #[test]
822    fn test_create_widget_serialization() {
823        let widget = CreateWidget {
824            dashboard_id: 2570,
825            visualization_id: Some(279_588),
826            text: String::new(),
827            width: 1,
828            options: WidgetOptions {
829                position: WidgetPosition {
830                    col: 0,
831                    row: 0,
832                    size_x: 3,
833                    size_y: 2,
834                },
835                parameter_mappings: None,
836            },
837        };
838
839        let json = serde_json::to_string(&widget).unwrap();
840        assert!(json.contains("\"dashboard_id\":2570"));
841        assert!(json.contains("\"visualization_id\":279588"));
842        assert!(json.contains("\"sizeX\":3"));
843        assert!(json.contains("\"sizeY\":2"));
844    }
845
846    #[test]
847    fn test_dashboards_response() {
848        let json = r#"{
849            "results": [
850                {
851                    "id": 2570,
852                    "name": "Dashboard 1",
853                    "slug": "dashboard-1",
854                    "is_draft": false,
855                    "is_archived": false
856                },
857                {
858                    "id": 2558,
859                    "name": "Dashboard 2",
860                    "slug": "dashboard-2",
861                    "is_draft": true,
862                    "is_archived": false
863                }
864            ],
865            "count": 2
866        }"#;
867
868        let response: DashboardsResponse = serde_json::from_str(json).unwrap();
869        assert_eq!(response.results.len(), 2);
870        assert_eq!(response.count, 2);
871        assert_eq!(response.results[0].id, 2570);
872        assert_eq!(response.results[0].name, "Dashboard 1");
873        assert_eq!(response.results[0].slug, "dashboard-1");
874        assert!(!response.results[0].is_draft);
875        assert!(!response.results[0].is_archived);
876        assert_eq!(response.results[1].id, 2558);
877        assert_eq!(response.results[1].slug, "dashboard-2");
878        assert!(response.results[1].is_draft);
879    }
880
881    #[test]
882    fn test_build_dashboard_level_parameter_mappings_empty() {
883        let result = build_dashboard_level_parameter_mappings(&[]);
884        assert_eq!(result, serde_json::json!({}));
885    }
886
887    #[test]
888    fn test_build_dashboard_level_parameter_mappings_with_params() {
889        let params = vec![
890            Parameter {
891                name: "channel".to_string(),
892                title: "Channel".to_string(),
893                param_type: "enum".to_string(),
894                value: None,
895                enum_options: None,
896                query_id: None,
897                multi_values_options: None,
898            },
899            Parameter {
900                name: "date".to_string(),
901                title: "Date".to_string(),
902                param_type: "date".to_string(),
903                value: None,
904                enum_options: None,
905                query_id: None,
906                multi_values_options: None,
907            },
908        ];
909
910        let result = build_dashboard_level_parameter_mappings(&params);
911
912        let expected = serde_json::json!({
913            "channel": {
914                "mapTo": "channel",
915                "name": "channel",
916                "title": "",
917                "type": "dashboard-level",
918                "value": null,
919            },
920            "date": {
921                "mapTo": "date",
922                "name": "date",
923                "title": "",
924                "type": "dashboard-level",
925                "value": null,
926            },
927        });
928
929        assert_eq!(result, expected);
930    }
931}