pleme-codegen 0.1.2

Code generation macros for Pleme services with Brazilian market features
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
//! Service structure macro implementation
//!
//! Generates complete service architectures with:
//! - Service trait definitions
//! - Business logic structure
//! - Error handling patterns
//! - Integration patterns
//! - GraphQL resolver generation

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

use crate::utils::*;

/// Implementation of the Service derive macro
pub fn derive_service(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let struct_name = &input.ident;
    let struct_name_str = struct_name.to_string();
    
    // Extract service attributes
    let service_name = get_attribute_value(&input.attrs, "service", "name")
        .unwrap_or_else(|| struct_name_str.to_lowercase());
    let features = get_service_features(&input.attrs);
    
    // Generate service trait
    let service_trait = generate_service_trait(struct_name, &features);
    
    // Generate service implementation
    let service_impl = generate_service_implementation(struct_name, &features);
    
    // Generate GraphQL resolvers if enabled
    let graphql_resolvers = if features.contains(&"graphql".to_string()) {
        generate_graphql_resolvers(struct_name)
    } else {
        quote! {}
    };
    
    // Generate error types
    let error_types = generate_service_error_types(struct_name);
    
    // Generate config types
    let config_types = generate_service_config_types(struct_name, &service_name);
    
    let expanded = quote! {
        #error_types
        #config_types
        #service_trait
        #service_impl
        #graphql_resolvers
    };
    
    TokenStream::from(expanded)
}

/// Extract service features from attributes
fn get_service_features(attrs: &[syn::Attribute]) -> Vec<String> {
    let mut features = Vec::new();
    
    for attr in attrs {
        if attr.path().is_ident("service") {
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("features") {
                    if let Ok(lit_str) = meta.value()?.parse::<syn::LitStr>() {
                        let feature_string = lit_str.value();
                        let feature_list: Vec<&str> = feature_string.split(',').collect();
                        for feature in feature_list {
                            features.push(feature.trim().to_string());
                        }
                    }
                }
                Ok(())
            });
        }
    }
    
    features
}

/// Generate service trait definition
fn generate_service_trait(struct_name: &syn::Ident, features: &[String]) -> TokenStream2 {
    let trait_name = syn::Ident::new(&format!("{}ServiceTrait", struct_name), proc_macro2::Span::call_site());
    let result_type = syn::Ident::new(&format!("{}Result", struct_name), proc_macro2::Span::call_site());
    
    // Generate basic CRUD methods
    let crud_methods = generate_crud_methods(struct_name, &result_type);
    
    // Generate feature-specific methods
    let feature_methods = generate_feature_methods(features, &result_type);
    
    quote! {
        /// Service trait for #struct_name
        #[async_trait::async_trait]
        pub trait #trait_name: Send + Sync {
            #crud_methods
            #feature_methods
        }
    }
}

