Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 119 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ license = "BlueOak-1.0.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
chrono-tz = "0.10.0"
color-eyre = "0.6.0"
dotenv = "0.15.0"
femme = "2.1.1"
Expand Down
27 changes: 11 additions & 16 deletions src/ipn_handler.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use chrono::prelude::*;
use chrono::Duration;
use chrono::SecondsFormat::Secs;
use serde::Deserialize;
use serde_json::json;
use tide::http::Method;
use tide::{Body, Response, StatusCode};

// The info! logging macro comes from crate::azure_function::logger
use crate::azure_function::{AzureFnLogger, AzureFnLoggerExt};
use crate::{AppRequest, MailchimpQuery, MailchimpResponse};
use crate::{
parse_mailchimp_date, safe_add_year, today_ppt, AppRequest, MailchimpDateFormat,
MailchimpQuery, MailchimpResponse,
};

#[allow(
clippy::upper_case_acronyms,
Expand Down Expand Up @@ -235,8 +236,8 @@ pub async fn ipn_handler(mut req: AppRequest) -> tide::Result<Response> {
));
}

let utc_now: DateTime<Utc> = Utc::now();
let mut utc_expires: DateTime<Utc> = Utc::now() + Duration::days(365);
let today: NaiveDate = today_ppt();
let mut expires: NaiveDate = safe_add_year(today, 1);

let status;
if mailchimp_res.status().is_client_error() {
Expand All @@ -257,20 +258,14 @@ pub async fn ipn_handler(mut req: AppRequest) -> tide::Result<Response> {
};

// Pick up an existing date if one exists and if we can parse it.
if let Ok(existing_expire_day) =
NaiveDate::parse_from_str(&mc_json.merge_fields.expires, "%Y-%m-%d")
{
let existing_expire = existing_expire_day
.and_hms_opt(12, 0, 0)
.expect("Failed to create a NaiveDateTime with the given date and time.");
let existing_expire = DateTime::from_naive_utc_and_offset(existing_expire, Utc);
if existing_expire > utc_expires {
if let Ok(existing_expire_day) = parse_mailchimp_date(&mc_json.merge_fields.expires) {
if existing_expire_day > expires {
info!(
logger,
"existing EXPIRES is beyond one year, using it: {}",
mc_json.merge_fields.expires
);
utc_expires = existing_expire;
expires = existing_expire_day;
}
} else {
// Weird, we couldn't parse the date. Maybe it was blank in mailchimp? (Some old members had blank fields.)
Expand All @@ -287,8 +282,8 @@ pub async fn ipn_handler(mut req: AppRequest) -> tide::Result<Response> {
"merge_fields": {
"FNAME": ipn_transaction_message.first_name,
"LNAME": ipn_transaction_message.last_name,
"JOINED": utc_now.to_rfc3339_opts(Secs, true),
"EXPIRES": utc_expires.to_rfc3339_opts(Secs, true),
"JOINED": today.to_mailchimp_format(),
"EXPIRES": expires.to_mailchimp_format(),
},
"status": status,
});
Expand Down
30 changes: 28 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,11 @@
clippy::used_underscore_binding
)]

use std::sync::Arc;

use chrono::{Datelike, Local, NaiveDate, ParseError};
use chrono_tz::America::Vancouver;
use log::warn;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use surf::Client;
use tide::{Request, Response, Server, StatusCode};

Expand All @@ -78,6 +79,31 @@ pub struct AppState {

pub type AppRequest = Request<Arc<AppState>>;

trait MailchimpDateFormat {
fn to_mailchimp_format(&self) -> String;
}

impl MailchimpDateFormat for NaiveDate {
fn to_mailchimp_format(&self) -> String {
self.format("%Y-%m-%d").to_string()
}
}

pub fn parse_mailchimp_date(iso_date: &str) -> Result<NaiveDate, ParseError> {
NaiveDate::parse_from_str(iso_date, "%Y-%m-%d")
}

pub fn today_ppt() -> NaiveDate {
Local::now().with_timezone(&Vancouver).date_naive()
}

pub fn safe_add_year(date: NaiveDate, years: i32) -> NaiveDate {
let target_year = date.year() + years;
date.with_year(target_year)
.or_else(|| NaiveDate::from_ymd_opt(target_year, 2, 28)) // Handle feb 29th edge case
.expect("Failed to calculate a valid date")
}

async fn get_ping(_req: AppRequest) -> tide::Result<Response> {
Ok(StatusCode::Ok.into())
}
Expand Down
13 changes: 8 additions & 5 deletions src/membership_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use tide::{Response, StatusCode};

// The info! logging macro comes from crate::azure_function::logger
use crate::azure_function::{AzureFnLogger, AzureFnLoggerExt};
use crate::{AppRequest, MailchimpQuery, MailchimpResponse};
use crate::{parse_mailchimp_date, today_ppt, AppRequest, MailchimpQuery, MailchimpResponse};

/// Check if an email is in MailChimp & when it's expiry date is, if available.
pub async fn membership_check(mut req: AppRequest) -> tide::Result<Response> {
Expand Down Expand Up @@ -49,10 +49,13 @@ pub async fn membership_check(mut req: AppRequest) -> tide::Result<Response> {
StatusCode::Ok => {
let mc_json: MailchimpResponse = mailchimp_res.body_json().await?;

let membership = if mc_json.status == "pending" || mc_json.status == "subscribed" {
"active"
} else {
"expired"
// Parse the expiration date from the MailChimp response
let expires_date = parse_mailchimp_date(&mc_json.merge_fields.expires);
let today = today_ppt();

let membership = match expires_date {
Ok(expiry) if expiry >= today => "active",
_ => "expired",
};

let body = json!({
Expand Down
Loading