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
//! Helper macros for the `odoo_api` crate

use proc_macro;
use quote::{quote, quote_spanned, ToTokens };
use syn::{Token, Ident, Lit, LitStr, Meta, MetaNameValue, ItemStruct, Type, Field};
use syn::parse::{Parse, ParseStream};
use proc_macro2::{Span, TokenStream};
use convert_case::{Case, Casing};

#[derive(Debug)]
enum Error {
    MacroError(String),

    TokenStream(TokenStream),
}

impl From<TokenStream> for Error {
    fn from(ts: TokenStream) -> Self {
        Self::TokenStream(ts)
    }
}

impl From<String> for Error {
    fn from(s: String) -> Self {
        Self::MacroError(s)
    }
}

impl From<&str> for Error {
    fn from(s: &str) -> Self {
        Self::MacroError(s.to_string())
    }
}

type Result<T> = std::result::Result<T, Error>;

/// A struct representing args to the `#[odoo_api_request(service, route)]` macro
struct OdooApiRequestArgs {
    /// Service: "common", "object", or "db"
    service: String,

    /// Method: THe method name, e.g., "execute_kw" or "create_database"
    method: String,
}

impl Parse for OdooApiRequestArgs {
    fn parse(input: ParseStream) -> syn::parse::Result<Self> {
        let service: LitStr = input.parse()?;
        input.parse::<Token![,]>()?;
        let method: LitStr = input.parse()?;

        Ok(OdooApiRequestArgs {
            service: service.value(),
            method: method.value(),
        })
    }
}

