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
//! # reinhardt-admin
//!
//! Admin functionality for Reinhardt framework.
//!
//! This crate contains admin-related functionality:
//! - **adapters**: Unified server/client imports for admin types
//! - **core**: Admin site registration, model admin configuration, and database helpers
//! - **pages**: Admin page rendering
//! - **server**: Server functions and HTTP handlers
//! - Storage-backed `FileField`/`ImageField` admin forms use multipart mutations
//! when the `file-uploads` feature is enabled
//! - **settings**: Server-side admin settings
//! - **types**: Shared request/response DTOs
//! - Per-object mutation history is persisted atomically without raw field values
//!
//! ## Inline related-model editing
//!
//! A manually configured [`core::ModelAdminConfig`] can include typed
//! [`core::InlineModelAdmin`] descriptors. Each descriptor renders foreign-key
//! children in a tabular or stacked section and may append configured blank
//! rows for child creation. The child model must have its own admin
//! registration for the same table so operation-specific permissions can be
//! checked. Parent and single-field child primary keys must be integer,
//! text-like, or UUID values.
//!
//! Inline submissions cannot choose their relationship value. The server
//! assigns the trusted parent key and persists the parent plus all requested
//! child creates, updates, and deletes in one transaction. Macro declarations,
//! nested inlines, and client-side dynamic row creation are intentionally not
//! provided.
//! - **changelist editing**: Opt-in, validated page batches committed atomically
//!
//! ## Features
//!
//! - `default`: No features enabled by default
//! - `all`: All admin functionality
//!
//! ## Examples
//!
//! ## Form customization
//!
//! Custom forms decorate only registered model fields. `normalize` receives
//! owned JSON data and `validate` borrows the normalized data; both hooks must
//! be synchronous and pure. Field
//! errors use their canonical field name; global errors have no field and are
//! returned to the client as `_all` with HTTP 422.
//!
//! ```
//! use reinhardt_admin::core::{AdminForm, AdminFormData, AdminFormErrors, AdminFormMode};
//! use serde_json::Value;
//!
//! #[derive(Debug)]
//! struct ArticleForm;
//!
//! impl AdminForm for ArticleForm {
//! fn normalize(
//! &self,
//! _mode: AdminFormMode,
//! mut data: AdminFormData,
//! ) -> Result<AdminFormData, AdminFormErrors> {
//! if let Some(Value::String(title)) = data.get_mut("title") {
//! *title = title.trim().to_owned();
//! }
//! Ok(data)
//! }
//!
//! fn validate(
//! &self,
//! _mode: AdminFormMode,
//! data: &AdminFormData,
//! ) -> Result<(), AdminFormErrors> {
//! if data.get("title") == Some(&Value::String(String::new())) {
//! return Err(AdminFormErrors::field("title", "Title is required"));
//! }
//! Ok(())
//! }
//! }
//! ```
//!
//! Builder overlays are applied property by property after inferred and
//! relation widgets. A form adapter's `schema()` overlays them last. They can
//! strengthen requiredness, but cannot make a model-required field optional.
//!
//! ```
//! use reinhardt_admin::core::{
//! AdminWidget, FormFieldOverride, ModelAdmin, ModelAdminConfig, PrepopulatedField,
//! };
//!
//! let admin = ModelAdminConfig::builder()
//! .model_name("Article")
//! .fields(vec!["title", "body", "slug"])
//! .formfield_overrides(vec![
//! FormFieldOverride::new("body").widget(AdminWidget::TextArea { rows: Some(8) }),
//! ])
//! .prepopulated_fields(vec![PrepopulatedField::new("slug", ["title"])])
//! .build()
//! .unwrap();
//!
//! assert_eq!(admin.prepopulated_fields()[0].target, "slug");
//! ```
//!
//! The equivalent `#[admin]` declaration uses a closed grammar. The custom
//! form type implements `AdminForm + Default + 'static`; the macro initializes
//! one shared default value.
//!
//! ```
//! # extern crate reinhardt_admin as reinhardt_admin_adapters;
//! use reinhardt_admin::adapters::AdminForm;
//! use reinhardt_macros::{admin, model};
//! use serde::{Deserialize, Serialize};
//!
//! #[model(app_label = "docs", table_name = "articles")]
//! #[derive(Clone, Debug, Deserialize, Serialize)]
//! struct Article {
//! #[field(primary_key = true)]
//! id: i64,
//! #[field(max_length = 255)]
//! title: String,
//! #[field(max_length = 255)]
//! body: String,
//! #[field(max_length = 255)]
//! slug: String,
//! }
//!
//! #[derive(Debug, Default)]
//! struct ArticleForm;
//!
//! impl AdminForm for ArticleForm {}
//!
//! #[admin(model,
//! for = Article,
//! name = "Article",
//! form = ArticleForm,
//! formfield_overrides = [(body, widget = textarea, rows = 8)],
//! prepopulated_fields = [(slug, sources = [title])],
//! )]
//! struct ArticleAdmin;
//! ```
//!
//! Prepopulation is client-side per mount: a non-empty edit target stays
//! locked, and editing or clearing a target makes it sticky. It never causes
//! server-side recomputation. Foreign-key and many-to-many widgets retain their
//! existing relation lookup, permission, and save-time validation contracts.
//! Arbitrary components, asynchronous validation, and virtual fields are not
//! supported.
//!
//! Many-to-many fields can use the same horizontal or vertical selector
//! configuration through [`core::ModelAdmin`], [`core::ModelAdminConfig`], or
//! the `admin` attribute macro:
//!
//! ```ignore
//! use reinhardt_admin::core::{ModelAdmin, ModelAdminConfig};
//!
//! impl ModelAdmin for ArticleAdmin {
//! fn model_name(&self) -> &str { "Article" }
//! fn table_name(&self) -> &str { "blog_articles" }
//! fn filter_horizontal(&self) -> Vec<&str> { vec!["tags"] }
//! fn filter_vertical(&self) -> Vec<&str> { vec!["reviewers"] }
//! }
//!
//! let configured = ModelAdminConfig::builder()
//! .model_name("Article")
//! .table_name("blog_articles")
//! .filter_horizontal(vec!["tags"])
//! .filter_vertical(vec!["reviewers"])
//! .build()?;
//!
//! #[admin(model,
//! for = Article,
//! name = "Article",
//! filter_horizontal = [tags],
//! filter_vertical = [reviewers],
//! )]
//! pub struct ArticleAdmin;
//! # Ok::<(), reinhardt_admin::types::AdminError>(())
//! ```
//!
//! Field names are matched exactly. The layouts cannot overlap, and selector
//! fields must be registered many-to-many relations. Reading or searching
//! options requires related-model View permission, which is checked again on
//! save. Lookup pages return at most 50 options, and **Load more** appends later
//! pages without dropping chosen values. Parent and join-table mutations share one atomic transaction, so a
//! join failure rolls back the parent mutation.
//! ### Foreign-key relation fields
//!
//! Relation controls are opt-in. `autocomplete_fields` renders a searchable
//! foreign-key control, while `raw_id_fields` renders a direct relation-ID
//! input. Either a logical relation name (`author`) or its persisted ID column
//! (`author_id`) can be configured; the server normalizes both names before
//! rendering or saving and honors an explicit foreign-key `to_field`.
//!
//! ```
//! use reinhardt_admin::core::{ModelAdmin, ModelAdminConfig};
//!
//! let post_admin = ModelAdminConfig::builder()
//! .model_name("Post")
//! .autocomplete_fields(vec!["author"])
//! .raw_id_fields(vec!["editor_id"])
//! .allow_all(true)
//! .build()
//! .expect("relation configuration is valid");
//!
//! assert_eq!(post_admin.autocomplete_fields(), vec!["author"]);
//! assert_eq!(post_admin.raw_id_fields(), vec!["editor_id"]);
//! ```
//!
//! Autocomplete searches use the related admin's `search_fields` and require
//! that list to be non-empty. `ModelAdmin::object_label` may provide a custom
//! label; the related target-field value is used when it returns `None`. Every
//! lookup checks view permission on both the source and related admins before
//! exposing rows or labels. Create and update revalidate the related view
//! permission, scalar ID, target existence, and foreign-key nullability after
//! the field allowlist/readonly checks and before sanitization or the database
//! write. Relation requests are bounded to a 200-byte query, pages 1 through
//! 10,000, and page sizes of 1 through 100 (default 20).
//! A manual [`core::ModelAdmin`] can publish stable action metadata and execute
//! the selected records through the server-owned transaction:
//!
//! ```
//! use async_trait::async_trait;
//! use reinhardt_admin::core::{AdminActionTransaction, AdminUser, ModelAdmin};
//! use reinhardt_admin::types::{
//! AdminAction, AdminActionOutcome, AdminError, AdminResult, ModelPermission,
//! };
//!
//! struct ArticleAdmin;
//!
//! # async fn publish_selected(
//! # ids: &[String],
//! # _transaction: &mut AdminActionTransaction,
//! # ) -> AdminResult<Vec<String>> {
//! # Ok(ids.to_vec())
//! # }
//! #[async_trait]
//! impl ModelAdmin for ArticleAdmin {
//! fn model_name(&self) -> &str {
//! "Article"
//! }
//!
//! fn table_name(&self) -> &str {
//! "articles"
//! }
//!
//! fn actions(&self) -> Vec<AdminAction> {
//! vec![AdminAction::new(
//! "publish",
//! "Publish selected",
//! ModelPermission::Change,
//! true,
//! )]
//! }
//!
//! async fn execute_action(
//! &self,
//! action: &str,
//! ids: &[String],
//! transaction: &mut AdminActionTransaction,
//! _user: &dyn AdminUser,
//! ) -> AdminResult<AdminActionOutcome> {
//! if action != "publish" {
//! return Err(AdminError::ValidationError(format!("Invalid action: {action}")));
//! }
//!
//! let successful_ids = publish_selected(ids, transaction).await?;
//! let affected = successful_ids.len() as u64;
//! Ok(AdminActionOutcome::new(successful_ids, affected))
//! }
//! }
//! ```
//!
//! The server validates CSRF, IDs, selection limits, and the declared model
//! permission before calling the hook. Returning an error rolls back the
//! transaction.
//! `ModelAdmin::fields()` remains the flat form configuration. Use
//! `ModelAdmin::fieldsets()` when the form needs ordered groups instead:
//!
//! ```rust
//! use reinhardt_admin::core::{Fieldset, ModelAdmin, ModelAdminConfig};
//!
//! let flat = ModelAdminConfig::builder()
//! .model_name("Article")
//! .fields(vec!["title", "body"])
//! .build()
//! .unwrap();
//! assert_eq!(flat.fields(), Some(vec!["title", "body"]));
//! assert_eq!(flat.fieldsets(), None);
//!
//! let grouped = ModelAdminConfig::builder()
//! .model_name("Article")
//! .fieldsets(vec![
//! Fieldset::new(Some("Content"), &["title", "body"]),
//! Fieldset::new(Some("Publishing"), &["published_at"]).collapsed(),
//! ])
//! .build()
//! .unwrap();
//! assert_eq!(grouped.fields(), None);
//! assert!(grouped.fieldsets().unwrap()[1].collapsed);
//! ```
//!
//! The `#[admin]` macro uses the same descriptors:
//!
//! ```ignore
//! use reinhardt::admin;
//! use crate::models::Article;
//!
//! #[admin(model,
//! for = Article,
//! name = "Article",
//! fieldsets = [
//! (title = "Content", fields = [title, body]),
//! (fields = [published_at], collapsed = true)
//! ]
//! )]
//! struct ArticleAdmin;
//! ```
//!
//! `collapsed` controls only the initial native `<details>` state; it is not
//! persisted. Nested fieldsets, custom layout classes, layout grids, and inline
//! form configuration are intentionally unsupported.
//!
//! ## Available Modules
//!
//! - [`adapters`] - Admin adapter implementations
//! - [`core`] - Admin core functionality
//! - [`pages`] - Admin page rendering
//! - [`server`] - Admin HTTP server
//! - [`types`] - Shared type definitions
pub use ;
// Register admin static files for auto-discovery by collectstatic
const _: = ;
// Register WASM build output for auto-discovery by collectstatic.
// The dist-admin/ directory may not exist if the WASM SPA has not been built;
// collectstatic gracefully skips non-existent directories.
const _: = ;
// Register vendor assets (CSS, JS, fonts) for download via the generic
// `reinhardt-utils::staticfiles::vendor` subsystem. Each entry is collected via
// the `inventory` crate and downloaded lazily on first admin request.
const _: = ;