odoo-api 0.2.5

Type-safe and full-coverage implementation of the Odoo JSON-RPC API, including ORM and Web methods. Supports sessioning, multi-database, async and blocking via reqwest, and bring-your-own requests.
Documentation
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! The Odoo "common" service (JSON-RPC)
//!
//! This service provides misc methods like `version` and `authenticate`.
//!
//! Note that the authentication methods (`login` and `authenticate`) are both "dumb";
//! that is, they do not work with Odoo's sessioning mechanism. The result is that
//! these methods will not work for non-JSON-RPC methods (e.g. "Web" methods), and
//! they will not handle multi-database Odoo deployments.

use crate as odoo_api;
use crate::jsonrpc::{OdooApiMethod, OdooId};
use odoo_api_macros::odoo_api;
use serde::ser::SerializeTuple;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use serde_tuple::Serialize_tuple;

/// Check the user credentials and return the user ID
///
/// This method performs a "login" to the Odoo server, and returns the corresponding
/// user ID (`uid`).
///
/// Note that the Odoo JSON-RPC API is stateless; there are no sessions or tokens,
/// each requests passes the password (or API key). Therefore, calling this method
/// "login" is a misnomer - it doesn't actually "login", just checks the credentials
/// and returns the ID.
///
/// ## Example
/// ```no_run
/// # #[cfg(not(feature = "types-only"))]
/// # fn test() -> Result<(), Box<dyn std::error::Error>> {
/// # use odoo_api::OdooClient;
/// # let client = OdooClient::new_reqwest_blocking("")?;
/// # let mut client = client.authenticate_manual("", "", 1, "", None);
/// // note that auth fields (db, login, password) are auto-filled
/// // for you by the client
/// let resp = client.common_login().send()?;
///
/// println!("UID: {}", resp.uid);
/// # Ok(())
/// # }
/// ```
///<br />
///
/// See: [odoo/service/common.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/service/common.py#L19-L20)  
/// See also: [base/models/res_users.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/addons/base/models/res_users.py#L762-L787)
#[odoo_api(
    service = "common",
    method = "login",
    name = "common_login",
    auth = true
)]
#[derive(Debug, Serialize_tuple)]
pub struct Login {
    /// The database name
    pub db: String,

    /// The username (e.g., email)
    pub login: String,

    /// The user password
    pub password: String,
}

/// Represents the response to an Odoo [`Login`] call
#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LoginResponse {
    pub uid: OdooId,
}

/// Check the user credentials and return the user ID (web)
///
/// This method performs a "login" to the Odoo server, and returns the corresponding
/// user ID (`uid`). It is identical to [`Login`], except that it accepts an extra
/// param `user_agent_env`, which is normally sent by the browser.
///
/// This method is inteded for browser-based API implementations. You should use [`Login`] instead.
///
/// ## Example
/// ```no_run
/// # #[cfg(not(feature = "types-only"))]
/// # fn test() -> Result<(), Box<dyn std::error::Error>> {
/// # use odoo_api::OdooClient;
/// # let client = OdooClient::new_reqwest_blocking("")?;
/// # let mut client = client.authenticate_manual("", "", 1, "", None);
/// use odoo_api::jmap;
///
/// // note that auth fields (db, login, password) are auto-filled
/// // for you by the client
/// let resp = client.common_authenticate(
///     jmap!{
///         "base_location": "https://demo.odoo.com"
///     }
/// ).send()?;
///
/// println!("UID: {}", resp.uid);
/// # Ok(())
/// # }
/// ```
///<br />
///
/// See: [odoo/service/common.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/service/common.py#L22-L29)  
/// See also: [base/models/res_users.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/addons/base/models/res_users.py#L762-L787)
#[odoo_api(
    service = "common",
    method = "authenticate",
    name = "common_authenticate",
    auth = true
)]
#[derive(Debug, Serialize_tuple)]
pub struct Authenticate {
    /// The database name
    pub db: String,

    /// The username (e.g., email)
    pub login: String,

    /// The user password
    pub password: String,

    /// A mapping of user agent env entries
    pub user_agent_env: Map<String, Value>,
}

/// Represents the response to an Odoo [`Authenticate`] call
#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AuthenticateResponse {
    pub uid: OdooId,
}

/// Fetch detailed information about the Odoo version
///
/// This method returns some information about the Odoo version (represented in
/// the [`ServerVersionInfo`] struct), along with some other metadata.
///
/// Odoo's versioning was inspired by Python's [`sys.version_info`](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/release.py#L11),
/// with an added field to indicate whether the server is running Enterprise or
/// Community edition. In practice, `minor` and `micro` are typically both `0`,
/// so an Odoo version looks something like: `14.0.0.final.0.e`
///
/// ## Example
/// ```no_run
/// # #[cfg(not(feature = "types-only"))]
/// # fn test() -> Result<(), Box<dyn std::error::Error>> {
/// # use odoo_api::OdooClient;
/// # let client = OdooClient::new_reqwest_blocking("")?;
/// # let mut client = client.authenticate_manual("", "", 1, "", None);
/// let resp = client.common_version().send()?;
///
/// println!("Version Info: {:#?}", resp);
/// # Ok(())
/// # }
/// ```
///<br />
///
/// See: [odoo/service/common.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/service/common.py#L31-L32)  
/// See also: [odoo/service/common.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/service/common.py#L12-L17)  
/// See also: [odoo/release.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/release.py)
#[odoo_api(
    service = "common",
    method = "version",
    name = "common_version",
    auth = false
)]
#[derive(Debug)]
pub struct Version {}