#[proc_macro_attribute]
pub fn odoo_api_request(args: proc_macro::TokenStream, input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    match odoo_api_request_impl(args, input) {
        Ok(ts) => { ts },
        Err(err) => {
            match err {
                Error::TokenStream(ts) => { ts },
                Error::MacroError(s) => { quote!(compile_error!(#s)) }
            }
        }
    }.into()
}

fn odoo_api_request_impl(args: proc_macro::TokenStream, input: proc_macro::TokenStream) -> Result<TokenStream> {
    // parse args and input (ensuring the macro was applied to a struct)
    let args: OdooApiRequestArgs = syn::parse(args).map_err(|e| e.to_compile_error())?;
    let input: ItemStruct = syn::parse(input).map_err(|e| e.to_compile_error())?;

    // make sure the struct has named fields, then parse
    let fields: Vec<Field> = match &input.fields {
        syn::Fields::Named(fields) => { fields.named.clone().into_iter().collect() },
        _ => {
            let span = Span::call_site();
            return Err(quote_spanned! {span=>
                compile_error!("expected a struct with named fields")
            }.into());
        }
    };

    // make sure the struct doesn't have any generic params
    if !input.generics.params.is_empty() {
        let span = input.ident.span();
        return Err(quote_spanned!{span=>
            compile_error!("a struct tagged with `odoo_api_request` cannot have generic params");
        }.into());
    }

    // fetch the struct name (and some variations)
    let name_struct = input.ident.clone().to_string();
    let name_response = format!("{}Response", &name_struct);
    let name_fn = name_struct.to_case(Case::Snake);
    let ident_struct = &input.ident;
    let ident_response = Ident::new(&name_response, Span::call_site());
    let ident_fn = Ident::new(&name_fn, Span::call_site());

    // extract doc comments from the original struct
    let mut doc = input.attrs.iter()
        .map(|attr| {
            if !attr.path.is_ident("doc") { return None }
            match attr.parse_meta() {
                Ok(meta) => {
                    match meta {
                        Meta::NameValue(MetaNameValue { lit: Lit::Str(lit_str), ..}) => {
                            Some(lit_str.value())
                        },
                        _ => { None }
                    }
                },
                _ => { None }
            }
        })
        .flatten()
        .collect::<Vec<String>>()
        .join("\n");
    if doc.is_empty() {
        doc.push_str(&format!(" For details, please see the [`{}`] struct.", &name_struct));
    }

    // parse the field names & types
    let mut has_db = false;
    let mut fields_args = Vec::<TokenStream>::new();
    let mut fields_assigns = Vec::<TokenStream>::new();
    let mut fields_call = Vec::<TokenStream>::new();
    for field in &fields {
        if let Type::Path(path) = &field.ty {
            if let Some(ident) = &field.ident {
                if ident.to_string() == "db" { has_db = true }
                let type_string = path.clone().into_token_stream().to_string();
                if type_string == "String" {
                    // rather than requiring full Strings, we'll accept &str and convert
                    fields_args.push(quote!(#ident: &str));
                    fields_assigns.push(quote!(#ident: #ident.to_string()));
                    fields_call.push(quote!(#ident));
                }
                else if type_string == "Vec < Value >" || type_string == "Map < String, Value >" {
                    fields_args.push(quote!(#ident: Value));
                    fields_assigns.push(quote!(#ident: ::serde_json::from_value(#ident)?));
                    fields_call.push(quote!(#ident));
                }
                else {
                    fields_args.push(quote!(#ident: #path));
                    fields_assigns.push(quote!(#ident: #ident));
                    fields_call.push(quote!(#ident));
                }
            }
        }
    }
    let mut fields_args2 = fields_args.clone();
    if !has_db {
        fields_args2.insert(0, quote!(db: &str))
    }

    // finally, generate the TokenStreams
    let out_api_method_impl = generate_api_method_impl(&ident_struct, &ident_response, &args)?;
    let out_serialize_impl = generate_serialize_impl(&ident_struct, &fields)?;
    let out_try_from_impl = generate_try_from_impl(&ident_response)?;
    let out_call = generate_call(&ident_struct, &ident_fn, &fields_args, &fields_assigns, &doc)?;
    let out_call_async = generate_call_async(&ident_struct, &ident_response, &ident_fn, &fields_args2, &fields_call, &doc)?;
    let out_call_blocking = generate_call_blocking(&ident_struct, &ident_response, &ident_fn, &fields_args2, &fields_call, &doc)?;

    Ok(quote!(
        #input
        #out_api_method_impl
        #out_serialize_impl
        #out_try_from_impl
        #out_call
        #out_call_async
        #out_call_blocking
    ))
}

fn generate_call(ident_struct: &Ident, ident_fn: &Ident, fields_args: &Vec<TokenStream>, fields_assigns: &Vec<TokenStream>, doc: &str) -> Result<TokenStream> {
    Ok(quote! {
        #[doc=#doc]
        pub fn #ident_fn(#(#fields_args),*) -> super::Result<super::OdooApiRequest<#ident_struct>> {
            #[cfg(not(test))]
            let id = {
                use ::rand::{Rng, thread_rng};
                let mut rng = thread_rng();
                rng.gen_range(1..10000)
            };

            #[cfg(test)]
            let id = 1000;

            Ok(super::OdooApiRequest {
                version: super::JsonRpcVersion::V2,
                method: super::JsonRpcMethod::Call,
                id: id,
                params: super::JsonRpcRequestParams {
                    args: #ident_struct {
                        #(
                            #fields_assigns,
                        )*
                    }
                }
            })
        }
    })
}

fn generate_call_async(ident_struct: &Ident, ident_response: &Ident, ident_fn: &Ident, fields_args: &Vec<TokenStream>, fields_call: &Vec<TokenStream>, doc: &str) -> Result<TokenStream> {
    let name_fn_async = format!("{}_async", &ident_fn.to_string());
    let ident_fn_async = Ident::new(&name_fn_async, Span::call_site());


    Ok(quote!(
        pub(crate) mod #ident_fn_async {
            use serde_json::{Value};
            use crate::jsonrpc::{OdooApiMethod};
            use super::{#ident_fn, #ident_struct, #ident_response};

            #[cfg(feature = "async")]
            #[doc=#doc]
            pub async fn #ident_fn_async(url: &str, #(#fields_args),*) -> crate::jsonrpc::Result<super::#ident_response> {
                let request = super::#ident_fn(#(#fields_call),*)?;
                let client = ::reqwest::Client::new();
                let response: crate::jsonrpc::OdooApiResponse<#ident_struct> = client.post(url)
                    .header("X-Odoo-Dbfilter", db.clone())
                    .json(&request)
                    .send().await?
                    .json().await?;

                match response {
                    crate::jsonrpc::OdooApiResponse::Success(resp) => {
                        Ok(resp.result)
                    },
                    crate::jsonrpc::OdooApiResponse::Error(resp) => {
                        if &resp.error.message == "Odoo Server Error" {
                            Err(crate::jsonrpc::Error::OdooServerError(resp.error))
                        }
                        else if &resp.error.message == "404: Not Found" {
                            Err(crate::jsonrpc::Error::OdooNotFoundError(resp.error))
                        }
                        else if &resp.error.message == "Odoo Session Expired" {
                            Err(crate::jsonrpc::Error::OdooSessionExpiredError(resp.error))
                        }
                        else {
                            Err(crate::jsonrpc::Error::OdooError(resp.error))
                        }
                    }
                }
            }
        }
    ))
}

fn generate_call_blocking(ident_struct: &Ident, ident_response: &Ident, ident_fn: &Ident, fields_args: &Vec<TokenStream>, fields_call: &Vec<TokenStream>, doc: &str) -> Result<TokenStream> {
    let name_fn_blocking = format!("{}_blocking", &ident_fn.to_string());
    let ident_fn_blocking = Ident::new(&name_fn_blocking, Span::call_site());

    Ok(quote!(
        pub(crate) mod #ident_fn_blocking {
            use serde_json::{Value};
            use crate::jsonrpc::{OdooApiMethod};
            use super::{#ident_fn, #ident_struct, #ident_response};

            #[cfg(feature = "blocking")]
            #[doc=#doc]
            pub fn #ident_fn_blocking(url: &str, #(#fields_args),*) -> crate::jsonrpc::Result<super::#ident_response> {
                let request = super::#ident_fn(#(#fields_call),*)?;
                let client = ::reqwest::blocking::Client::new();
                let response: crate::jsonrpc::OdooApiResponse<#ident_struct> = client.post(url)
                    .header("X-Odoo-Dbfilter", db.clone())
                    .json(&request)
                    .send()?
                    .json()?;

                match response {
                    crate::jsonrpc::OdooApiResponse::Success(resp) => {
                        Ok(resp.result)
                    },
                    crate::jsonrpc::OdooApiResponse::Error(resp) => {
                        if &resp.error.message == "Odoo Server Error" {
                            Err(crate::jsonrpc::Error::OdooServerError(resp.error))
                        }
                        else if &resp.error.message == "404: Not Found" {
                            Err(crate::jsonrpc::Error::OdooNotFoundError(resp.error))
                        }
                        else if &resp.error.message == "404: Not Found" {
                            Err(crate::jsonrpc::Error::OdooSessionExpiredError(resp.error))
                        }
                        else {
                            Err(crate::jsonrpc::Error::OdooError(resp.error))
                        }
                    }
                }
            }
        }
    ))
}

fn generate_api_method_impl(ident_struct: &Ident, ident_response: &Ident, args: &OdooApiRequestArgs) -> Result<TokenStream> {
    let service = &args.service;
    let method = &args.method;
    Ok(quote! {
        impl super::OdooApiMethod for #ident_struct {
            type Response = #ident_response;

            fn describe_odoo_api_method(&self) -> (&'static str, &'static str) {
                (#service, #method)
            }

            fn parse_json_response(&self, json_data: &str) -> ::serde_json::Result<super::OdooApiResponse<Self>> {
                ::serde_json::from_str(json_data)
            }
        }
    })
}

fn generate_serialize_impl(ident_struct: &Ident, fields: &Vec<Field>) -> Result<TokenStream> {
    let field_count = fields.iter().map(|field| &field.ident).len();
    let field_names = fields.iter().map(|field| &field.ident);

    Ok(quote! {
        impl ::serde::Serialize for #ident_struct {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: ::serde::Serializer,
            {
                use ::serde::ser::SerializeSeq;

                let mut state = serializer.serialize_seq(Some(#field_count))?;
                #(
                    state.serialize_element(&self.#field_names)?;
                )*
                state.end()
            }
        }
    })
}

fn generate_try_from_impl(ident_response: &Ident) -> Result<TokenStream> {
    
    Ok(quote!(
        impl TryFrom<String> for #ident_response {
            type Error = crate::jsonrpc::Error;

            fn try_from(value: String) -> ::std::result::Result<#ident_response, crate::jsonrpc::Error> {
                Ok(serde_json::from_str(&value)?)
            }
        }

        impl TryFrom<serde_json::Value> for #ident_response {
            type Error = crate::jsonrpc::Error;

            fn try_from(value: serde_json::Value) -> ::std::result::Result<#ident_response, crate::jsonrpc::Error> {
                Ok(serde_json::from_value(value)?)
            }
        }
    ))
}