Skip to main content

fauna_api/magpie/
portfolio.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4
5use crate::authentification::CredentialsOrApiKey;
6use crate::error::Result;
7use crate::groups::Group;
8use crate::http::{client, deserialize_date, encode, ok, serialize_date};
9
10pub use super::room::{PortfolioEntry, PortfolioRoom};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
14pub enum Asset {
15    Equity,
16    Crypto,
17    MoneyMarket,
18    Other,
19}
20
21impl Asset {
22    pub(crate) fn as_str(self) -> &'static str {
23        match self {
24            Asset::Equity => "EQUITY",
25            Asset::Crypto => "CRYPTO",
26            Asset::MoneyMarket => "MONEY_MARKET",
27            Asset::Other => "OTHER",
28        }
29    }
30}
31
32fn source<'de, D: serde::Deserializer<'de>>(
33    deserializer: D,
34) -> std::result::Result<Option<String>, D::Error> {
35    Ok(Value::deserialize(deserializer)?
36        .as_str()
37        .filter(|source| !source.is_empty())
38        .map(str::to_string))
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct Position {
44    pub id: String,
45    pub asset: Asset,
46    pub symbol: String,
47    pub name: String,
48    pub quantity: f64,
49    pub cost_basis: f64,
50    #[serde(
51        deserialize_with = "deserialize_date",
52        serialize_with = "serialize_date"
53    )]
54    pub date: DateTime<Utc>,
55    /// HTTPS URL Magpie pulls for OTHER quotes. Ignored for other assets.
56    #[serde(
57        default,
58        deserialize_with = "source",
59        skip_serializing_if = "Option::is_none"
60    )]
61    pub source: Option<String>,
62}
63
64/// `{ value, date }` in the TypeScript SDK: one estimate of a holding's worth.
65#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
66pub struct Estimate {
67    pub value: f64,
68    #[serde(
69        deserialize_with = "deserialize_date",
70        serialize_with = "serialize_date"
71    )]
72    pub date: DateTime<Utc>,
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76pub struct Holding {
77    pub id: String,
78    pub name: String,
79    #[serde(default)]
80    pub estimates: Vec<Estimate>,
81}
82
83/// `Position | Holding` in the TypeScript SDK: an entry with an `asset` is a position.
84#[derive(Debug, Clone, PartialEq, Serialize)]
85#[serde(untagged)]
86pub enum PositionOrHolding {
87    Position(Position),
88    Holding(Holding),
89}
90
91impl<'de> Deserialize<'de> for PositionOrHolding {
92    fn deserialize<D: serde::Deserializer<'de>>(
93        deserializer: D,
94    ) -> std::result::Result<Self, D::Error> {
95        let raw = Value::deserialize(deserializer)?;
96        if raw.get("asset").is_some() {
97            serde_json::from_value(raw)
98                .map(PositionOrHolding::Position)
99                .map_err(serde::de::Error::custom)
100        } else {
101            serde_json::from_value(raw)
102                .map(PositionOrHolding::Holding)
103                .map_err(serde::de::Error::custom)
104        }
105    }
106}
107
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110pub struct Portfolio {
111    pub id: String,
112    pub name: String,
113    #[serde(default)]
114    pub profile: Vec<PositionOrHolding>,
115    #[serde(
116        deserialize_with = "deserialize_date",
117        serialize_with = "serialize_date"
118    )]
119    pub created: DateTime<Utc>,
120    #[serde(
121        deserialize_with = "deserialize_date",
122        serialize_with = "serialize_date"
123    )]
124    pub last_modified: DateTime<Utc>,
125}
126
127#[derive(Debug, Clone, Default)]
128pub struct GroupOpts {
129    pub group: Option<Group>,
130}
131
132fn request(
133    request: reqwest::RequestBuilder,
134    authorization: &CredentialsOrApiKey,
135    opts: &GroupOpts,
136) -> reqwest::RequestBuilder {
137    let request = request.header(
138        "Authorization",
139        match authorization {
140            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
141            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
142        },
143    );
144    match &opts.group {
145        Some(group) => request.header("Group", &group.id),
146        None => request,
147    }
148}
149
150fn portfolio_url(portfolio_id: &str) -> String {
151    format!(
152        "{}/magpie/portfolios/{}",
153        super::get_url(),
154        encode(portfolio_id)
155    )
156}
157
158pub async fn get_portfolios(
159    authorization: &CredentialsOrApiKey,
160    opts: GroupOpts,
161) -> Result<Vec<Portfolio>> {
162    let response = request(
163        client().get(format!("{}/magpie/portfolios", super::get_url())),
164        authorization,
165        &opts,
166    )
167    .send()
168    .await?;
169    Ok(ok(response).await?.json().await?)
170}
171
172pub async fn get_portfolio(
173    authorization: &CredentialsOrApiKey,
174    portfolio_id: &str,
175    opts: GroupOpts,
176) -> Result<Portfolio> {
177    let response = request(
178        client().get(portfolio_url(portfolio_id)),
179        authorization,
180        &opts,
181    )
182    .send()
183    .await?;
184    Ok(ok(response).await?.json().await?)
185}
186
187async fn created_id(response: reqwest::Response) -> Result<String> {
188    let json: Value = ok(response).await?.json().await?;
189    Ok(match &json["id"] {
190        Value::String(id) => id.clone(),
191        Value::Null => String::new(),
192        id => id.to_string(),
193    })
194}
195
196pub async fn create_portfolio(
197    authorization: &CredentialsOrApiKey,
198    name: &str,
199    opts: GroupOpts,
200) -> Result<String> {
201    let response = request(
202        client().post(format!("{}/magpie/portfolios", super::get_url())),
203        authorization,
204        &opts,
205    )
206    .json(&json!({ "name": name }))
207    .send()
208    .await?;
209    created_id(response).await
210}
211
212pub async fn remove_portfolio(
213    authorization: &CredentialsOrApiKey,
214    portfolio_id: &str,
215    opts: GroupOpts,
216) -> Result<()> {
217    let response = request(
218        client().delete(portfolio_url(portfolio_id)),
219        authorization,
220        &opts,
221    )
222    .send()
223    .await?;
224    ok(response).await?;
225    Ok(())
226}
227
228/// `Omit<Position, 'id'>` in the TypeScript SDK.
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230#[serde(rename_all = "camelCase")]
231pub struct PositionDraft {
232    pub asset: Asset,
233    pub symbol: String,
234    pub name: String,
235    pub quantity: f64,
236    pub cost_basis: f64,
237    #[serde(
238        deserialize_with = "deserialize_date",
239        serialize_with = "serialize_date"
240    )]
241    pub date: DateTime<Utc>,
242    /// HTTPS URL Magpie pulls for OTHER quotes. Ignored for other assets.
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub source: Option<String>,
245}
246
247pub async fn add_position(
248    authorization: &CredentialsOrApiKey,
249    portfolio_id: &str,
250    position: &PositionDraft,
251    opts: GroupOpts,
252) -> Result<String> {
253    let response = request(
254        client().post(format!("{}/positions", portfolio_url(portfolio_id))),
255        authorization,
256        &opts,
257    )
258    .json(&json!({ "position": position }))
259    .send()
260    .await?;
261    created_id(response).await
262}
263
264fn serialize_optional_date<S: serde::Serializer>(
265    date: &Option<DateTime<Utc>>,
266    serializer: S,
267) -> std::result::Result<S::Ok, S::Error> {
268    match date {
269        Some(date) => serialize_date(date, serializer),
270        None => serializer.serialize_none(),
271    }
272}
273
274/// `Partial<Position>` in the TypeScript SDK.
275#[derive(Debug, Clone, Default, PartialEq, Serialize)]
276#[serde(rename_all = "camelCase")]
277pub struct PartialPosition {
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub id: Option<String>,
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub asset: Option<Asset>,
282    #[serde(skip_serializing_if = "Option::is_none")]
283    pub symbol: Option<String>,
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub name: Option<String>,
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub quantity: Option<f64>,
288    #[serde(skip_serializing_if = "Option::is_none")]
289    pub cost_basis: Option<f64>,
290    #[serde(
291        skip_serializing_if = "Option::is_none",
292        serialize_with = "serialize_optional_date"
293    )]
294    pub date: Option<DateTime<Utc>>,
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub source: Option<String>,
297}
298
299pub async fn update_position(
300    authorization: &CredentialsOrApiKey,
301    portfolio_id: &str,
302    position_id: &str,
303    updates: &PartialPosition,
304    opts: GroupOpts,
305) -> Result<()> {
306    let response = request(
307        client().patch(format!(
308            "{}/positions/{}",
309            portfolio_url(portfolio_id),
310            encode(position_id)
311        )),
312        authorization,
313        &opts,
314    )
315    .json(&json!({ "updates": updates }))
316    .send()
317    .await?;
318    ok(response).await?;
319    Ok(())
320}
321
322pub async fn remove_position(
323    authorization: &CredentialsOrApiKey,
324    portfolio_id: &str,
325    position_id: &str,
326    opts: GroupOpts,
327) -> Result<()> {
328    let response = request(
329        client().delete(format!(
330            "{}/positions/{}",
331            portfolio_url(portfolio_id),
332            encode(position_id)
333        )),
334        authorization,
335        &opts,
336    )
337    .send()
338    .await?;
339    ok(response).await?;
340    Ok(())
341}
342
343/// `Omit<Holding, 'id'>` in the TypeScript SDK.
344#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
345pub struct HoldingDraft {
346    pub name: String,
347    pub estimates: Vec<Estimate>,
348}
349
350pub async fn add_holding(
351    authorization: &CredentialsOrApiKey,
352    portfolio_id: &str,
353    holding: &HoldingDraft,
354    opts: GroupOpts,
355) -> Result<String> {
356    let response = request(
357        client().post(format!("{}/holdings", portfolio_url(portfolio_id))),
358        authorization,
359        &opts,
360    )
361    .json(&json!({ "holding": holding }))
362    .send()
363    .await?;
364    created_id(response).await
365}
366
367pub async fn add_estimate(
368    authorization: &CredentialsOrApiKey,
369    portfolio_id: &str,
370    holding_id: &str,
371    estimate: &Estimate,
372    opts: GroupOpts,
373) -> Result<()> {
374    let response = request(
375        client().post(format!(
376            "{}/holdings/{}/estimates",
377            portfolio_url(portfolio_id),
378            encode(holding_id)
379        )),
380        authorization,
381        &opts,
382    )
383    .json(&json!({ "estimate": estimate }))
384    .send()
385    .await?;
386    ok(response).await?;
387    Ok(())
388}
389
390pub async fn remove_holding(
391    authorization: &CredentialsOrApiKey,
392    portfolio_id: &str,
393    holding_id: &str,
394    opts: GroupOpts,
395) -> Result<()> {
396    let response = request(
397        client().delete(format!(
398            "{}/holdings/{}",
399            portfolio_url(portfolio_id),
400            encode(holding_id)
401        )),
402        authorization,
403        &opts,
404    )
405    .send()
406    .await?;
407    ok(response).await?;
408    Ok(())
409}