sz_configtool_lib/functions/
standardize.rs1use crate::error::SzConfigError;
7use crate::helpers::{
8 add_to_config_array, delete_from_config_array, find_in_config_array, get_next_id,
9};
10use serde_json::{Value, json};
11
12#[derive(Debug, Clone, Default)]
18pub struct AddStandardizeFunctionParams<'a> {
19 pub connect_str: &'a str,
20 pub description: Option<&'a str>,
21 pub language: Option<&'a str>,
22}
23
24impl<'a> TryFrom<&'a Value> for AddStandardizeFunctionParams<'a> {
25 type Error = SzConfigError;
26
27 fn try_from(json: &'a Value) -> Result<Self, SzConfigError> {
28 Ok(Self {
29 connect_str: json
30 .get("connectStr")
31 .and_then(|v| v.as_str())
32 .ok_or_else(|| SzConfigError::MissingField("connectStr".to_string()))?,
33 description: json.get("description").and_then(|v| v.as_str()),
34 language: json.get("language").and_then(|v| v.as_str()),
35 })
36 }
37}
38
39#[derive(Debug, Clone, Default)]
41pub struct SetStandardizeFunctionParams<'a> {
42 pub connect_str: Option<&'a str>,
43 pub description: Option<&'a str>,
44 pub language: Option<&'a str>,
45}
46
47pub fn add_standardize_function(
60 config_json: &str,
61 sfunc_code: &str,
62 params: AddStandardizeFunctionParams,
63) -> Result<(String, Value), SzConfigError> {
64 let sfunc_code = sfunc_code.to_uppercase();
65
66 if find_in_config_array(config_json, "CFG_SFUNC", "SFUNC_CODE", &sfunc_code)?.is_some() {
68 return Err(SzConfigError::validation(format!(
69 "Standardize function already exists: {sfunc_code}"
70 )));
71 }
72
73 let config_data: Value =
75 serde_json::from_str(config_json).map_err(|e| SzConfigError::json_parse(e.to_string()))?;
76 let sfunc_id = get_next_id(&config_data, "G2_CONFIG.CFG_SFUNC", "SFUNC_ID", 1)?;
77
78 let mut new_record = json!({
80 "SFUNC_ID": sfunc_id,
81 "SFUNC_CODE": sfunc_code,
82 "CONNECT_STR": params.connect_str,
83 });
84
85 new_record["SFUNC_DESC"] = match params.description {
87 Some(desc) => json!(desc),
88 None => Value::Null,
89 };
90 new_record["LANGUAGE"] = match params.language {
91 Some(lang) => json!(lang),
92 None => Value::Null,
93 };
94
95 let modified_json = add_to_config_array(config_json, "CFG_SFUNC", new_record.clone())?;
97
98 Ok((modified_json, new_record))
99}
100
101pub fn delete_standardize_function(
113 config_json: &str,
114 sfunc_code: &str,
115) -> Result<(String, Value), SzConfigError> {
116 let sfunc_code = sfunc_code.to_uppercase();
117
118 let function = find_in_config_array(config_json, "CFG_SFUNC", "SFUNC_CODE", &sfunc_code)?
120 .ok_or_else(|| {
121 SzConfigError::not_found(format!("Standardize function not found: {sfunc_code}"))
122 })?;
123
124 let modified_json =
126 delete_from_config_array(config_json, "CFG_SFUNC", "SFUNC_CODE", &sfunc_code)?;
127
128 Ok((modified_json, function))
129}
130
131pub fn get_standardize_function(
143 config_json: &str,
144 sfunc_code: &str,
145) -> Result<Value, SzConfigError> {
146 let sfunc_code = sfunc_code.to_uppercase();
147
148 find_in_config_array(config_json, "CFG_SFUNC", "SFUNC_CODE", &sfunc_code)?.ok_or_else(|| {
149 SzConfigError::not_found(format!("Standardize function not found: {sfunc_code}"))
150 })
151}
152
153pub fn list_standardize_functions(config_json: &str) -> Result<Vec<Value>, SzConfigError> {
164 let config_data: Value =
165 serde_json::from_str(config_json).map_err(|e| SzConfigError::json_parse(e.to_string()))?;
166
167 let items: Vec<Value> = if let Some(g2_config) = config_data.get("G2_CONFIG")
168 && let Some(array) = g2_config.get("CFG_SFUNC")
169 && let Some(items) = array.as_array()
170 {
171 items
172 .iter()
173 .map(|item| {
174 json!({
175 "id": item.get("SFUNC_ID").and_then(|v| v.as_i64()).unwrap_or(0),
176 "function": item.get("SFUNC_CODE").and_then(|v| v.as_str()).unwrap_or(""),
177 "connectStr": item.get("CONNECT_STR").and_then(|v| v.as_str()).unwrap_or(""),
178 "language": item.get("LANGUAGE").and_then(|v| v.as_str()).unwrap_or("")
179 })
180 })
181 .collect()
182 } else {
183 Vec::new()
184 };
185
186 Ok(items)
187}
188
189pub fn set_standardize_function(
202 config_json: &str,
203 sfunc_code: &str,
204 params: SetStandardizeFunctionParams,
205) -> Result<(String, Value), SzConfigError> {
206 let sfunc_code = sfunc_code.to_uppercase();
207
208 let mut function = find_in_config_array(config_json, "CFG_SFUNC", "SFUNC_CODE", &sfunc_code)?
210 .ok_or_else(|| {
211 SzConfigError::not_found(format!("Standardize function not found: {sfunc_code}"))
212 })?;
213
214 if let Some(obj) = function.as_object_mut() {
216 if let Some(conn) = params.connect_str {
217 obj.insert("CONNECT_STR".to_string(), json!(conn));
218 }
219 if let Some(desc) = params.description {
220 obj.insert("SFUNC_DESC".to_string(), json!(desc));
221 }
222 if let Some(lang) = params.language {
223 obj.insert("LANGUAGE".to_string(), json!(lang));
224 }
225 }
226
227 let temp_json = delete_from_config_array(config_json, "CFG_SFUNC", "SFUNC_CODE", &sfunc_code)?;
229 let modified_json = add_to_config_array(&temp_json, "CFG_SFUNC", function.clone())?;
230
231 Ok((modified_json, function))
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 fn get_test_config() -> String {
239 json!({
240 "G2_CONFIG": {
241 "CFG_SFUNC": [
242 {
243 "SFUNC_ID": 1,
244 "SFUNC_CODE": "PARSE_NAME",
245 "CONNECT_STR": "g2ParseName",
246 "LANGUAGE": "en"
247 }
248 ]
249 }
250 })
251 .to_string()
252 }
253
254 #[test]
255 fn test_add_standardize_function() {
256 let config = get_test_config();
257 let result = add_standardize_function(
258 &config,
259 "custom_parse",
260 AddStandardizeFunctionParams {
261 connect_str: "g2CustomParse",
262 description: Some("Custom parser"),
263 language: Some("en"),
264 },
265 );
266 assert!(result.is_ok());
267 let (modified, record) = result.unwrap();
268 assert!(modified.contains("CUSTOM_PARSE"));
269 assert_eq!(record["SFUNC_CODE"], "CUSTOM_PARSE");
270 }
271
272 #[test]
273 fn test_list_standardize_functions() {
274 let config = get_test_config();
275 let result = list_standardize_functions(&config);
276 assert!(result.is_ok());
277 let items = result.unwrap();
278 assert_eq!(items.len(), 1);
279 assert_eq!(items[0]["function"], "PARSE_NAME");
280 }
281
282 #[test]
283 fn test_get_standardize_function() {
284 let config = get_test_config();
285 let result = get_standardize_function(&config, "PARSE_NAME");
286 assert!(result.is_ok());
287 let func = result.unwrap();
288 assert_eq!(func["SFUNC_CODE"], "PARSE_NAME");
289 }
290
291 #[test]
292 fn test_delete_standardize_function() {
293 let config = get_test_config();
294 let result = delete_standardize_function(&config, "PARSE_NAME");
295 assert!(result.is_ok());
296 let (modified, _) = result.unwrap();
297 assert!(!modified.contains("PARSE_NAME"));
298 }
299}