/// Generate CRUD methods for service trait
fn generate_crud_methods(struct_name: &syn::Ident, result_type: &syn::Ident) -> TokenStream2 {
    let entity_name = struct_name.to_string().replace("Service", "");
    let entity_ident = syn::Ident::new(&entity_name, proc_macro2::Span::call_site());
    let create_input = syn::Ident::new(&format!("Create{}Input", entity_name), proc_macro2::Span::call_site());
    let update_input = syn::Ident::new(&format!("Update{}Input", entity_name), proc_macro2::Span::call_site());
    
    quote! {
        /// Create a new entity
        async fn create(&self, product: &str, input: #create_input) -> #result_type<#entity_ident>;
        
        /// Get entity by ID
        async fn get_by_id(&self, id: uuid::Uuid, product: &str) -> #result_type<Option<#entity_ident>>;
        
        /// Update an existing entity
        async fn update(&self, id: uuid::Uuid, product: &str, input: #update_input) -> #result_type<#entity_ident>;
        
        /// Delete an entity
        async fn delete(&self, id: uuid::Uuid, product: &str) -> #result_type<bool>;
        
        /// List entities with pagination
        async fn list(&self, product: &str, limit: i64, offset: i64) -> #result_type<Vec<#entity_ident>>;
        
        /// Count total entities for product
        async fn count(&self, product: &str) -> #result_type<i64>;
        
        /// Check if entity exists
        async fn exists(&self, id: uuid::Uuid, product: &str) -> #result_type<bool>;
    }
}

/// Generate feature-specific methods
fn generate_feature_methods(features: &[String], result_type: &syn::Ident) -> TokenStream2 {
    let mut methods = Vec::new();
    
    if features.contains(&"brazilian".to_string()) {
        methods.push(quote! {
            /// Validate Brazilian CPF
            async fn validate_cpf(&self, cpf: &str) -> #result_type<bool>;
            
            /// Validate Brazilian CEP
            async fn validate_cep(&self, cep: &str) -> #result_type<bool>;
        });
    }
    
    if features.contains(&"payments".to_string()) {
        methods.push(quote! {
            /// Process payment for entity
            async fn process_payment(&self, entity_id: uuid::Uuid, payment_method: PaymentMethod) -> #result_type<PaymentResult>;
            
            /// Generate PIX payment
            async fn generate_pix_payment(&self, entity_id: uuid::Uuid) -> #result_type<PixPaymentData>;
            
            /// Generate Boleto payment  
            async fn generate_boleto_payment(&self, entity_id: uuid::Uuid) -> #result_type<BoletoPaymentData>;
        });
    }
    
    if features.contains(&"notifications".to_string()) {
        methods.push(quote! {
            /// Send notification for entity
            async fn send_notification(&self, entity_id: uuid::Uuid, notification_type: NotificationType) -> #result_type<()>;
        });
    }
    
    quote! {
        #(#methods)*
    }
}

/// Generate service implementation structure
fn generate_service_implementation(struct_name: &syn::Ident, features: &[String]) -> TokenStream2 {
    let trait_name = syn::Ident::new(&format!("{}ServiceTrait", struct_name), proc_macro2::Span::call_site());
    let result_type = syn::Ident::new(&format!("{}Result", struct_name), proc_macro2::Span::call_site());
    let error_type = syn::Ident::new(&format!("{}Error", struct_name), proc_macro2::Span::call_site());
    let config_type = syn::Ident::new(&format!("{}Config", struct_name), proc_macro2::Span::call_site());
    
    let entity_name = struct_name.to_string().replace("Service", "");
    let entity_ident = syn::Ident::new(&entity_name, proc_macro2::Span::call_site());
    let repository_trait = syn::Ident::new(&format!("{}RepositoryTrait", entity_name), proc_macro2::Span::call_site());
    let create_input = syn::Ident::new(&format!("Create{}Input", entity_name), proc_macro2::Span::call_site());
    let update_input = syn::Ident::new(&format!("Update{}Input", entity_name), proc_macro2::Span::call_site());
    
    // Generate dependency fields based on features
    let dependency_fields = generate_dependency_fields(features);
    let constructor_params = generate_constructor_params(features);
    let constructor_assigns = generate_constructor_assigns(features);
    
    quote! {
        /// Service implementation for #struct_name
        pub struct #struct_name {
            repository: std::sync::Arc<dyn #repository_trait>,
            config: #config_type,
            #dependency_fields
        }
        
        impl #struct_name {
            /// Create a new service instance
            pub fn new(
                repository: std::sync::Arc<dyn #repository_trait>,
                config: #config_type,
                #constructor_params
            ) -> Self {
                Self {
                    repository,
                    config,
                    #constructor_assigns
                }
            }
        }
        
        #[async_trait::async_trait]
        impl #trait_name for #struct_name {
            async fn create(&self, product: &str, input: #create_input) -> #result_type<#entity_ident> {
                // Validate input
                input.validate().map_err(#error_type::Validation)?;
                
                // Create entity
                let entity = #entity_ident::new(product.to_string(), /* fields from input */);
                
                // Save via repository
                let saved_entity = self.repository.create(&entity).await?;
                
                Ok(saved_entity)
            }
            
            async fn get_by_id(&self, id: uuid::Uuid, product: &str) -> #result_type<Option<#entity_ident>> {
                self.repository.find_by_id(id, product).await
            }
            
            async fn update(&self, id: uuid::Uuid, product: &str, input: #update_input) -> #result_type<#entity_ident> {
                // Get existing entity
                let mut entity = self.repository.find_by_id(id, product)
                    .await?
                    .ok_or_else(|| #error_type::NotFound(format!("Entity not found: {}", id)))?;
                
                // Apply updates
                // entity.update_from_input(input);
                
                // Save changes
                let updated_entity = self.repository.update(&entity).await?;
                
                Ok(updated_entity)
            }
            
            async fn delete(&self, id: uuid::Uuid, product: &str) -> #result_type<bool> {
                self.repository.delete(id, product).await
            }
            
            async fn list(&self, product: &str, limit: i64, offset: i64) -> #result_type<Vec<#entity_ident>> {
                self.repository.list_by_product(product, limit, offset).await
            }
            
            async fn count(&self, product: &str) -> #result_type<i64> {
                self.repository.count_by_product(product).await
            }
            
            async fn exists(&self, id: uuid::Uuid, product: &str) -> #result_type<bool> {
                self.repository.exists(id, product).await
            }
        }
    }
}