// Version has no fields, but needs to output in JSON: `[]`
impl Serialize for Version {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let state = serializer.serialize_tuple(0)?;
        state.end()
    }
}

/// Represents the response to an Odoo [`Version`] call
#[derive(Debug, Serialize, Deserialize)]
pub struct VersionResponse {
    /// The "pretty" version, normally something like `16.0+e` or `15.0`
    pub server_version: String,

    /// The "full" version. See [`ServerVersionInfo`] for details
    pub server_version_info: ServerVersionInfo,

    /// The server "series"; like `server_version`, but without any indication of Enterprise vs Community (e.g., `16.0` or `15.0`)
    pub server_serie: String,

    /// The Odoo "protocol version". At the time of writing, it isn't clear where this is actually used, and `1` is always returned
    pub protocol_version: u32,
}

/// A struct representing the Odoo server version info
///
/// See: [odoo/services/common.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/service/common.py#L12-L17)  
/// See also: [odoo/release.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/release.py)
#[derive(Debug, Serialize_tuple, Deserialize)]
pub struct ServerVersionInfo {
    /// The "major" version (e.g., `16`)
    pub major: u32,

    /// The "minor" version (e.g., `0`)
    pub minor: u32,

    /// The "micro" version (e.g., `0`)
    pub micro: u32,

    /// The "release level"; one of `alpha`, `beta`, `candidate`, or `final`. For live servers, this is almost always `final`
    pub release_level: String,

    /// The release serial
    pub serial: u32,

    /// A string indicating whether Odoo is running in Enterprise or Community mode; `None` = Community, Some("e") = Enterprise
    pub enterprise: Option<String>,
}

/// Fetch basic information about the Odoo version
///
/// Returns a link to the old OpenERP website, and optionally the "basic" Odoo
/// version string (e.g. `16.0+e`).
///
/// This call isn't particularly useful on its own - you probably want to use [`Version`]
/// instead.
///
/// ## Example
/// ```no_run
/// # #[cfg(not(feature = "types-only"))]
/// # fn test() -> Result<(), Box<dyn std::error::Error>> {
/// # use odoo_api::OdooClient;
/// # let client = OdooClient::new_reqwest_blocking("")?;
/// # let mut client = client.authenticate_manual("", "", 1, "", None);
/// let resp = client.common_about(true).send()?;
///
/// println!("About Info: {:?}", resp);
/// # Ok(())
/// # }
/// ```
///<br />
///
/// See: [odoo/service/common.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/service/common.py#L34-L45)  
/// See also: [odoo/release.py](https://github.com/odoo/odoo/blob/b6e195ccb3a6c37b0d980af159e546bdc67b1e42/odoo/release.py)
#[odoo_api(
    service = "common",
    method = "about",
    name = "common_about",
    auth = false
)]
#[derive(Debug, Serialize_tuple)]
pub struct About {
    pub extended: bool,
}

//TODO: flat deserializ so we can have either `result: "http://..."` or `result: ["http://..", "14.0+e"]`
/// Represents the response to an Odoo [`About`] call
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AboutResponse {
    /// Basic response; includes only the `info` string
    Basic(AboutResponseBasic),

    /// Extended response; includes `info` string and version info
    Extended(AboutResponseExtended),
}

/// Represents the response to an Odoo [`About`] call
#[derive(Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AboutResponseBasic {
    /// The "info" string
    ///
    /// At the time of writing, this is hard-coded to `See http://openerp.com`
    pub info: String,
}

/// Represents the response to an Odoo [`About`] call
#[derive(Debug, Serialize_tuple, Deserialize)]
pub struct AboutResponseExtended {
    /// The "info" string
    ///
    /// At the time of writing, this is hard-coded to `See http://openerp.com`
    pub info: String,

    /// The "pretty" version, normally something like `16.0+e` or `15.0`
    ///
    /// Note that this is only returned when the original reques was made with
    /// `extended: true` (see [`AboutResponse`])
    pub server_version: String,
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::client::error::Result;
    use crate::jmap;
    use crate::jsonrpc::{JsonRpcParams, JsonRpcResponse};
    use serde_json::{from_value, json, to_value};

    /// See [`crate::service::object::test::execute`] for more info
    #[test]
    fn login() -> Result<()> {
        let expected = json!({
            "jsonrpc": "2.0",
            "method": "call",
            "id": 1000,
            "params": {
                "service": "common",
                "method": "login",
                "args": [
                    "some-database",
                    "admin",
                    "password",
                ]
            }
        });
        let actual = to_value(
            Login {
                db: "some-database".into(),
                login: "admin".into(),
                password: "password".into(),
            }
            .build(1000),
        )?;

        assert_eq!(actual, expected);

        Ok(())
    }

