volumeleaders-client 0.1.2

Browser-session API client for VolumeLeaders data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Alert configuration and alert DataTables endpoints.

use serde::Serialize;
use tracing::instrument;

use crate::client::Client;
use crate::datatables::{
    DataTablesColumn, DataTablesRequest, DataTablesResponse, fetch_limit,
    impl_datatables_request_methods,
};
use crate::error::Result;
use crate::models::{AlertConfig, TradeAlert, TradeClusterAlert};

/// Browser endpoint path for saving alert configurations.
pub(crate) const ALERT_CONFIG_PATH: &str = "/AlertConfig";

/// Browser endpoint path for alert configuration DataTables rows.
pub(crate) const ALERT_CONFIGS_GET_ALERT_CONFIGS_PATH: &str = "/AlertConfigs/GetAlertConfigs";

/// Browser endpoint path for deleting alert configurations.
pub(crate) const ALERT_CONFIGS_DELETE_ALERT_CONFIG_PATH: &str = "/AlertConfigs/DeleteAlertConfig";

/// Browser endpoint path for trade alert DataTables rows.
pub(crate) const TRADE_ALERTS_GET_TRADE_ALERTS_PATH: &str = "/TradeAlerts/GetTradeAlerts";

/// Browser endpoint path for trade cluster alert DataTables rows.
pub(crate) const TRADE_CLUSTER_ALERTS_GET_TRADE_CLUSTER_ALERTS_PATH: &str =
    "/TradeClusterAlerts/GetTradeClusterAlerts";

/// Redirect path VolumeLeaders uses after a successful alert configuration save.
const ALERT_CONFIGS_SUCCESS_REDIRECT: &str = "/AlertConfigs";

/// Request parameters for `/AlertConfigs/GetAlertConfigs`.
#[derive(Clone, Debug)]
pub struct AlertConfigsRequest(pub(crate) DataTablesRequest);

impl_datatables_request_methods!(AlertConfigsRequest);

impl AlertConfigsRequest {
    /// Create an alert configs request with default column definitions.
    #[must_use]
    pub fn new() -> Self {
        Self(DataTablesRequest {
            columns: alert_configs_columns(),
            ..DataTablesRequest::default()
        })
    }

    /// Return raw key-value pairs for form submission.
    pub(crate) fn to_pairs(&self) -> Vec<(String, String)> {
        self.0.to_pairs()
    }
}

impl Default for AlertConfigsRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// Request parameters for `/TradeAlerts/GetTradeAlerts`.
#[derive(Clone, Debug)]
pub struct TradeAlertsRequest(pub(crate) DataTablesRequest);

impl_datatables_request_methods!(TradeAlertsRequest);

impl TradeAlertsRequest {
    /// Create a trade alerts request with default column definitions.
    #[must_use]
    pub fn new() -> Self {
        Self(DataTablesRequest {
            columns: trade_alerts_columns(),
            ..DataTablesRequest::default()
        })
    }

    /// Set the alert date filter.
    #[must_use]
    pub fn with_date(mut self, date: impl Into<String>) -> Self {
        self.0 = self.0.with_extra_value("Date", date);
        self
    }

    /// Return raw key-value pairs for form submission.
    pub(crate) fn to_pairs(&self) -> Vec<(String, String)> {
        self.0.to_pairs()
    }
}

impl Default for TradeAlertsRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// Request parameters for `/TradeClusterAlerts/GetTradeClusterAlerts`.
#[derive(Clone, Debug)]
pub struct TradeClusterAlertsRequest(pub(crate) DataTablesRequest);

impl_datatables_request_methods!(TradeClusterAlertsRequest);

impl TradeClusterAlertsRequest {
    /// Create a trade cluster alerts request with default column definitions.
    #[must_use]
    pub fn new() -> Self {
        Self(DataTablesRequest {
            columns: trade_cluster_alerts_columns(),
            ..DataTablesRequest::default()
        })
    }

    /// Set the alert date filter.
    #[must_use]
    pub fn with_date(mut self, date: impl Into<String>) -> Self {
        self.0 = self.0.with_extra_value("Date", date);
        self
    }

    /// Return raw key-value pairs for form submission.
    pub(crate) fn to_pairs(&self) -> Vec<(String, String)> {
        self.0.to_pairs()
    }
}

impl Default for TradeClusterAlertsRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// Multipart form payload for creating or editing an alert configuration.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SaveAlertConfigRequest {
    /// Raw browser field names and values accepted by VolumeLeaders.
    fields: Vec<(String, String)>,
}

