adminx 0.2.6

A powerful, modern admin panel framework for Rust built on Actix Web and MongoDB with automatic CRUD, role-based access control, and a beautiful responsive UI
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// crates/adminx/src/resource.rs - Enhanced with file upload support
use actix_web::{HttpRequest, HttpResponse, ResponseError};
use async_trait::async_trait;
use futures::future::BoxFuture;
use serde_json::{json, Value};
use crate::menu::{MenuItem, MenuAction};
use crate::actions::CustomAction;
use crate::nested::AdmixNestedResource;
use crate::error::AdminxError;
use crate::filters::parse_query;
use crate::pagination::PaginatedResponse;
use mongodb::{Collection, bson::{doc, oid::ObjectId, Document}};
use futures::TryStreamExt;
use std::collections::HashMap;
use crate::helpers::resource_helper::convert_form_data_to_json;

#[async_trait]
pub trait AdmixResource: Send + Sync {
    // ===========================
    // REQUIRED METHODS (Must be implemented)
    // ===========================
    fn new() -> Self where Self: Sized;
    fn resource_name(&self) -> &'static str;
    fn base_path(&self) -> &'static str;
    fn collection_name(&self) -> &'static str; 
    fn get_collection(&self) -> Collection<Document>;
    fn clone_box(&self) -> Box<dyn AdmixResource>;

    // ===========================
    // CONFIGURATION (Optional - with defaults)
    // ===========================