/// Generate dependency fields based on features
fn generate_dependency_fields(features: &[String]) -> TokenStream2 {
    let mut fields = Vec::new();
    
    if features.contains(&"cache".to_string()) {
        fields.push(quote! { cache: std::sync::Arc<dyn CacheServiceTrait>, });
    }
    
    if features.contains(&"payments".to_string()) {
        fields.push(quote! { payment_service: std::sync::Arc<dyn PaymentServiceTrait>, });
    }
    
    if features.contains(&"notifications".to_string()) {
        fields.push(quote! { notification_service: std::sync::Arc<dyn NotificationServiceTrait>, });
    }
    
    quote! { #(#fields)* }
}

/// Generate constructor parameters based on features
fn generate_constructor_params(features: &[String]) -> TokenStream2 {
    let mut params = Vec::new();
    
    if features.contains(&"cache".to_string()) {
        params.push(quote! { cache: std::sync::Arc<dyn CacheServiceTrait>, });
    }
    
    if features.contains(&"payments".to_string()) {
        params.push(quote! { payment_service: std::sync::Arc<dyn PaymentServiceTrait>, });
    }
    
    if features.contains(&"notifications".to_string()) {
        params.push(quote! { notification_service: std::sync::Arc<dyn NotificationServiceTrait>, });
    }
    
    quote! { #(#params)* }
}

/// Generate constructor assignments based on features
fn generate_constructor_assigns(features: &[String]) -> TokenStream2 {
    let mut assigns = Vec::new();
    
    if features.contains(&"cache".to_string()) {
        assigns.push(quote! { cache, });
    }
    
    if features.contains(&"payments".to_string()) {
        assigns.push(quote! { payment_service, });
    }
    
    if features.contains(&"notifications".to_string()) {
        assigns.push(quote! { notification_service, });
    }
    
    quote! { #(#assigns)* }
}

/// Generate GraphQL resolvers
fn generate_graphql_resolvers(struct_name: &syn::Ident) -> TokenStream2 {
    let entity_name = struct_name.to_string().replace("Service", "");
    let query_name = syn::Ident::new(&format!("{}Query", entity_name), proc_macro2::Span::call_site());
    let mutation_name = syn::Ident::new(&format!("{}Mutation", entity_name), proc_macro2::Span::call_site());
    let service_trait = syn::Ident::new(&format!("{}ServiceTrait", struct_name), proc_macro2::Span::call_site());
    
    quote! {
        /// GraphQL Query resolvers
        pub struct #query_name;
        
        #[async_graphql::Object]
        impl #query_name {
            /// Get entity by ID
            async fn get_by_id(
                &self,
                ctx: &async_graphql::Context<'_>,
                id: uuid::Uuid,
            ) -> async_graphql::Result<Option<crate::models::#entity_name>> {
                let service = ctx.data::<std::sync::Arc<dyn #service_trait>>()?;
                let product = ctx.data::<String>()?; // Product from context
                
                let result = service.get_by_id(id, product).await?;
                Ok(result)
            }
            
            /// List entities with pagination
            async fn list(
                &self,
                ctx: &async_graphql::Context<'_>,
                limit: Option<i32>,
                offset: Option<i32>,
            ) -> async_graphql::Result<Vec<crate::models::#entity_name>> {
                let service = ctx.data::<std::sync::Arc<dyn #service_trait>>()?;
                let product = ctx.data::<String>()?;
                
                let limit = limit.unwrap_or(50) as i64;
                let offset = offset.unwrap_or(0) as i64;
                
                let result = service.list(product, limit, offset).await?;
                Ok(result)
            }
        }
        
        /// GraphQL Mutation resolvers
        pub struct #mutation_name;
        
        #[async_graphql::Object]
        impl #mutation_name {
            /// Create new entity
            async fn create(
                &self,
                ctx: &async_graphql::Context<'_>,
                input: crate::api::CreateInput,
            ) -> async_graphql::Result<crate::models::Entity> {
                let service = ctx.data::<std::sync::Arc<dyn #service_trait>>()?;
                let product = ctx.data::<String>()?;
                
                let result = service.create(product, input.into()).await?;
                Ok(result)
            }
            
            /// Update existing entity
            async fn update(
                &self,
                ctx: &async_graphql::Context<'_>,
                id: uuid::Uuid,
                input: crate::api::UpdateInput,
            ) -> async_graphql::Result<crate::models::Entity> {
                let service = ctx.data::<std::sync::Arc<dyn #service_trait>>()?;
                let product = ctx.data::<String>()?;
                
                let result = service.update(id, product, input.into()).await?;
                Ok(result)
            }
            
            /// Delete entity
            async fn delete(
                &self,
                ctx: &async_graphql::Context<'_>,
                id: uuid::Uuid,
            ) -> async_graphql::Result<bool> {
                let service = ctx.data::<std::sync::Arc<dyn #service_trait>>()?;
                let product = ctx.data::<String>()?;
                
                let result = service.delete(id, product).await?;
                Ok(result)
            }
        }
    }
}

