reinhardt-forms 0.1.0-rc.15

Form handling and validation
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
//! ModelFormSet implementation for managing multiple model forms
//!
//! ModelFormSets allow editing multiple model instances at once, handling
//! creation, updates, and deletion in a single form submission.

use crate::FormError;
use crate::formset::FormSet;
use crate::model_form::{FormModel, ModelForm, ModelFormConfig};
use std::collections::HashMap;
use std::marker::PhantomData;

/// Configuration for ModelFormSet
#[derive(Debug, Clone)]
pub struct ModelFormSetConfig {
	/// Configuration for individual model forms
	pub form_config: ModelFormConfig,
	/// Allow deletion of instances
	pub can_delete: bool,
	/// Allow ordering of instances
	pub can_order: bool,
	/// Number of extra forms to display
	pub extra: usize,
	/// Maximum number of forms
	pub max_num: Option<usize>,
	/// Minimum number of forms
	pub min_num: usize,
}

impl Default for ModelFormSetConfig {
	fn default() -> Self {
		Self {
			form_config: ModelFormConfig::default(),
			can_delete: false,
			can_order: false,
			extra: 1,
			max_num: Some(1000),
			min_num: 0,
		}
	}
}

impl ModelFormSetConfig {
	/// Create a new ModelFormSetConfig
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::ModelFormSetConfig;
	///
	/// let config = ModelFormSetConfig::new();
	/// assert_eq!(config.extra, 1);
	/// assert!(!config.can_delete);
	/// ```
	pub fn new() -> Self {
		Self::default()
	}
	/// Set the number of extra forms
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::ModelFormSetConfig;
	///
	/// let config = ModelFormSetConfig::new().with_extra(3);
	/// assert_eq!(config.extra, 3);
	/// ```
	pub fn with_extra(mut self, extra: usize) -> Self {
		self.extra = extra;
		self
	}
	/// Enable or disable deletion
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::ModelFormSetConfig;
	///
	/// let config = ModelFormSetConfig::new().with_can_delete(true);
	/// assert!(config.can_delete);
	/// ```
	pub fn with_can_delete(mut self, can_delete: bool) -> Self {
		self.can_delete = can_delete;
		self
	}
	/// Enable or disable ordering
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::ModelFormSetConfig;
	///
	/// let config = ModelFormSetConfig::new().with_can_order(true);
	/// assert!(config.can_order);
	/// ```
	pub fn with_can_order(mut self, can_order: bool) -> Self {
		self.can_order = can_order;
		self
	}
	/// Set maximum number of forms
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::ModelFormSetConfig;
	///
	/// let config = ModelFormSetConfig::new().with_max_num(Some(10));
	/// assert_eq!(config.max_num, Some(10));
	/// ```
	pub fn with_max_num(mut self, max_num: Option<usize>) -> Self {
		self.max_num = max_num;
		self
	}
	/// Set minimum number of forms
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::ModelFormSetConfig;
	///
	/// let config = ModelFormSetConfig::new().with_min_num(2);
	/// assert_eq!(config.min_num, 2);
	/// ```
	pub fn with_min_num(mut self, min_num: usize) -> Self {
		self.min_num = min_num;
		self
	}
	/// Set the form configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_forms::{ModelFormSetConfig, ModelFormConfig};
	///
	/// let form_config = ModelFormConfig::new()
	///     .fields(vec!["name".to_string(), "email".to_string()]);
	/// let config = ModelFormSetConfig::new().with_form_config(form_config);
	/// assert!(config.form_config.fields.is_some());
	/// ```
	pub fn with_form_config(mut self, form_config: ModelFormConfig) -> Self {
		self.form_config = form_config;
		self
	}
}

/// A formset for managing multiple model instances
pub struct ModelFormSet<T: FormModel> {
	model_forms: Vec<ModelForm<T>>,
	formset: FormSet,
	_phantom: PhantomData<T>,
}

