Skip to main content

pkpass/pass/
fields.rs

1use chrono::{DateTime, Utc};
2use is_empty::IsEmpty;
3use serde::{Deserialize, Serialize};
4
5use super::semantic_tags::SemanticTags;
6
7/// Represents the groups of fields that display information on the front and back of a pass.
8#[derive(Serialize, Deserialize, Debug)]
9#[serde(rename_all = "camelCase")]
10pub struct Fields {
11    /// Represents the fields that display additional information on the front of a pass.
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub auxiliary_fields: Option<Vec<Content>>,
14
15    /// Represents the fields that display information on the back of a pass.
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub back_fields: Option<Vec<Content>>,
18
19    /// Represents the fields that display information at the top of a pass.
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub header_fields: Option<Vec<Content>>,
22
23    /// Represents the fields that display the most important information on a pass.
24    pub primary_fields: Vec<Content>,
25
26    /// Represents the fields that display supporting information on the front of a pass.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub secondary_fields: Option<Vec<Content>>,
29}
30
31impl Default for Fields {
32    /// Creates an empty `Fields`.
33    fn default() -> Self {
34        Self {
35            auxiliary_fields: None,
36            back_fields: None,
37            header_fields: None,
38            primary_fields: Vec::new(),
39            secondary_fields: None,
40        }
41    }
42}
43
44#[derive(Serialize, Deserialize, Debug)]
45#[serde(untagged)]
46pub enum ContentValue {
47    String(String),
48    Date(DateTime<Utc>),
49    Int(i64),
50    Float(f64),
51}
52
53impl From<String> for ContentValue {
54    fn from(value: String) -> Self {
55        Self::String(value)
56    }
57}
58
59impl From<&str> for ContentValue {
60    fn from(value: &str) -> Self {
61        Self::String(value.to_string())
62    }
63}
64
65impl From<DateTime<Utc>> for ContentValue {
66    fn from(value: DateTime<Utc>) -> Self {
67        Self::Date(value)
68    }
69}
70
71impl From<i64> for ContentValue {
72    fn from(value: i64) -> Self {
73        Self::Int(value)
74    }
75}
76
77impl From<f64> for ContentValue {
78    fn from(value: f64) -> Self {
79        Self::Float(value)
80    }
81}
82
83/// Represents the information to display in a field on a pass.
84#[derive(Serialize, Deserialize, Debug)]
85#[serde(rename_all = "camelCase")]
86pub struct Content {
87    /// (Required) A unique key that identifies a field in the pass; for example, “departure-gate”.
88    pub key: String,
89
90    /// (Required) The value to use for the field; for example, 42. A date or time value must include a time zone.
91    pub value: ContentValue,
92
93    /// All optionals
94    #[serde(flatten)]
95    pub options: ContentOptions,
96}
97
98impl Content {
99    /// Creates `FieldContent`.
100    #[must_use]
101    pub fn new(key: &str, value: &str, options: ContentOptions) -> Self {
102        Self {
103            key: String::from(key),
104            value: ContentValue::from(value),
105            options,
106        }
107    }
108}
109
110/// Represents options for `FieldContent`
111#[derive(Serialize, Deserialize, Debug)]
112#[serde(rename_all = "camelCase")]
113pub struct ContentOptions {
114    /// The value of the field, including HTML markup for links.
115    ///
116    /// The only supported tag is the `<a>` tag and its href attribute.
117    ///
118    /// The value of this key overrides that of the value key.
119    #[serde(default)]
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub attributed_value: Option<String>,
122
123    /// A format string for the alert text to display when the pass is updated.
124    ///
125    /// The format string must contain the escape %@, which is replaced with the field’s new value.
126    /// For example, “Gate changed to %@”.
127    ///
128    /// You must provide a value for the system to show a change notification.
129    ///
130    /// This field isn’t used for watchOS.
131    #[serde(default)]
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub change_message: Option<String>,
134
135    /// The currency code to use for the value of the field.
136    #[serde(default)]
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub currency_code: Option<String>,
139
140    /// The data detectors to apply to the value of a field on the back of the pass.
141    ///
142    /// The default is to apply all data detectors. To use no data detectors, specify an empty array.
143    ///
144    /// You don’t use data detectors for fields on the front of the pass.
145    ///
146    /// This field isn’t used for watchOS.
147    #[serde(default)]
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub data_detector_types: Option<DetectorType>,
150
151    /// The style of the date to display in the field.
152    #[serde(default)]
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub date_style: Option<DateStyle>,
155
156    /// A Boolean value that controls the time zone for the time and date to display in the field.
157    ///
158    /// The default value is false, which displays the time and date using the current device’s time zone.
159    /// Otherwise, the time and date appear in the time zone associated with the date and time of value.
160    ///
161    /// This key doesn’t affect the pass relevance calculation.
162    #[serde(default)]
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub ignores_time_zone: Option<bool>,
165
166    /// A Boolean value that controls whether the date appears as a relative date.\
167    ///
168    /// The default value is false, which displays the date as an absolute date.
169    ///
170    /// This key doesn’t affect the pass relevance calculation.
171    #[serde(default)]
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub is_relative: Option<bool>,
174
175    /// The text for a field label.
176    #[serde(default)]
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub label: Option<String>,
179
180    /// The style of the number to display in the field.
181    ///
182    /// Formatter styles have the same meaning as the formats with corresponding names in NumberFormatter.Style.
183    #[serde(default)]
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub number_style: Option<NumberStyle>,
186
187    /// The alignment for the content of a field. The default is natural alignment, which aligns the text based on its script direction.
188    ///
189    /// This key is invalid for primary and back fields.
190    #[serde(default)]
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub text_alignment: Option<TextAlignment>,
193
194    /// The style of the time displayed in the field.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub time_style: Option<DateStyle>,
197
198    /// Semantic tags
199    ///
200    /// Metadata the system uses to offer a pass and suggest related actions.
201    #[serde(default)]
202    #[serde(skip_serializing_if = "SemanticTags::is_empty")]
203    pub semantics: SemanticTags,
204}
205
206impl Default for ContentOptions {
207    /// Creates an empty `FieldContentOptions`.
208    fn default() -> Self {
209        Self {
210            attributed_value: None,
211            change_message: None,
212            currency_code: None,
213            data_detector_types: None,
214            date_style: None,
215            ignores_time_zone: None,
216            is_relative: None,
217            label: None,
218            number_style: None,
219            text_alignment: None,
220            time_style: None,
221            semantics: SemanticTags::default(),
222        }
223    }
224}
225
226/// The data detectors to apply to the value of a field on the back of the pass.
227#[derive(Serialize, Deserialize, Debug)]
228pub enum DetectorType {
229    #[serde(rename = "PKDataDetectorTypePhoneNumber")]
230    PhoneNumber,
231    #[serde(rename = "PKDataDetectorTypeLink")]
232    Link,
233    #[serde(rename = "PKDataDetectorTypeAddress")]
234    Address,
235    #[serde(rename = "PKDataDetectorTypeCalendarEvent")]
236    CalendarEvent,
237}
238
239/// The style of the date to display in the field.
240#[derive(Serialize, Deserialize, Debug)]
241pub enum DateStyle {
242    #[serde(rename = "PKDateStyleNone")]
243    None,
244    #[serde(rename = "PKDateStyleShort")]
245    Short,
246    #[serde(rename = "PKDateStyleMedium")]
247    Medium,
248    #[serde(rename = "PKDateStyleLong")]
249    Long,
250    #[serde(rename = "PKDateStyleFull")]
251    Full,
252}
253
254/// The style of the number to display in the field.
255#[derive(Serialize, Deserialize, Debug)]
256pub enum NumberStyle {
257    #[serde(rename = "PKNumberStyleDecimal")]
258    Decimal,
259    #[serde(rename = "PKNumberStylePercent")]
260    Percent,
261    #[serde(rename = "PKNumberStyleScientific")]
262    Scientific,
263    #[serde(rename = "PKNumberStyleSpellOut")]
264    SpellOut,
265}
266
267/// The alignment for the content of a field.
268#[derive(Serialize, Deserialize, Debug)]
269pub enum TextAlignment {
270    #[serde(rename = "PKTextAlignmentLeft")]
271    Left,
272    #[serde(rename = "PKTextAlignmentCenter")]
273    Center,
274    #[serde(rename = "PKTextAlignmentRight")]
275    Right,
276    #[serde(rename = "PKTextAlignmentNatural")]
277    Natural,
278}
279
280/// Groups of fields that display information on the front and back of a pass.
281#[derive(Serialize, Deserialize, Debug)]
282#[serde(rename_all = "camelCase")]
283pub enum Type {
284    /// Represents the groups of fields that display the information for a boarding pass.
285    BoardingPass {
286        /// Groups of fields that display information on the front and back of a pass.
287        #[serde(flatten)]
288        pass_fields: Fields,
289
290        /// (Required) The type of transit for a boarding pass. This key is invalid for other types of passes.
291        #[serde(rename = "transitType")]
292        transit_type: TransitType,
293    },
294    /// Represents the groups of fields that display the information for a coupon.
295    Coupon {
296        /// Groups of fields that display information on the front and back of a pass.
297        #[serde(flatten)]
298        pass_fields: Fields,
299    },
300    /// Represents the groups of fields that display the information for an event ticket.
301    EventTicket {
302        /// Groups of fields that display information on the front and back of a pass.
303        #[serde(flatten)]
304        pass_fields: Fields,
305    },
306    /// Represents the groups of fields that display the information for an event ticket.
307    StoreCard {
308        /// Groups of fields that display information on the front and back of a pass.
309        #[serde(flatten)]
310        pass_fields: Fields,
311    },
312    /// Represents the groups of fields that display the information for a generic pass.
313    Generic {
314        /// Groups of fields that display information on the front and back of a pass.
315        #[serde(flatten)]
316        pass_fields: Fields,
317    },
318}
319
320/// The type of transit for a boarding pass.
321#[derive(Serialize, Deserialize, Debug)]
322pub enum TransitType {
323    #[serde(rename = "PKTransitTypeAir")]
324    Air,
325    #[serde(rename = "PKTransitTypeBoat")]
326    Boat,
327    #[serde(rename = "PKTransitTypeBus")]
328    Bus,
329    #[serde(rename = "PKTransitTypeGeneric")]
330    Generic,
331    #[serde(rename = "PKTransitTypeTrain")]
332    Train,
333}
334
335impl Type {
336    /// Add field that display additional information on the front of a pass.
337    #[must_use]
338    pub fn add_auxiliary_field(mut self, field: Content) -> Self {
339        match self {
340            Self::BoardingPass {
341                ref mut pass_fields,
342                transit_type: _,
343            }
344            | Self::Coupon {
345                ref mut pass_fields,
346            }
347            | Self::EventTicket {
348                ref mut pass_fields,
349            }
350            | Self::StoreCard {
351                ref mut pass_fields,
352            }
353            | Self::Generic {
354                ref mut pass_fields,
355            } => pass_fields
356                .auxiliary_fields
357                .get_or_insert_default()
358                .push(field),
359        }
360        self
361    }
362
363    /// Add field that display information on the back of a pass.
364    #[must_use]
365    pub fn add_back_field(mut self, field: Content) -> Self {
366        match self {
367            Self::BoardingPass {
368                ref mut pass_fields,
369                transit_type: _,
370            }
371            | Self::Coupon {
372                ref mut pass_fields,
373            }
374            | Self::EventTicket {
375                ref mut pass_fields,
376            }
377            | Self::StoreCard {
378                ref mut pass_fields,
379            }
380            | Self::Generic {
381                ref mut pass_fields,
382            } => pass_fields.back_fields.get_or_insert_default().push(field),
383        }
384        self
385    }
386
387    /// Add field that display information at the top of a pass.
388    #[must_use]
389    pub fn add_header_field(mut self, field: Content) -> Self {
390        match self {
391            Self::BoardingPass {
392                ref mut pass_fields,
393                transit_type: _,
394            }
395            | Self::Coupon {
396                ref mut pass_fields,
397            }
398            | Self::EventTicket {
399                ref mut pass_fields,
400            }
401            | Self::StoreCard {
402                ref mut pass_fields,
403            }
404            | Self::Generic {
405                ref mut pass_fields,
406            } => pass_fields
407                .header_fields
408                .get_or_insert_default()
409                .push(field),
410        }
411        self
412    }
413
414    /// Add field that display the most important information on a pass.
415    #[must_use]
416    pub fn add_primary_field(mut self, field: Content) -> Self {
417        match self {
418            Self::BoardingPass {
419                ref mut pass_fields,
420                transit_type: _,
421            }
422            | Self::Coupon {
423                ref mut pass_fields,
424            }
425            | Self::EventTicket {
426                ref mut pass_fields,
427            }
428            | Self::StoreCard {
429                ref mut pass_fields,
430            }
431            | Self::Generic {
432                ref mut pass_fields,
433            } => pass_fields.primary_fields.push(field),
434        }
435        self
436    }
437
438    /// Add field that display supporting information on the front of a pass.
439    #[must_use]
440    pub fn add_secondary_field(mut self, field: Content) -> Self {
441        match self {
442            Self::BoardingPass {
443                ref mut pass_fields,
444                transit_type: _,
445            }
446            | Self::Coupon {
447                ref mut pass_fields,
448            }
449            | Self::EventTicket {
450                ref mut pass_fields,
451            }
452            | Self::StoreCard {
453                ref mut pass_fields,
454            }
455            | Self::Generic {
456                ref mut pass_fields,
457            } => pass_fields
458                .secondary_fields
459                .get_or_insert_default()
460                .push(field),
461        }
462        self
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use crate::pass::semantic_tags::SemanticTagSeat;
469
470    use super::*;
471
472    #[test]
473    fn make_pass() {
474        // Serialization test
475        let pass = Type::Generic {
476            pass_fields: Fields {
477                ..Default::default()
478            },
479        };
480
481        let json = serde_json::to_string_pretty(&pass).unwrap();
482
483        println!("{json}");
484
485        let json_expected = r#"{
486  "generic": {
487    "primaryFields": []
488  }
489}"#;
490        assert_eq!(json_expected, json);
491
492        // Deserialization test
493        let pass: Type = serde_json::from_str(json_expected).unwrap();
494        let json = serde_json::to_string_pretty(&pass).unwrap();
495        assert_eq!(json_expected, json);
496    }
497
498    #[test]
499    fn make_boarding_pass() {
500        // Serialization test
501        let boarding_pass = Type::BoardingPass {
502            pass_fields: Fields {
503                ..Default::default()
504            },
505            transit_type: TransitType::Air,
506        }
507        .add_primary_field(Content::new(
508            "title",
509            "Airplane Ticket",
510            ContentOptions::default(),
511        ))
512        .add_primary_field(Content::new(
513            "seat",
514            "12",
515            ContentOptions {
516                semantics: SemanticTags {
517                    seats: vec![SemanticTagSeat {
518                        seat_number: String::from("12").into(),
519                        seat_row: String::from("5A").into(),
520                        seat_section: String::from("A").into(),
521                        ..Default::default()
522                    }],
523                    ..Default::default()
524                },
525                label: String::from("Seat").into(),
526                ..Default::default()
527            },
528        ))
529        .add_header_field(Content::new("company", "DAL", ContentOptions::default()))
530        .add_header_field(Content::new(
531            "company_sub",
532            "Dodo Air Lines",
533            ContentOptions::default(),
534        ))
535        .add_secondary_field(Content::new(
536            "description",
537            "Some information here",
538            ContentOptions::default(),
539        ));
540
541        let json = serde_json::to_string_pretty(&boarding_pass).unwrap();
542
543        println!("{json}");
544
545        let json_expected = r#"{
546  "boardingPass": {
547    "headerFields": [
548      {
549        "key": "company",
550        "value": "DAL"
551      },
552      {
553        "key": "company_sub",
554        "value": "Dodo Air Lines"
555      }
556    ],
557    "primaryFields": [
558      {
559        "key": "title",
560        "value": "Airplane Ticket"
561      },
562      {
563        "key": "seat",
564        "value": "12",
565        "label": "Seat",
566        "semantics": {
567          "seats": [
568            {
569              "seatNumber": "12",
570              "seatRow": "5A",
571              "seatSection": "A"
572            }
573          ]
574        }
575      }
576    ],
577    "secondaryFields": [
578      {
579        "key": "description",
580        "value": "Some information here"
581      }
582    ],
583    "transitType": "PKTransitTypeAir"
584  }
585}"#;
586        assert_eq!(json_expected, json);
587
588        // Deserialization test
589        let boarding_pass: Type = serde_json::from_str(json_expected).unwrap();
590        let json = serde_json::to_string_pretty(&boarding_pass).unwrap();
591        assert_eq!(json_expected, json);
592    }
593
594    #[test]
595    fn make_event_ticket() {
596        // Serialization test
597        let event_ticket = Type::EventTicket {
598            pass_fields: Fields {
599                ..Default::default()
600            },
601        }
602        .add_primary_field(Content::new(
603            "title",
604            "Super Ticket",
605            ContentOptions {
606                label: String::from("NAME").into(),
607                ..Default::default()
608            },
609        ))
610        .add_primary_field(Content::new("seat", "12", ContentOptions::default()))
611        .add_header_field(Content::new(
612            "event_title",
613            "KKK",
614            ContentOptions::default(),
615        ))
616        .add_header_field(Content::new("some", "123", ContentOptions::default()))
617        .add_secondary_field(Content::new(
618            "description",
619            "Some information here",
620            ContentOptions::default(),
621        ));
622
623        let json = serde_json::to_string_pretty(&event_ticket).unwrap();
624
625        println!("{json}");
626
627        let json_expected = r#"{
628  "eventTicket": {
629    "headerFields": [
630      {
631        "key": "event_title",
632        "value": "KKK"
633      },
634      {
635        "key": "some",
636        "value": "123"
637      }
638    ],
639    "primaryFields": [
640      {
641        "key": "title",
642        "value": "Super Ticket",
643        "label": "NAME"
644      },
645      {
646        "key": "seat",
647        "value": "12"
648      }
649    ],
650    "secondaryFields": [
651      {
652        "key": "description",
653        "value": "Some information here"
654      }
655    ]
656  }
657}"#;
658        assert_eq!(json_expected, json);
659
660        // Deserialization test
661        let event_ticket: Type = serde_json::from_str(json_expected).unwrap();
662        let json = serde_json::to_string_pretty(&event_ticket).unwrap();
663        assert_eq!(json_expected, json);
664    }
665}