/// Generate error types
fn generate_service_error_types(struct_name: &syn::Ident) -> TokenStream2 {
    let error_name = syn::Ident::new(&format!("{}Error", struct_name), proc_macro2::Span::call_site());
    let result_name = syn::Ident::new(&format!("{}Result", struct_name), proc_macro2::Span::call_site());
    
    quote! {
        /// Error types for #struct_name
        #[derive(Debug, thiserror::Error)]
        pub enum #error_name {
            #[error("Not found: {0}")]
            NotFound(String),
            
            #[error("Validation error: {0}")]
            Validation(String),
            
            #[error("Database error: {0}")]
            Database(#[from] sqlx::Error),
            
            #[error("Cache error: {0}")]
            Cache(String),
            
            #[error("Internal error: {0}")]
            Internal(String),
        }
        
        /// Result type alias for #struct_name operations
        pub type #result_name<T> = Result<T, #error_name>;
    }
}

/// Generate config types
fn generate_service_config_types(struct_name: &syn::Ident, service_name: &str) -> TokenStream2 {
    let config_name = syn::Ident::new(&format!("{}Config", struct_name), proc_macro2::Span::call_site());
    
    quote! {
        /// Configuration for #struct_name
        #[derive(Debug, Clone, serde::Deserialize)]
        pub struct #config_name {
            /// Service name
            pub service_name: String,
            
            /// Database configuration
            pub database: DatabaseConfig,
            
            /// Cache configuration
            pub cache: CacheConfig,
            
            /// Feature flags
            pub features: std::collections::HashMap<String, bool>,
        }
        
        impl Default for #config_name {
            fn default() -> Self {
                Self {
                    service_name: #service_name.to_string(),
                    database: DatabaseConfig::default(),
                    cache: CacheConfig::default(),
                    features: std::collections::HashMap::new(),
                }
            }
        }
        
        impl #config_name {
            /// Load configuration from environment
            pub fn from_env() -> Result<Self, Box<dyn std::error::Error>> {
                // Implementation would read from environment variables
                Ok(Self::default())
            }
            
            /// Check if feature is enabled
            pub fn is_feature_enabled(&self, feature: &str) -> bool {
                self.features.get(feature).copied().unwrap_or(false)
            }
        }
    }
}