/// Typed values for creating or editing an alert configuration.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SaveAlertConfigFields {
    pub alert_config_key: i64,
    pub name: String,
    pub ticker_group: String,
    pub tickers: String,
    pub trade_rank_lte: i64,
    pub trade_vcd_gte: i64,
    pub trade_mult_gte: i64,
    pub trade_volume_gte: i64,
    pub trade_dollars_gte: i64,
    pub trade_conditions: String,
    pub dark_pool: bool,
    pub sweep: bool,
    pub closing_trade_rank_lte: i64,
    pub closing_trade_vcd_gte: i64,
    pub closing_trade_mult_gte: i64,
    pub closing_trade_volume_gte: i64,
    pub closing_trade_dollars_gte: i64,
    pub closing_trade_conditions: String,
    pub cluster_rank_lte: i64,
    pub cluster_vcd_gte: i64,
    pub cluster_mult_gte: i64,
    pub cluster_volume_gte: i64,
    pub cluster_dollars_gte: i64,
    pub total_rank_lte: i64,
    pub total_volume_gte: i64,
    pub total_dollars_gte: i64,
    pub ah_rank_lte: i64,
    pub ah_volume_gte: i64,
    pub ah_dollars_gte: i64,
    pub offsetting_print: bool,
    pub phantom_print: bool,
}

impl SaveAlertConfigRequest {
    /// Create a save request from captured browser form fields in client tests.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn new(fields: Vec<(String, String)>) -> Self {
        Self { fields }
    }

    /// Return the encoded browser form fields for assertions and submission.
    #[must_use]
    pub fn fields(&self) -> &[(String, String)] {
        &self.fields
    }

    /// Create a save request from typed alert configuration values.
    #[must_use]
    pub fn from_config(config: SaveAlertConfigFields) -> Self {
        let mut fields = vec![
            ("AlertConfigKey".into(), config.alert_config_key.to_string()),
            ("Name".into(), config.name),
            ("TickerGroup".into(), config.ticker_group),
            ("Tickers".into(), config.tickers),
            ("TradeRankLTE".into(), config.trade_rank_lte.to_string()),
            ("TradeVCDGTE".into(), config.trade_vcd_gte.to_string()),
            ("TradeMultGTE".into(), config.trade_mult_gte.to_string()),
            ("TradeVolumeGTE".into(), config.trade_volume_gte.to_string()),
            (
                "TradeDollarsGTE".into(),
                config.trade_dollars_gte.to_string(),
            ),
            ("TradeConditions".into(), config.trade_conditions),
            (
                "ClosingTradeRankLTE".into(),
                config.closing_trade_rank_lte.to_string(),
            ),
            (
                "ClosingTradeVCDGTE".into(),
                config.closing_trade_vcd_gte.to_string(),
            ),
            (
                "ClosingTradeMultGTE".into(),
                config.closing_trade_mult_gte.to_string(),
            ),
            (
                "ClosingTradeVolumeGTE".into(),
                config.closing_trade_volume_gte.to_string(),
            ),
            (
                "ClosingTradeDollarsGTE".into(),
                config.closing_trade_dollars_gte.to_string(),
            ),
            (
                "ClosingTradeConditions".into(),
                config.closing_trade_conditions,
            ),
            (
                "TradeClusterRankLTE".into(),
                config.cluster_rank_lte.to_string(),
            ),
            (
                "TradeClusterVCDGTE".into(),
                config.cluster_vcd_gte.to_string(),
            ),
            (
                "TradeClusterMultGTE".into(),
                config.cluster_mult_gte.to_string(),
            ),
            (
                "TradeClusterVolumeGTE".into(),
                config.cluster_volume_gte.to_string(),
            ),
            (
                "TradeClusterDollarsGTE".into(),
                config.cluster_dollars_gte.to_string(),
            ),
            ("TotalRankLTE".into(), config.total_rank_lte.to_string()),
            ("TotalVolumeGTE".into(), config.total_volume_gte.to_string()),
            (
                "TotalDollarsGTE".into(),
                config.total_dollars_gte.to_string(),
            ),
            ("AHRankLTE".into(), config.ah_rank_lte.to_string()),
            ("AHVolumeGTE".into(), config.ah_volume_gte.to_string()),
            ("AHDollarsGTE".into(), config.ah_dollars_gte.to_string()),
        ];
        push_bool_field(&mut fields, "DarkPool", config.dark_pool);
        push_bool_field(&mut fields, "Sweep", config.sweep);
        push_bool_field(&mut fields, "OffsettingPrint", config.offsetting_print);
        push_bool_field(&mut fields, "PhantomPrint", config.phantom_print);
        Self { fields }
    }
}

