diff options
Diffstat (limited to 'src/core/components/clone.rs')
| -rw-r--r-- | src/core/components/clone.rs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/core/components/clone.rs b/src/core/components/clone.rs new file mode 100644 index 0000000..023ca16 --- /dev/null +++ b/src/core/components/clone.rs @@ -0,0 +1,69 @@ +use serde_json::{Map, Value}; + +/// Utilities to prepare cloned JSON records for INSERT dialogs. +/// These helpers mutate a cloned Value by clearing identifiers/unique fields, +/// removing editor metadata and timestamps, and optionally appending a suffix to a name field. + +/// Remove common editor metadata and timestamp/audit fields from an object map. +fn remove_metadata_fields(obj: &mut Map<String, Value>) { + // Remove __editor_* keys + let keys: Vec<String> = obj + .keys() + .filter(|k| k.starts_with("__editor_")) + .cloned() + .collect(); + for k in keys { + obj.remove(&k); + } + + // Common timestamp/audit fields we don't want to copy + for k in [ + "created_at", + "created_date", + "created_by", + "last_modified", + "last_modified_at", + "last_modified_date", + "last_modified_by", + "last_modified_by_username", + "updated_at", + ] { + obj.remove(k); + } +} + +/// Clear a list of keys by setting them to an empty string (so editor treats as blank/new). +fn clear_keys(obj: &mut Map<String, Value>, keys_to_clear: &[&str]) { + for k in keys_to_clear { + obj.insert((*k).to_string(), Value::String(String::new())); + } +} + +/// Optionally append a suffix to the value of a given field if it is a string. +fn append_suffix(obj: &mut Map<String, Value>, field: &str, suffix: &str) { + if let Some(name) = obj.get(field).and_then(|v| v.as_str()) { + let new_val = format!("{}{}", name, suffix); + obj.insert(field.to_string(), Value::String(new_val)); + } +} + +/// Prepare a cloned Value for opening an "Add" dialog. +/// - Clears provided keys (e.g., id, codes) by setting them to "" +/// - Removes common metadata/timestamps and editor-only fields +/// - Optionally appends a suffix to a display/name field +pub fn prepare_cloned_value( + original: &Value, + keys_to_clear: &[&str], + name_field: Option<&str>, + name_suffix: Option<&str>, +) -> Value { + let mut cloned = original.clone(); + if let Some(obj) = cloned.as_object_mut() { + remove_metadata_fields(obj); + clear_keys(obj, keys_to_clear); + if let (Some(field), Some(suffix)) = (name_field, name_suffix) { + append_suffix(obj, field, suffix); + } + } + cloned +} |