    /// Optional parent/super menu name to group this resource under.
    fn menu_group(&self) -> Option<&'static str> {
        None
    }

    /// Menu label for this resource (default: same as resource_name)
    fn menu(&self) -> &'static str {
        self.resource_name()
    }

    fn allowed_roles(&self) -> Vec<String> {
        vec!["admin".to_string()]
    }

    fn allowed_roles_with_permissions(&self) -> Value {
        json!({})
    }

    fn visible_fields_for_role(&self, _roles: &[String]) -> Vec<String> {
        vec![]
    }

    fn nested_resources(&self) -> Vec<Box<dyn AdmixNestedResource>> {
        vec![]
    }

    fn custom_actions(&self) -> Vec<CustomAction> {
        vec![]
    }

    fn allowed_actions(&self) -> Option<Vec<MenuAction>> {
        None // None means all actions are allowed
    }

    fn permit_keys(&self) -> Vec<&'static str> {
        vec![] // Override this to specify which fields can be created/updated
    }

    fn readonly_keys(&self) -> Vec<&'static str> {
        vec!["_id", "created_at", "updated_at"]
    }

    // ===========================
    // FILE UPLOAD CONFIGURATION (New)
    // ===========================
    
    /// Return true if this resource supports file uploads
    fn supports_file_upload(&self) -> bool {
        false
    }
    
    /// Maximum file size in bytes (default: 10MB)
    fn max_file_size(&self) -> usize {
        10 * 1024 * 1024 // 10MB
    }
    
    /// Allowed file extensions
    fn allowed_file_extensions(&self) -> Vec<&'static str> {
        vec!["jpg", "jpeg", "png", "gif", "webp"]
    }
    
    /// File upload configuration
    fn file_upload_config(&self) -> Option<Value> {
        None
    }
    
    /* -----------------------------------------------------------
    START - Image specific resource
    ------------------------------------------------------------ */
    /// Handle file upload processing - override this for custom file handling
    fn process_file_upload(&self, _field_name: &str, _file_data: &[u8], _filename: &str) -> BoxFuture<'static, Result<HashMap<String, String>, AdminxError>> {
        Box::pin(async move {
            Err(AdminxError::BadRequest("File upload not implemented for this resource".into()))
        })
    }


    // In your adminx crate: crates/adminx/src/resource.rs

    fn create(&self, _req: &HttpRequest, payload: Value) -> BoxFuture<'static, HttpResponse> {
        // Extract everything we need BEFORE the async block
        let collection = self.get_collection();
        let permitted = self.permit_keys().into_iter().collect::<std::collections::HashSet<_>>();
        let resource_name = self.resource_name().to_string();
        
        Box::pin(async move {
            // Now _req is not captured in this async block
            tracing::info!("Default create implementation for resource: {} with payload: {:?}", resource_name, payload);
            
            let mut clean_map = serde_json::Map::new();
            if let Value::Object(map) = payload {
                for (key, value) in map {
                    if permitted.contains(key.as_str()) {
                        clean_map.insert(key, value);
                    }
                }
            }

            let now = mongodb::bson::DateTime::now();
            clean_map.insert("created_at".to_string(), json!(now));
            clean_map.insert("updated_at".to_string(), json!(now));

            if permitted.contains("deleted") && !clean_map.contains_key("deleted") {
                clean_map.insert("deleted".to_string(), json!(false));
            }

            tracing::debug!("Cleaned payload for {}: {:?}", resource_name, clean_map);

            match mongodb::bson::to_document(&Value::Object(clean_map)) {
                Ok(document) => {
                    match collection.insert_one(document, None).await {
                        Ok(insert_result) => {
                            tracing::info!("Document created successfully for {}: {:?}", resource_name, insert_result.inserted_id);
                            HttpResponse::Created().json(json!({
                                "success": true,
                                "message": format!("{} created successfully", resource_name),
                                "id": insert_result.inserted_id
                            }))
                        },
                        Err(e) => {
                            tracing::error!("Error inserting document for {}: {}", resource_name, e);
                            AdminxError::InternalError.error_response()
                        }
                    }
                },
                Err(e) => {
                    tracing::error!("Error converting payload to BSON for {}: {}", resource_name, e);
                    AdminxError::BadRequest("Invalid input data".into()).error_response()
                }
            }
        })
    }

    fn update(&self, _req: &HttpRequest, id: String, payload: Value) -> BoxFuture<'static, HttpResponse> {
        // Extract everything we need BEFORE the async block
        let collection = self.get_collection();
        let permitted = self.permit_keys().into_iter().collect::<std::collections::HashSet<_>>();
        let resource_name = self.resource_name().to_string();
        
        Box::pin(async move {
            // Now _req is not captured in this async block
            tracing::info!("Default update implementation for resource: {} with id: {} and payload: {:?}", 
                         resource_name, id, payload);
            
            match ObjectId::parse_str(&id) {
                Ok(oid) => {
                    let mut clean_map = serde_json::Map::new();
                    if let Value::Object(map) = payload {
                        for (key, value) in map {
                            if permitted.contains(key.as_str()) {
                                clean_map.insert(key, value);
                            }
                        }
                    }

                    clean_map.insert("updated_at".to_string(), json!(mongodb::bson::DateTime::now()));

                    let bson_payload: Document = match mongodb::bson::to_document(&Value::Object(clean_map)) {
                        Ok(doc) => doc,
                        Err(e) => {
                            tracing::error!("Error converting payload to BSON for {}: {}", resource_name, e);
                            return AdminxError::BadRequest("Invalid payload format".into()).error_response();
                        }
                    };

                    let update_doc = doc! { "$set": bson_payload };

                    match collection.update_one(doc! { "_id": oid }, update_doc, None).await {
                        Ok(result) => {
                            if result.modified_count > 0 {
                                tracing::info!("Document {} updated successfully for {}", id, resource_name);
                                HttpResponse::Ok().json(json!({
                                    "success": true,
                                    "message": format!("{} updated successfully", resource_name),
                                    "modified_count": result.modified_count
                                }))
                            } else {
                                tracing::warn!("No document found to update with id: {} for {}", id, resource_name);
                                AdminxError::NotFound.error_response()
                            }
                        },
                        Err(e) => {
                            tracing::error!("Error updating document {} for {}: {}", id, resource_name, e);
                            AdminxError::InternalError.error_response()
                        }
                    }
                }
                Err(e) => {
                    tracing::error!("Invalid ObjectId {} for {}: {}", id, resource_name, e);
                    AdminxError::BadRequest("Invalid ID format".into()).error_response()
                }
            }
        })
    }


    fn create_with_files(
        &self,
        _req: &HttpRequest,
        mut form_data: std::collections::HashMap<String, String>,
        files: std::collections::HashMap<String, (String, Vec<u8>)>,
    ) -> futures::future::BoxFuture<'static, actix_web::HttpResponse> {
        let resource = self.clone_box();

        Box::pin(async move {
            // 1) first finish file upload process
            for (field_name, (filename, file_data)) in files {
                match resource.process_file_upload(&field_name, &file_data, &filename).await {
                    Ok(upload_results) => {
                        for (k, v) in upload_results {

                            println!("k!!!!!!!!! {:?}", v);

                            form_data.insert(k, v);
                        }
                    }
                    Err(e) => {
                        tracing::error!("File upload failed for field {}: {:?}", field_name, e);
                        return actix_web::HttpResponse::BadRequest().json(serde_json::json!({
                            "error": format!("File upload failed: {:?}", e)
                        }));
                    }
                }
            }

            // 2) form_data → JSON
            let json_payload = convert_form_data_to_json(form_data);

            // 3) ⬇️ HttpRequest को inner scope में बनाइए; future निकालिए; फिर outer में await कीजिए
            let fut = {
                let test_req = actix_web::test::TestRequest::default().to_http_request();

                println!("WOW!!!!!!!!! {:#?}", json_payload);
                resource.create(&test_req, json_payload)
            };

            // अब यहाँ HttpRequest drop हो चुका होगा, इसलिए future `Send` रहेगा
            fut.await
        })
    }

    fn update_with_files(
        &self,
        _req: &HttpRequest,
        id: String,
        mut form_data: std::collections::HashMap<String, String>,
        files: std::collections::HashMap<String, (String, Vec<u8>)>,
    ) -> futures::future::BoxFuture<'static, actix_web::HttpResponse> {
        let resource = self.clone_box();

        Box::pin(async move {
            for (field_name, (filename, file_data)) in files {
                if !file_data.is_empty() {
                    match resource.process_file_upload(&field_name, &file_data, &filename).await {
                        Ok(upload_results) => {
                            for (k, v) in upload_results {
                                form_data.insert(k, v);
                            }
                        }
                        Err(e) => {
                            tracing::error!("File upload failed for field {}: {:?}", field_name, e);
                            return actix_web::HttpResponse::BadRequest().json(serde_json::json!({
                                "error": format!("File upload failed: {:?}", e)
                            }));
                        }
                    }
                }
            }

            let json_payload = convert_form_data_to_json(form_data);

            let fut = {
                let test_req = actix_web::test::TestRequest::default().to_http_request();
                resource.update(&test_req, id, json_payload)
            };

            fut.await
        })
    }

    /* -----------------------------------------------------------
    END - Image specific resource
    ------------------------------------------------------------ */

    // ===========================
    // UI STRUCTURE METHODS (Optional)
    // ===========================
    fn form_structure(&self) -> Option<Value> {
        None // Override to customize create/edit forms
    }

    fn list_structure(&self) -> Option<Value> {
        None // Override to customize list view
    }

    fn view_structure(&self) -> Option<Value> {
        None // Override to customize detail view
    }

    fn filters(&self) -> Option<Value> {
        None // Override to add search/filter functionality
    }

    // ===========================
    // ENHANCED CRUD IMPLEMENTATIONS
    // ===========================
    
    fn list(&self, _req: &HttpRequest, query: String) -> BoxFuture<'static, HttpResponse> {
        let collection = self.get_collection();
        let resource_name = self.resource_name().to_string();
        
        Box::pin(async move {
            tracing::info!("Default list implementation for resource: {}", resource_name);
            
            let opts = parse_query(&query);
            
            let total = match collection.count_documents(opts.filter.clone(), None).await {
                Ok(count) => count,
                Err(e) => {
                    tracing::error!("Error counting documents for {}: {}", resource_name, e);
                    return AdminxError::InternalError.error_response();
                }
            };
            
            let mut find_options = mongodb::options::FindOptions::default();
            find_options.skip = Some(opts.skip);
            find_options.limit = Some(opts.limit as i64);
            if let Some(sort) = opts.sort {
                find_options.sort = Some(sort);
            }
            
            match collection.find(opts.filter, find_options).await {
                Ok(mut cursor) => {
                    let mut documents = Vec::new();
                    while let Some(doc) = cursor.try_next().await.unwrap_or(None) {
                        documents.push(doc);
                    }

                    tracing::info!("Found {} documents for {} out of {} total", 
                                 documents.len(), resource_name, total);
                    
                    HttpResponse::Ok().json(PaginatedResponse {
                        data: documents,
                        total,
                        page: (opts.skip / opts.limit) + 1,
                        per_page: opts.limit,
                    })
                }
                Err(e) => {
                    tracing::error!("Error executing find query for {}: {}", resource_name, e);
                    AdminxError::InternalError.error_response()
                }
            }
        })
    }

    fn get(&self, _req: &HttpRequest, id: String) -> BoxFuture<'static, HttpResponse> {
        let collection = self.get_collection();
        let resource_name = self.resource_name().to_string();
        
        Box::pin(async move {
            tracing::info!("Default get implementation for resource: {} with id: {}", resource_name, id);
            
            match ObjectId::parse_str(&id) {
                Ok(oid) => {
                    match collection.find_one(doc! { "_id": oid }, None).await {
                        Ok(Some(document)) => {
                            tracing::info!("Found document with id: {} for resource: {}", id, resource_name);
                            HttpResponse::Ok().json(document)
                        },
                        Ok(None) => {
                            tracing::warn!("Document not found with id: {} for resource: {}", id, resource_name);
                            AdminxError::NotFound.error_response()
                        },
                        Err(e) => {
                            tracing::error!("Database error getting document {} for {}: {}", id, resource_name, e);
                            AdminxError::InternalError.error_response()
                        }
                    }
                },
                Err(e) => {
                    tracing::error!("Invalid ObjectId {} for {}: {}", id, resource_name, e);
                    AdminxError::BadRequest("Invalid ID format".into()).error_response()
                }
            }
        })
    }

    // /// Enhanced create method that can handle both regular form data and file uploads
    // fn create(&self, _req: &HttpRequest, payload: Value) -> BoxFuture<'static, HttpResponse> {
    //     let collection = self.get_collection();
    //     let permitted = self.permit_keys().into_iter().collect::<std::collections::HashSet<_>>();
    //     let resource_name = self.resource_name().to_string();
        
    //     Box::pin(async move {
    //         tracing::info!("Default create implementation for resource: {} with payload: {:?}", resource_name, payload);
            
    //         let mut clean_map = serde_json::Map::new();
    //         if let Value::Object(map) = payload {
    //             for (key, value) in map {
    //                 if permitted.contains(key.as_str()) {
    //                     clean_map.insert(key, value);
    //                 }
    //             }
    //         }

    //         let now = mongodb::bson::DateTime::now();
    //         clean_map.insert("created_at".to_string(), json!(now));
    //         clean_map.insert("updated_at".to_string(), json!(now));

    //         // Add default values for file upload resources
    //         if permitted.contains("deleted") && !clean_map.contains_key("deleted") {
    //             clean_map.insert("deleted".to_string(), json!(false));
    //         }

    //         tracing::debug!("Cleaned payload for {}: {:?}", resource_name, clean_map);

    //         match mongodb::bson::to_document(&Value::Object(clean_map)) {
    //             Ok(document) => {
    //                 match collection.insert_one(document, None).await {
    //                     Ok(insert_result) => {
    //                         tracing::info!("Document created successfully for {}: {:?}", resource_name, insert_result.inserted_id);
    //                         HttpResponse::Created().json(json!({
    //                             "success": true,
    //                             "message": format!("{} created successfully", resource_name),
    //                             "id": insert_result.inserted_id
    //                         }))
    //                     },
    //                     Err(e) => {
    //                         tracing::error!("Error inserting document for {}: {}", resource_name, e);
    //                         AdminxError::InternalError.error_response()
    //                     }
    //                 }
    //             },
    //             Err(e) => {
    //                 tracing::error!("Error converting payload to BSON for {}: {}", resource_name, e);
    //                 AdminxError::BadRequest("Invalid input data".into()).error_response()
    //             }
    //         }
    //     })
    // }

    // /// Enhanced update method with soft delete support
    // fn update(&self, _req: &HttpRequest, id: String, payload: Value) -> BoxFuture<'static, HttpResponse> {
    //     let collection = self.get_collection();
    //     let permitted = self.permit_keys().into_iter().collect::<std::collections::HashSet<_>>();
    //     let resource_name = self.resource_name().to_string();
        
    //     Box::pin(async move {
    //         tracing::info!("Default update implementation for resource: {} with id: {} and payload: {:?}", 
    //                      resource_name, id, payload);
            
    //         match ObjectId::parse_str(&id) {
    //             Ok(oid) => {
    //                 let mut clean_map = serde_json::Map::new();
    //                 if let Value::Object(map) = payload {
    //                     for (key, value) in map {
    //                         if permitted.contains(key.as_str()) {
    //                             clean_map.insert(key, value);
    //                         }
    //                     }
    //                 }

    //                 clean_map.insert("updated_at".to_string(), json!(mongodb::bson::DateTime::now()));

    //                 let bson_payload: Document = match mongodb::bson::to_document(&Value::Object(clean_map)) {
    //                     Ok(doc) => doc,
    //                     Err(e) => {
    //                         tracing::error!("Error converting payload to BSON for {}: {}", resource_name, e);
    //                         return AdminxError::BadRequest("Invalid payload format".into()).error_response();
    //                     }
    //                 };

    //                 let update_doc = doc! { "$set": bson_payload };

    //                 match collection.update_one(doc! { "_id": oid }, update_doc, None).await {
    //                     Ok(result) => {
    //                         if result.modified_count > 0 {
    //                             tracing::info!("Document {} updated successfully for {}", id, resource_name);
    //                             HttpResponse::Ok().json(json!({
    //                                 "success": true,
    //                                 "message": format!("{} updated successfully", resource_name),
    //                                 "modified_count": result.modified_count
    //                             }))
    //                         } else {
    //                             tracing::warn!("No document found to update with id: {} for {}", id, resource_name);
    //                             AdminxError::NotFound.error_response()
    //                         }
    //                     },
    //                     Err(e) => {
    //                         tracing::error!("Error updating document {} for {}: {}", id, resource_name, e);
    //                         AdminxError::InternalError.error_response()
    //                     }
    //                 }
    //             }
    //             Err(e) => {
    //                 tracing::error!("Invalid ObjectId {} for {}: {}", id, resource_name, e);
    //                 AdminxError::BadRequest("Invalid ID format".into()).error_response()
    //             }
    //         }
    //     })
    // }

    /// Enhanced delete with soft delete support
    fn delete(&self, _req: &HttpRequest, id: String) -> BoxFuture<'static, HttpResponse> {
        let collection = self.get_collection();
        let resource_name = self.resource_name().to_string();
        let permitted = self.permit_keys().into_iter().collect::<std::collections::HashSet<_>>();
        
        Box::pin(async move {
            tracing::info!("Default delete implementation for resource: {} with id: {}", resource_name, id);
            
            match ObjectId::parse_str(&id) {
                Ok(oid) => {
                    // If resource supports soft delete (has "deleted" in permitted keys), use soft delete
                    if permitted.contains("deleted") {
                        let update_doc = doc! { 
                            "$set": {
                                "deleted": true,
                                "updated_at": mongodb::bson::DateTime::now()
                            }
                        };
                        
                        match collection.update_one(doc! { "_id": oid }, update_doc, None).await {
                            Ok(result) => {
                                if result.modified_count > 0 {
                                    tracing::info!("Document {} soft deleted successfully for {}", id, resource_name);
                                    HttpResponse::Ok().json(json!({
                                        "success": true,
                                        "message": format!("{} deleted successfully", resource_name),
                                        "soft_delete": true,
                                        "modified_count": result.modified_count
                                    }))
                                } else {
                                    tracing::warn!("No document found to soft delete with id: {} for {}", id, resource_name);
                                    AdminxError::NotFound.error_response()
                                }
                            },
                            Err(e) => {
                                tracing::error!("Error soft deleting document {} for {}: {}", id, resource_name, e);
                                AdminxError::InternalError.error_response()
                            }
                        }
                    } else {
                        // Hard delete
                        match collection.delete_one(doc! { "_id": oid }, None).await {
                            Ok(result) => {
                                if result.deleted_count > 0 {
                                    tracing::info!("Document {} hard deleted successfully for {}", id, resource_name);
                                    HttpResponse::Ok().json(json!({
                                        "success": true,
                                        "message": format!("{} deleted successfully", resource_name),
                                        "soft_delete": false,
                                        "deleted_count": result.deleted_count
                                    }))
                                } else {
                                    tracing::warn!("No document found to hard delete with id: {} for {}", id, resource_name);
                                    AdminxError::NotFound.error_response()
                                }
                            },
                            Err(e) => {
                                tracing::error!("Error hard deleting document {} for {}: {}", id, resource_name, e);
                                AdminxError::InternalError.error_response()
                            }
                        }
                    }
                },
                Err(e) => {
                    tracing::error!("Invalid ObjectId {} for {}: {}", id, resource_name, e);
                    AdminxError::BadRequest("Invalid ID format".into()).error_response()
                }
            }
        })
    }

    
    // ===========================
    // MENU GENERATION
    // ===========================
    fn generate_menu(&self) -> Option<MenuItem> {
        Some(MenuItem {
            title: self.menu().to_string(),
            path: self.base_path().to_string(),
            icon: Some(if self.supports_file_upload() { "image".to_string() } else { "users".to_string() }),
            order: Some(10),
            children: None,
        })
    }

    fn build_adminx_menus(&self) -> Option<MenuItem> {
        self.generate_menu()
    }
}

// Manual clone implementation
impl Clone for Box<dyn AdmixResource> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}