fn push_bool_field(fields: &mut Vec<(String, String)>, name: &str, value: bool) {
    if value {
        fields.push((name.to_string(), "true".to_string()));
    }
    fields.push((name.to_string(), "false".to_string()));
}

/// JSON payload for deleting an alert configuration.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct DeleteAlertConfigRequest {
    pub alert_config_key: i64,
}

/// Return the DataTables column definitions for alert configurations.
#[must_use]
pub fn alert_configs_columns() -> Vec<DataTablesColumn> {
    vec![
        DataTablesColumn::new("Name", "", true, false),
        DataTablesColumn::new("Name", "Name", true, true),
        DataTablesColumn::new("Tickers", "Tickers", true, true),
        DataTablesColumn::new("Conditions", "Conditions", true, false),
    ]
}

/// Return the DataTables column definitions for trade alerts.
#[must_use]
pub fn trade_alerts_columns() -> Vec<DataTablesColumn> {
    crate::trades::trades_columns()
}

/// Return the DataTables column definitions for trade cluster alerts.
#[must_use]
pub fn trade_cluster_alerts_columns() -> Vec<DataTablesColumn> {
    crate::clusters::trade_clusters_columns()
}

impl Client {
    /// Post a DataTables request to `/AlertConfigs/GetAlertConfigs`.
    #[instrument(skip_all)]
    pub async fn get_alert_configs(
        &self,
        request: &AlertConfigsRequest,
    ) -> Result<DataTablesResponse<AlertConfig>> {
        let body = self
            .post_form(ALERT_CONFIGS_GET_ALERT_CONFIGS_PATH, request.to_pairs())
            .await?;
        Ok(serde_json::from_str(&body)?)
    }

    /// Fetch up to `limit` alert configurations by paginating the endpoint.
    #[instrument(skip_all)]
    pub async fn get_alert_configs_limit(
        &self,
        request: &AlertConfigsRequest,
        limit: usize,
    ) -> Result<Vec<AlertConfig>> {
        fetch_limit(
            self,
            ALERT_CONFIGS_GET_ALERT_CONFIGS_PATH,
            request.0.clone(),
            limit,
        )
        .await
    }

    /// Post a DataTables request to `/TradeAlerts/GetTradeAlerts`.
    #[instrument(skip_all)]
    pub async fn get_trade_alerts(
        &self,
        request: &TradeAlertsRequest,
    ) -> Result<DataTablesResponse<TradeAlert>> {
        let body = self
            .post_form(TRADE_ALERTS_GET_TRADE_ALERTS_PATH, request.to_pairs())
            .await?;
        Ok(serde_json::from_str(&body)?)
    }

    /// Fetch up to `limit` trade alerts by paginating the endpoint.
    #[instrument(skip_all)]
    pub async fn get_trade_alerts_limit(
        &self,
        request: &TradeAlertsRequest,
        limit: usize,
    ) -> Result<Vec<TradeAlert>> {
        fetch_limit(
            self,
            TRADE_ALERTS_GET_TRADE_ALERTS_PATH,
            request.0.clone(),
            limit,
        )
        .await
    }

    /// Post a DataTables request to `/TradeClusterAlerts/GetTradeClusterAlerts`.
    #[instrument(skip_all)]
    pub async fn get_trade_cluster_alerts(
        &self,
        request: &TradeClusterAlertsRequest,
    ) -> Result<DataTablesResponse<TradeClusterAlert>> {
        let body = self
            .post_form(
                TRADE_CLUSTER_ALERTS_GET_TRADE_CLUSTER_ALERTS_PATH,
                request.to_pairs(),
            )
            .await?;
        Ok(serde_json::from_str(&body)?)
    }

    /// Fetch up to `limit` trade cluster alerts by paginating the endpoint.
    #[instrument(skip_all)]
    pub async fn get_trade_cluster_alerts_limit(
        &self,
        request: &TradeClusterAlertsRequest,
        limit: usize,
    ) -> Result<Vec<TradeClusterAlert>> {
        fetch_limit(
            self,
            TRADE_CLUSTER_ALERTS_GET_TRADE_CLUSTER_ALERTS_PATH,
            request.0.clone(),
            limit,
        )
        .await
    }

