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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
// src/validation.rs
//
// Validation functions for OMS documents
use crate::{OmsError, OmsResult};
use crate::types::*;
use validator::ValidationError;
/// Validates a complete OmsDocument
pub fn validate_document(document: &OmsDocument) -> OmsResult<()> {
// Check that at least one item exists
if document.items.is_empty() {
return Err(OmsError::ValidationError(validator::ValidationErrors::new()));
}
// Validate each item's customizations
for item in &document.items {
if let Some(customizations) = &item.customizations {
validate_customizations(customizations)?;
}
// Validate selected customizations against available customizations
if let Some(selected) = &item.selected_customizations {
if let Some(available) = &item.customizations {
validate_selected_customizations(selected, available)?;
} else {
return Err(OmsError::ValidationError(validator::ValidationErrors::new()));
}
}
}
// If order exists, validate it
if let Some(order) = &document.order {
validate_order(order, &document.items)?;
}
Ok(())
}
/// Validates customization definitions
fn validate_customizations(customizations: &[Customization]) -> OmsResult<()> {
for customization in customizations {
match customization.r#type {
CustomizationType::SingleSelect | CustomizationType::MultiSelect => {
// Options are required for select types
if customization.options.is_none() || customization.options.as_ref().unwrap().is_empty() {
return Err(OmsError::MissingRequiredField(format!("options for customization {}", customization.id)));
}
// Validate default values
match &customization.r#type {
CustomizationType::SingleSelect => {
match &customization.default {
CustomizationDefault::String(default_id) => {
// Check that default exists in options
let options = customization.options.as_ref().unwrap();
if !options.iter().any(|opt| &opt.id == default_id) {
return Err(OmsError::InvalidFieldValue(format!(
"default value '{}' not found in options for customization {}",
default_id, customization.id
)));
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"default value type mismatch for single_select customization {}",
customization.id
))),
}
},
CustomizationType::MultiSelect => {
match &customization.default {
CustomizationDefault::StringArray(default_ids) => {
// Check that defaults exist in options
let options = customization.options.as_ref().unwrap();
for default_id in default_ids {
if !options.iter().any(|opt| &opt.id == default_id) {
return Err(OmsError::InvalidFieldValue(format!(
"default value '{}' not found in options for customization {}",
default_id, customization.id
)));
}
}
// Check min/max selections
if let Some(min) = customization.min_selections {
if default_ids.len() < min as usize {
return Err(OmsError::InvalidFieldValue(format!(
"default selections count is less than min_selections for customization {}",
customization.id
)));
}
}
if let Some(max) = customization.max_selections {
if default_ids.len() > max as usize {
return Err(OmsError::InvalidFieldValue(format!(
"default selections count is greater than max_selections for customization {}",
customization.id
)));
}
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"default value type mismatch for multi_select customization {}",
customization.id
))),
}
},
_ => unreachable!(),
}
},
CustomizationType::Quantity => {
// Validate default is a number
match customization.default {
CustomizationDefault::Number(value) => {
// Check min/max constraints
if let Some(min) = customization.min {
if value < min {
return Err(OmsError::InvalidFieldValue(format!(
"default value {} is less than min {} for customization {}",
value, min, customization.id
)));
}
}
if let Some(max) = customization.max {
if value > max {
return Err(OmsError::InvalidFieldValue(format!(
"default value {} is greater than max {} for customization {}",
value, max, customization.id
)));
}
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"default value type mismatch for quantity customization {}",
customization.id
))),
}
},
CustomizationType::Boolean => {
// Validate default is a boolean
match customization.default {
CustomizationDefault::Boolean(_) => (), // Valid
_ => return Err(OmsError::InvalidFieldValue(format!(
"default value type mismatch for boolean customization {}",
customization.id
))),
}
},
CustomizationType::Text => {
// Validate default is a string
match customization.default {
CustomizationDefault::String(_) => (), // Valid
_ => return Err(OmsError::InvalidFieldValue(format!(
"default value type mismatch for text customization {}",
customization.id
))),
}
},
CustomizationType::Range => {
// Validate default is a number
match customization.default {
CustomizationDefault::Number(value) => {
// Check min/max constraints
if let Some(min) = customization.min {
if value < min {
return Err(OmsError::InvalidFieldValue(format!(
"default value {} is less than min {} for customization {}",
value, min, customization.id
)));
}
}
if let Some(max) = customization.max {
if value > max {
return Err(OmsError::InvalidFieldValue(format!(
"default value {} is greater than max {} for customization {}",
value, max, customization.id
)));
}
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"default value type mismatch for range customization {}",
customization.id
))),
}
},
}
}
Ok(())
}
/// Validates selected customizations against available customizations
fn validate_selected_customizations(
selected: &[SelectedCustomization],
available: &[Customization]
) -> OmsResult<()> {
// Build a map of available customizations for quick lookup
let mut avail_map = std::collections::HashMap::new();
for customization in available {
avail_map.insert(&customization.id, customization);
}
// Check that all required customizations are selected
for customization in available {
if customization.required {
if !selected.iter().any(|sel| sel.customization_id == customization.id) {
return Err(OmsError::MissingRequiredField(format!(
"required customization {} not selected",
customization.id
)));
}
}
}
// Validate each selection
for selection in selected {
// Check that the customization exists
let customization = match avail_map.get(&selection.customization_id) {
Some(c) => c,
None => return Err(OmsError::InvalidFieldValue(format!(
"selected customization {} not found in available customizations",
selection.customization_id
))),
};
// Validate the selection based on customization type
match customization.r#type {
CustomizationType::SingleSelect => {
match &selection.selection {
CustomizationSelection::String(selected_id) => {
// Check that the selection exists in options
let options = customization.options.as_ref().unwrap();
if !options.iter().any(|opt| &opt.id == selected_id) {
return Err(OmsError::InvalidFieldValue(format!(
"selected value '{}' not found in options for customization {}",
selected_id, customization.id
)));
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"selection type mismatch for single_select customization {}",
customization.id
))),
}
},
CustomizationType::MultiSelect => {
match &selection.selection {
CustomizationSelection::StringArray(selected_ids) => {
// Check that selections exist in options
let options = customization.options.as_ref().unwrap();
for selected_id in selected_ids {
if !options.iter().any(|opt| &opt.id == selected_id) {
return Err(OmsError::InvalidFieldValue(format!(
"selected value '{}' not found in options for customization {}",
selected_id, customization.id
)));
}
}
// Check min/max selections
if let Some(min) = customization.min_selections {
if selected_ids.len() < min as usize {
return Err(OmsError::InvalidFieldValue(format!(
"selections count is less than min_selections for customization {}",
customization.id
)));
}
}
if let Some(max) = customization.max_selections {
if selected_ids.len() > max as usize {
return Err(OmsError::InvalidFieldValue(format!(
"selections count is greater than max_selections for customization {}",
customization.id
)));
}
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"selection type mismatch for multi_select customization {}",
customization.id
))),
}
},
CustomizationType::Quantity => {
match selection.selection {
CustomizationSelection::Number(value) => {
// Check min/max constraints
if let Some(min) = customization.min {
if value < min {
return Err(OmsError::InvalidFieldValue(format!(
"selected value {} is less than min {} for customization {}",
value, min, customization.id
)));
}
}
if let Some(max) = customization.max {
if value > max {
return Err(OmsError::InvalidFieldValue(format!(
"selected value {} is greater than max {} for customization {}",
value, max, customization.id
)));
}
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"selection type mismatch for quantity customization {}",
customization.id
))),
}
},
CustomizationType::Boolean => {
match selection.selection {
CustomizationSelection::Boolean(_) => (), // Valid
_ => return Err(OmsError::InvalidFieldValue(format!(
"selection type mismatch for boolean customization {}",
customization.id
))),
}
},
CustomizationType::Text => {
match &selection.selection {
CustomizationSelection::String(_) => (), // Valid
_ => return Err(OmsError::InvalidFieldValue(format!(
"selection type mismatch for text customization {}",
customization.id
))),
}
},
CustomizationType::Range => {
match selection.selection {
CustomizationSelection::Number(value) => {
// Check min/max constraints
if let Some(min) = customization.min {
if value < min {
return Err(OmsError::InvalidFieldValue(format!(
"selected value {} is less than min {} for customization {}",
value, min, customization.id
)));
}
}
if let Some(max) = customization.max {
if value > max {
return Err(OmsError::InvalidFieldValue(format!(
"selected value {} is greater than max {} for customization {}",
value, max, customization.id
)));
}
}
},
_ => return Err(OmsError::InvalidFieldValue(format!(
"selection type mismatch for range customization {}",
customization.id
))),
}
},
}
}
Ok(())
}
/// Validates order information
fn validate_order(order: &Order, items: &[Item]) -> OmsResult<()> {
// Check that there are items in the order
if items.is_empty() {
return Err(OmsError::ValidationError(validator::ValidationErrors::new()));
}
// Validate payment information
if let Some(payment) = &order.payment {
// Check that total is greater than zero
if payment.total <= 0.0 {
return Err(OmsError::InvalidFieldValue("payment total must be greater than zero".to_string()));
}
// If subtotal, tax, and tip are all provided, check that they add up to total
if let (Some(subtotal), Some(tax), Some(tip)) = (payment.subtotal, payment.tax, payment.tip) {
let calculated_total = subtotal + tax + tip;
let epsilon = 0.01; // Allow for small floating-point errors
if (calculated_total - payment.total).abs() > epsilon {
return Err(OmsError::InvalidFieldValue(format!(
"payment components (subtotal + tax + tip = {}) do not add up to total ({})",
calculated_total, payment.total
)));
}
}
}
// Validate delivery information
if let Some(delivery) = &order.delivery {
// If delivery type is specified, it should be "delivery"
if let Some(order_type) = &order.r#type {
if *order_type != OrderType::Delivery {
return Err(OmsError::InvalidFieldValue(
"order.type must be 'delivery' when delivery information is provided".to_string()
));
}
}
}
// If order type is "delivery", delivery information should be provided
if let Some(OrderType::Delivery) = &order.r#type {
if order.delivery.is_none() {
return Err(OmsError::MissingRequiredField(
"delivery information is required for delivery orders".to_string()
));
}
}
Ok(())
}
/// Validation function for customization type
pub fn validate_customization_type(type_str: &str) -> Result<(), ValidationError> {
let valid_types = [
"single_select", "multi_select", "quantity", "boolean", "text", "range",
];
if valid_types.contains(&type_str) {
Ok(())
} else {
let mut error = ValidationError::new("invalid_customization_type");
error.message = Some(format!("Invalid customization type: {}. Must be one of: {}",
type_str, valid_types.join(", ")).into());
Err(error)
}
}
/// Validation function for vendor type
pub fn validate_vendor_type(type_str: &str) -> Result<(), ValidationError> {
let valid_types = [
"restaurant", "cafe", "fast-food", "coffee-shop", "bakery", "grocery",
"food-truck", "catering", "pizzeria", "pub", "bar",
];
if valid_types.contains(&type_str) || !type_str.is_empty() {
Ok(())
} else {
let mut error = ValidationError::new("invalid_vendor_type");
error.message = Some(format!("Invalid vendor type: {}. Common types include: {}",
type_str, valid_types.join(", ")).into());
Err(error)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::*;
#[test]
fn test_validate_empty_document() {
// Create a document with no items
let doc = OmsDocument {
oms_version: "1.0".to_string(),
metadata: Metadata {
created: chrono::Utc::now(),
source: "test".to_string(),
locale: "en-US".to_string(),
},
vendor: Vendor {
id: "test".to_string(),
name: "Test Vendor".to_string(),
r#type: "restaurant".to_string(),
location_id: None,
location_name: None,
address: None,
contact: None,
hours: None,
cuisine: None,
services: None,
},
items: vec![],
order: None,
extensions: None,
};
// Validation should fail
let result = validate_document(&doc);
assert!(result.is_err());
}
#[test]
fn test_validate_customizations() {
// Valid single_select customization
let single_select = Customization {
id: "test-single".to_string(),
name: "Test Single".to_string(),
r#type: CustomizationType::SingleSelect,
required: true,
default: CustomizationDefault::String("option1".to_string()),
min_selections: None,
max_selections: None,
min: None,
max: None,
step: None,
unit_price_adjustment: None,
unit_nutrition_adjustments: None,
options: Some(vec![
CustomizationOption {
id: "option1".to_string(),
name: "Option 1".to_string(),
price_adjustment: None,
nutrition_adjustments: None,
allergens: None,
dietary_flags: None,
},
CustomizationOption {
id: "option2".to_string(),
name: "Option 2".to_string(),
price_adjustment: None,
nutrition_adjustments: None,
allergens: None,
dietary_flags: None,
},
]),
};
// Test valid customization
let result = validate_customizations(&[single_select.clone()]);
assert!(result.is_ok());
// Test invalid default value
let mut invalid_default = single_select.clone();
invalid_default.default = CustomizationDefault::String("nonexistent".to_string());
let result = validate_customizations(&[invalid_default]);
assert!(result.is_err());
// Test invalid default type
let mut invalid_type = single_select.clone();
invalid_type.default = CustomizationDefault::Number(1.0);
let result = validate_customizations(&[invalid_type]);
assert!(result.is_err());
// Test missing options
let mut missing_options = single_select;
missing_options.options = None;
let result = validate_customizations(&[missing_options]);
assert!(result.is_err());
}
#[test]
fn test_validate_selected_customizations() {
// Available customizations
let customizations = vec![
Customization {
id: "test-single".to_string(),
name: "Test Single".to_string(),
r#type: CustomizationType::SingleSelect,
required: true,
default: CustomizationDefault::String("option1".to_string()),
min_selections: None,
max_selections: None,
min: None,
max: None,
step: None,
unit_price_adjustment: None,
unit_nutrition_adjustments: None,
options: Some(vec![
CustomizationOption {
id: "option1".to_string(),
name: "Option 1".to_string(),
price_adjustment: None,
nutrition_adjustments: None,
allergens: None,
dietary_flags: None,
},
CustomizationOption {
id: "option2".to_string(),
name: "Option 2".to_string(),
price_adjustment: None,
nutrition_adjustments: None,
allergens: None,
dietary_flags: None,
},
]),
},
Customization {
id: "test-multi".to_string(),
name: "Test Multi".to_string(),
r#type: CustomizationType::MultiSelect,
required: false,
default: CustomizationDefault::StringArray(vec!["option1".to_string()]),
min_selections: Some(0),
max_selections: Some(2),
min: None,
max: None,
step: None,
unit_price_adjustment: None,
unit_nutrition_adjustments: None,
options: Some(vec![
CustomizationOption {
id: "option1".to_string(),
name: "Option 1".to_string(),
price_adjustment: None,
nutrition_adjustments: None,
allergens: None,
dietary_flags: None,
},
CustomizationOption {
id: "option2".to_string(),
name: "Option 2".to_string(),
price_adjustment: None,
nutrition_adjustments: None,
allergens: None,
dietary_flags: None,
},
]),
},
];
// Valid selections
let selections = vec![
SelectedCustomization {
customization_id: "test-single".to_string(),
selection: CustomizationSelection::String("option2".to_string()),
},
SelectedCustomization {
customization_id: "test-multi".to_string(),
selection: CustomizationSelection::StringArray(vec!["option1".to_string(), "option2".to_string()]),
},
];
// Test valid selections
let result = validate_selected_customizations(&selections, &customizations);
assert!(result.is_ok());
// Test missing required customization
let missing_required = vec![
SelectedCustomization {
customization_id: "test-multi".to_string(),
selection: CustomizationSelection::StringArray(vec!["option1".to_string()]),
},
];
let result = validate_selected_customizations(&missing_required, &customizations);
assert!(result.is_err());
// Test invalid selection value
let invalid_selection = vec![
SelectedCustomization {
customization_id: "test-single".to_string(),
selection: CustomizationSelection::String("nonexistent".to_string()),
},
];
let result = validate_selected_customizations(&invalid_selection, &customizations);
assert!(result.is_err());
// Test invalid selection type
let invalid_type = vec![
SelectedCustomization {
customization_id: "test-single".to_string(),
selection: CustomizationSelection::Number(1.0),
},
];
let result = validate_selected_customizations(&invalid_type, &customizations);
assert!(result.is_err());
// Test nonexistent customization
let nonexistent = vec![
SelectedCustomization {
customization_id: "nonexistent".to_string(),
selection: CustomizationSelection::String("option1".to_string()),
},
];
let result = validate_selected_customizations(&nonexistent, &customizations);
assert!(result.is_err());
}
#[test]
fn test_validate_order() {
// Create items for the order
let items = vec![
Item {
id: "item1".to_string(),
name: "Item 1".to_string(),
category: "test".to_string(),
vendor_id: None,
description: None,
subcategory: None,
image_url: None,
base_price: Some(10.0),
currency: Some("USD".to_string()),
nutrition: None,
customizations: None,
selected_customizations: None,
quantity: Some(1),
item_note: None,
calculated: None,
components: None,
availability: None,
popularity: None,
},
];
// Valid order
let order = Order {
id: Some("order1".to_string()),
status: Some(OrderStatus::Draft),
created: Some(chrono::Utc::now()),
pickup_time: None,
delivery_time: None,
r#type: Some(OrderType::Pickup),
customer_notes: None,
payment: Some(Payment {
status: Some(PaymentStatus::Unpaid),
method: None,
subtotal: Some(10.0),
tax: Some(0.8),
tip: Some(2.0),
total: 12.8,
currency: "USD".to_string(),
}),
customer: None,
delivery: None,
};
// Test valid order
let result = validate_order(&order, &items);
assert!(result.is_ok());
// Test invalid payment total
let mut invalid_total = order.clone();
if let Some(payment) = &mut invalid_total.payment {
payment.total = 0.0;
}
let result = validate_order(&invalid_total, &items);
assert!(result.is_err());
// Test inconsistent payment components
let mut inconsistent = order.clone();
if let Some(payment) = &mut inconsistent.payment {
payment.total = 15.0; // Doesn't match subtotal + tax + tip
}
let result = validate_order(&inconsistent, &items);
assert!(result.is_err());
// Test delivery order without delivery info
let mut missing_delivery = order.clone();
missing_delivery.r#type = Some(OrderType::Delivery);
let result = validate_order(&missing_delivery, &items);
assert!(result.is_err());
// Test valid delivery order
let mut valid_delivery = order;
valid_delivery.r#type = Some(OrderType::Delivery);
valid_delivery.delivery = Some(Delivery {
address: Address {
street: "123 Main St".to_string(),
city: "Anytown".to_string(),
region: "State".to_string(),
postal_code: "12345".to_string(),
country: "USA".to_string(),
},
instructions: None,
});
let result = validate_order(&valid_delivery, &items);
assert!(result.is_ok());
}
}