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
use std::collections::HashMap;
use std::env;

use airtable_api::{Airtable, Record, User as AirtableUser};
use chrono::naive::NaiveDate;
use chrono::offset::Utc;
use chrono::DateTime;
use chrono_humanize::HumanTime;
use serde::{Deserialize, Serialize};
use serde_json::Value;

static BASE_ID_CUSTOMER_LEADS: &str = "appr7imQLcR3pWaNa";
static MAILING_LIST_SIGNUPS_TABLE: &str = "Mailing List Signups";

/// The data type for a Journal Club Meeting.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JournalClubMeeting {
    pub title: String,
    pub issue: String,
    pub papers: Vec<Paper>,
    pub date: NaiveDate,
    pub coordinator: String,
    pub state: String,
    pub recording: String,
}

impl JournalClubMeeting {
    pub fn as_slack_msg(&self) -> Value {
        let mut color = "#ED64A6";
        if self.state == "closed" {
            color = "#ED8936";
        }

        let mut objects: Vec<Value> = Default::default();

        if !self.recording.is_empty() {
            objects.push(json!({
                "elements": [{
                    "text": format!("<{}|Meeting recording>", self.recording),
                    "type": "mrkdwn"
                }],
                "type": "context"
            }));
        }

        for p in self.papers.clone() {
            let mut title = p.title.to_string();
            if p.title == self.title {
                title = "Paper".to_string();
            }
            objects.push(json!({
                "elements": [{
                    "text": format!("<{}|{}>", p.link, title),
                    "type": "mrkdwn"
                }],
                "type": "context"
            }));
        }

        json!({
            "response_type": "in_channel",
             "attachments": [{
                    "blocks": [{
                    "text": {
                        "text": format!("<{}|*{}*>", self.issue, self.title),
                        "type": "mrkdwn"
                    },
                    "type": "section"
                },
                {
                    "elements": [{
                        "text": "<https://github.com/oxidecomputer/papers/blob/master/os/countering-ipc-threats-minix3.pdf|Countering IPC Threats in Multiserver Operating Systems>",
                        "type": "mrkdwn"
                    }],
                    "type": "context"
                },
                {
                    "elements": [{
                        "text": format!("<https://github.com/{}|@{}> | {} | status: *{}*",self.coordinator,self.coordinator,self.date.format("%m/%d/%Y"),self.state),
                        "type": "mrkdwn"
                    }],
                    "type": "context"
                }],
                "color": color
            }]
        })
    }
}

/// The data type for a paper.
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct Paper {
    pub title: String,
    pub link: String,
}

/// The data type for an RFD.
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct RFD {
    pub number: String,
    pub title: String,
    pub link: String,
    pub state: String,
    pub discussion: String,
}

impl RFD {
    pub fn as_slack_msg(&self, num: i32) -> String {
        let mut msg = format!("RFD {} {} (_*{}*_) <https://{}.rfd.oxide.computer|github> <https://rfd.shared.oxide.computer/rfd/{}|rendered>", num, self.title, self.state, num, self.number);

        if !self.discussion.is_empty() {
            msg += &format!(" <{}|discussion>", self.discussion);
        }

        msg
    }
}

/// The Airtable fields type for RFDs.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RFDFields {
    #[serde(rename = "Number")]
    pub number: i32,
    #[serde(rename = "State")]
    pub state: String,
    #[serde(rename = "Title")]
    pub title: String,
    // Never modify this, it is based on a function.
    #[serde(skip_serializing_if = "Option::is_none", rename = "Name")]
    pub name: Option<String>,
    // Never modify this, it is based on a function.
    #[serde(skip_serializing_if = "Option::is_none", rename = "Link")]
    pub link: Option<String>,
}

/// The Airtable fields type for Customer Interactions.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomerInteractionFields {
    #[serde(rename = "Name")]
    pub name: String,
    #[serde(rename = "Company")]
    pub company: Vec<String>,
    #[serde(with = "meeting_date_format", rename = "Date")]
    pub date: NaiveDate,
    #[serde(rename = "Type")]
    pub meeting_type: String,
    #[serde(rename = "Phase")]
    pub phase: String,
    #[serde(rename = "People")]
    pub people: Vec<String>,
    #[serde(rename = "Oxide Folks")]
    pub oxide_folks: Vec<AirtableUser>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Link to Notes")]
    pub notes_link: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Notes")]
    pub notes: Option<String>,
}

/// The Airtable fields type for discussion topics.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DiscussionFields {
    #[serde(rename = "Topic")]
    pub topic: String,
    #[serde(rename = "Submitter")]
    pub submitter: AirtableUser,
    #[serde(rename = "Priority")]
    pub priority: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Notes")]
    pub notes: Option<String>,
    // Never modify this, it is a linked record.
    #[serde(rename = "Associated meetings")]
    pub associated_meetings: Vec<String>,
}

/// The Airtable fields type for a mailing list signup.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MailingListSignupFields {
    #[serde(rename = "Email Address")]
    pub email: String,
    #[serde(rename = "First Name")]
    pub first_name: String,
    #[serde(rename = "Last Name")]
    pub last_name: String,
    #[serde(rename = "Company")]
    pub company: String,
    #[serde(rename = "What is your interest in Oxide Computer Company?")]
    pub interest: String,
    #[serde(rename = "Interested in On the Metal podcast updates?")]
    pub wants_podcast_updates: bool,
    #[serde(rename = "Interested in the Oxide newsletter?")]
    pub wants_newsletter: bool,
    #[serde(rename = "Interested in product updates?")]
    pub wants_product_updates: bool,
    #[serde(rename = "Date Added")]
    pub date_added: DateTime<Utc>,
    #[serde(rename = "Opt-in Date")]
    pub optin_date: DateTime<Utc>,
    #[serde(rename = "Last Changed")]
    pub last_changed: DateTime<Utc>,
}

