kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
Documentation
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
//! Query builder utilities for filtering and sorting

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Sort direction
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum SortDirection {
    /// Ascending order (smallest first)
    Asc,
    /// Descending order (largest first)
    #[default]
    Desc,
}

impl SortDirection {
    /// Convert to the SQL keyword (`ASC` or `DESC`)
    pub fn to_sql(&self) -> &'static str {
        match self {
            SortDirection::Asc => "ASC",
            SortDirection::Desc => "DESC",
        }
    }
}

/// Sort field specification
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SortBy {
    /// Field name to sort by
    pub field: String,
    /// Sort direction
    #[serde(default)]
    pub direction: SortDirection,
}

impl SortBy {
    /// Create a sort specification for `field` in the given `direction`
    pub fn new(field: impl Into<String>, direction: SortDirection) -> Self {
        Self {
            field: field.into(),
            direction,
        }
    }

    /// Create an ascending sort on `field`
    pub fn asc(field: impl Into<String>) -> Self {
        Self::new(field, SortDirection::Asc)
    }

    /// Create a descending sort on `field`
    pub fn desc(field: impl Into<String>) -> Self {
        Self::new(field, SortDirection::Desc)
    }

    /// Convert to SQL ORDER BY clause
    pub fn to_sql(&self, allowed_fields: &[&str]) -> Result<String, String> {
        if !allowed_fields.contains(&self.field.as_str()) {
            return Err(format!("Invalid sort field: {}", self.field));
        }
        Ok(format!("{} {}", self.field, self.direction.to_sql()))
    }
}

/// Filter operator
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FilterOperator {
    /// Equal (`=`)
    Eq,
    /// Not equal (`!=`)
    Ne,
    /// Greater than (`>`)
    Gt,
    /// Greater than or equal (`>=`)
    Gte,
    /// Less than (`<`)
    Lt,
    /// Less than or equal (`<=`)
    Lte,
    /// SQL `LIKE` pattern match
    Like,
    /// SQL `IN (...)` membership check
    In,
    /// SQL `NOT IN (...)` exclusion check
    NotIn,
    /// SQL `IS NULL` null check
    IsNull,
    /// SQL `IS NOT NULL` non-null check
    NotNull,
}

impl FilterOperator {
    /// Convert to the SQL operator string
    pub fn to_sql(&self) -> &'static str {
        match self {
            FilterOperator::Eq => "=",
            FilterOperator::Ne => "!=",
            FilterOperator::Gt => ">",
            FilterOperator::Gte => ">=",
            FilterOperator::Lt => "<",
            FilterOperator::Lte => "<=",
            FilterOperator::Like => "LIKE",
            FilterOperator::In => "IN",
            FilterOperator::NotIn => "NOT IN",
            FilterOperator::IsNull => "IS NULL",
            FilterOperator::NotNull => "IS NOT NULL",
        }
    }
}

/// Filter condition
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Filter {
    /// Field name
    pub field: String,
    /// Operator
    pub operator: FilterOperator,
    /// Value (for operators that need it)
    pub value: Option<serde_json::Value>,
}

impl Filter {
    /// Create a filter without a value (for null-check operators)
    pub fn new(field: impl Into<String>, operator: FilterOperator) -> Self {
        Self {
            field: field.into(),
            operator,
            value: None,
        }
    }

    /// Set the comparison value for this filter
    pub fn with_value(mut self, value: serde_json::Value) -> Self {
        self.value = Some(value);
        self
    }

    /// Create equality filter
    pub fn eq(field: impl Into<String>, value: serde_json::Value) -> Self {
        Self::new(field, FilterOperator::Eq).with_value(value)
    }

    /// Create greater than filter
    pub fn gt(field: impl Into<String>, value: serde_json::Value) -> Self {
        Self::new(field, FilterOperator::Gt).with_value(value)
    }

    /// Create less than filter
    pub fn lt(field: impl Into<String>, value: serde_json::Value) -> Self {
        Self::new(field, FilterOperator::Lt).with_value(value)
    }

    /// Create LIKE filter
    pub fn like(field: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self::new(field, FilterOperator::Like).with_value(serde_json::Value::String(pattern.into()))
    }

    /// Create IS NULL filter
    pub fn is_null(field: impl Into<String>) -> Self {
        Self::new(field, FilterOperator::IsNull)
    }

    /// Create IS NOT NULL filter
    pub fn not_null(field: impl Into<String>) -> Self {
        Self::new(field, FilterOperator::NotNull)
    }