    /// Post a multipart create or edit request to `/AlertConfig`.
    #[instrument(skip_all)]
    pub async fn save_alert_config(&self, request: SaveAlertConfigRequest) -> Result<()> {
        self.post_multipart_form(
            ALERT_CONFIG_PATH,
            multipart_form_from_fields(request.fields()),
            ALERT_CONFIGS_SUCCESS_REDIRECT,
        )
        .await
    }

    /// Post a JSON delete request to `/AlertConfigs/DeleteAlertConfig`.
    #[instrument(skip_all)]
    pub async fn delete_alert_config(&self, request: &DeleteAlertConfigRequest) -> Result<()> {
        self.post_json(ALERT_CONFIGS_DELETE_ALERT_CONFIG_PATH, request)
            .await
            .map(|_| ())
    }
}

fn multipart_form_from_fields(fields: &[(String, String)]) -> reqwest::multipart::Form {
    let mut form = reqwest::multipart::Form::new();
    for (key, value) in fields {
        form = form.text(key.clone(), value.clone());
    }
    form
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::ClientConfig;
    use crate::session::{
        COOKIE_DOMAIN, Cookie, FORMS_AUTH_COOKIE_NAME, SESSION_COOKIE_NAME, Session,
    };

    fn test_session() -> Session {
        Session::new(
            vec![
                Cookie::new(SESSION_COOKIE_NAME, "session-123", COOKIE_DOMAIN),
                Cookie::new(FORMS_AUTH_COOKIE_NAME, "auth-456", COOKIE_DOMAIN),
            ],
            "xsrf-789",
        )
    }

    fn test_client(server: &mockito::Server) -> Client {
        Client::with_config(
            test_session(),
            ClientConfig {
                base_url: server.url(),
                ..ClientConfig::default()
            },
        )
        .unwrap()
    }

    fn datatables_body<T: Serialize>(data: Vec<T>) -> String {
        serde_json::to_string(&DataTablesResponse {
            draw: 1,
            records_total: data.len() as i32,
            records_filtered: data.len() as i32,
            data,
            error: None,
        })
        .unwrap()
    }

    #[test]
    fn alert_configs_columns_match_go_source() {
        let columns = alert_configs_columns();

        assert_eq!(columns.len(), 4);
        assert_eq!(columns[0], DataTablesColumn::new("Name", "", true, false));
        assert_eq!(
            columns[1],
            DataTablesColumn::new("Name", "Name", true, true)
        );
        assert_eq!(
            columns[2],
            DataTablesColumn::new("Tickers", "Tickers", true, true)
        );
        assert_eq!(
            columns[3],
            DataTablesColumn::new("Conditions", "Conditions", true, false)
        );
    }

    #[test]
    fn alert_trade_columns_reuse_captured_trade_layouts() {
        assert_eq!(trade_alerts_columns(), crate::trades::trades_columns());
        assert_eq!(
            trade_cluster_alerts_columns(),
            crate::clusters::trade_clusters_columns()
        );
    }

    #[tokio::test]
    async fn get_alert_configs_posts_datatables_request() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", ALERT_CONFIGS_GET_ALERT_CONFIGS_PATH)
            .match_header(
                "content-type",
                "application/x-www-form-urlencoded; charset=UTF-8",
            )
            .match_body(mockito::Matcher::Regex(
                r"(?:^|&)columns\[0\]\[data\]=Name(?:&|.*&)columns\[2\]\[data\]=Tickers(?:&|.*&)columns\[3\]\[data\]=Conditions"
                    .to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"AlertConfigKey":42088,"Name":"testing 2","Tickers":"[ALL TICKERS]","TradeConditions":null}]}"#)
            .create_async()
            .await;
        let client = test_client(&server);

        let response = client
            .get_alert_configs(&AlertConfigsRequest::new())
            .await
            .unwrap();

        assert_eq!(response.data.len(), 1);
        assert_eq!(response.data[0].alert_config_key, Some(42088));
        assert_eq!(response.data[0].trade_conditions, None);
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn get_trade_alerts_posts_datatables_request() {
        let mut server = mockito::Server::new_async().await;
        let mut request = TradeAlertsRequest::new();
        request
            .0
            .extra_values
            .push(("Date".to_string(), "2026-05-07".to_string()));
        let mock = server
            .mock("POST", TRADE_ALERTS_GET_TRADE_ALERTS_PATH)
            .match_body(mockito::Matcher::Regex(
                r"(?:^|&)columns\[0\]\[data\]=FullTimeString24(?:&|.*&)columns\[4\]\[data\]=Trade(?:&|.*&)Date=2026-05-07(?:&|$)"
                    .to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"Ticker":"AMD","TradeID":123456,"AlertType":"Trade","Sweep":1}]}"#)
            .create_async()
            .await;
        let client = test_client(&server);

        let response = client.get_trade_alerts(&request).await.unwrap();

        assert_eq!(response.data[0].trade_id, Some(123456));
        assert_eq!(
            response.data[0].sweep,
            Some(crate::models::FlexBool(Some(true)))
        );
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn get_trade_cluster_alerts_posts_datatables_request() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", TRADE_CLUSTER_ALERTS_GET_TRADE_CLUSTER_ALERTS_PATH)
            .match_body(mockito::Matcher::Regex(
                r"(?:^|&)columns\[0\]\[data\]=MinFullTimeString24(?:&|.*&)columns\[12\]\[data\]=TradeClusterRank"
                    .to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"Ticker":"AMD","TradeClusterRank":8,"TradeCount":4}]}"#)
            .create_async()
            .await;
        let client = test_client(&server);

        let response = client
            .get_trade_cluster_alerts(&TradeClusterAlertsRequest::new())
            .await
            .unwrap();

        assert_eq!(response.data[0].trade_cluster_rank, Some(8));
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn alert_limit_methods_page_through_results() {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("POST", ALERT_CONFIGS_GET_ALERT_CONFIGS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(datatables_body(vec![
                serde_json::json!({"AlertConfigKey": 1}),
            ]))
            .create_async()
            .await;
        server
            .mock("POST", TRADE_ALERTS_GET_TRADE_ALERTS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(datatables_body(vec![serde_json::json!({"TradeID": 2})]))
            .create_async()
            .await;
        server
            .mock("POST", TRADE_CLUSTER_ALERTS_GET_TRADE_CLUSTER_ALERTS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(datatables_body(vec![
                serde_json::json!({"TradeClusterRank": 3}),
            ]))
            .create_async()
            .await;
        let client = test_client(&server);

        let configs = client
            .get_alert_configs_limit(&AlertConfigsRequest::new(), 1)
            .await
            .unwrap();
        let trades = client
            .get_trade_alerts_limit(&TradeAlertsRequest::new(), 1)
            .await
            .unwrap();
        let clusters = client
            .get_trade_cluster_alerts_limit(&TradeClusterAlertsRequest::new(), 1)
            .await
            .unwrap();

        assert_eq!(configs[0].alert_config_key, Some(1));
        assert_eq!(trades[0].trade_id, Some(2));
        assert_eq!(clusters[0].trade_cluster_rank, Some(3));
    }

    #[tokio::test]
    async fn save_alert_config_posts_multipart_form_and_accepts_redirect() {
        let mut server = mockito::Server::new_async().await;
        let save = server
            .mock("POST", ALERT_CONFIG_PATH)
            .match_header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
            .match_body(mockito::Matcher::Regex(
                r#"(?s)name="AlertConfigKey"\r\n\r\n42089.*name="OffsettingPrint"\r\n\r\ntrue.*name="OffsettingPrint"\r\n\r\nfalse"#
                    .to_string(),
            ))
            .with_status(302)
            .with_header("location", "/AlertConfigs?ViewMode=Desktop")
            .create_async()
            .await;
        let follow = server
            .mock("GET", "/AlertConfigs?ViewMode=Desktop")
            .with_status(200)
            .with_header("content-type", "text/html")
            .with_body("saved")
            .create_async()
            .await;
        let client = test_client(&server);

        client
            .save_alert_config(SaveAlertConfigRequest::new(vec![
                ("AlertConfigKey".to_string(), "42089".to_string()),
                ("Name".to_string(), "Testing 2".to_string()),
                ("OffsettingPrint".to_string(), "true".to_string()),
                ("OffsettingPrint".to_string(), "false".to_string()),
            ]))
            .await
            .unwrap();

        save.assert_async().await;
        follow.assert_async().await;
    }

    #[tokio::test]
    async fn delete_alert_config_posts_json_request() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", ALERT_CONFIGS_DELETE_ALERT_CONFIG_PATH)
            .match_header("content-type", "application/json; charset=UTF-8")
            .match_header("x-requested-with", "XMLHttpRequest")
            .match_body(r#"{"AlertConfigKey":42088}"#)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body("42088")
            .create_async()
            .await;
        let client = test_client(&server);

        client
            .delete_alert_config(&DeleteAlertConfigRequest {
                alert_config_key: 42088,
            })
            .await
            .unwrap();

        mock.assert_async().await;
    }
}