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
//! # Indeed Search
//!
//! Builds Indeed url query string from search params

use std::fmt;
use url::{ParseError, Url};

#[macro_use]
extern crate derive_builder;

/// Sort decending by relevance to query or by date posted
#[derive(Clone, Debug)]
pub enum SortBy {
    /// Job relevance to query
    Relevance,
    /// Date posted
    Date,
}
impl fmt::Display for SortBy {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use SortBy::*;
        write!(
            f,
            "{}",
            match self {
                Relevance => "relevance",
                Date => "date",
            },
        )
    }
}

/// Filter jobs by jobtite or employer
#[derive(Clone, Debug)]
pub enum ShowFrom {
    All,
    JobSite,
    Employer,
}
impl fmt::Display for ShowFrom {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ShowFrom::*;
        write!(
            f,
            "{}",
            match self {
                All => "",
                JobSite => "jobsite",
                Employer => "employer",
            },
        )
    }
}

/// Filter jobs by job type
#[derive(Clone, Debug)]
pub enum JobType {
    AllJobTypes,
    FullTime,
    Contract,
    PartTime,
    Temporary,
    Internship,
    Commission,
}
impl fmt::Display for JobType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use JobType::*;
        write!(
            f,
            "{}",
            match self {
                AllJobTypes => "",
                FullTime => "fulltime",
                Contract => "contract",
                PartTime => "parttime",
                Temporary => "temporary",
                Internship => "internship",
                Commission => "commission",
            },
        )
    }
}

/// Filter jobs by required experience level
#[derive(Clone, Debug)]
pub enum ExperienceLevel {
    /// Don't filter by experience level
    AllLevels,
    /// Entry Level jobs only
    EntryLevel,
    /// Mid Level jobs only
    MidLevel,
    /// Senoir Level jobs only
    SeniorLevel,
}
impl fmt::Display for ExperienceLevel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ExperienceLevel::*;
        write!(
            f,
            "{}",
            match self {
                AllLevels => "",
                EntryLevel => "entry_level",
                MidLevel => "mid_level",
                SeniorLevel => "senior_level",
            },
        )
    }
}

/// Whether to exclude staffing aggencies postings
#[derive(Clone, Debug)]
pub enum ExcludeStaffingAgencies {
    /// Exclude jobs posted by staffing agencies
    True,
    /// Don't exclude jobs posted by staffing agencies
    False,
}
impl fmt::Display for ExcludeStaffingAgencies {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ExcludeStaffingAgencies::*;
        write!(
            f,
            "{}",
            match self {
                True => "directhire",
                False => "",
            },
        )
    }
}

/// Filter by city
#[derive(Clone, Debug)]
pub enum City {
    /// `CityState` is the city and state: (City, State)
    CityState(String, String),
    /// ``ZipCode` is the zip code of the city
    ZipCode(String),
}
impl fmt::Display for City {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use City::*;
        write!(
            f,
            "{}",
            match self {
                CityState(city, state) => format!("{}, {}", city, state).to_string(),
                ZipCode(zip) => zip.to_string(),
            },
        )
    }
}

/// IndeedQuery configuration
/// # Examples
/// ```
///use indeed_search::{ JobType, IndeedQueryBuilder, ExperienceLevel, ExcludeStaffingAgencies, SortBy, City};
///
///let query = IndeedQueryBuilder::default()
///    .has_words_in_title(vec!["Developer".to_string()])
///    .excludes_all_words(vec![
///        "C#".to_string(),
///        ".NET".to_string(),
///        "Azure".to_string(),
///        "Unpaid".to_string(),
///        "Senior".to_string(),
///    ])
///    .exclude_staffing_agencies(ExcludeStaffingAgencies::True)
///    .has_any_words(vec![
///        "Embedded".to_string(),
///        "Full-Stack".to_string(),
///        "Linux".to_string(),
///        "Rust".to_string(),
///        "Unix".to_string(),
///        "Web".to_string(),
///    ])
///    .min_salary(85000 as u32)
///    .city(City::CityState(
///        "San Francisco".to_string(),
///        "CA".to_string(),
///    ))
///    .radius(40 as u32)
///    .job_type(JobType::FullTime)
///    .experience_level(ExperienceLevel::EntryLevel)
///    .sort_by(SortBy::Date)
///    .max_age(14 as u32)
///    .build()
///    .unwrap();
///assert_eq!(query.build_url().unwrap(), "https://www.indeed.com/jobs?as_and=&as_phr=&as_any=Embedded+Full-Stack+Linux+Rust+Unix+Web&as_not=C%23+.NET+Azure+Unpaid+Senior&as_ttl=Developer&as_cmp=&jt=fulltime&st=&explvl=entry_level&sr=directhire&salary=85000&radius=40&l=San+Francisco%2C+CA&fromage=14&limit=50&sort=date&psf=advsrch&from=advancedsearch&start=0");
/// ```