    /// Validate filter field
    pub fn validate(&self, allowed_fields: &[&str]) -> Result<(), String> {
        if !allowed_fields.contains(&self.field.as_str()) {
            return Err(format!("Invalid filter field: {}", self.field));
        }

        // Check if value is required for operator
        match self.operator {
            FilterOperator::IsNull | FilterOperator::NotNull => {
                // These don't need values
                Ok(())
            }
            _ => {
                if self.value.is_none() {
                    Err(format!(
                        "Value required for {} operator",
                        self.operator.to_sql()
                    ))
                } else {
                    Ok(())
                }
            }
        }
    }
}

/// Date range filter helper
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DateRange {
    /// Inclusive lower bound of the date range
    pub from: Option<DateTime<Utc>>,
    /// Inclusive upper bound of the date range
    pub to: Option<DateTime<Utc>>,
}

impl DateRange {
    /// Create a date range with optional lower and upper bounds
    pub fn new(from: Option<DateTime<Utc>>, to: Option<DateTime<Utc>>) -> Self {
        Self { from, to }
    }

    /// Create a range with only a lower bound
    pub fn from(from: DateTime<Utc>) -> Self {
        Self {
            from: Some(from),
            to: None,
        }
    }

    /// Create a range with only an upper bound
    pub fn to(to: DateTime<Utc>) -> Self {
        Self {
            from: None,
            to: Some(to),
        }
    }

    /// Create a closed range with both lower and upper bounds
    pub fn between(from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
        Self {
            from: Some(from),
            to: Some(to),
        }
    }

    /// Convert to filters
    pub fn to_filters(&self, field: &str) -> Vec<Filter> {
        let mut filters = Vec::new();

        if let Some(from) = self.from {
            filters.push(
                Filter::new(field, FilterOperator::Gte)
                    .with_value(serde_json::to_value(from.to_rfc3339()).unwrap()),
            );
        }

        if let Some(to) = self.to {
            filters.push(
                Filter::new(field, FilterOperator::Lte)
                    .with_value(serde_json::to_value(to.to_rfc3339()).unwrap()),
            );
        }

        filters
    }
}

/// Numeric range filter helper
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NumericRange {
    /// Inclusive lower bound
    pub min: Option<Decimal>,
    /// Inclusive upper bound
    pub max: Option<Decimal>,
}

impl NumericRange {
    /// Create a numeric range with optional lower and upper bounds
    pub fn new(min: Option<Decimal>, max: Option<Decimal>) -> Self {
        Self { min, max }
    }

    /// Create a range with only a lower bound
    pub fn min(min: Decimal) -> Self {
        Self {
            min: Some(min),
            max: None,
        }
    }

    /// Create a range with only an upper bound
    pub fn max(max: Decimal) -> Self {
        Self {
            min: None,
            max: Some(max),
        }
    }

    /// Create a closed range with both bounds
    pub fn between(min: Decimal, max: Decimal) -> Self {
        Self {
            min: Some(min),
            max: Some(max),
        }
    }

    /// Convert to filters
    pub fn to_filters(&self, field: &str) -> Vec<Filter> {
        let mut filters = Vec::new();

        if let Some(min) = self.min {
            filters.push(
                Filter::new(field, FilterOperator::Gte)
                    .with_value(serde_json::to_value(min).unwrap()),
            );
        }

        if let Some(max) = self.max {
            filters.push(
                Filter::new(field, FilterOperator::Lte)
                    .with_value(serde_json::to_value(max).unwrap()),
            );
        }

        filters
    }
}

/// Query builder for complex queries
#[derive(Debug, Clone, Default)]
pub struct QueryBuilder {
    /// Accumulated filter conditions
    filters: Vec<Filter>,
    /// Accumulated sort specifications
    sort_by: Vec<SortBy>,
}

impl QueryBuilder {
    /// Create an empty query builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a filter
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Add multiple filters
    pub fn filters(mut self, filters: Vec<Filter>) -> Self {
        self.filters.extend(filters);
        self
    }

    /// Add sorting
    pub fn sort(mut self, sort: SortBy) -> Self {
        self.sort_by.push(sort);
        self
    }

    /// Add sorting by field (descending by default)
    pub fn sort_by(mut self, field: impl Into<String>) -> Self {
        self.sort_by.push(SortBy::desc(field));
        self
    }

    /// Add ascending sort
    pub fn sort_asc(mut self, field: impl Into<String>) -> Self {
        self.sort_by.push(SortBy::asc(field));
        self
    }

