use chrono::{Datelike, Local};
use crate::errors::ValidationError;
use crate::traits::{PrimitiveValue, ValueObject};
pub type CardExpiryDateInput = String;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct CardExpiryDate(String);
impl ValueObject for CardExpiryDate {
type Input = CardExpiryDateInput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
let trimmed = value.trim();
if trimmed.is_empty() {
return Err(ValidationError::empty("CardExpiryDate"));
}
let parts: Vec<&str> = trimmed.split('/').collect();
if parts.len() != 2 {
return Err(ValidationError::invalid("CardExpiryDate", trimmed));
}
let month: u8 = parts[0]
.parse()
.map_err(|_| ValidationError::invalid("CardExpiryDate", trimmed))?;
if !(1..=12).contains(&month) {
return Err(ValidationError::invalid("CardExpiryDate", trimmed));
}
let year_str = parts[1];
let full_year: u16 = match year_str.len() {
2 => {
let yy: u16 = year_str
.parse()
.map_err(|_| ValidationError::invalid("CardExpiryDate", trimmed))?;
2000 + yy
}
4 => year_str
.parse()
.map_err(|_| ValidationError::invalid("CardExpiryDate", trimmed))?,
_ => return Err(ValidationError::invalid("CardExpiryDate", trimmed)),
};
let now = Local::now();
let current_year = now.year() as u16;
let current_month = now.month() as u8;
if full_year < current_year || (full_year == current_year && month < current_month) {
return Err(ValidationError::invalid("CardExpiryDate", trimmed));
}
let canonical = format!("{:02}/{:02}", month, full_year % 100);
Ok(Self(canonical))
}
fn into_inner(self) -> Self::Input {
self.0
}
}
impl PrimitiveValue for CardExpiryDate {
type Primitive = String;
fn value(&self) -> &String {
&self.0
}
}
impl CardExpiryDate {
pub fn month(&self) -> u8 {
self.0[..2].parse().unwrap()
}
pub fn year(&self) -> u16 {
let yy: u16 = self.0[3..].parse().unwrap();
2000 + yy
}
pub fn months_until(&self) -> u32 {
let now = Local::now();
let current_year = now.year() as u16;
let current_month = now.month() as u8;
let expiry_months = self.year() * 12 + self.month() as u16;
let current_months = current_year * 12 + current_month as u16;
expiry_months.saturating_sub(current_months) as u32
}
}
impl TryFrom<String> for CardExpiryDate {
type Error = ValidationError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
#[cfg(feature = "serde")]
impl From<CardExpiryDate> for String {
fn from(v: CardExpiryDate) -> String {
v.0
}
}
impl TryFrom<&str> for CardExpiryDate {
type Error = ValidationError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value.to_owned())
}
}
impl std::fmt::Display for CardExpiryDate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_future_mm_yy() {
let e = CardExpiryDate::new("12/28".into()).unwrap();
assert_eq!(e.value(), "12/28");
}
#[test]
fn accepts_future_mm_yyyy() {
let e = CardExpiryDate::new("06/2030".into()).unwrap();
assert_eq!(e.value(), "06/30");
}
#[test]
fn accepts_current_month() {
let e = CardExpiryDate::new("04/26".into()).unwrap();
assert_eq!(e.value(), "04/26");
}
#[test]
fn month_accessor() {
let e = CardExpiryDate::new("12/28".into()).unwrap();
assert_eq!(e.month(), 12);
}
#[test]
fn year_accessor() {
let e = CardExpiryDate::new("12/28".into()).unwrap();
assert_eq!(e.year(), 2028);
}
#[test]
fn rejects_past_date() {
assert!(CardExpiryDate::new("01/25".into()).is_err());
}
#[test]
fn rejects_previous_month() {
assert!(CardExpiryDate::new("03/26".into()).is_err());
}
#[test]
fn rejects_empty() {
assert!(CardExpiryDate::new(String::new()).is_err());
}
#[test]
fn rejects_invalid_month() {
assert!(CardExpiryDate::new("13/28".into()).is_err());
assert!(CardExpiryDate::new("00/28".into()).is_err());
}
#[test]
fn rejects_invalid_format() {
assert!(CardExpiryDate::new("12-28".into()).is_err());
assert!(CardExpiryDate::new("1228".into()).is_err());
}
#[test]
fn try_from_str() {
let e: CardExpiryDate = "12/28".try_into().unwrap();
assert_eq!(e.value(), "12/28");
}
}