rumtk-web 0.5.3

Web framework part of the RUMTK framework that attempts to simplify and expedite dashboard development in Healthcare.
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
/*
 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
 * This toolkit aims to be reliable, simple, performant, and standards compliant.
 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
 * Copyright (C) 2025  Ethan Dixon
 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
use crate::jobs::{Job, JobID};
use crate::utils::defaults::DEFAULT_TEXT_ITEM;
use crate::utils::types::RUMString;
use axum::extract::State;
use phf::OrderedMap;
pub use phf_macros::phf_ordered_map as rumtk_create_const_ordered_map;
use rumtk_core::net::tcp::SafeLock;
use rumtk_core::strings::RUMStringConversions;
use rumtk_core::types::{RUMDeserialize, RUMDeserializer, RUMSerialize, RUMSerializer, RUMID};
use rumtk_core::types::{RUMHashMap, RUMOrderedMap};
use rumtk_core::{rumtk_critical_section_read, rumtk_generate_id, rumtk_new_lock};

pub type TextMap = RUMOrderedMap<RUMString, RUMString>;
pub type NestedTextMap = RUMOrderedMap<RUMString, TextMap>;
pub type NestedNestedTextMap = RUMOrderedMap<RUMString, NestedTextMap>;
pub type RootNestedNestedTextMap = RUMOrderedMap<RUMString, NestedNestedTextMap>;

pub type ConstTextMap = OrderedMap<&'static str, &'static str>;
pub type ConstNestedTextMap = OrderedMap<&'static str, &'static ConstTextMap>;
pub type ConstNestedNestedTextMap = OrderedMap<&'static str, &'static ConstNestedTextMap>;

#[derive(RUMSerialize, RUMDeserialize, PartialEq, Debug, Clone, Default)]
pub struct HeaderConf {
    pub logo_size: RUMString,
    pub disable_navlinks: bool,
    pub disable_logo: bool,
}

#[derive(RUMSerialize, RUMDeserialize, PartialEq, Debug, Clone, Default)]
pub struct FooterConf {
    pub socials_list: RUMString,
    pub disable_contact_button: bool,
}

///
/// This is a core structure in a web project using the RUMTK framework. This structure contains
/// a series of fields that represent the web app initial state or configuration. The idea is that
/// the web app can come bundled with a JSON config file following this structure which we can load
/// at runtime. The settings will dictate a few key project behaviors such as properly labeling
/// some components with the company name or use the correct language text.
///
#[derive(RUMSerialize, RUMDeserialize, PartialEq, Debug, Clone, Default)]
pub struct AppConf {
    pub title: RUMString,
    pub description: RUMString,
    pub company: RUMString,
    pub copyright: RUMString,
    pub lang: RUMString,
    pub theme: RUMString,
    pub custom_css: bool,
    pub header_conf: HeaderConf,
    pub footer_conf: FooterConf,

    strings: RootNestedNestedTextMap,
    config: NestedNestedTextMap,
    //pub opts: TextMap,
}

impl AppConf {
    pub fn update_site_info(
        &mut self,
        title: RUMString,
        description: RUMString,
        company: RUMString,
        copyright: RUMString,
    ) {
        if !title.is_empty() {
            self.title = title;
        }
        if !company.is_empty() {
            self.company = company;
        }
        if !description.is_empty() {
            self.description = description;
        }
        if !copyright.is_empty() {
            self.copyright = copyright;
        }
    }

    pub fn get_text(&self, item: &str) -> NestedTextMap {
        match self.strings.get(&self.lang) {
            Some(l) => match l.get(item) {
                Some(i) => i.clone(),
                None => NestedTextMap::default(),
            },
            None => NestedTextMap::default(),
        }
    }

    pub fn get_section(&self, section: &str) -> TextMap {
        match self.config.get(&self.lang) {
            Some(l) => match l.get(section) {
                Some(i) => i.clone(),
                None => match self.config.get(DEFAULT_TEXT_ITEM) {
                    Some(l) => match l.get(section) {
                        Some(i) => i.clone(),
                        None => TextMap::default(),
                    },
                    None => TextMap::default(),
                },
            },
            None => match self.config.get(DEFAULT_TEXT_ITEM) {
                Some(l) => match l.get(section) {
                    Some(i) => i.clone(),
                    None => TextMap::default(),
                },
                None => TextMap::default(),
            },
        }
    }
}

pub type ClipboardID = RUMString;
///
/// Main internal structure for holding the initial app configuration ([AppConf](crate::utils::AppConf)),
/// the `clipboard` containing dynamically generated state ([NestedTextMap](crate::utils::NestedTextMap)),
/// and the `jobs` field containing
///
#[derive(Default, Debug, Clone)]
pub struct AppState {
    config: AppConf,
    clipboard: NestedTextMap,
    jobs: RUMHashMap<RUMID, Job>,
}

pub type SharedAppState = SafeLock<AppState>;

impl AppState {
    pub fn new() -> AppState {
        AppState {
            config: AppConf::default(),
            clipboard: NestedTextMap::default(),
            jobs: RUMHashMap::default(),
        }
    }

    pub fn new_safe() -> SharedAppState {
        rumtk_new_lock!(AppState::new())
    }

    pub fn from_safe(conf: AppConf) -> SharedAppState {
        rumtk_new_lock!(AppState::from(conf))
    }

    pub fn get_config(&self) -> &AppConf {
        &self.config
    }

    pub fn get_config_mut(&mut self) -> &mut AppConf {
        &mut self.config
    }

    pub fn has_clipboard(&self, id: &ClipboardID) -> bool {
        self.clipboard.contains_key(id)
    }

    pub fn has_job(&self, id: &JobID) -> bool {
        self.jobs.contains_key(id)
    }

    pub fn push_job_result(&mut self, id: &JobID, job: Job) {
        self.jobs.insert(id.clone(), job);
    }

    pub fn push_to_clipboard(&mut self, data: TextMap) -> ClipboardID {
        let clipboard_id = rumtk_generate_id!().to_rumstring();
        self.clipboard.insert(clipboard_id.clone(), data);
        clipboard_id
    }

    pub fn request_clipboard_slice(&mut self) -> ClipboardID {
        let clipboard_id = rumtk_generate_id!().to_rumstring();
        self.clipboard
            .insert(clipboard_id.clone(), TextMap::default());
        clipboard_id
    }

    pub fn pop_job(&mut self, id: &RUMID) -> Option<Job> {
        self.jobs.remove(id)
    }

    pub fn pop_clipboard(&mut self, id: &ClipboardID) -> Option<TextMap> {
        self.clipboard.shift_remove(id)
    }
}

impl From<AppConf> for AppState {
    fn from(config: AppConf) -> Self {
        AppState {
            config,
            clipboard: NestedTextMap::default(),
            jobs: RUMHashMap::default(),
        }
    }
}

pub type RouterAppState = State<SharedAppState>;

///
/// Load the configuration for this app at the specified path. By default, we look into `./app.json`
/// as the location of the configuration.
///
/// ## Example
/// ```
/// use std::fs;
/// use rumtk_core::rumtk_new_lock;
/// use rumtk_web::{rumtk_web_save_conf, rumtk_web_load_conf, rumtk_web_get_config};
/// use rumtk_web::{AppConf};
/// use rumtk_core::strings::RUMString;
///
/// #[derive(Default)]
/// struct Args {
///     title: RUMString,
///     description: RUMString,
///     company: RUMString,
///     copyright: RUMString,
///     css_source_dir: RUMString,
///     ip: RUMString,
///     upload_limit: usize,
///     threads: usize,
///     skip_default_css: bool,
/// }
///
/// let path = "./test_conf.json";
///
/// rumtk_web_save_conf!(&path);
/// let app_state = rumtk_web_load_conf!(Args::default());
/// let config = rumtk_web_get_config!(app_state).clone();
///
/// if fs::exists(&path).unwrap() {
///     fs::remove_file(&path).unwrap();
/// }
///
/// assert_eq!(config, AppConf::default(), "Configuration was not loaded properly!");
/// ```
///
#[macro_export]
macro_rules! rumtk_web_load_conf {
    ( $args:expr ) => {{
        rumtk_web_load_conf!($args, "./app.json")
    }};
    ( $args:expr, $path:expr ) => {{
        use rumtk_core::rumtk_deserialize;
        use rumtk_core::strings::RUMStringConversions;
        use rumtk_core::types::RUMHashMap;
        use $crate::AppConf;
        use std::fs;

        use $crate::rumtk_web_save_conf;
        use $crate::utils::{AppState, TextMap};

        let json = match fs::read_to_string($path) {
            Ok(json) => json,
            Err(err) => rumtk_web_save_conf!($path),
        };

        let mut conf: AppConf = match rumtk_deserialize!(json) {
            Ok(conf) => conf,
            Err(err) => panic!(
                "The App config file in {} does not meet the expected structure. \
                    See the documentation for more information. Error: {}\n{}",
                $path, err, json
            ),
        };
        conf.update_site_info(
            $args.title.clone(),
            $args.description.clone(),
            $args.company.clone(),
            $args.copyright.clone(),
        );
        AppState::from_safe(conf)
    }};
}

///
/// Serializes [AppConf] default contents and saves it to a file on disk at a specified path or relative to
/// the current working directory. This is done to pre-craft a default configuration skeleton so
/// a consumer of the framework can simply update that file before testing and shipping to production.
///
/// By default, we generate the skeleton in `./app.json`.
///
/// ## Example
/// ```
/// use std::fs;
/// use rumtk_core::rumtk_new_lock;
/// use rumtk_web::rumtk_web_save_conf;
/// use rumtk_core::strings::RUMString;
///
/// let path = "./test_conf.json";
///
/// if fs::exists(&path).unwrap() {
///     fs::remove_file(&path).unwrap();
/// }
///
/// assert!(!fs::exists(&path).unwrap(), "File was not deleted as expected!");
///
/// rumtk_web_save_conf!(&path);
///
/// assert!(fs::exists(&path).unwrap(), "File was not created as expected!");
///
/// if fs::exists(&path).unwrap() {
///     fs::remove_file(&path).unwrap();
/// }
/// ```
///
#[macro_export]
macro_rules! rumtk_web_save_conf {
    (  ) => {{
        rumtk_web_save_conf!("./app.json")
    }};
    ( $path:expr ) => {{
        use rumtk_core::rumtk_serialize;
        use rumtk_core::strings::RUMStringConversions;
        use std::fs;
        use $crate::utils::AppConf;

        let json = rumtk_serialize!(AppConf::default(), true).unwrap_or_default();
        fs::write($path, &json);
        json
    }};
}

///
/// Retrieve a configuration ([AppConf]) static string. These are strings driven by the app designer's
/// generated configuration.
///
#[macro_export]
macro_rules! rumtk_web_get_config_string {
    ( $conf:expr, $item:expr ) => {{
        use $crate::rumtk_web_get_config;
        use $crate::AppConf;
        rumtk_web_get_config!($conf).get_text($item)
    }};
}

///
/// Retrieve a configuration ([AppConf]) item. These are strings driven by the app designer's
/// generated configuration. Unlike [rumtk_web_get_config_string](crate::rumtk_web_get_config_string), the item
/// retrieved here is separate from the strings section.
///
#[macro_export]
macro_rules! rumtk_web_get_config_section {
    ( $conf:expr, $item:expr ) => {{
        use $crate::rumtk_web_get_config;
        use $crate::AppConf;
        rumtk_web_get_config!($conf).get_section($item)
    }};
}

///
/// Get field state from the configuration section of the [SharedAppState] object. The configuration
/// is of type [AppConf].
///
/// ## Example
/// ```
/// use rumtk_core::rumtk_new_lock;
/// use rumtk_core::strings::RUMString;
/// use rumtk_web::{AppState, ClipboardID, SharedAppState, AppConf};
/// use rumtk_web::{rumtk_web_set_config, rumtk_web_get_config};
///
/// let state = rumtk_new_lock!(AppState::new());
///
/// let new_lang = rumtk_web_get_config!(state).lang.clone();
///
/// assert_eq!(new_lang, "", "Language field in the configuration was not empty!");
/// ```
///
#[macro_export]
macro_rules! rumtk_web_get_config {
    ( $state:expr ) => {{
        use rumtk_core::{rumtk_lock_read};
        rumtk_lock_read!($state.clone()).get_config()
    }};
}

///
/// Set field or state in the configuration section of the [SharedAppState] object. The configuration
/// is of type [AppConf].
///
/// ## Example
/// ```
/// use rumtk_core::rumtk_new_lock;
/// use rumtk_core::strings::RUMString;
/// use rumtk_web::{AppState, ClipboardID, SharedAppState, AppConf};
/// use rumtk_web::{rumtk_web_set_config, rumtk_web_get_config};
///
/// let state = rumtk_new_lock!(AppState::new());
/// let lang = RUMString::from("en");
///
/// rumtk_web_set_config!(state).lang = RUMString::from(lang.clone());
///
/// let new_lang = rumtk_web_get_config!(state).lang.clone();
///
/// assert_eq!(new_lang, lang, "Changing the language field in the configuration was not successful!");
/// ```
///
#[macro_export]
macro_rules! rumtk_web_set_config {
    ( $state:expr ) => {{
        use rumtk_core::rumtk_lock_write;
        rumtk_lock_write!($state.clone()).get_config_mut()
    }};
}

///
/// Facility for modifying the state in an instance of [SharedAppState].
///
/// ## Example
/// ```
/// use rumtk_core::rumtk_new_lock;
/// use rumtk_core::strings::RUMString;
/// use rumtk_web::{AppState, ClipboardID, SharedAppState};
/// use rumtk_web::rumtk_web_modify_state;
///
/// let state = rumtk_new_lock!(AppState::new());
/// let clipboard_id = ClipboardID::new("");
///
/// let item_list = rumtk_web_modify_state!(state).pop_clipboard(&clipboard_id);
///
/// assert_eq!(item_list, None, "A non empty item list was retrieved from the app state.");
/// ```
///
#[macro_export]
macro_rules! rumtk_web_modify_state {
    ( $state:expr ) => {{
        use rumtk_core::rumtk_lock_write;
        rumtk_lock_write!($state.clone())
    }};
}

/*
   Default non static data to minimize allocations.
*/
pub const DEFAULT_TEXT: fn() -> RUMString = || RUMString::default();
pub const DEFAULT_TEXTMAP: fn() -> TextMap = || TextMap::default();
pub const DEFAULT_NESTEDTEXTMAP: fn() -> NestedTextMap = || NestedTextMap::default();
pub const DEFAULT_NESTEDNESTEDTEXTMAP: fn() -> NestedNestedTextMap =
    || NestedNestedTextMap::default();