    /// Add descending sort
    pub fn sort_desc(mut self, field: impl Into<String>) -> Self {
        self.sort_by.push(SortBy::desc(field));
        self
    }

    /// Add date range filter
    pub fn date_range(self, field: &str, range: DateRange) -> Self {
        self.filters(range.to_filters(field))
    }

    /// Add numeric range filter
    pub fn numeric_range(self, field: &str, range: NumericRange) -> Self {
        self.filters(range.to_filters(field))
    }

    /// Add filter for UUID field
    pub fn filter_uuid(self, field: impl Into<String>, uuid: Uuid) -> Self {
        self.filter(Filter::eq(field, serde_json::to_value(uuid).unwrap()))
    }

    /// Add filter for string field
    pub fn filter_string(self, field: impl Into<String>, value: impl Into<String>) -> Self {
        self.filter(Filter::eq(field, serde_json::Value::String(value.into())))
    }

    /// Add search filter (LIKE)
    pub fn search(self, field: impl Into<String>, pattern: impl Into<String>) -> Self {
        self.filter(Filter::like(field, format!("%{}%", pattern.into())))
    }

    /// Get all filters
    pub fn get_filters(&self) -> &[Filter] {
        &self.filters
    }

    /// Get all sorting
    pub fn get_sort(&self) -> &[SortBy] {
        &self.sort_by
    }

    /// Validate all filters and sorts
    pub fn validate(&self, allowed_fields: &[&str]) -> Result<(), String> {
        for filter in &self.filters {
            filter.validate(allowed_fields)?;
        }

        for sort in &self.sort_by {
            sort.to_sql(allowed_fields)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn test_sort_direction() {
        assert_eq!(SortDirection::Asc.to_sql(), "ASC");
        assert_eq!(SortDirection::Desc.to_sql(), "DESC");
    }

    #[test]
    fn test_sort_by() {
        let sort = SortBy::asc("created_at");
        assert_eq!(sort.field, "created_at");
        assert_eq!(sort.direction, SortDirection::Asc);

        let allowed = &["created_at", "updated_at"];
        assert!(sort.to_sql(allowed).is_ok());

        let invalid = SortBy::desc("invalid_field");
        assert!(invalid.to_sql(allowed).is_err());
    }

    #[test]
    fn test_filter_operator() {
        assert_eq!(FilterOperator::Eq.to_sql(), "=");
        assert_eq!(FilterOperator::Gt.to_sql(), ">");
        assert_eq!(FilterOperator::Like.to_sql(), "LIKE");
    }

    #[test]
    fn test_filter_creation() {
        let filter = Filter::eq("status", serde_json::Value::String("active".to_string()));
        assert_eq!(filter.field, "status");
        assert_eq!(filter.operator, FilterOperator::Eq);
        assert!(filter.value.is_some());

        let null_filter = Filter::is_null("deleted_at");
        assert_eq!(null_filter.operator, FilterOperator::IsNull);
        assert!(null_filter.value.is_none());
    }

    #[test]
    fn test_date_range() {
        let now = Utc::now();
        let range = DateRange::between(now, now);

        let filters = range.to_filters("created_at");
        assert_eq!(filters.len(), 2);
        assert_eq!(filters[0].operator, FilterOperator::Gte);
        assert_eq!(filters[1].operator, FilterOperator::Lte);
    }

    #[test]
    fn test_numeric_range() {
        let range = NumericRange::between(dec!(10), dec!(100));

        let filters = range.to_filters("price");
        assert_eq!(filters.len(), 2);
        assert_eq!(filters[0].operator, FilterOperator::Gte);
        assert_eq!(filters[1].operator, FilterOperator::Lte);
    }

    #[test]
    fn test_query_builder() {
        let query = QueryBuilder::new()
            .filter_string("status", "active")
            .search("name", "test")
            .sort_desc("created_at")
            .sort_asc("name");

        assert_eq!(query.get_filters().len(), 2);
        assert_eq!(query.get_sort().len(), 2);
    }

    #[test]
    fn test_query_validation() {
        let query = QueryBuilder::new()
            .filter_string("status", "active")
            .sort_desc("created_at");

        let allowed = &["status", "created_at", "name"];
        assert!(query.validate(allowed).is_ok());

        let invalid_query = QueryBuilder::new().filter_string("invalid", "value");
        assert!(invalid_query.validate(allowed).is_err());
    }
}