Skip to content

Commit

Permalink
currency config (#32)
Browse files Browse the repository at this point in the history
* currency config

* fix fmt

* currency constructor

* Added test

* cargo fmt

---------

Co-authored-by: alvarocabo <alvarocaboac2@gmail.com>
  • Loading branch information
pxp9 and 0xCAB0 authored Jul 15, 2023
1 parent 22564e0 commit 229c391
Show file tree
Hide file tree
Showing 3 changed files with 181 additions and 11 deletions.
82 changes: 72 additions & 10 deletions src/model/filter.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use typed_builder::TypedBuilder;

use crate::queries::Host;

pub mod brand;
pub mod category;
pub mod category_tree;
Expand Down Expand Up @@ -224,25 +226,85 @@ pub struct Filter {
#[builder(default, setter(strip_option))]
pub price_to: Option<u32>,
}
/**
Represents the currency for filtering items
/*
Represents the article status for filtering items.
*/

Variants:
- `NewTags`: The article status for new items with tags.
- `NewNoTags`: The article status for new items without tags.
- `VeryGood`: The article status for items in very good condition.
- `Good`: The article status for items in good condition.
- `Satisfactory`: The article status for items in satisfactory condition.
// TODO problema si se quiere filtrar por moneda , se tiene que cambiar el host del pais y al cambiar el host del pais se debe refrescar cookies
// GBP => Host uk
// EUR => Pais de Europa sera el default
// USD => Host com
// CSK => Host cz
// PLN => Host pl
// SEK => Host se
// RON => Host ro
// HUF => Host hu
#[derive(Debug, Clone)]
pub enum Currency {
/// Euro
EUR,
/// US Dollar
USD,
/// Great Britain Pound
GBP,
/// Czech korona
CZK,
/// Polish złoty
PLN,
/// Swedish krona
SEK,
/// Romanian leu
RON,
/// Hungarian forint
HUF,
}

Trait Implementations:
- `From<&ArticleStatus> for &str>`: Converts an `ArticleStatus` variant to a string slice. */
impl From<Currency> for Host {
fn from(currency: Currency) -> Self {
match currency {
Currency::USD => Host::Com,
Currency::GBP => Host::Uk,
Currency::CZK => Host::Cz,
Currency::PLN => Host::Pl,
Currency::SEK => Host::Se,
Currency::RON => Host::Ro,
Currency::HUF => Host::Hu,
Currency::EUR => Host::random_euro_host(),
}
}
}

impl From<Currency> for &str {
fn from(currency: Currency) -> Self {
match currency {
Currency::USD => "USD",
Currency::GBP => "GBP",
Currency::CZK => "CZK",
Currency::PLN => "PLN",
Currency::SEK => "SEK",
Currency::RON => "RON",
Currency::HUF => "HUF",
Currency::EUR => "EUR",
}
}
}

/**
Represents the article status for filtering items.
*/
#[derive(Debug, Clone)]
pub enum ArticleStatus {
/// The article status for new items with tags.
NewTags,
/// The article status for new items without tags.
NewNoTags,
/// The article status for items in very good condition.
VeryGood,
/// Good`: The article status for items in good condition.
Good,
/// The article status for items in satisfactory condition.
Satisfactory,
}

Expand Down
83 changes: 83 additions & 0 deletions src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ use reqwest_cookie_store::CookieStoreMutex;
use std::sync::Arc;
use thiserror::Error;

use crate::model::filter::Currency;
use crate::model::filter::Filter;
use crate::model::items::Items;

Expand Down Expand Up @@ -89,6 +90,55 @@ pub enum Host {
Hu,
}

impl Host {
/// Returns true if a Host has the Euro as the currency
pub fn is_euro_host(&self) -> bool {
!matches!(
self,
Host::Com | Host::Uk | Host::Cz | Host::Pl | Host::Se | Host::Ro | Host::Hu
)
}

/// Returns a Host that has Euro as currency
pub fn random_euro_host() -> Self {
let domains_euro: Vec<Host> = DOMAINS
.iter()
.map(|domain_str| (*domain_str).into())
.filter(|domain: &Host| domain.is_euro_host())
.collect();

let random_index = rand::thread_rng().gen_range(0..domains_euro.len());

domains_euro[random_index].clone()
}
}

impl From<&str> for Host {
fn from(string: &str) -> Self {
match string {
"fr" => Host::Fr,
"be" => Host::Be,
"es" => Host::Es,
"lu" => Host::Lu,
"nl" => Host::Nl,
"lt" => Host::Lt,
"de" => Host::De,
"at" => Host::At,
"it" => Host::It,
"uk" => Host::Uk,
"pt" => Host::Pt,
"com" => Host::Com,
"cz" => Host::Cz,
"sk" => Host::Sk,
"pl" => Host::Pl,
"se" => Host::Se,
"ro" => Host::Ro,
"hu" => Host::Hu,
_ => panic!("Not valid host"),
}
}
}

impl From<Host> for &str {
fn from(val: Host) -> Self {
match val {
Expand Down Expand Up @@ -196,6 +246,24 @@ impl<'a> VintedWrapper<'a> {
cookie_store,
}
}
/// Creates a new `VintedWrapper` with the specified currency.
///
/// The `new_with_currency` function creates a new `VintedWrapper` instance with the specified currency. It initializes the cookie store and client for making requests to the Vinted API.
///
/// # Arguments
///
/// * `currency` - The currency is translated to a Host that will be used in the wrapper.
///
/// # Examples
///
/// ```rust
/// use vinted_rs::VintedWrapper;
/// use vinted_rs::model::filter::Currency;
/// let wrapper = VintedWrapper::new_with_currency(Currency::EUR);
/// ```
pub fn new_with_currency(currency: Currency) -> Self {
VintedWrapper::new_with_host(currency.into())
}
/// Returns the current host domain.
///
/// The `get_host` method returns the current host domain used by the `VintedWrapper` instance.
Expand All @@ -215,7 +283,10 @@ impl<'a> VintedWrapper<'a> {
pub fn get_host(&self) -> &str {
self.host
}
/**
After changing host is always necessary to refresh cookies
*/
pub fn set_new_random_host(&mut self) {
self.host = random_host();
}
Expand All @@ -224,6 +295,18 @@ impl<'a> VintedWrapper<'a> {
self.host = host.into();
}

pub fn set_host_by_currency(&mut self, currency: Currency) {
let host: Host = currency.into();

let actual_host: Host = self.host.into();

if !host.is_euro_host() || !actual_host.is_euro_host() {
let host_str: &str = host.into();

self.host = host_str;
}
}

fn get_client(&self) -> &'static Client {
CLIENT.get_or_init(|| -> Client {
reqwest::ClientBuilder::new()
Expand Down
27 changes: 26 additions & 1 deletion src/tests/queries.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::db::DbController;
use crate::model::filter::Filter;
use crate::model::filter::{Currency, Filter};
use crate::queries::VintedWrapperError;
use crate::VintedWrapper;
use bb8_postgres::tokio_postgres::NoTls;
Expand Down Expand Up @@ -206,3 +206,28 @@ async fn test_get_items_by_color() {
},
};
}

#[tokio::test]
async fn test_get_items_by_currency() {
let vinted = VintedWrapper::new_with_currency(Currency::CZK);

let filter: Filter = Filter::builder().build();

let num: usize = 20;

match vinted.get_items(&filter, num as u32).await {
Ok(items) => {
assert_eq!(items.items.len(), num);
let ok: bool = items.items.iter().all(|item| {
let c: &str = Currency::CZK.into();
item.currency == c
});

assert!(ok);
}
Err(err) => match err {
VintedWrapperError::ItemNumberError => unreachable!(),
VintedWrapperError::CookiesError(_) => (),
},
};
}

0 comments on commit 229c391

Please sign in to comment.