impl<T: FormModel> ModelFormSet<T> {
	/// Create a new ModelFormSet with instances
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::{ModelFormSet, ModelFormSetConfig};
	///
	/// let config = ModelFormSetConfig::new();
	/// let instances = vec![]; // Empty list of model instances
	/// let formset = ModelFormSet::<MyModel>::new("formset".to_string(), instances, config);
	/// assert_eq!(formset.prefix(), "formset");
	/// ```
	pub fn new(prefix: String, instances: Vec<T>, config: ModelFormSetConfig) -> Self {
		let mut model_forms = Vec::new();

		// Create ModelForm for each instance
		for instance in instances {
			let model_form = ModelForm::new(Some(instance), config.form_config.clone());
			model_forms.push(model_form);
		}

		// Add extra empty forms
		for _ in 0..config.extra {
			let model_form = ModelForm::empty(config.form_config.clone());
			model_forms.push(model_form);
		}

		// Create FormSet for management data
		let formset = FormSet::new(prefix)
			.with_extra(config.extra)
			.with_can_delete(config.can_delete)
			.with_can_order(config.can_order)
			.with_max_num(config.max_num)
			.with_min_num(config.min_num);

		Self {
			model_forms,
			formset,
			_phantom: PhantomData,
		}
	}
	/// Create an empty ModelFormSet (for creating new instances)
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::{ModelFormSet, ModelFormSetConfig};
	///
	/// let config = ModelFormSetConfig::new().with_extra(3);
	/// let formset = ModelFormSet::<MyModel>::empty("formset".to_string(), config);
	/// assert_eq!(formset.total_form_count(), 3);
	/// ```
	pub fn empty(prefix: String, config: ModelFormSetConfig) -> Self {
		Self::new(prefix, Vec::new(), config)
	}
	/// Returns the prefix used for form field naming.
	pub fn prefix(&self) -> &str {
		self.formset.prefix()
	}
	/// Returns references to all model instances that have been loaded.
	pub fn instances(&self) -> Vec<&T> {
		self.model_forms
			.iter()
			.filter_map(|form| form.instance())
			.collect()
	}
	/// Returns the number of forms backed by existing model instances.
	pub fn form_count(&self) -> usize {
		// Return number of forms with instances (not including extra empty forms)
		self.model_forms
			.iter()
			.filter(|form| form.instance().is_some())
			.count()
	}
	/// Returns the total number of forms, including extra empty forms.
	pub fn total_form_count(&self) -> usize {
		// Return total number of forms including extras
		self.model_forms.len()
	}
	/// Validate all forms in the formset
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::{ModelFormSet, ModelFormSetConfig};
	///
	/// let config = ModelFormSetConfig::new();
	/// let mut formset = ModelFormSet::<MyModel>::empty("formset".to_string(), config);
	/// let is_valid = formset.is_valid();
	/// ```
	pub fn is_valid(&mut self) -> bool {
		// Validate all model forms
		self.model_forms.iter_mut().all(|form| form.is_valid())
	}
	/// Collects and returns all validation errors from every form in the set.
	pub fn errors(&self) -> Vec<String> {
		// Collect errors from all model forms
		self.model_forms
			.iter()
			.flat_map(|model_form| {
				model_form
					.form()
					.errors()
					.values()
					.flat_map(|errors| errors.iter().cloned())
			})
			.collect()
	}
	/// Save all valid forms to the database
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::{ModelFormSet, ModelFormSetConfig};
	///
	/// let config = ModelFormSetConfig::new();
	/// let mut formset = ModelFormSet::<MyModel>::empty("formset".to_string(), config);
	/// let result = formset.save();
	/// ```
	pub fn save(&mut self) -> Result<Vec<T>, FormError> {
		if !self.is_valid() {
			return Err(FormError::Validation("Formset is not valid".to_string()));
		}

		let mut saved_instances = Vec::new();

		// Iterate through each ModelForm and save if it has changes
		for model_form in &mut self.model_forms {
			// Check if form has an instance (skip empty forms)
			if model_form.instance().is_some() {
				// Save the instance
				let instance = model_form.save()?;
				saved_instances.push(instance);
			}
		}

		Ok(saved_instances)
	}
	/// Get management form data for HTML rendering
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::{ModelFormSet, ModelFormSetConfig};
	///
	/// let config = ModelFormSetConfig::new().with_extra(2);
	/// let formset = ModelFormSet::<MyModel>::empty("article".to_string(), config);
	/// let mgmt_data = formset.management_form_data();
	///
	/// assert!(mgmt_data.contains_key("article-TOTAL_FORMS"));
	/// assert_eq!(mgmt_data.get("article-TOTAL_FORMS"), Some(&"2".to_string()));
	/// ```
	pub fn management_form_data(&self) -> HashMap<String, String> {
		self.formset.management_form_data()
	}
}

/// Builder for creating ModelFormSet instances
pub struct ModelFormSetBuilder<T: FormModel> {
	config: ModelFormSetConfig,
	_phantom: PhantomData<T>,
}