    /// See [`crate::service::object::test::execute_response`] for more info
    #[test]
    fn login_response() -> Result<()> {
        let payload = json!({
            "jsonrpc": "2.0",
            "id": 1000,
            "result": 2
        });

        let response: JsonRpcResponse<LoginResponse> = from_value(payload)?;
        match response {
            JsonRpcResponse::Error(e) => Err(e.error.into()),
            JsonRpcResponse::Success(_) => Ok(()),
        }
    }

    /// See [`crate::service::object::test::execute`] for more info
    #[test]
    fn authenticate() -> Result<()> {
        let expected = json!({
            "jsonrpc": "2.0",
            "method": "call",
            "id": 1000,
            "params": {
                "service": "common",
                "method": "authenticate",
                "args": [
                    "some-database",
                    "admin",
                    "password",
                    {
                        "base_location": "https://demo.odoo.com"
                    }
                ]
            }
        });
        let actual = to_value(
            Authenticate {
                db: "some-database".into(),
                login: "admin".into(),
                password: "password".into(),
                user_agent_env: jmap! {
                    "base_location": "https://demo.odoo.com"
                },
            }
            .build(1000),
        )?;

        assert_eq!(actual, expected);

        Ok(())
    }

    /// See [`crate::service::object::test::execute_response`] for more info
    #[test]
    fn authenticate_response() -> Result<()> {
        let payload = json!({
            "jsonrpc": "2.0",
            "id": 1000,
            "result": 2
        });

        let response: JsonRpcResponse<AuthenticateResponse> = from_value(payload)?;
        match response {
            JsonRpcResponse::Error(e) => Err(e.error.into()),
            JsonRpcResponse::Success(_) => Ok(()),
        }
    }

    /// See [`crate::service::object::test::execute`] for more info
    #[test]
    fn version() -> Result<()> {
        let expected = json!({
            "jsonrpc": "2.0",
            "method": "call",
            "id": 1000,
            "params": {
                "service": "common",
                "method": "version",
                "args": []
            }
        });
        let actual = to_value(Version {}.build(1000))?;

        assert_eq!(actual, expected);

        Ok(())
    }

    /// See [`crate::service::object::test::execute_response`] for more info
    #[test]
    fn version_response() -> Result<()> {
        let payload = json!({
            "jsonrpc": "2.0",
            "id": 1000,
            "result": {
                "server_version": "14.0+e",
                "server_version_info": [
                    14,
                    0,
                    0,
                    "final",
                    0,
                    "e"
                ],
                "server_serie": "14.0",
                "protocol_version": 1
            }
        });

        let response: JsonRpcResponse<VersionResponse> = from_value(payload)?;
        match response {
            JsonRpcResponse::Error(e) => Err(e.error.into()),
            JsonRpcResponse::Success(_) => Ok(()),
        }
    }

    /// See [`crate::service::object::test::execute`] for more info
    #[test]
    fn about_basic() -> Result<()> {
        let expected = json!({
            "jsonrpc": "2.0",
            "method": "call",
            "id": 1000,
            "params": {
                "service": "common",
                "method": "about",
                "args": [
                    false
                ]
            }
        });
        let actual = to_value(About { extended: false }.build(1000))?;

        assert_eq!(actual, expected);

        Ok(())
    }

    /// See [`crate::service::object::test::execute_response`] for more info
    #[test]
    fn about_basic_response() -> Result<()> {
        let payload = json!({
            "jsonrpc": "2.0",
            "id": 1000,
            "result": "See http://openerp.com"
        });

        let response: JsonRpcResponse<AboutResponse> = from_value(payload)?;
        match response {
            JsonRpcResponse::Error(e) => Err(e.error.into()),
            JsonRpcResponse::Success(data) => match data.result {
                AboutResponse::Basic(_) => Ok(()),
                AboutResponse::Extended(_) => {
                    panic!("Expected the `Basic` response, but got `Extended`")
                }
            },
        }
    }

    /// See [`crate::service::object::test::execute`] for more info
    #[test]
    fn about_extended() -> Result<()> {
        let expected = json!({
            "jsonrpc": "2.0",
            "method": "call",
            "id": 1000,
            "params": {
                "service": "common",
                "method": "about",
                "args": [
                    true
                ]
            }
        });
        let actual = to_value(About { extended: true }.build(1000))?;

        assert_eq!(actual, expected);

        Ok(())
    }

    /// See [`crate::service::object::test::execute_response`] for more info
    #[test]
    fn about_extended_response() -> Result<()> {
        let payload = json!({
            "jsonrpc": "2.0",
            "id": 1000,
            "result": [
                "See http://openerp.com",
                "14.0+e"
            ]
        });

        let response: JsonRpcResponse<AboutResponse> = from_value(payload)?;
        match response {
            JsonRpcResponse::Error(e) => Err(e.error.into()),
            JsonRpcResponse::Success(data) => match data.result {
                AboutResponse::Extended(_) => Ok(()),
                AboutResponse::Basic(_) => {
                    panic!("Expected the `Extended` response, but got `Basic`")
                }
            },
        }
    }
}