impl MailingListSignupFields {
    pub fn new(params: HashMap<String, String>) -> Self {
        let email = if let Some(e) = params.get("data[email]") {
            e.trim().to_string()
        } else {
            "".to_string()
        };
        let first_name = if let Some(f) = params.get("data[merges][FNAME]") {
            f.trim().to_string()
        } else {
            "".to_string()
        };
        let last_name = if let Some(l) = params.get("data[merges][LNAME]") {
            l.trim().to_string()
        } else {
            "".to_string()
        };
        let company = if let Some(c) = params.get("data[merges][COMPANY]") {
            c.trim().to_string()
        } else {
            "".to_string()
        };
        let interest = if let Some(i) = params.get("data[merges][INTEREST]") {
            i.trim().to_string()
        } else {
            "".to_string()
        };

        let wants_podcast_updates =
            params.get("data[merges][GROUPINGS][0][groups]").is_some();
        let wants_newsletter =
            params.get("data[merges][GROUPINGS][1][groups]").is_some();
        let wants_product_updates =
            params.get("data[merges][GROUPINGS][2][groups]").is_some();

        let time: DateTime<Utc> = if let Some(f) = params.get("fired_at") {
            DateTime::parse_from_str(
                &(f.to_owned() + " +00:00"),
                "%Y-%m-%d %H:%M:%S  %:z",
            )
            .unwrap()
            .with_timezone(&Utc)
        } else {
            println!(
                "could not parse mailchimp date time so defaulting to now"
            );

            Utc::now()
        };

        MailingListSignupFields {
            email,
            first_name,
            last_name,
            company,
            interest,
            wants_podcast_updates,
            wants_newsletter,
            wants_product_updates,
            date_added: time,
            optin_date: time,
            last_changed: time,
        }
    }

    pub async fn push_to_airtable(&self) {
        let api_key = env::var("AIRTABLE_API_KEY").unwrap();
        // Initialize the Airtable client.
        let airtable =
            Airtable::new(api_key.to_string(), BASE_ID_CUSTOMER_LEADS);

        // Create the record.
        let record = Record {
            id: None,
            created_time: None,
            fields: serde_json::to_value(self).unwrap(),
        };

        // Send the new record to the airtable client.
        // Batch can only handle 10 at a time.
        airtable
            .create_records(MAILING_LIST_SIGNUPS_TABLE, vec![record])
            .await
            .unwrap();

        println!("created mailing list record in airtable: {:?}", self);
    }

    pub fn as_slack_msg(&self) -> Value {
        let dur = self.date_added - Utc::now();
        let time = HumanTime::from(dur);

        let mut msg = format!(
            "*{} {}* <mailto:{}|{}>",
            self.first_name, self.last_name, self.email, self.email
        );
        if !self.interest.is_empty() {
            msg += &format!("\n>{}", self.interest.trim());
        }

        let updates = format!(
            "podcast updates: _{}_ | newsletter: _{}_ | product updates: _{}_",
            self.wants_podcast_updates,
            self.wants_newsletter,
            self.wants_product_updates
        );

        let mut context = "".to_string();
        if !self.company.is_empty() {
            context += &format!("works at {} | ", self.company);
        }
        context += &format!("subscribed to mailing list {}", time);

        json!({
            "attachments": [
                {
                    "color": "#F6E05E",
                    "blocks": [
                        {
                            "type": "section",
                            "text": {
                                "type": "mrkdwn",
                                "text": msg
                            }
                        },
                        {
                            "type": "context",
                            "elements": [{
                                "type": "mrkdwn",
                                "text": updates
                            }]
                        },
                        {
                            "type": "context",
                            "elements": [{
                                "type": "mrkdwn",
                                "text": context
                            }]
                        }
                    ]
                }
            ]
        })
    }
}

/// The Airtable fields type for meetings.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MeetingFields {
    #[serde(rename = "Name")]
    pub name: String,
    #[serde(with = "meeting_date_format", rename = "Date")]
    pub date: NaiveDate,
    #[serde(rename = "Week")]
    pub week: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Notes")]
    pub notes: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Action items")]
    pub action_items: Option<String>,
    // Never modify this, it is a linked record.
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "Proposed discussion"
    )]
    pub proposed_discussion: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Recording")]
    pub recording: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "Attendees")]
    pub attendees: Option<Vec<AirtableUser>>,
}

/// Convert the date format `%Y-%m-%d` to a NaiveDate.
mod meeting_date_format {
    use chrono::naive::NaiveDate;
    use serde::{self, Deserialize, Deserializer, Serializer};

    const FORMAT: &str = "%Y-%m-%d";

    // The signature of a serialize_with function must follow the pattern:
    //
    //    fn serialize<S>(&T, S) -> Result<S::Ok, S::Error>
    //    where
    //        S: Serializer
    //
    // although it may also be generic over the input types T.
    pub fn serialize<S>(
        date: &NaiveDate,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s = format!("{}", date.format(FORMAT));
        serializer.serialize_str(&s)
    }

    // The signature of a deserialize_with function must follow the pattern:
    //
    //    fn deserialize<'de, D>(D) -> Result<T, D::Error>
    //    where
    //        D: Deserializer<'de>
    //
    // although it may also be generic over the output types T.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<NaiveDate, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;

        Ok(NaiveDate::parse_from_str(&s, FORMAT).unwrap())
    }
}

/// The data type for sending reminders for the product huddle meetings.
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
pub struct ProductEmailData {
    pub date: String,
    pub topics: Vec<DiscussionFields>,
    pub last_meeting_reports_link: String,
    pub meeting_id: String,
    pub should_send: bool,
}