impl<T: FormModel> ModelFormSetBuilder<T> {
	/// Create a new builder
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new();
	/// ```
	pub fn new() -> Self {
		Self {
			config: ModelFormSetConfig::default(),
			_phantom: PhantomData,
		}
	}
	/// Set the number of extra forms
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new().extra(5);
	/// ```
	pub fn extra(mut self, extra: usize) -> Self {
		self.config.extra = extra;
		self
	}
	/// Enable deletion
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new().can_delete(true);
	/// ```
	pub fn can_delete(mut self, can_delete: bool) -> Self {
		self.config.can_delete = can_delete;
		self
	}
	/// Enable ordering
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new().can_order(true);
	/// ```
	pub fn can_order(mut self, can_order: bool) -> Self {
		self.config.can_order = can_order;
		self
	}
	/// Set maximum number of forms
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new().max_num(10);
	/// ```
	pub fn max_num(mut self, max_num: usize) -> Self {
		self.config.max_num = Some(max_num);
		self
	}
	/// Set minimum number of forms
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new().min_num(1);
	/// ```
	pub fn min_num(mut self, min_num: usize) -> Self {
		self.config.min_num = min_num;
		self
	}
	/// Build the formset with instances
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let instances = vec![]; // Empty list of model instances
	/// let builder = ModelFormSetBuilder::<MyModel>::new();
	/// let formset = builder.build("formset".to_string(), instances);
	/// ```
	pub fn build(self, prefix: String, instances: Vec<T>) -> ModelFormSet<T> {
		ModelFormSet::new(prefix, instances, self.config)
	}
	/// Build an empty formset
	///
	/// # Examples
	///
	/// ```ignore
	/// use reinhardt_forms::ModelFormSetBuilder;
	///
	/// let builder = ModelFormSetBuilder::<MyModel>::new().extra(3);
	/// let formset = builder.build_empty("formset".to_string());
	/// ```
	pub fn build_empty(self, prefix: String) -> ModelFormSet<T> {
		ModelFormSet::empty(prefix, self.config)
	}
}

impl<T: FormModel> Default for ModelFormSetBuilder<T> {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json::Value;

	// Mock model for testing
	struct Article {
		id: i32,
		title: String,
		content: String,
	}

	impl FormModel for Article {
		fn field_names() -> Vec<String> {
			vec!["id".to_string(), "title".to_string(), "content".to_string()]
		}

		fn get_field(&self, name: &str) -> Option<Value> {
			match name {
				"id" => Some(Value::Number(self.id.into())),
				"title" => Some(Value::String(self.title.clone())),
				"content" => Some(Value::String(self.content.clone())),
				_ => None,
			}
		}

		fn set_field(&mut self, name: &str, value: Value) -> Result<(), String> {
			match name {
				"id" => {
					if let Value::Number(n) = value {
						self.id = n.as_i64().unwrap() as i32;
						Ok(())
					} else {
						Err("Invalid type for id".to_string())
					}
				}
				"title" => {
					if let Value::String(s) = value {
						self.title = s;
						Ok(())
					} else {
						Err("Invalid type for title".to_string())
					}
				}
				"content" => {
					if let Value::String(s) = value {
						self.content = s;
						Ok(())
					} else {
						Err("Invalid type for content".to_string())
					}
				}
				_ => Err(format!("Unknown field: {}", name)),
			}
		}

		fn save(&mut self) -> Result<(), String> {
			// Mock save
			Ok(())
		}
	}

	#[test]
	fn test_model_formset_config() {
		let config = ModelFormSetConfig::new()
			.with_extra(3)
			.with_can_delete(true)
			.with_max_num(Some(10))
			.with_min_num(1);

		assert_eq!(config.extra, 3);
		assert!(config.can_delete);
		assert_eq!(config.max_num, Some(10));
		assert_eq!(config.min_num, 1);
	}

	#[test]
	fn test_model_formset_empty() {
		let config = ModelFormSetConfig::new().with_extra(2);
		let formset = ModelFormSet::<Article>::empty("article".to_string(), config);

		assert_eq!(formset.prefix(), "article");
		assert_eq!(formset.instances().len(), 0);
		assert_eq!(formset.total_form_count(), 2);
	}

	#[test]
	fn test_model_formset_with_instances() {
		let instances = vec![
			Article {
				id: 1,
				title: "First Article".to_string(),
				content: "Content 1".to_string(),
			},
			Article {
				id: 2,
				title: "Second Article".to_string(),
				content: "Content 2".to_string(),
			},
		];

		let config = ModelFormSetConfig::new();
		let formset = ModelFormSet::new("article".to_string(), instances, config);

		assert_eq!(formset.instances().len(), 2);
		assert_eq!(formset.form_count(), 2);
	}

	#[test]
	fn test_model_formset_builder() {
		let formset = ModelFormSetBuilder::<Article>::new()
			.extra(3)
			.can_delete(true)
			.max_num(5)
			.build_empty("article".to_string());

		assert_eq!(formset.total_form_count(), 3);
	}

	#[test]
	fn test_model_formset_management_data() {
		let config = ModelFormSetConfig::new().with_extra(2).with_min_num(1);
		let formset = ModelFormSet::<Article>::empty("article".to_string(), config);

		let mgmt_data = formset.management_form_data();

		assert_eq!(mgmt_data.get("article-TOTAL_FORMS"), Some(&"2".to_string()));
		assert_eq!(
			mgmt_data.get("article-INITIAL_FORMS"),
			Some(&"0".to_string())
		);
		assert_eq!(
			mgmt_data.get("article-MIN_NUM_FORMS"),
			Some(&"1".to_string())
		);
	}
}