#[allow(dead_code)]
#[derive(Builder, Debug, Clone)]
#[builder(setter(into))]
pub struct IndeedQuery {
    /// target city
    #[builder(default = "City::ZipCode("")")]
    pub city: City,

    #[builder(default = "0")]
    /// maximum distance in miles from target city
    pub radius: u32,

    /// max number of days since jobs were posted
    #[builder(default = "14")]
    pub max_age: u32,

    /// minimum expecteded salary for all jobs
    #[builder(default = "0")]
    pub min_salary: u32,

    /// experience level filter for all jobs
    #[builder(default = "ExperienceLevel::AllLevels")]
    pub experience_level: ExperienceLevel,

    /// job type filter for all jobs
    #[builder(default = "JobType::AllJobTypes")]
    pub job_type: JobType,

    /// job posting must contain all keywords
    #[builder(default = "Vec::new()")]
    pub contains_all_words: Vec<String>,

    /// job posting must contain exact phrase
    #[builder(default = "String::new()")]
    pub has_exact_phrase: String,

    /// job posting must contain at least one keyword
    #[builder(default = "Vec::new()")]
    pub has_any_words: Vec<String>,

    /// job posting must not contain any keyword
    #[builder(default = "Vec::new()")]
    pub excludes_all_words: Vec<String>,

    /// job posting must contain all words in job title
    #[builder(default = "Vec::new()")]
    pub has_words_in_title: Vec<String>,

    /// jobs only posted by a specified company
    #[builder(default = "String::new()")]
    pub company: String,

    /// whether or not to include postings from staffing agencies in result
    #[builder(default = "ExcludeStaffingAgencies::False")]
    pub exclude_staffing_agencies: ExcludeStaffingAgencies,

    /// show from filter
    #[builder(default = "ShowFrom::All")]
    pub show_from: ShowFrom,

    /// sort resuts by relevance or date posted
    #[builder(default = "SortBy::Relevance")]
    pub sort_by: SortBy,

    /// limit number of jobs per page
    #[builder(default = "50")]
    pub limit: u32,

    /// show results starting after `n` number of jobs
    #[builder(default = "0")]
    pub start: u32,
}
impl IndeedQuery {
    /// convert query to url string
    pub fn build_url(&self) -> Result<String, ParseError> {
        let url = Url::parse_with_params(
            "https://www.indeed.com/jobs",
            &[
                ("as_and", self.contains_all_words.join(" ")),
                ("as_phr", self.has_exact_phrase.to_string()),
                ("as_any", self.has_any_words.join(" ")),
                ("as_not", self.excludes_all_words.join(" ")),
                ("as_ttl", self.has_words_in_title.join(" ")),
                ("as_cmp", self.company.to_string()),
                ("jt", self.job_type.to_string()),
                ("st", self.show_from.to_string()),
                ("explvl", self.experience_level.to_string()),
                ("sr", self.exclude_staffing_agencies.to_string()),
                ("salary", self.min_salary.to_string()),
                ("radius", self.radius.to_string()),
                ("l", self.city.to_string()),
                ("fromage", self.max_age.to_string()),
                ("limit", self.limit.to_string()),
                ("sort", self.sort_by.to_string()),
                ("psf", "advsrch".to_string()),
                ("from", "advancedsearch".to_string()),
                ("start", self.start.to_string()),
            ],
        )?;
        Ok(url.as_ref().to_string())
    }

    /// increments start offset to next page of results
    pub fn increment_page(&mut self) {
        self.start += self.limit;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn build_url_test() {
        let query = IndeedQueryBuilder::default()
            .has_words_in_title(vec!["Developer".to_string()])
            .excludes_all_words(vec![
                "C#".to_string(),
                ".NET".to_string(),
                "Azure".to_string(),
                "Unpaid".to_string(),
                "Senior".to_string(),
            ])
            .exclude_staffing_agencies(ExcludeStaffingAgencies::True)
            .has_any_words(vec![
                "Embedded".to_string(),
                "Full-Stack".to_string(),
                "Linux".to_string(),
                "Rust".to_string(),
                "Unix".to_string(),
                "Web".to_string(),
            ])
            .min_salary(85000 as u32)
            .city(City::CityState(
                "San Francisco".to_string(),
                "CA".to_string(),
            ))
            .radius(40 as u32)
            .job_type(JobType::FullTime)
            .experience_level(ExperienceLevel::EntryLevel)
            .sort_by(SortBy::Date)
            .max_age(14 as u32)
            .build()
            .unwrap();
        assert_eq!(query.build_url().unwrap(), "https://www.indeed.com/jobs?as_and=&as_phr=&as_any=Embedded+Full-Stack+Linux+Rust+Unix+Web&as_not=C%23+.NET+Azure+Unpaid+Senior&as_ttl=Developer&as_cmp=&jt=fulltime&st=&explvl=entry_level&sr=directhire&salary=85000&radius=40&l=San+Francisco%2C+CA&fromage=14&limit=50&sort=date&psf=advsrch&from=advancedsearch&start=0");
    }
}