Compare commits
115 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1ebe4732f | ||
|
|
7b7f3ca05a | ||
|
|
234613f831 | ||
|
|
f6d84e70cc | ||
|
|
5cd324b6ae | ||
|
|
a7457f5749 | ||
|
|
a5afc75099 | ||
|
|
625c9b3e09 | ||
|
|
e20623ed53 | ||
|
|
aa9adf7348 | ||
|
|
2e82aba0d1 | ||
|
|
b7a3f0f8d9 | ||
|
|
38c82389f7 | ||
|
|
cb0a2bee17 | ||
|
|
dc99131794 | ||
|
|
5c23f61a10 | ||
|
|
f87e3c03cb | ||
|
|
d346670839 | ||
|
|
560d8b7234 | ||
|
|
b297c2b311 | ||
|
|
d390c567d5 | ||
|
|
029e614b9c | ||
|
|
f9a78e4eec | ||
|
|
d8758f7531 | ||
|
|
4e86ecff84 | ||
|
|
070d091e07 | ||
|
|
7403b3c3f8 | ||
|
|
1b1e7b7205 | ||
|
|
1b8f19f1ce | ||
|
|
2a14eadf34 | ||
|
|
fd36cd5795 | ||
|
|
f4286ac3c9 | ||
|
|
92d5eb4844 | ||
|
|
87b9f6ab87 | ||
|
|
06d98aab5c | ||
|
|
298f56a53c | ||
|
|
714a5f2f1c | ||
|
|
4e29d0084f | ||
|
|
63f1b4da2e | ||
|
|
9477f53432 | ||
|
|
ed786f087c | ||
|
|
8e22ea05ff | ||
|
|
8414657224 | ||
|
|
e25213ed1b | ||
|
|
4843b0778c | ||
|
|
f5fae98c69 | ||
|
|
6faf0a4a31 | ||
|
|
011fafc0ff | ||
|
|
8ebe74484c | ||
|
|
3eb9523103 | ||
|
|
3dfa922b9e | ||
|
|
248d54a30f | ||
|
|
b30fef4ccd | ||
|
|
a9c4527318 | ||
|
|
c31f08d5b8 | ||
|
|
9e0fa9ddb1 | ||
|
|
8fcd28832d | ||
|
|
cccf029464 | ||
|
|
512e7fb9e7 | ||
|
|
0e69df8282 | ||
|
|
eb5532c200 | ||
|
|
49ed1dfe33 | ||
|
|
62d1c3f7f5 | ||
|
|
b49dce3334 | ||
|
|
8ace9bc4d1 | ||
|
|
ce490007ed | ||
|
|
eb96c64e26 | ||
|
|
2ac96a8486 | ||
|
|
b8e6cc22af | ||
|
|
634a01f618 | ||
|
|
6abea062ba | ||
|
|
f50887a326 | ||
|
|
3c0af05a3c | ||
|
|
c9131d4457 | ||
|
|
2af79a3ef2 | ||
|
|
afd9228efa | ||
|
|
495d77fda5 | ||
|
|
679bb3b6ab | ||
|
|
350c522d19 | ||
|
|
4760f42589 | ||
|
|
50d15e321f | ||
|
|
a3e7fd8f0a | ||
|
|
645172747a | ||
|
|
7c4ac1eebc | ||
|
|
4b4301ad49 | ||
|
|
b60e03eb70 | ||
|
|
2c7bda3ff1 | ||
|
|
eeaaa3635b | ||
|
|
e61cbb3956 | ||
|
|
f9841f2ef3 | ||
|
|
dc232b2523 | ||
|
|
b086b3e236 | ||
|
|
387e1a0fe0 | ||
|
|
08e01d41f2 | ||
|
|
f5edf52571 | ||
|
|
02c62213c3 | ||
|
|
d0722fbbbe | ||
|
|
4ec569342d | ||
|
|
9540d9ccb9 | ||
|
|
6b5cbe854b | ||
|
|
59ed52814e | ||
|
|
3488ab4f6b | ||
|
|
6e2fc5349b | ||
|
|
ea88c2686d | ||
|
|
3df4baec92 | ||
|
|
ff74e1aaa1 | ||
|
|
b0c865ab76 | ||
|
|
3dbc086f10 | ||
|
|
e9b4b34fb4 | ||
|
|
668eeee197 | ||
|
|
799d8471c9 | ||
|
|
f77c16dec9 | ||
|
|
45026cac6a | ||
|
|
edf6ab5bca | ||
|
|
462b1f14e2 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +1,4 @@
|
|||||||
/target
|
/target
|
||||||
.env
|
.env
|
||||||
|
/tantivy_indexes
|
||||||
|
server/tantivy_indexes
|
||||||
|
|||||||
747
Cargo.lock
generated
747
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
28
Cargo.toml
28
Cargo.toml
@@ -1,5 +1,5 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = ["client", "server", "common"]
|
members = ["client", "server", "common", "search"]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
@@ -16,4 +16,28 @@ categories = ["command-line-interface"]
|
|||||||
|
|
||||||
# [workspace.metadata]
|
# [workspace.metadata]
|
||||||
# TODO:
|
# TODO:
|
||||||
# documentation = "https://docs.rs/accounting-client"`
|
# documentation = "https://docs.rs/accounting-client"
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
# Async and gRPC
|
||||||
|
tokio = { version = "1.44.2", features = ["full"] }
|
||||||
|
tonic = "0.13.0"
|
||||||
|
prost = "0.13.5"
|
||||||
|
async-trait = "0.1.88"
|
||||||
|
prost-types = "0.13.0"
|
||||||
|
|
||||||
|
# Data Handling & Serialization
|
||||||
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
|
serde_json = "1.0.140"
|
||||||
|
time = "0.3.41"
|
||||||
|
|
||||||
|
# Utilities & Error Handling
|
||||||
|
anyhow = "1.0.98"
|
||||||
|
dotenvy = "0.15.7"
|
||||||
|
lazy_static = "1.5.0"
|
||||||
|
tracing = "0.1.41"
|
||||||
|
|
||||||
|
# Search crate
|
||||||
|
tantivy = "0.24.1"
|
||||||
|
|
||||||
|
common = { path = "./common" }
|
||||||
|
|||||||
@@ -18,3 +18,8 @@ Client with tracing:
|
|||||||
```
|
```
|
||||||
ENABLE_TRACING=1 RUST_LOG=client=debug cargo watch -x 'run --package client -- client'
|
ENABLE_TRACING=1 RUST_LOG=client=debug cargo watch -x 'run --package client -- client'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Client with debug that cant be traced
|
||||||
|
```
|
||||||
|
cargo run --package client --features ui-debug -- client
|
||||||
|
```
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ anyhow = "1.0.98"
|
|||||||
async-trait = "0.1.88"
|
async-trait = "0.1.88"
|
||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
|
|
||||||
|
prost-types = { workspace = true }
|
||||||
crossterm = "0.28.1"
|
crossterm = "0.28.1"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
@@ -26,3 +27,13 @@ tracing-subscriber = "0.3.19"
|
|||||||
tui-textarea = { version = "0.7.0", features = ["crossterm", "ratatui", "search"] }
|
tui-textarea = { version = "0.7.0", features = ["crossterm", "ratatui", "search"] }
|
||||||
unicode-segmentation = "1.12.0"
|
unicode-segmentation = "1.12.0"
|
||||||
unicode-width = "0.2.0"
|
unicode-width = "0.2.0"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
ui-debug = []
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
rstest = "0.25.0"
|
||||||
|
tokio-test = "0.4.4"
|
||||||
|
uuid = { version = "1.17.0", features = ["v4"] }
|
||||||
|
futures = "0.3.31"
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ toggle_buffer_list = ["ctrl+b"]
|
|||||||
next_field = ["Tab"]
|
next_field = ["Tab"]
|
||||||
prev_field = ["Shift+Tab"]
|
prev_field = ["Shift+Tab"]
|
||||||
exit_table_scroll = ["esc"]
|
exit_table_scroll = ["esc"]
|
||||||
|
open_search = ["ctrl+f"]
|
||||||
|
|
||||||
[keybindings.common]
|
[keybindings.common]
|
||||||
save = ["ctrl+s"]
|
save = ["ctrl+s"]
|
||||||
@@ -69,10 +70,11 @@ prev_field = ["shift+enter"]
|
|||||||
exit = ["esc", "ctrl+e"]
|
exit = ["esc", "ctrl+e"]
|
||||||
delete_char_forward = ["delete"]
|
delete_char_forward = ["delete"]
|
||||||
delete_char_backward = ["backspace"]
|
delete_char_backward = ["backspace"]
|
||||||
move_left = ["left"]
|
move_left = [""]
|
||||||
move_right = ["right"]
|
move_right = ["right"]
|
||||||
suggestion_down = ["ctrl+n", "tab"]
|
suggestion_down = ["ctrl+n", "tab"]
|
||||||
suggestion_up = ["ctrl+p", "shift+tab"]
|
suggestion_up = ["ctrl+p", "shift+tab"]
|
||||||
|
trigger_autocomplete = ["left"]
|
||||||
|
|
||||||
[keybindings.command]
|
[keybindings.command]
|
||||||
exit_command_mode = ["ctrl+g", "esc"]
|
exit_command_mode = ["ctrl+g", "esc"]
|
||||||
@@ -83,6 +85,7 @@ quit = ["q"]
|
|||||||
force_quit = ["q!"]
|
force_quit = ["q!"]
|
||||||
save_and_quit = ["wq"]
|
save_and_quit = ["wq"]
|
||||||
revert = ["r"]
|
revert = ["r"]
|
||||||
|
find_file_palette_toggle = ["ff"]
|
||||||
|
|
||||||
[editor]
|
[editor]
|
||||||
keybinding_mode = "vim" # Options: "default", "vim", "emacs"
|
keybinding_mode = "vim" # Options: "default", "vim", "emacs"
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ pub mod text_editor;
|
|||||||
pub mod background;
|
pub mod background;
|
||||||
pub mod dialog;
|
pub mod dialog;
|
||||||
pub mod autocomplete;
|
pub mod autocomplete;
|
||||||
|
pub mod search_palette;
|
||||||
|
pub mod find_file_palette;
|
||||||
|
|
||||||
pub use command_line::*;
|
pub use command_line::*;
|
||||||
pub use status_line::*;
|
pub use status_line::*;
|
||||||
@@ -12,3 +14,5 @@ pub use text_editor::*;
|
|||||||
pub use background::*;
|
pub use background::*;
|
||||||
pub use dialog::*;
|
pub use dialog::*;
|
||||||
pub use autocomplete::*;
|
pub use autocomplete::*;
|
||||||
|
pub use search_palette::*;
|
||||||
|
pub use find_file_palette::*;
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// src/components/common/autocomplete.rs
|
// src/components/common/autocomplete.rs
|
||||||
|
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
|
use common::proto::multieko2::search::search_response::Hit;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::Rect,
|
layout::Rect,
|
||||||
style::{Color, Modifier, Style},
|
style::{Color, Modifier, Style},
|
||||||
@@ -9,7 +11,8 @@ use ratatui::{
|
|||||||
};
|
};
|
||||||
use unicode_width::UnicodeWidthStr;
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
/// Renders an opaque dropdown list for autocomplete suggestions.
|
/// Renders an opaque dropdown list for simple string-based suggestions.
|
||||||
|
/// THIS IS THE RESTORED FUNCTION.
|
||||||
pub fn render_autocomplete_dropdown(
|
pub fn render_autocomplete_dropdown(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
input_rect: Rect,
|
input_rect: Rect,
|
||||||
@@ -21,39 +24,32 @@ pub fn render_autocomplete_dropdown(
|
|||||||
if suggestions.is_empty() {
|
if suggestions.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// --- Calculate Dropdown Size & Position ---
|
let max_suggestion_width =
|
||||||
let max_suggestion_width = suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
|
suggestions.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
|
||||||
let horizontal_padding: u16 = 2;
|
let horizontal_padding: u16 = 2;
|
||||||
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
|
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
|
||||||
let dropdown_height = (suggestions.len() as u16).min(5);
|
let dropdown_height = (suggestions.len() as u16).min(5);
|
||||||
|
|
||||||
let mut dropdown_area = Rect {
|
let mut dropdown_area = Rect {
|
||||||
x: input_rect.x, // Align horizontally with input
|
x: input_rect.x,
|
||||||
y: input_rect.y + 1, // Position directly below input
|
y: input_rect.y + 1,
|
||||||
width: dropdown_width,
|
width: dropdown_width,
|
||||||
height: dropdown_height,
|
height: dropdown_height,
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Clamping Logic (prevent rendering off-screen) ---
|
|
||||||
// Clamp vertically (if it goes below the frame)
|
|
||||||
if dropdown_area.bottom() > frame_area.height {
|
if dropdown_area.bottom() > frame_area.height {
|
||||||
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height); // Try rendering above
|
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height);
|
||||||
}
|
}
|
||||||
// Clamp horizontally (if it goes past the right edge)
|
|
||||||
if dropdown_area.right() > frame_area.width {
|
if dropdown_area.right() > frame_area.width {
|
||||||
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
|
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
|
||||||
}
|
}
|
||||||
// Ensure x is not negative (if clamping pushes it left)
|
|
||||||
dropdown_area.x = dropdown_area.x.max(0);
|
dropdown_area.x = dropdown_area.x.max(0);
|
||||||
// Ensure y is not negative (if clamping pushes it up)
|
|
||||||
dropdown_area.y = dropdown_area.y.max(0);
|
dropdown_area.y = dropdown_area.y.max(0);
|
||||||
// --- End Clamping ---
|
|
||||||
|
|
||||||
// Render a solid background block first to ensure opacity
|
let background_block =
|
||||||
let background_block = Block::default().style(Style::default().bg(Color::DarkGray));
|
Block::default().style(Style::default().bg(Color::DarkGray));
|
||||||
f.render_widget(background_block, dropdown_area);
|
f.render_widget(background_block, dropdown_area);
|
||||||
|
|
||||||
// Create list items, ensuring each has a defined background
|
|
||||||
let items: Vec<ListItem> = suggestions
|
let items: Vec<ListItem> = suggestions
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -61,30 +57,97 @@ pub fn render_autocomplete_dropdown(
|
|||||||
let is_selected = selected_index == Some(i);
|
let is_selected = selected_index == Some(i);
|
||||||
let s_width = s.width() as u16;
|
let s_width = s.width() as u16;
|
||||||
let padding_needed = dropdown_width.saturating_sub(s_width);
|
let padding_needed = dropdown_width.saturating_sub(s_width);
|
||||||
let padded_s = format!("{}{}", s, " ".repeat(padding_needed as usize));
|
let padded_s =
|
||||||
|
format!("{}{}", s, " ".repeat(padding_needed as usize));
|
||||||
|
|
||||||
ListItem::new(padded_s).style(if is_selected {
|
ListItem::new(padded_s).style(if is_selected {
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.bg) // Text color on highlight
|
.fg(theme.bg)
|
||||||
.bg(theme.highlight) // Highlight background
|
.bg(theme.highlight)
|
||||||
.add_modifier(Modifier::BOLD)
|
.add_modifier(Modifier::BOLD)
|
||||||
} else {
|
} else {
|
||||||
// Style for non-selected items (matching background block)
|
Style::default().fg(theme.fg).bg(Color::DarkGray)
|
||||||
Style::default()
|
|
||||||
.fg(theme.fg) // Text color on gray
|
|
||||||
.bg(Color::DarkGray) // Explicit gray background
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// Create the list widget (without its own block)
|
|
||||||
let list = List::new(items);
|
let list = List::new(items);
|
||||||
|
let mut list_state = ListState::default();
|
||||||
|
list_state.select(selected_index);
|
||||||
|
|
||||||
// State for managing selection highlight (still needed for logic)
|
f.render_stateful_widget(list, dropdown_area, &mut list_state);
|
||||||
let mut profile_list_state = ListState::default();
|
|
||||||
profile_list_state.select(selected_index);
|
|
||||||
|
|
||||||
// Render the list statefully *over* the background block
|
|
||||||
f.render_stateful_widget(list, dropdown_area, &mut profile_list_state);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Renders an opaque dropdown list for rich `Hit`-based suggestions.
|
||||||
|
/// RENAMED from render_rich_autocomplete_dropdown
|
||||||
|
pub fn render_hit_autocomplete_dropdown(
|
||||||
|
f: &mut Frame,
|
||||||
|
input_rect: Rect,
|
||||||
|
frame_area: Rect,
|
||||||
|
theme: &Theme,
|
||||||
|
suggestions: &[Hit],
|
||||||
|
selected_index: Option<usize>,
|
||||||
|
form_state: &FormState,
|
||||||
|
) {
|
||||||
|
if suggestions.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let display_names: Vec<String> = suggestions
|
||||||
|
.iter()
|
||||||
|
.map(|hit| form_state.get_display_name_for_hit(hit))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let max_suggestion_width =
|
||||||
|
display_names.iter().map(|s| s.width()).max().unwrap_or(0) as u16;
|
||||||
|
let horizontal_padding: u16 = 2;
|
||||||
|
let dropdown_width = (max_suggestion_width + horizontal_padding).max(10);
|
||||||
|
let dropdown_height = (suggestions.len() as u16).min(5);
|
||||||
|
|
||||||
|
let mut dropdown_area = Rect {
|
||||||
|
x: input_rect.x,
|
||||||
|
y: input_rect.y + 1,
|
||||||
|
width: dropdown_width,
|
||||||
|
height: dropdown_height,
|
||||||
|
};
|
||||||
|
|
||||||
|
if dropdown_area.bottom() > frame_area.height {
|
||||||
|
dropdown_area.y = input_rect.y.saturating_sub(dropdown_height);
|
||||||
|
}
|
||||||
|
if dropdown_area.right() > frame_area.width {
|
||||||
|
dropdown_area.x = frame_area.width.saturating_sub(dropdown_width);
|
||||||
|
}
|
||||||
|
dropdown_area.x = dropdown_area.x.max(0);
|
||||||
|
dropdown_area.y = dropdown_area.y.max(0);
|
||||||
|
|
||||||
|
let background_block =
|
||||||
|
Block::default().style(Style::default().bg(Color::DarkGray));
|
||||||
|
f.render_widget(background_block, dropdown_area);
|
||||||
|
|
||||||
|
let items: Vec<ListItem> = display_names
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, s)| {
|
||||||
|
let is_selected = selected_index == Some(i);
|
||||||
|
let s_width = s.width() as u16;
|
||||||
|
let padding_needed = dropdown_width.saturating_sub(s_width);
|
||||||
|
let padded_s =
|
||||||
|
format!("{}{}", s, " ".repeat(padding_needed as usize));
|
||||||
|
|
||||||
|
ListItem::new(padded_s).style(if is_selected {
|
||||||
|
Style::default()
|
||||||
|
.fg(theme.bg)
|
||||||
|
.bg(theme.highlight)
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg).bg(Color::DarkGray)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let list = List::new(items);
|
||||||
|
let mut list_state = ListState::default();
|
||||||
|
list_state.select(selected_index);
|
||||||
|
|
||||||
|
f.render_stateful_widget(list, dropdown_area, &mut list_state);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
// src/client/components/command_line.rs
|
// src/components/common/command_line.rs
|
||||||
|
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
widgets::{Block, Paragraph},
|
widgets::{Block, Paragraph},
|
||||||
style::Style,
|
style::Style,
|
||||||
@@ -6,30 +7,63 @@ use ratatui::{
|
|||||||
Frame,
|
Frame,
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
|
use unicode_width::UnicodeWidthStr; // Import for width calculation
|
||||||
|
|
||||||
pub fn render_command_line(f: &mut Frame, area: Rect, input: &str, active: bool, theme: &Theme, message: &str) {
|
pub fn render_command_line(
|
||||||
let prompt = if active {
|
f: &mut Frame,
|
||||||
":"
|
area: Rect,
|
||||||
} else {
|
input: &str, // This is event_handler.command_input
|
||||||
""
|
active: bool, // This is event_handler.command_mode
|
||||||
|
theme: &Theme,
|
||||||
|
message: &str, // This is event_handler.command_message
|
||||||
|
) {
|
||||||
|
// Original logic for determining display_text
|
||||||
|
let display_text = if !active {
|
||||||
|
// If not in normal command mode, but there's a message (e.g. from Find File palette closing)
|
||||||
|
// Or if command mode is off and message is empty (render minimally)
|
||||||
|
if message.is_empty() {
|
||||||
|
"".to_string() // Render an empty string, background will cover
|
||||||
|
} else {
|
||||||
|
message.to_string()
|
||||||
|
}
|
||||||
|
} else { // active is true (normal command mode)
|
||||||
|
let prompt = ":";
|
||||||
|
if message.is_empty() || message == ":" {
|
||||||
|
format!("{}{}", prompt, input)
|
||||||
|
} else {
|
||||||
|
if input.is_empty() { // If command was just executed, input is cleared, show message
|
||||||
|
message.to_string()
|
||||||
|
} else { // Show input and message
|
||||||
|
format!("{}{} | {}", prompt, input, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Combine the prompt, input, and message
|
let content_width = UnicodeWidthStr::width(display_text.as_str());
|
||||||
let display_text = if message.is_empty() {
|
let available_width = area.width as usize;
|
||||||
format!("{}{}", prompt, input)
|
let padding_needed = available_width.saturating_sub(content_width);
|
||||||
|
|
||||||
|
let display_text_padded = if padding_needed > 0 {
|
||||||
|
format!("{}{}", display_text, " ".repeat(padding_needed))
|
||||||
} else {
|
} else {
|
||||||
format!("{}{} | {}", prompt, input, message)
|
// If text is too long, ratatui's Paragraph will handle truncation.
|
||||||
|
// We could also truncate here if specific behavior is needed:
|
||||||
|
// display_text.chars().take(available_width).collect::<String>()
|
||||||
|
display_text
|
||||||
};
|
};
|
||||||
|
|
||||||
let style = if active {
|
// Determine style based on active state, but apply to the whole paragraph
|
||||||
|
let text_style = if active {
|
||||||
Style::default().fg(theme.accent)
|
Style::default().fg(theme.accent)
|
||||||
} else {
|
} else {
|
||||||
|
// If not active, but there's a message, use default foreground.
|
||||||
|
// If message is also empty, this style won't matter much for empty text.
|
||||||
Style::default().fg(theme.fg)
|
Style::default().fg(theme.fg)
|
||||||
};
|
};
|
||||||
|
|
||||||
let paragraph = Paragraph::new(display_text)
|
let paragraph = Paragraph::new(display_text_padded)
|
||||||
.block(Block::default().style(Style::default().bg(theme.bg)))
|
.block(Block::default().style(Style::default().bg(theme.bg))) // Block ensures bg for whole area
|
||||||
.style(style);
|
.style(text_style); // Style for the text itself
|
||||||
|
|
||||||
f.render_widget(paragraph, area);
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
|
|||||||
142
client/src/components/common/find_file_palette.rs
Normal file
142
client/src/components/common/find_file_palette.rs
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
// src/components/common/find_file_palette.rs
|
||||||
|
|
||||||
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::modes::general::command_navigation::NavigationState; // Corrected path
|
||||||
|
use ratatui::{
|
||||||
|
layout::{Constraint, Direction, Layout, Rect},
|
||||||
|
style::Style,
|
||||||
|
widgets::{Block, List, ListItem, Paragraph},
|
||||||
|
Frame,
|
||||||
|
};
|
||||||
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
|
const PALETTE_MAX_VISIBLE_OPTIONS: usize = 15;
|
||||||
|
const PADDING_CHAR: &str = " ";
|
||||||
|
|
||||||
|
pub fn render_find_file_palette(
|
||||||
|
f: &mut Frame,
|
||||||
|
area: Rect,
|
||||||
|
theme: &Theme,
|
||||||
|
navigation_state: &NavigationState,
|
||||||
|
) {
|
||||||
|
let palette_display_input = navigation_state.get_display_input(); // Use the new method
|
||||||
|
|
||||||
|
let num_total_filtered = navigation_state.filtered_options.len();
|
||||||
|
let current_selected_list_idx = navigation_state.selected_index;
|
||||||
|
|
||||||
|
let mut display_start_offset = 0;
|
||||||
|
if num_total_filtered > PALETTE_MAX_VISIBLE_OPTIONS {
|
||||||
|
if let Some(sel_idx) = current_selected_list_idx {
|
||||||
|
if sel_idx >= display_start_offset + PALETTE_MAX_VISIBLE_OPTIONS {
|
||||||
|
display_start_offset = sel_idx - PALETTE_MAX_VISIBLE_OPTIONS + 1;
|
||||||
|
} else if sel_idx < display_start_offset {
|
||||||
|
display_start_offset = sel_idx;
|
||||||
|
}
|
||||||
|
display_start_offset = display_start_offset
|
||||||
|
.min(num_total_filtered.saturating_sub(PALETTE_MAX_VISIBLE_OPTIONS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
display_start_offset = display_start_offset.max(0);
|
||||||
|
|
||||||
|
let display_end_offset = (display_start_offset + PALETTE_MAX_VISIBLE_OPTIONS)
|
||||||
|
.min(num_total_filtered);
|
||||||
|
|
||||||
|
// navigation_state.filtered_options is Vec<(usize, String)>
|
||||||
|
// We only need the String part for display.
|
||||||
|
let visible_options_slice: Vec<&String> = if num_total_filtered > 0 {
|
||||||
|
navigation_state.filtered_options
|
||||||
|
[display_start_offset..display_end_offset]
|
||||||
|
.iter()
|
||||||
|
.map(|(_, opt_str)| opt_str)
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
let chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(1), // For palette input line
|
||||||
|
Constraint::Min(0), // For options list, take remaining space
|
||||||
|
])
|
||||||
|
.split(area);
|
||||||
|
|
||||||
|
// Ensure list_area height does not exceed PALETTE_MAX_VISIBLE_OPTIONS
|
||||||
|
let list_area_height = std::cmp::min(chunks[1].height, PALETTE_MAX_VISIBLE_OPTIONS as u16);
|
||||||
|
let final_list_area = Rect::new(chunks[1].x, chunks[1].y, chunks[1].width, list_area_height);
|
||||||
|
|
||||||
|
|
||||||
|
let input_area = chunks[0];
|
||||||
|
// let list_area = chunks[1]; // Use final_list_area
|
||||||
|
|
||||||
|
let prompt_prefix = match navigation_state.navigation_type {
|
||||||
|
crate::modes::general::command_navigation::NavigationType::FindFile => "Find File: ",
|
||||||
|
crate::modes::general::command_navigation::NavigationType::TableTree => "Table Path: ",
|
||||||
|
};
|
||||||
|
let base_prompt_text = format!("{}{}", prompt_prefix, palette_display_input);
|
||||||
|
let prompt_text_width = UnicodeWidthStr::width(base_prompt_text.as_str());
|
||||||
|
let input_area_width = input_area.width as usize;
|
||||||
|
let input_padding_needed =
|
||||||
|
input_area_width.saturating_sub(prompt_text_width);
|
||||||
|
|
||||||
|
let padded_prompt_text = if input_padding_needed > 0 {
|
||||||
|
format!(
|
||||||
|
"{}{}",
|
||||||
|
base_prompt_text,
|
||||||
|
PADDING_CHAR.repeat(input_padding_needed)
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
base_prompt_text
|
||||||
|
};
|
||||||
|
|
||||||
|
let input_paragraph = Paragraph::new(padded_prompt_text)
|
||||||
|
.style(Style::default().fg(theme.accent).bg(theme.bg));
|
||||||
|
f.render_widget(input_paragraph, input_area);
|
||||||
|
|
||||||
|
let mut display_list_items: Vec<ListItem> =
|
||||||
|
Vec::with_capacity(PALETTE_MAX_VISIBLE_OPTIONS);
|
||||||
|
|
||||||
|
for (idx_in_visible_slice, opt_str) in
|
||||||
|
visible_options_slice.iter().enumerate()
|
||||||
|
{
|
||||||
|
// The selected_index in navigation_state is relative to the full filtered_options list.
|
||||||
|
// We need to check if the current item (from the visible slice) corresponds to the selected_index.
|
||||||
|
let original_filtered_idx = display_start_offset + idx_in_visible_slice;
|
||||||
|
let is_selected =
|
||||||
|
current_selected_list_idx == Some(original_filtered_idx);
|
||||||
|
|
||||||
|
let style = if is_selected {
|
||||||
|
Style::default().fg(theme.bg).bg(theme.accent)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg).bg(theme.bg)
|
||||||
|
};
|
||||||
|
|
||||||
|
let opt_width = opt_str.width() as u16;
|
||||||
|
let list_item_width = final_list_area.width;
|
||||||
|
let padding_amount = list_item_width.saturating_sub(opt_width);
|
||||||
|
let padded_opt_str = format!(
|
||||||
|
"{}{}",
|
||||||
|
opt_str,
|
||||||
|
PADDING_CHAR.repeat(padding_amount as usize)
|
||||||
|
);
|
||||||
|
display_list_items.push(ListItem::new(padded_opt_str).style(style));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill remaining lines in the list area to maintain fixed height appearance
|
||||||
|
let num_rendered_options = display_list_items.len();
|
||||||
|
if num_rendered_options < PALETTE_MAX_VISIBLE_OPTIONS && (final_list_area.height as usize) > num_rendered_options {
|
||||||
|
for _ in num_rendered_options..(final_list_area.height as usize) {
|
||||||
|
let empty_padded_str =
|
||||||
|
PADDING_CHAR.repeat(final_list_area.width as usize);
|
||||||
|
display_list_items.push(
|
||||||
|
ListItem::new(empty_padded_str)
|
||||||
|
.style(Style::default().fg(theme.bg).bg(theme.bg)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
let options_list_widget = List::new(display_list_items)
|
||||||
|
.block(Block::default().style(Style::default().bg(theme.bg)));
|
||||||
|
f.render_widget(options_list_widget, final_list_area);
|
||||||
|
}
|
||||||
121
client/src/components/common/search_palette.rs
Normal file
121
client/src/components/common/search_palette.rs
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
// src/components/common/search_palette.rs
|
||||||
|
|
||||||
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::state::app::search::SearchState;
|
||||||
|
use ratatui::{
|
||||||
|
layout::{Constraint, Direction, Layout, Rect},
|
||||||
|
style::{Modifier, Style},
|
||||||
|
text::{Line, Span},
|
||||||
|
widgets::{Block, Borders, Clear, List, ListItem, Paragraph},
|
||||||
|
Frame,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Renders the search palette dialog over the main UI.
|
||||||
|
pub fn render_search_palette(
|
||||||
|
f: &mut Frame,
|
||||||
|
area: Rect,
|
||||||
|
theme: &Theme,
|
||||||
|
state: &SearchState,
|
||||||
|
) {
|
||||||
|
// --- Dialog Area Calculation ---
|
||||||
|
let height = (area.height as f32 * 0.7).min(30.0) as u16;
|
||||||
|
let width = (area.width as f32 * 0.6).min(100.0) as u16;
|
||||||
|
let dialog_area = Rect {
|
||||||
|
x: area.x + (area.width - width) / 2,
|
||||||
|
y: area.y + (area.height - height) / 4,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
};
|
||||||
|
|
||||||
|
f.render_widget(Clear, dialog_area); // Clear background
|
||||||
|
|
||||||
|
let block = Block::default()
|
||||||
|
.title(format!(" Search in '{}' ", state.table_name))
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_style(Style::default().fg(theme.accent));
|
||||||
|
f.render_widget(block.clone(), dialog_area);
|
||||||
|
|
||||||
|
// --- Inner Layout (Input + Results) ---
|
||||||
|
let inner_chunks = Layout::default()
|
||||||
|
.direction(Direction::Vertical)
|
||||||
|
.margin(1)
|
||||||
|
.constraints([
|
||||||
|
Constraint::Length(3), // For input box
|
||||||
|
Constraint::Min(0), // For results list
|
||||||
|
])
|
||||||
|
.split(dialog_area);
|
||||||
|
|
||||||
|
// --- Render Input Box ---
|
||||||
|
let input_block = Block::default()
|
||||||
|
.title("Query")
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.border_style(Style::default().fg(theme.border));
|
||||||
|
let input_text = Paragraph::new(state.input.as_str())
|
||||||
|
.block(input_block)
|
||||||
|
.style(Style::default().fg(theme.fg));
|
||||||
|
f.render_widget(input_text, inner_chunks[0]);
|
||||||
|
// Set cursor position
|
||||||
|
f.set_cursor(
|
||||||
|
inner_chunks[0].x + state.cursor_position as u16 + 1,
|
||||||
|
inner_chunks[0].y + 1,
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Render Results List ---
|
||||||
|
if state.is_loading {
|
||||||
|
let loading_p = Paragraph::new("Searching...")
|
||||||
|
.style(Style::default().fg(theme.fg).add_modifier(Modifier::ITALIC));
|
||||||
|
f.render_widget(loading_p, inner_chunks[1]);
|
||||||
|
} else {
|
||||||
|
let list_items: Vec<ListItem> = state
|
||||||
|
.results
|
||||||
|
.iter()
|
||||||
|
.map(|hit| {
|
||||||
|
// Parse the JSON string to make it readable
|
||||||
|
let content_summary = match serde_json::from_str::<
|
||||||
|
serde_json::Value,
|
||||||
|
>(&hit.content_json)
|
||||||
|
{
|
||||||
|
Ok(json) => {
|
||||||
|
if let Some(obj) = json.as_object() {
|
||||||
|
// Create a summary from the first few non-null string values
|
||||||
|
obj.values()
|
||||||
|
.filter_map(|v| v.as_str())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.take(3)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" | ")
|
||||||
|
} else {
|
||||||
|
"Non-object JSON".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => "Invalid JSON content".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let line = Line::from(vec![
|
||||||
|
Span::styled(
|
||||||
|
format!("{:<4.2} ", hit.score),
|
||||||
|
Style::default().fg(theme.accent),
|
||||||
|
),
|
||||||
|
Span::raw(content_summary),
|
||||||
|
]);
|
||||||
|
ListItem::new(line)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let results_list = List::new(list_items)
|
||||||
|
.block(Block::default().title("Results"))
|
||||||
|
.highlight_style(
|
||||||
|
Style::default()
|
||||||
|
.bg(theme.highlight)
|
||||||
|
.fg(theme.bg)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
)
|
||||||
|
.highlight_symbol(">> ");
|
||||||
|
|
||||||
|
// We need a mutable ListState to render the selection
|
||||||
|
let mut list_state =
|
||||||
|
ratatui::widgets::ListState::default().with_selected(Some(state.selected_index));
|
||||||
|
|
||||||
|
f.render_stateful_widget(results_list, inner_chunks[1], &mut list_state);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
use ratatui::{
|
// client/src/components/common/status_line.rs
|
||||||
style::Style,
|
|
||||||
layout::Rect,
|
|
||||||
Frame,
|
|
||||||
text::{Line, Span},
|
|
||||||
widgets::Paragraph,
|
|
||||||
};
|
|
||||||
use unicode_width::UnicodeWidthStr;
|
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
|
use ratatui::{
|
||||||
|
layout::Rect,
|
||||||
|
style::Style,
|
||||||
|
text::{Line, Span, Text},
|
||||||
|
widgets::{Paragraph, Wrap}, // Make sure Wrap is imported
|
||||||
|
Frame,
|
||||||
|
};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
pub fn render_status_line(
|
pub fn render_status_line(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
@@ -16,11 +18,41 @@ pub fn render_status_line(
|
|||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
is_edit_mode: bool,
|
is_edit_mode: bool,
|
||||||
current_fps: f64,
|
current_fps: f64,
|
||||||
|
app_state: &AppState,
|
||||||
) {
|
) {
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
{
|
||||||
|
if let Some(debug_state) = &app_state.debug_state {
|
||||||
|
let paragraph = if debug_state.is_error {
|
||||||
|
// --- THIS IS THE CRITICAL LOGIC FOR ERRORS ---
|
||||||
|
// 1. Create a `Text` object, which can contain multiple lines.
|
||||||
|
let error_text = Text::from(debug_state.displayed_message.clone());
|
||||||
|
|
||||||
|
// 2. Create a Paragraph from the Text and TELL IT TO WRAP.
|
||||||
|
Paragraph::new(error_text)
|
||||||
|
.wrap(Wrap { trim: true }) // This line makes the text break into new rows.
|
||||||
|
.style(Style::default().bg(theme.highlight).fg(theme.bg))
|
||||||
|
} else {
|
||||||
|
// --- This is for normal, single-line info messages ---
|
||||||
|
Paragraph::new(debug_state.displayed_message.as_str())
|
||||||
|
.style(Style::default().fg(theme.accent).bg(theme.bg))
|
||||||
|
};
|
||||||
|
f.render_widget(paragraph, area);
|
||||||
|
} else {
|
||||||
|
// Fallback for when debug state is None
|
||||||
|
let paragraph = Paragraph::new("").style(Style::default().bg(theme.bg));
|
||||||
|
f.render_widget(paragraph, area);
|
||||||
|
}
|
||||||
|
return; // Stop here and don't render the normal status line.
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- The normal status line rendering logic (unchanged) ---
|
||||||
let program_info = format!("multieko2 v{}", env!("CARGO_PKG_VERSION"));
|
let program_info = format!("multieko2 v{}", env!("CARGO_PKG_VERSION"));
|
||||||
let mode_text = if is_edit_mode { "[EDIT]" } else { "[READ-ONLY]" };
|
let mode_text = if is_edit_mode { "[EDIT]" } else { "[READ-ONLY]" };
|
||||||
|
|
||||||
let home_dir = dirs::home_dir().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
|
let home_dir = dirs::home_dir()
|
||||||
|
.map(|p| p.to_string_lossy().into_owned())
|
||||||
|
.unwrap_or_default();
|
||||||
let display_dir = if current_dir.starts_with(&home_dir) {
|
let display_dir = if current_dir.starts_with(&home_dir) {
|
||||||
current_dir.replacen(&home_dir, "~", 1)
|
current_dir.replacen(&home_dir, "~", 1)
|
||||||
} else {
|
} else {
|
||||||
@@ -35,16 +67,30 @@ pub fn render_status_line(
|
|||||||
let separator = " | ";
|
let separator = " | ";
|
||||||
let separator_width = UnicodeWidthStr::width(separator);
|
let separator_width = UnicodeWidthStr::width(separator);
|
||||||
|
|
||||||
let fixed_width_with_fps = mode_width + separator_width + separator_width +
|
let fixed_width_with_fps = mode_width
|
||||||
program_info_width + separator_width + fps_width;
|
+ separator_width
|
||||||
let show_fps = fixed_width_with_fps < available_width;
|
+ separator_width
|
||||||
|
+ program_info_width
|
||||||
|
+ separator_width
|
||||||
|
+ fps_width;
|
||||||
|
|
||||||
|
let show_fps = fixed_width_with_fps <= available_width;
|
||||||
|
|
||||||
let remaining_width_for_dir = available_width.saturating_sub(
|
let remaining_width_for_dir = available_width.saturating_sub(
|
||||||
mode_width + separator_width + separator_width + program_info_width +
|
mode_width
|
||||||
if show_fps { separator_width + fps_width } else { 0 }
|
+ separator_width
|
||||||
|
+ separator_width
|
||||||
|
+ program_info_width
|
||||||
|
+ (if show_fps {
|
||||||
|
separator_width + fps_width
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
let dir_display_text = if UnicodeWidthStr::width(display_dir.as_str()) <= remaining_width_for_dir {
|
let dir_display_text_str = if UnicodeWidthStr::width(display_dir.as_str())
|
||||||
|
<= remaining_width_for_dir
|
||||||
|
{
|
||||||
display_dir
|
display_dir
|
||||||
} else {
|
} else {
|
||||||
let dir_name = Path::new(current_dir)
|
let dir_name = Path::new(current_dir)
|
||||||
@@ -54,25 +100,55 @@ pub fn render_status_line(
|
|||||||
if UnicodeWidthStr::width(dir_name) <= remaining_width_for_dir {
|
if UnicodeWidthStr::width(dir_name) <= remaining_width_for_dir {
|
||||||
dir_name.to_string()
|
dir_name.to_string()
|
||||||
} else {
|
} else {
|
||||||
dir_name.chars().take(remaining_width_for_dir).collect()
|
dir_name
|
||||||
|
.chars()
|
||||||
|
.take(remaining_width_for_dir)
|
||||||
|
.collect::<String>()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut spans = vec![
|
let mut current_content_width = mode_width
|
||||||
|
+ separator_width
|
||||||
|
+ UnicodeWidthStr::width(dir_display_text_str.as_str())
|
||||||
|
+ separator_width
|
||||||
|
+ program_info_width;
|
||||||
|
if show_fps {
|
||||||
|
current_content_width += separator_width + fps_width;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut line_spans = vec![
|
||||||
Span::styled(mode_text, Style::default().fg(theme.accent)),
|
Span::styled(mode_text, Style::default().fg(theme.accent)),
|
||||||
Span::styled(" | ", Style::default().fg(theme.border)),
|
Span::styled(separator, Style::default().fg(theme.border)),
|
||||||
Span::styled(dir_display_text, Style::default().fg(theme.fg)),
|
Span::styled(
|
||||||
Span::styled(" | ", Style::default().fg(theme.border)),
|
dir_display_text_str.as_str(),
|
||||||
Span::styled(program_info, Style::default().fg(theme.secondary)),
|
Style::default().fg(theme.fg),
|
||||||
|
),
|
||||||
|
Span::styled(separator, Style::default().fg(theme.border)),
|
||||||
|
Span::styled(
|
||||||
|
program_info.as_str(),
|
||||||
|
Style::default().fg(theme.secondary),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
if show_fps {
|
if show_fps {
|
||||||
spans.push(Span::styled(" | ", Style::default().fg(theme.border)));
|
line_spans
|
||||||
spans.push(Span::styled(fps_text, Style::default().fg(theme.secondary)));
|
.push(Span::styled(separator, Style::default().fg(theme.border)));
|
||||||
|
line_spans.push(Span::styled(
|
||||||
|
fps_text.as_str(),
|
||||||
|
Style::default().fg(theme.secondary),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let paragraph = Paragraph::new(Line::from(spans))
|
let padding_needed = available_width.saturating_sub(current_content_width);
|
||||||
.style(Style::default().bg(theme.bg));
|
if padding_needed > 0 {
|
||||||
|
line_spans.push(Span::styled(
|
||||||
|
" ".repeat(padding_needed),
|
||||||
|
Style::default().bg(theme.bg),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let paragraph =
|
||||||
|
Paragraph::new(Line::from(line_spans)).style(Style::default().bg(theme.bg));
|
||||||
|
|
||||||
f.render_widget(paragraph, area);
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,69 +1,115 @@
|
|||||||
// src/components/form/form.rs
|
// src/components/form/form.rs
|
||||||
|
use crate::components::common::autocomplete;
|
||||||
|
use crate::components::handlers::canvas::render_canvas;
|
||||||
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::state::app::highlight::HighlightState;
|
||||||
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
widgets::{Paragraph, Block, Borders},
|
layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
|
||||||
layout::{Layout, Constraint, Direction, Rect, Margin, Alignment},
|
|
||||||
style::Style,
|
style::Style,
|
||||||
|
widgets::{Block, Borders, Paragraph},
|
||||||
Frame,
|
Frame,
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
|
||||||
use crate::state::app::highlight::HighlightState;
|
|
||||||
use crate::components::handlers::canvas::render_canvas;
|
|
||||||
|
|
||||||
pub fn render_form(
|
pub fn render_form(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
area: Rect,
|
area: Rect,
|
||||||
form_state: &impl CanvasState,
|
form_state: &FormState, // <--- CHANGE THIS to the concrete type
|
||||||
fields: &[&str],
|
fields: &[&str],
|
||||||
current_field: &usize,
|
current_field_idx: &usize,
|
||||||
inputs: &[&String],
|
inputs: &[&String],
|
||||||
|
table_name: &str,
|
||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
is_edit_mode: bool,
|
is_edit_mode: bool,
|
||||||
highlight_state: &HighlightState,
|
highlight_state: &HighlightState,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
current_position: u64,
|
current_position: u64,
|
||||||
) {
|
) {
|
||||||
// Create Adresar card
|
let card_title = format!(" {} ", table_name);
|
||||||
|
|
||||||
let adresar_card = Block::default()
|
let adresar_card = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.border_style(Style::default().fg(theme.border))
|
.border_style(Style::default().fg(theme.border))
|
||||||
.title(" Adresar ")
|
.title(card_title)
|
||||||
.style(Style::default().bg(theme.bg).fg(theme.fg));
|
.style(Style::default().bg(theme.bg).fg(theme.fg));
|
||||||
|
|
||||||
f.render_widget(adresar_card, area);
|
f.render_widget(adresar_card, area);
|
||||||
|
|
||||||
// Define inner area
|
|
||||||
let inner_area = area.inner(Margin {
|
let inner_area = area.inner(Margin {
|
||||||
horizontal: 1,
|
horizontal: 1,
|
||||||
vertical: 1,
|
vertical: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create main layout
|
|
||||||
let main_layout = Layout::default()
|
let main_layout = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints([Constraint::Length(1), Constraint::Min(1)])
|
||||||
Constraint::Length(1),
|
|
||||||
Constraint::Min(1),
|
|
||||||
])
|
|
||||||
.split(inner_area);
|
.split(inner_area);
|
||||||
|
|
||||||
// Render count/position
|
let count_position_text = if total_count == 0 && current_position == 1 {
|
||||||
let count_position_text = format!("Total: {} | Position: {}", total_count, current_position);
|
"Total: 0 | New Entry".to_string()
|
||||||
|
} else if current_position > total_count && total_count > 0 {
|
||||||
|
format!("Total: {} | New Entry ({})", total_count, current_position)
|
||||||
|
} else if total_count == 0 && current_position > 1 {
|
||||||
|
format!("Total: 0 | New Entry ({})", current_position)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"Total: {} | Position: {}/{}",
|
||||||
|
total_count, current_position, total_count
|
||||||
|
)
|
||||||
|
};
|
||||||
let count_para = Paragraph::new(count_position_text)
|
let count_para = Paragraph::new(count_position_text)
|
||||||
.style(Style::default().fg(theme.fg))
|
.style(Style::default().fg(theme.fg))
|
||||||
.alignment(Alignment::Left);
|
.alignment(Alignment::Left);
|
||||||
f.render_widget(count_para, main_layout[0]);
|
f.render_widget(count_para, main_layout[0]);
|
||||||
|
|
||||||
// Delegate input handling to canvas
|
// Get the active field's rect from render_canvas
|
||||||
render_canvas(
|
let active_field_rect = render_canvas(
|
||||||
f,
|
f,
|
||||||
main_layout[1],
|
main_layout[1],
|
||||||
form_state,
|
form_state,
|
||||||
fields,
|
fields,
|
||||||
current_field,
|
current_field_idx,
|
||||||
inputs,
|
inputs,
|
||||||
theme,
|
theme,
|
||||||
is_edit_mode,
|
is_edit_mode,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// --- NEW: RENDER AUTOCOMPLETE ---
|
||||||
|
if form_state.autocomplete_active {
|
||||||
|
if let Some(active_rect) = active_field_rect {
|
||||||
|
let selected_index = form_state.get_selected_suggestion_index();
|
||||||
|
|
||||||
|
if let Some(rich_suggestions) = form_state.get_rich_suggestions() {
|
||||||
|
if !rich_suggestions.is_empty() {
|
||||||
|
// CHANGE THIS to call the renamed function
|
||||||
|
autocomplete::render_hit_autocomplete_dropdown(
|
||||||
|
f,
|
||||||
|
active_rect,
|
||||||
|
f.area(),
|
||||||
|
theme,
|
||||||
|
rich_suggestions,
|
||||||
|
selected_index,
|
||||||
|
form_state,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The fallback to simple suggestions is now correctly handled
|
||||||
|
// because the original render_autocomplete_dropdown exists again.
|
||||||
|
else if let Some(simple_suggestions) = form_state.get_suggestions() {
|
||||||
|
if !simple_suggestions.is_empty() {
|
||||||
|
autocomplete::render_autocomplete_dropdown(
|
||||||
|
f,
|
||||||
|
active_rect,
|
||||||
|
f.area(),
|
||||||
|
theme,
|
||||||
|
simple_suggestions,
|
||||||
|
selected_index,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ pub fn render_buffer_list(
|
|||||||
area: Rect,
|
area: Rect,
|
||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
buffer_state: &BufferState,
|
buffer_state: &BufferState,
|
||||||
app_state: &AppState, // Add this parameter
|
app_state: &AppState,
|
||||||
) {
|
) {
|
||||||
// --- Style Definitions ---
|
// --- Style Definitions ---
|
||||||
let active_style = Style::default()
|
let active_style = Style::default()
|
||||||
@@ -39,8 +39,7 @@ pub fn render_buffer_list(
|
|||||||
let mut spans = Vec::new();
|
let mut spans = Vec::new();
|
||||||
let mut current_width = 0;
|
let mut current_width = 0;
|
||||||
|
|
||||||
// TODO: Replace with actual table name from server response
|
let current_table_name = app_state.current_view_table_name.as_deref();
|
||||||
let current_table_name = Some("2025_customer");
|
|
||||||
|
|
||||||
for (original_index, view) in buffer_state.history.iter().enumerate() {
|
for (original_index, view) in buffer_state.history.iter().enumerate() {
|
||||||
// Filter: Only process views matching the active layer
|
// Filter: Only process views matching the active layer
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
// src/components/handlers/canvas.rs
|
// src/components/handlers/canvas.rs
|
||||||
|
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
widgets::{Paragraph, Block, Borders},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
layout::{Layout, Constraint, Direction, Rect},
|
style::{Modifier, Style},
|
||||||
style::{Style, Modifier},
|
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
|
widgets::{Block, Borders, Paragraph},
|
||||||
Frame,
|
Frame,
|
||||||
prelude::Alignment,
|
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
|
use crate::state::app::highlight::HighlightState;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::app::highlight::HighlightState; // Ensure correct import path
|
use std::cmp::{max, min};
|
||||||
use std::cmp::{min, max};
|
|
||||||
|
|
||||||
pub fn render_canvas(
|
pub fn render_canvas(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
@@ -21,9 +21,8 @@ pub fn render_canvas(
|
|||||||
inputs: &[&String],
|
inputs: &[&String],
|
||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
is_edit_mode: bool,
|
is_edit_mode: bool,
|
||||||
highlight_state: &HighlightState, // Using the enum state
|
highlight_state: &HighlightState,
|
||||||
) -> Option<Rect> {
|
) -> Option<Rect> {
|
||||||
// ... (setup code remains the same) ...
|
|
||||||
let columns = Layout::default()
|
let columns = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
|
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
|
||||||
@@ -58,46 +57,47 @@ pub fn render_canvas(
|
|||||||
|
|
||||||
let mut active_field_input_rect = None;
|
let mut active_field_input_rect = None;
|
||||||
|
|
||||||
// Render labels
|
|
||||||
for (i, field) in fields.iter().enumerate() {
|
for (i, field) in fields.iter().enumerate() {
|
||||||
let label = Paragraph::new(Line::from(Span::styled(
|
let label = Paragraph::new(Line::from(Span::styled(
|
||||||
format!("{}:", field),
|
format!("{}:", field),
|
||||||
Style::default().fg(theme.fg)),
|
Style::default().fg(theme.fg),
|
||||||
));
|
)));
|
||||||
f.render_widget(label, Rect {
|
f.render_widget(
|
||||||
x: columns[0].x,
|
label,
|
||||||
y: input_block.y + 1 + i as u16,
|
Rect {
|
||||||
width: columns[0].width,
|
x: columns[0].x,
|
||||||
height: 1,
|
y: input_block.y + 1 + i as u16,
|
||||||
});
|
width: columns[0].width,
|
||||||
|
height: 1,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (i, _input) in inputs.iter().enumerate() {
|
||||||
// Render inputs and cursor
|
|
||||||
for (i, input) in inputs.iter().enumerate() {
|
|
||||||
let is_active = i == *current_field_idx;
|
let is_active = i == *current_field_idx;
|
||||||
let current_cursor_pos = form_state.current_cursor_pos();
|
let current_cursor_pos = form_state.current_cursor_pos();
|
||||||
let text = input.as_str();
|
|
||||||
let text_len = text.chars().count();
|
|
||||||
|
|
||||||
|
// Use the trait method to get display value
|
||||||
|
let text = form_state.get_display_value_for_field(i);
|
||||||
|
let text_len = text.chars().count();
|
||||||
let line: Line;
|
let line: Line;
|
||||||
|
|
||||||
// --- Use match on the highlight_state enum ---
|
|
||||||
match highlight_state {
|
match highlight_state {
|
||||||
HighlightState::Off => {
|
HighlightState::Off => {
|
||||||
// Not in highlight mode, render normally
|
|
||||||
line = Line::from(Span::styled(
|
line = Line::from(Span::styled(
|
||||||
text,
|
text,
|
||||||
if is_active { Style::default().fg(theme.highlight) } else { Style::default().fg(theme.fg) }
|
if is_active {
|
||||||
|
Style::default().fg(theme.highlight)
|
||||||
|
} else {
|
||||||
|
Style::default().fg(theme.fg)
|
||||||
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
HighlightState::Characterwise { anchor } => {
|
HighlightState::Characterwise { anchor } => {
|
||||||
// --- Character-wise Highlight Logic ---
|
|
||||||
let (anchor_field, anchor_char) = *anchor;
|
let (anchor_field, anchor_char) = *anchor;
|
||||||
let start_field = min(anchor_field, *current_field_idx);
|
let start_field = min(anchor_field, *current_field_idx);
|
||||||
let end_field = max(anchor_field, *current_field_idx);
|
let end_field = max(anchor_field, *current_field_idx);
|
||||||
|
|
||||||
// Use start_char and end_char consistently
|
|
||||||
let (start_char, end_char) = if anchor_field == *current_field_idx {
|
let (start_char, end_char) = if anchor_field == *current_field_idx {
|
||||||
(min(anchor_char, current_cursor_pos), max(anchor_char, current_cursor_pos))
|
(min(anchor_char, current_cursor_pos), max(anchor_char, current_cursor_pos))
|
||||||
} else if anchor_field < *current_field_idx {
|
} else if anchor_field < *current_field_idx {
|
||||||
@@ -111,24 +111,20 @@ pub fn render_canvas(
|
|||||||
let normal_style_outside = Style::default().fg(theme.fg);
|
let normal_style_outside = Style::default().fg(theme.fg);
|
||||||
|
|
||||||
if i >= start_field && i <= end_field {
|
if i >= start_field && i <= end_field {
|
||||||
// This line is within the character-wise highlight range
|
if start_field == end_field {
|
||||||
if start_field == end_field { // Case 1: Single Line Highlight
|
|
||||||
// Use start_char and end_char here
|
|
||||||
let clamped_start = start_char.min(text_len);
|
let clamped_start = start_char.min(text_len);
|
||||||
let clamped_end = end_char.min(text_len); // Use text_len for slicing logic
|
let clamped_end = end_char.min(text_len);
|
||||||
|
|
||||||
let before: String = text.chars().take(clamped_start).collect();
|
let before: String = text.chars().take(clamped_start).collect();
|
||||||
let highlighted: String = text.chars().skip(clamped_start).take(clamped_end.saturating_sub(clamped_start) + 1).collect();
|
let highlighted: String = text.chars().skip(clamped_start).take(clamped_end.saturating_sub(clamped_start) + 1).collect();
|
||||||
// Define 'after' here
|
|
||||||
let after: String = text.chars().skip(clamped_end + 1).collect();
|
let after: String = text.chars().skip(clamped_end + 1).collect();
|
||||||
|
|
||||||
line = Line::from(vec![
|
line = Line::from(vec![
|
||||||
Span::styled(before, normal_style_in_highlight),
|
Span::styled(before, normal_style_in_highlight),
|
||||||
Span::styled(highlighted, highlight_style),
|
Span::styled(highlighted, highlight_style),
|
||||||
Span::styled(after, normal_style_in_highlight), // Use defined 'after'
|
Span::styled(after, normal_style_in_highlight),
|
||||||
]);
|
]);
|
||||||
} else if i == start_field { // Case 2: Multi-Line Highlight - Start Line
|
} else if i == start_field {
|
||||||
// Use start_char here
|
|
||||||
let safe_start = start_char.min(text_len);
|
let safe_start = start_char.min(text_len);
|
||||||
let before: String = text.chars().take(safe_start).collect();
|
let before: String = text.chars().take(safe_start).collect();
|
||||||
let highlighted: String = text.chars().skip(safe_start).collect();
|
let highlighted: String = text.chars().skip(safe_start).collect();
|
||||||
@@ -136,8 +132,7 @@ pub fn render_canvas(
|
|||||||
Span::styled(before, normal_style_in_highlight),
|
Span::styled(before, normal_style_in_highlight),
|
||||||
Span::styled(highlighted, highlight_style),
|
Span::styled(highlighted, highlight_style),
|
||||||
]);
|
]);
|
||||||
} else if i == end_field { // Case 3: Multi-Line Highlight - End Line (Corrected index)
|
} else if i == end_field {
|
||||||
// Use end_char here
|
|
||||||
let safe_end_inclusive = if text_len > 0 { end_char.min(text_len - 1) } else { 0 };
|
let safe_end_inclusive = if text_len > 0 { end_char.min(text_len - 1) } else { 0 };
|
||||||
let highlighted: String = text.chars().take(safe_end_inclusive + 1).collect();
|
let highlighted: String = text.chars().take(safe_end_inclusive + 1).collect();
|
||||||
let after: String = text.chars().skip(safe_end_inclusive + 1).collect();
|
let after: String = text.chars().skip(safe_end_inclusive + 1).collect();
|
||||||
@@ -145,19 +140,17 @@ pub fn render_canvas(
|
|||||||
Span::styled(highlighted, highlight_style),
|
Span::styled(highlighted, highlight_style),
|
||||||
Span::styled(after, normal_style_in_highlight),
|
Span::styled(after, normal_style_in_highlight),
|
||||||
]);
|
]);
|
||||||
} else { // Case 4: Multi-Line Highlight - Middle Line (Corrected index)
|
} else {
|
||||||
line = Line::from(Span::styled(text, highlight_style)); // Highlight whole line
|
line = Line::from(Span::styled(text, highlight_style));
|
||||||
}
|
}
|
||||||
} else { // Case 5: Line Outside Character-wise Highlight Range
|
} else {
|
||||||
line = Line::from(Span::styled(
|
line = Line::from(Span::styled(
|
||||||
text,
|
text,
|
||||||
// Use normal styling (active or inactive)
|
|
||||||
if is_active { normal_style_in_highlight } else { normal_style_outside }
|
if is_active { normal_style_in_highlight } else { normal_style_outside }
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
HighlightState::Linewise { anchor_line } => {
|
HighlightState::Linewise { anchor_line } => {
|
||||||
// --- Linewise Highlight Logic ---
|
|
||||||
let start_field = min(*anchor_line, *current_field_idx);
|
let start_field = min(*anchor_line, *current_field_idx);
|
||||||
let end_field = max(*anchor_line, *current_field_idx);
|
let end_field = max(*anchor_line, *current_field_idx);
|
||||||
let highlight_style = Style::default().fg(theme.highlight).bg(theme.highlight_bg).add_modifier(Modifier::BOLD);
|
let highlight_style = Style::default().fg(theme.highlight).bg(theme.highlight_bg).add_modifier(Modifier::BOLD);
|
||||||
@@ -165,25 +158,31 @@ pub fn render_canvas(
|
|||||||
let normal_style_outside = Style::default().fg(theme.fg);
|
let normal_style_outside = Style::default().fg(theme.fg);
|
||||||
|
|
||||||
if i >= start_field && i <= end_field {
|
if i >= start_field && i <= end_field {
|
||||||
// Highlight the entire line
|
|
||||||
line = Line::from(Span::styled(text, highlight_style));
|
line = Line::from(Span::styled(text, highlight_style));
|
||||||
} else {
|
} else {
|
||||||
// Line outside linewise highlight range
|
|
||||||
line = Line::from(Span::styled(
|
line = Line::from(Span::styled(
|
||||||
text,
|
text,
|
||||||
// Use normal styling (active or inactive)
|
|
||||||
if is_active { normal_style_in_highlight } else { normal_style_outside }
|
if is_active { normal_style_in_highlight } else { normal_style_outside }
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} // End match highlight_state
|
}
|
||||||
|
|
||||||
let input_display = Paragraph::new(line).alignment(Alignment::Left);
|
let input_display = Paragraph::new(line).alignment(Alignment::Left);
|
||||||
f.render_widget(input_display, input_rows[i]);
|
f.render_widget(input_display, input_rows[i]);
|
||||||
|
|
||||||
if is_active {
|
if is_active {
|
||||||
active_field_input_rect = Some(input_rows[i]);
|
active_field_input_rect = Some(input_rows[i]);
|
||||||
let cursor_x = input_rows[i].x + form_state.current_cursor_pos() as u16;
|
|
||||||
|
// --- CORRECTED CURSOR POSITIONING LOGIC ---
|
||||||
|
// Use the new generic trait method to check for an override.
|
||||||
|
let cursor_x = if form_state.has_display_override(i) {
|
||||||
|
// If an override exists, place the cursor at the end.
|
||||||
|
input_rows[i].x + text.chars().count() as u16
|
||||||
|
} else {
|
||||||
|
// Otherwise, use the real cursor position.
|
||||||
|
input_rows[i].x + form_state.current_cursor_pos() as u16
|
||||||
|
};
|
||||||
let cursor_y = input_rows[i].y;
|
let cursor_y = input_rows[i].y;
|
||||||
f.set_cursor_position((cursor_x, cursor_y));
|
f.set_cursor_position((cursor_x, cursor_y));
|
||||||
}
|
}
|
||||||
@@ -191,4 +190,3 @@ pub fn render_canvas(
|
|||||||
|
|
||||||
active_field_input_rect
|
active_field_input_rect
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use crate::services::grpc_client::GrpcClient;
|
|||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use crate::state::pages::auth::RegisterState;
|
use crate::state::pages::auth::RegisterState;
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
use crate::tui::functions::common::form::{revert, save};
|
use crate::tui::functions::common::form::{revert, save};
|
||||||
use crossterm::event::{KeyCode, KeyEvent};
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
@@ -13,6 +14,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
action: &str,
|
action: &str,
|
||||||
state: &mut S,
|
state: &mut S,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &AppState,
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
@@ -27,10 +29,9 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
match action {
|
match action {
|
||||||
"save" => {
|
"save" => {
|
||||||
let outcome = save(
|
let outcome = save(
|
||||||
|
app_state,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let message = format!("Save successful: {:?}", outcome); // Simple message for now
|
let message = format!("Save successful: {:?}", outcome); // Simple message for now
|
||||||
@@ -40,8 +41,6 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
revert(
|
revert(
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
use crate::tui::functions::common::form::{revert, save};
|
use crate::tui::functions::common::form::{revert, save};
|
||||||
use crate::tui::functions::common::form::SaveOutcome;
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
@@ -14,8 +15,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
action: &str,
|
action: &str,
|
||||||
state: &mut S,
|
state: &mut S,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
app_state: &AppState,
|
||||||
total_count: u64,
|
|
||||||
) -> Result<EventOutcome> {
|
) -> Result<EventOutcome> {
|
||||||
match action {
|
match action {
|
||||||
"save" | "revert" => {
|
"save" | "revert" => {
|
||||||
@@ -28,10 +28,9 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
match action {
|
match action {
|
||||||
"save" => {
|
"save" => {
|
||||||
let save_result = save(
|
let save_result = save(
|
||||||
|
app_state,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await;
|
).await;
|
||||||
|
|
||||||
match save_result {
|
match save_result {
|
||||||
@@ -50,8 +49,6 @@ pub async fn execute_common_action<S: CanvasState + Any>(
|
|||||||
let revert_result = revert(
|
let revert_result = revert(
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await;
|
).await;
|
||||||
|
|
||||||
match revert_result {
|
match revert_result {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ pub mod components;
|
|||||||
pub mod modes;
|
pub mod modes;
|
||||||
pub mod functions;
|
pub mod functions;
|
||||||
pub mod services;
|
pub mod services;
|
||||||
|
pub mod utils;
|
||||||
|
|
||||||
pub use ui::run_ui;
|
pub use ui::run_ui;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
// client/src/main.rs
|
// client/src/main.rs
|
||||||
use client::run_ui;
|
use client::run_ui;
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
use client::utils::debug_logger::UiDebugWriter;
|
||||||
use dotenvy::dotenv;
|
use dotenvy::dotenv;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use tracing_subscriber;
|
use tracing_subscriber;
|
||||||
@@ -7,8 +9,22 @@ use std::env;
|
|||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
if env::var("ENABLE_TRACING").is_ok() {
|
#[cfg(feature = "ui-debug")]
|
||||||
tracing_subscriber::fmt::init();
|
{
|
||||||
|
// If ui-debug is on, set up our custom writer.
|
||||||
|
let writer = UiDebugWriter::new();
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_level(false) // Don't show INFO, ERROR, etc.
|
||||||
|
.with_target(false) // Don't show the module path.
|
||||||
|
.without_time() // This is the correct and simpler method.
|
||||||
|
.with_writer(move || writer.clone())
|
||||||
|
.init();
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "ui-debug"))]
|
||||||
|
{
|
||||||
|
if env::var("ENABLE_TRACING").is_ok() {
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dotenv().ok();
|
dotenv().ok();
|
||||||
|
|||||||
@@ -24,8 +24,6 @@ pub async fn handle_core_action(
|
|||||||
auth_client: &mut AuthClient,
|
auth_client: &mut AuthClient,
|
||||||
terminal: &mut TerminalCore,
|
terminal: &mut TerminalCore,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<EventOutcome> {
|
) -> Result<EventOutcome> {
|
||||||
match action {
|
match action {
|
||||||
"save" => {
|
"save" => {
|
||||||
@@ -34,10 +32,9 @@ pub async fn handle_core_action(
|
|||||||
Ok(EventOutcome::Ok(message))
|
Ok(EventOutcome::Ok(message))
|
||||||
} else {
|
} else {
|
||||||
let save_outcome = form_save(
|
let save_outcome = form_save(
|
||||||
|
app_state,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await.context("Register save action failed")?;
|
).await.context("Register save action failed")?;
|
||||||
let message = match save_outcome {
|
let message = match save_outcome {
|
||||||
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||||
@@ -56,10 +53,9 @@ pub async fn handle_core_action(
|
|||||||
login_save(auth_state, login_state, auth_client, app_state).await.context("Login save n quit action failed")?
|
login_save(auth_state, login_state, auth_client, app_state).await.context("Login save n quit action failed")?
|
||||||
} else {
|
} else {
|
||||||
let save_outcome = form_save(
|
let save_outcome = form_save(
|
||||||
|
app_state,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await?;
|
).await?;
|
||||||
match save_outcome {
|
match save_outcome {
|
||||||
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
SaveOutcome::NoChange => "No changes to save.".to_string(),
|
||||||
@@ -81,8 +77,6 @@ pub async fn handle_core_action(
|
|||||||
let message = form_revert(
|
let message = form_revert(
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await.context("Form revert x action failed")?;
|
).await.context("Form revert x action failed")?;
|
||||||
Ok(EventOutcome::Ok(message))
|
Ok(EventOutcome::Ok(message))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,22 @@
|
|||||||
// src/modes/canvas/edit.rs
|
// src/modes/canvas/edit.rs
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
|
use crate::functions::modes::edit::{
|
||||||
|
add_logic_e, add_table_e, auth_e, form_e,
|
||||||
|
};
|
||||||
|
use crate::modes::handlers::event::EventHandler;
|
||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
|
use crate::state::pages::admin::AdminState;
|
||||||
use crate::state::pages::{
|
use crate::state::pages::{
|
||||||
auth::{LoginState, RegisterState},
|
auth::{LoginState, RegisterState},
|
||||||
canvas_state::CanvasState,
|
canvas_state::CanvasState,
|
||||||
|
form::FormState,
|
||||||
};
|
};
|
||||||
use crate::state::pages::form::FormState; // <<< ADD THIS LINE
|
|
||||||
// AddLogicState is already imported
|
|
||||||
// AddTableState is already imported
|
|
||||||
use crate::state::pages::admin::AdminState;
|
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
|
||||||
use crate::functions::modes::edit::{add_logic_e, auth_e, form_e, add_table_e};
|
|
||||||
use crate::state::app::state::AppState;
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crossterm::event::KeyEvent; // Removed KeyCode, KeyModifiers as they were unused
|
use common::proto::multieko2::search::search_response::Hit;
|
||||||
use tracing::debug;
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use tracing::{debug, info};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum EditEventOutcome {
|
pub enum EditEventOutcome {
|
||||||
@@ -22,231 +24,313 @@ pub enum EditEventOutcome {
|
|||||||
ExitEditMode,
|
ExitEditMode,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Helper function to spawn a non-blocking search task for autocomplete.
|
||||||
|
async fn trigger_form_autocomplete_search(
|
||||||
|
form_state: &mut FormState,
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
sender: mpsc::UnboundedSender<Vec<Hit>>,
|
||||||
|
) {
|
||||||
|
if let Some(field_def) = form_state.fields.get(form_state.current_field) {
|
||||||
|
if field_def.is_link {
|
||||||
|
if let Some(target_table) = &field_def.link_target_table {
|
||||||
|
// 1. Update state for immediate UI feedback
|
||||||
|
form_state.autocomplete_loading = true;
|
||||||
|
form_state.autocomplete_active = true;
|
||||||
|
form_state.autocomplete_suggestions.clear();
|
||||||
|
form_state.selected_suggestion_index = None;
|
||||||
|
|
||||||
|
// 2. Clone everything needed for the background task
|
||||||
|
let query = form_state.get_current_input().to_string();
|
||||||
|
let table_to_search = target_table.clone();
|
||||||
|
let mut grpc_client_clone = grpc_client.clone();
|
||||||
|
|
||||||
|
info!(
|
||||||
|
"[Autocomplete] Spawning search in '{}' for query: '{}'",
|
||||||
|
table_to_search, query
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. Spawn the non-blocking task
|
||||||
|
tokio::spawn(async move {
|
||||||
|
match grpc_client_clone
|
||||||
|
.search_table(table_to_search, query)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(response) => {
|
||||||
|
// Send results back through the channel
|
||||||
|
let _ = sender.send(response.hits);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(
|
||||||
|
"[Autocomplete] Search failed: {:?}",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
// Send an empty vec on error so the UI can stop loading
|
||||||
|
let _ = sender.send(vec![]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub async fn handle_edit_event(
|
pub async fn handle_edit_event(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
form_state: &mut FormState, // Now FormState is in scope
|
form_state: &mut FormState,
|
||||||
login_state: &mut LoginState,
|
login_state: &mut LoginState,
|
||||||
register_state: &mut RegisterState,
|
register_state: &mut RegisterState,
|
||||||
admin_state: &mut AdminState,
|
admin_state: &mut AdminState,
|
||||||
ideal_cursor_column: &mut usize,
|
|
||||||
current_position: &mut u64,
|
current_position: &mut u64,
|
||||||
total_count: u64,
|
total_count: u64,
|
||||||
grpc_client: &mut GrpcClient,
|
event_handler: &mut EventHandler,
|
||||||
app_state: &AppState,
|
app_state: &AppState,
|
||||||
) -> Result<EditEventOutcome> {
|
) -> Result<EditEventOutcome> {
|
||||||
// --- Global command mode check ---
|
// --- AUTOCOMPLETE-SPECIFIC KEY HANDLING ---
|
||||||
if let Some("enter_command_mode") = config.get_action_for_key_in_mode(
|
if app_state.ui.show_form && form_state.autocomplete_active {
|
||||||
&config.keybindings.global, // Assuming command mode can be entered globally
|
if let Some(action) =
|
||||||
key.code,
|
config.get_edit_action_for_key(key.code, key.modifiers)
|
||||||
key.modifiers,
|
{
|
||||||
) {
|
match action {
|
||||||
// This check might be redundant if EventHandler already prevents entering Edit mode
|
"suggestion_down" => {
|
||||||
// when command_mode is true. However, it's a safeguard.
|
if !form_state.autocomplete_suggestions.is_empty() {
|
||||||
return Ok(EditEventOutcome::Message(
|
let current =
|
||||||
"Cannot enter command mode from edit mode here.".to_string(),
|
form_state.selected_suggestion_index.unwrap_or(0);
|
||||||
));
|
let next = (current + 1)
|
||||||
}
|
% form_state.autocomplete_suggestions.len();
|
||||||
|
form_state.selected_suggestion_index = Some(next);
|
||||||
// --- Common actions (save, revert) ---
|
}
|
||||||
if let Some(action) = config.get_action_for_key_in_mode(
|
return Ok(EditEventOutcome::Message(String::new()));
|
||||||
&config.keybindings.common,
|
|
||||||
key.code,
|
|
||||||
key.modifiers,
|
|
||||||
).as_deref() {
|
|
||||||
if matches!(action, "save" | "revert") {
|
|
||||||
let message_string: String = if app_state.ui.show_login {
|
|
||||||
auth_e::execute_common_action(action, login_state, grpc_client, current_position, total_count).await?
|
|
||||||
} else if app_state.ui.show_register {
|
|
||||||
auth_e::execute_common_action(action, register_state, grpc_client, current_position, total_count).await?
|
|
||||||
} else if app_state.ui.show_add_table {
|
|
||||||
// TODO: Implement common actions for AddTable if needed
|
|
||||||
format!("Action '{}' not implemented for Add Table in edit mode.", action)
|
|
||||||
} else if app_state.ui.show_add_logic {
|
|
||||||
// TODO: Implement common actions for AddLogic if needed
|
|
||||||
format!("Action '{}' not implemented for Add Logic in edit mode.", action)
|
|
||||||
} else { // Assuming Form view
|
|
||||||
let outcome = form_e::execute_common_action(action, form_state, grpc_client, current_position, total_count).await?;
|
|
||||||
match outcome {
|
|
||||||
EventOutcome::Ok(msg) | EventOutcome::DataSaved(_, msg) => msg,
|
|
||||||
_ => format!("Unexpected outcome from common action: {:?}", outcome),
|
|
||||||
}
|
}
|
||||||
};
|
"suggestion_up" => {
|
||||||
return Ok(EditEventOutcome::Message(message_string));
|
if !form_state.autocomplete_suggestions.is_empty() {
|
||||||
|
let current =
|
||||||
|
form_state.selected_suggestion_index.unwrap_or(0);
|
||||||
|
let prev = if current == 0 {
|
||||||
|
form_state.autocomplete_suggestions.len() - 1
|
||||||
|
} else {
|
||||||
|
current - 1
|
||||||
|
};
|
||||||
|
form_state.selected_suggestion_index = Some(prev);
|
||||||
|
}
|
||||||
|
return Ok(EditEventOutcome::Message(String::new()));
|
||||||
|
}
|
||||||
|
"exit" => {
|
||||||
|
form_state.deactivate_autocomplete();
|
||||||
|
return Ok(EditEventOutcome::Message(
|
||||||
|
"Autocomplete cancelled".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
"enter_decider" => {
|
||||||
|
if let Some(selected_idx) =
|
||||||
|
form_state.selected_suggestion_index
|
||||||
|
{
|
||||||
|
if let Some(selection) = form_state
|
||||||
|
.autocomplete_suggestions
|
||||||
|
.get(selected_idx)
|
||||||
|
.cloned()
|
||||||
|
{
|
||||||
|
// --- THIS IS THE CORE LOGIC CHANGE ---
|
||||||
|
|
||||||
|
// 1. Get the friendly display name for the UI
|
||||||
|
let display_name =
|
||||||
|
form_state.get_display_name_for_hit(&selection);
|
||||||
|
|
||||||
|
// 2. Store the REAL ID in the form's values
|
||||||
|
let current_input =
|
||||||
|
form_state.get_current_input_mut();
|
||||||
|
*current_input = selection.id.to_string();
|
||||||
|
|
||||||
|
// 3. Set the persistent display override in the map
|
||||||
|
form_state.link_display_map.insert(
|
||||||
|
form_state.current_field,
|
||||||
|
display_name,
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Finalize state
|
||||||
|
form_state.deactivate_autocomplete();
|
||||||
|
form_state.set_has_unsaved_changes(true);
|
||||||
|
return Ok(EditEventOutcome::Message(
|
||||||
|
"Selection made".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
form_state.deactivate_autocomplete();
|
||||||
|
// Fall through to default 'enter' behavior
|
||||||
|
}
|
||||||
|
_ => {} // Let other keys fall through to the live search logic
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Edit-specific actions ---
|
// --- LIVE AUTOCOMPLETE TRIGGER LOGIC ---
|
||||||
if let Some(action_str) = config.get_edit_action_for_key(key.code, key.modifiers).as_deref() {
|
let mut trigger_search = false;
|
||||||
// --- Handle "enter_decider" (Enter key) ---
|
|
||||||
if action_str == "enter_decider" {
|
|
||||||
let effective_action = if app_state.ui.show_register
|
|
||||||
&& register_state.in_suggestion_mode
|
|
||||||
&& register_state.current_field() == 4 { // Role field
|
|
||||||
"select_suggestion"
|
|
||||||
} else if app_state.ui.show_add_logic
|
|
||||||
&& admin_state.add_logic_state.in_target_column_suggestion_mode
|
|
||||||
&& admin_state.add_logic_state.current_field() == 1 { // Target Column field
|
|
||||||
"select_suggestion"
|
|
||||||
} else {
|
|
||||||
"next_field" // Default action for Enter
|
|
||||||
};
|
|
||||||
|
|
||||||
let msg = if app_state.ui.show_login {
|
if app_state.ui.show_form {
|
||||||
auth_e::execute_edit_action(effective_action, key, login_state, ideal_cursor_column).await?
|
// Manual trigger
|
||||||
} else if app_state.ui.show_add_table {
|
if let Some("trigger_autocomplete") =
|
||||||
add_table_e::execute_edit_action(effective_action, key, &mut admin_state.add_table_state, ideal_cursor_column).await?
|
config.get_edit_action_for_key(key.code, key.modifiers)
|
||||||
} else if app_state.ui.show_add_logic {
|
{
|
||||||
add_logic_e::execute_edit_action(effective_action, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?
|
if !form_state.autocomplete_active {
|
||||||
} else if app_state.ui.show_register {
|
trigger_search = true;
|
||||||
auth_e::execute_edit_action(effective_action, key, register_state, ideal_cursor_column).await?
|
}
|
||||||
} else { // Form view
|
}
|
||||||
form_e::execute_edit_action(effective_action, key, form_state, ideal_cursor_column).await?
|
// Live search trigger while typing
|
||||||
};
|
else if form_state.autocomplete_active {
|
||||||
|
if let KeyCode::Char(_) | KeyCode::Backspace = key.code {
|
||||||
|
let action = if let KeyCode::Backspace = key.code {
|
||||||
|
"delete_char_backward"
|
||||||
|
} else {
|
||||||
|
"insert_char"
|
||||||
|
};
|
||||||
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
form_e::execute_edit_action(
|
||||||
|
action,
|
||||||
|
key,
|
||||||
|
form_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
trigger_search = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if trigger_search {
|
||||||
|
trigger_form_autocomplete_search(
|
||||||
|
form_state,
|
||||||
|
&mut event_handler.grpc_client,
|
||||||
|
event_handler.autocomplete_result_sender.clone(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
return Ok(EditEventOutcome::Message("Searching...".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- GENERAL EDIT MODE EVENT HANDLING (IF NOT AUTOCOMPLETE) ---
|
||||||
|
|
||||||
|
if let Some(action_str) =
|
||||||
|
config.get_edit_action_for_key(key.code, key.modifiers)
|
||||||
|
{
|
||||||
|
// Handle Enter key (next field)
|
||||||
|
if action_str == "enter_decider" {
|
||||||
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
let msg = form_e::execute_edit_action(
|
||||||
|
"next_field",
|
||||||
|
key,
|
||||||
|
form_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Handle "exit" (Escape key) ---
|
// Handle exiting edit mode
|
||||||
if action_str == "exit" {
|
if action_str == "exit" {
|
||||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
return Ok(EditEventOutcome::ExitEditMode);
|
||||||
let msg = auth_e::execute_edit_action("exit_suggestion_mode", key, register_state, ideal_cursor_column).await?;
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
|
||||||
} else if app_state.ui.show_add_logic && admin_state.add_logic_state.in_target_column_suggestion_mode {
|
|
||||||
admin_state.add_logic_state.in_target_column_suggestion_mode = false;
|
|
||||||
admin_state.add_logic_state.show_target_column_suggestions = false;
|
|
||||||
admin_state.add_logic_state.selected_target_column_suggestion_index = None;
|
|
||||||
return Ok(EditEventOutcome::Message("Exited column suggestions".to_string()));
|
|
||||||
} else {
|
|
||||||
return Ok(EditEventOutcome::ExitEditMode);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Autocomplete for AddLogicState Target Column ---
|
// Handle all other edit actions
|
||||||
if app_state.ui.show_add_logic && admin_state.add_logic_state.current_field() == 1 { // Target Column field
|
|
||||||
if action_str == "suggestion_down" { // "Tab" is mapped to suggestion_down
|
|
||||||
if !admin_state.add_logic_state.in_target_column_suggestion_mode {
|
|
||||||
// Attempt to open suggestions
|
|
||||||
if let Some(profile_name) = admin_state.add_logic_state.profile_name.clone().into() {
|
|
||||||
if let Some(table_name) = admin_state.add_logic_state.selected_table_name.clone() {
|
|
||||||
debug!("Fetching table structure for autocomplete: Profile='{}', Table='{}'", profile_name, table_name);
|
|
||||||
match grpc_client.get_table_structure(profile_name, table_name).await {
|
|
||||||
Ok(ts_response) => {
|
|
||||||
admin_state.add_logic_state.table_columns_for_suggestions =
|
|
||||||
ts_response.columns.into_iter().map(|c| c.name).collect();
|
|
||||||
admin_state.add_logic_state.update_target_column_suggestions();
|
|
||||||
if !admin_state.add_logic_state.target_column_suggestions.is_empty() {
|
|
||||||
admin_state.add_logic_state.in_target_column_suggestion_mode = true;
|
|
||||||
// update_target_column_suggestions handles initial selection
|
|
||||||
return Ok(EditEventOutcome::Message("Column suggestions shown".to_string()));
|
|
||||||
} else {
|
|
||||||
return Ok(EditEventOutcome::Message("No column suggestions for current input".to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
debug!("Error fetching table structure: {}", e);
|
|
||||||
admin_state.add_logic_state.table_columns_for_suggestions.clear(); // Clear old data on error
|
|
||||||
admin_state.add_logic_state.update_target_column_suggestions();
|
|
||||||
return Ok(EditEventOutcome::Message(format!("Error fetching columns: {}", e)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Ok(EditEventOutcome::Message("No table selected for column suggestions".to_string()));
|
|
||||||
}
|
|
||||||
} else { // Should not happen if AddLogic is properly initialized
|
|
||||||
return Ok(EditEventOutcome::Message("Profile name missing for column suggestions".to_string()));
|
|
||||||
}
|
|
||||||
} else { // Already in suggestion mode, navigate down
|
|
||||||
let msg = add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?;
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
|
||||||
}
|
|
||||||
} else if admin_state.add_logic_state.in_target_column_suggestion_mode && action_str == "suggestion_up" {
|
|
||||||
let msg = add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?;
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Autocomplete for RegisterState Role Field ---
|
|
||||||
if app_state.ui.show_register && register_state.current_field() == 4 { // Role field
|
|
||||||
if !register_state.in_suggestion_mode && action_str == "suggestion_down" { // Tab
|
|
||||||
register_state.update_role_suggestions();
|
|
||||||
if !register_state.role_suggestions.is_empty() {
|
|
||||||
register_state.in_suggestion_mode = true;
|
|
||||||
// update_role_suggestions should handle initial selection
|
|
||||||
return Ok(EditEventOutcome::Message("Role suggestions shown".to_string()));
|
|
||||||
} else {
|
|
||||||
// If Tab doesn't open suggestions, it might fall through to "next_field"
|
|
||||||
// or you might want specific behavior. For now, let it fall through.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if register_state.in_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up") {
|
|
||||||
let msg = auth_e::execute_edit_action(action_str, key, register_state, ideal_cursor_column).await?;
|
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Dispatch other edit actions ---
|
|
||||||
let msg = if app_state.ui.show_login {
|
let msg = if app_state.ui.show_login {
|
||||||
auth_e::execute_edit_action(action_str, key, login_state, ideal_cursor_column).await?
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
auth_e::execute_edit_action(
|
||||||
|
action_str,
|
||||||
|
key,
|
||||||
|
login_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
} else if app_state.ui.show_add_table {
|
} else if app_state.ui.show_add_table {
|
||||||
add_table_e::execute_edit_action(action_str, key, &mut admin_state.add_table_state, ideal_cursor_column).await?
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
add_table_e::execute_edit_action(
|
||||||
|
action_str,
|
||||||
|
key,
|
||||||
|
&mut admin_state.add_table_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
} else if app_state.ui.show_add_logic {
|
} else if app_state.ui.show_add_logic {
|
||||||
// If not a suggestion action handled above for AddLogic
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
if !(admin_state.add_logic_state.in_target_column_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up")) {
|
add_logic_e::execute_edit_action(
|
||||||
add_logic_e::execute_edit_action(action_str, key, &mut admin_state.add_logic_state, ideal_cursor_column).await?
|
action_str,
|
||||||
} else { String::new() /* Already handled */ }
|
key,
|
||||||
|
&mut admin_state.add_logic_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
} else if app_state.ui.show_register {
|
} else if app_state.ui.show_register {
|
||||||
if !(register_state.in_suggestion_mode && matches!(action_str, "suggestion_down" | "suggestion_up")) {
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
auth_e::execute_edit_action(action_str, key, register_state, ideal_cursor_column).await?
|
auth_e::execute_edit_action(
|
||||||
} else { String::new() /* Already handled */ }
|
action_str,
|
||||||
} else { // Form view
|
key,
|
||||||
form_e::execute_edit_action(action_str, key, form_state, ideal_cursor_column).await?
|
register_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
form_e::execute_edit_action(
|
||||||
|
action_str,
|
||||||
|
key,
|
||||||
|
form_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
};
|
};
|
||||||
return Ok(EditEventOutcome::Message(msg));
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Character insertion ---
|
// --- FALLBACK FOR CHARACTER INSERTION (IF NO OTHER BINDING MATCHED) ---
|
||||||
// If character insertion happens while in suggestion mode, exit suggestion mode first.
|
if let KeyCode::Char(_) = key.code {
|
||||||
let mut exited_suggestion_mode_for_typing = false;
|
let msg = if app_state.ui.show_login {
|
||||||
if app_state.ui.show_register && register_state.in_suggestion_mode {
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
register_state.in_suggestion_mode = false;
|
auth_e::execute_edit_action(
|
||||||
register_state.show_role_suggestions = false;
|
"insert_char",
|
||||||
register_state.selected_suggestion_index = None;
|
key,
|
||||||
exited_suggestion_mode_for_typing = true;
|
login_state,
|
||||||
}
|
&mut event_handler.ideal_cursor_column,
|
||||||
if app_state.ui.show_add_logic && admin_state.add_logic_state.in_target_column_suggestion_mode {
|
)
|
||||||
admin_state.add_logic_state.in_target_column_suggestion_mode = false;
|
.await?
|
||||||
admin_state.add_logic_state.show_target_column_suggestions = false;
|
} else if app_state.ui.show_add_table {
|
||||||
admin_state.add_logic_state.selected_target_column_suggestion_index = None;
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
exited_suggestion_mode_for_typing = true;
|
add_table_e::execute_edit_action(
|
||||||
|
"insert_char",
|
||||||
|
key,
|
||||||
|
&mut admin_state.add_table_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_add_logic {
|
||||||
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
add_logic_e::execute_edit_action(
|
||||||
|
"insert_char",
|
||||||
|
key,
|
||||||
|
&mut admin_state.add_logic_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else if app_state.ui.show_register {
|
||||||
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
auth_e::execute_edit_action(
|
||||||
|
"insert_char",
|
||||||
|
key,
|
||||||
|
register_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
// FIX: Pass &mut event_handler.ideal_cursor_column
|
||||||
|
form_e::execute_edit_action(
|
||||||
|
"insert_char",
|
||||||
|
key,
|
||||||
|
form_state,
|
||||||
|
&mut event_handler.ideal_cursor_column,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
};
|
||||||
|
return Ok(EditEventOutcome::Message(msg));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut char_insert_msg = if app_state.ui.show_login {
|
Ok(EditEventOutcome::Message(String::new())) // No action taken
|
||||||
auth_e::execute_edit_action("insert_char", key, login_state, ideal_cursor_column).await?
|
|
||||||
} else if app_state.ui.show_add_table {
|
|
||||||
add_table_e::execute_edit_action("insert_char", key, &mut admin_state.add_table_state, ideal_cursor_column).await?
|
|
||||||
} else if app_state.ui.show_add_logic {
|
|
||||||
add_logic_e::execute_edit_action("insert_char", key, &mut admin_state.add_logic_state, ideal_cursor_column).await?
|
|
||||||
} else if app_state.ui.show_register {
|
|
||||||
auth_e::execute_edit_action("insert_char", key, register_state, ideal_cursor_column).await?
|
|
||||||
} else { // Form view
|
|
||||||
form_e::execute_edit_action("insert_char", key, form_state, ideal_cursor_column).await?
|
|
||||||
};
|
|
||||||
|
|
||||||
// After character insertion, update suggestions if applicable
|
|
||||||
if app_state.ui.show_register && register_state.current_field() == 4 {
|
|
||||||
register_state.update_role_suggestions();
|
|
||||||
// If we just exited suggestion mode by typing, don't immediately show them again unless Tab is pressed.
|
|
||||||
// However, update_role_suggestions will set show_role_suggestions if matches are found.
|
|
||||||
// This is fine, as the render logic checks in_suggestion_mode.
|
|
||||||
}
|
|
||||||
if app_state.ui.show_add_logic && admin_state.add_logic_state.current_field() == 1 {
|
|
||||||
admin_state.add_logic_state.update_target_column_suggestions();
|
|
||||||
}
|
|
||||||
|
|
||||||
if exited_suggestion_mode_for_typing && char_insert_msg.is_empty() {
|
|
||||||
char_insert_msg = "Suggestions hidden".to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
Ok(EditEventOutcome::Message(char_insert_msg))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,8 +23,6 @@ pub async fn handle_read_only_event(
|
|||||||
add_table_state: &mut AddTableState,
|
add_table_state: &mut AddTableState,
|
||||||
add_logic_state: &mut AddLogicState,
|
add_logic_state: &mut AddLogicState,
|
||||||
key_sequence_tracker: &mut KeySequenceTracker,
|
key_sequence_tracker: &mut KeySequenceTracker,
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
edit_mode_cooldown: &mut bool,
|
edit_mode_cooldown: &mut bool,
|
||||||
@@ -74,12 +72,10 @@ pub async fn handle_read_only_event(
|
|||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
|
||||||
crate::tui::functions::login::handle_action(action).await?
|
crate::tui::functions::login::handle_action(action).await?
|
||||||
} else if app_state.ui.show_add_table {
|
} else if app_state.ui.show_add_table {
|
||||||
add_table_ro::execute_action(
|
add_table_ro::execute_action(
|
||||||
@@ -143,12 +139,10 @@ pub async fn handle_read_only_event(
|
|||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) { // Handle login context actions
|
} else if app_state.ui.show_login && CONTEXT_ACTIONS_LOGIN.contains(&action) {
|
||||||
crate::tui::functions::login::handle_action(action).await?
|
crate::tui::functions::login::handle_action(action).await?
|
||||||
} else if app_state.ui.show_add_table {
|
} else if app_state.ui.show_add_table {
|
||||||
add_table_ro::execute_action(
|
add_table_ro::execute_action(
|
||||||
@@ -177,7 +171,7 @@ pub async fn handle_read_only_event(
|
|||||||
key_sequence_tracker,
|
key_sequence_tracker,
|
||||||
command_message,
|
command_message,
|
||||||
).await?
|
).await?
|
||||||
} else if app_state.ui.show_login { // Handle login general actions
|
} else if app_state.ui.show_login {
|
||||||
auth_ro::execute_action(
|
auth_ro::execute_action(
|
||||||
action,
|
action,
|
||||||
app_state,
|
app_state,
|
||||||
@@ -211,8 +205,6 @@ pub async fn handle_read_only_event(
|
|||||||
action,
|
action,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
ideal_cursor_column,
|
ideal_cursor_column,
|
||||||
)
|
)
|
||||||
.await?
|
.await?
|
||||||
@@ -245,7 +237,7 @@ pub async fn handle_read_only_event(
|
|||||||
key_sequence_tracker,
|
key_sequence_tracker,
|
||||||
command_message,
|
command_message,
|
||||||
).await?
|
).await?
|
||||||
} else if app_state.ui.show_login { // Handle login general actions
|
} else if app_state.ui.show_login {
|
||||||
auth_ro::execute_action(
|
auth_ro::execute_action(
|
||||||
action,
|
action,
|
||||||
app_state,
|
app_state,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use anyhow::Result;
|
|||||||
pub async fn handle_command_event(
|
pub async fn handle_command_event(
|
||||||
key: KeyEvent,
|
key: KeyEvent,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
app_state: &AppState,
|
app_state: &mut AppState,
|
||||||
login_state: &LoginState,
|
login_state: &LoginState,
|
||||||
register_state: &RegisterState,
|
register_state: &RegisterState,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
@@ -74,7 +74,7 @@ pub async fn handle_command_event(
|
|||||||
async fn process_command(
|
async fn process_command(
|
||||||
config: &Config,
|
config: &Config,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
app_state: &AppState,
|
app_state: &mut AppState,
|
||||||
login_state: &LoginState,
|
login_state: &LoginState,
|
||||||
register_state: &RegisterState,
|
register_state: &RegisterState,
|
||||||
command_input: &mut String,
|
command_input: &mut String,
|
||||||
@@ -117,10 +117,9 @@ async fn process_command(
|
|||||||
},
|
},
|
||||||
"save" => {
|
"save" => {
|
||||||
let outcome = save(
|
let outcome = save(
|
||||||
|
app_state,
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await?;
|
).await?;
|
||||||
let message = match outcome {
|
let message = match outcome {
|
||||||
SaveOutcome::CreatedNew(_) => "New entry created".to_string(),
|
SaveOutcome::CreatedNew(_) => "New entry created".to_string(),
|
||||||
@@ -134,8 +133,6 @@ async fn process_command(
|
|||||||
let message = revert(
|
let message = revert(
|
||||||
form_state,
|
form_state,
|
||||||
grpc_client,
|
grpc_client,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
).await?;
|
).await?;
|
||||||
command_input.clear();
|
command_input.clear();
|
||||||
Ok(EventOutcome::Ok(message))
|
Ok(EventOutcome::Ok(message))
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
// src/client/modes/general.rs
|
// src/client/modes/general.rs
|
||||||
pub mod navigation;
|
pub mod navigation;
|
||||||
pub mod dialog;
|
pub mod dialog;
|
||||||
|
pub mod command_navigation;
|
||||||
|
|||||||
396
client/src/modes/general/command_navigation.rs
Normal file
396
client/src/modes/general/command_navigation.rs
Normal file
@@ -0,0 +1,396 @@
|
|||||||
|
// src/modes/general/command_navigation.rs
|
||||||
|
use crate::config::binds::config::Config;
|
||||||
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
use anyhow::Result;
|
||||||
|
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
||||||
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum NavigationType {
|
||||||
|
FindFile,
|
||||||
|
TableTree,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct TableDependencyGraph {
|
||||||
|
all_tables: HashSet<String>,
|
||||||
|
dependents_map: HashMap<String, Vec<String>>,
|
||||||
|
root_tables: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableDependencyGraph {
|
||||||
|
pub fn from_profile_tree(profile_tree: &ProfileTreeResponse) -> Self {
|
||||||
|
let mut dependents_map: HashMap<String, Vec<String>> = HashMap::new();
|
||||||
|
let mut all_tables_set: HashSet<String> = HashSet::new();
|
||||||
|
let mut table_dependencies: HashMap<String, Vec<String>> = HashMap::new();
|
||||||
|
|
||||||
|
for profile in &profile_tree.profiles {
|
||||||
|
for table in &profile.tables {
|
||||||
|
all_tables_set.insert(table.name.clone());
|
||||||
|
table_dependencies.insert(table.name.clone(), table.depends_on.clone());
|
||||||
|
|
||||||
|
for dependency_name in &table.depends_on {
|
||||||
|
dependents_map
|
||||||
|
.entry(dependency_name.clone())
|
||||||
|
.or_default()
|
||||||
|
.push(table.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let root_tables: Vec<String> = all_tables_set
|
||||||
|
.iter()
|
||||||
|
.filter(|name| {
|
||||||
|
table_dependencies
|
||||||
|
.get(*name)
|
||||||
|
.map_or(true, |deps| deps.is_empty())
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut sorted_root_tables = root_tables;
|
||||||
|
sorted_root_tables.sort();
|
||||||
|
|
||||||
|
for dependents_list in dependents_map.values_mut() {
|
||||||
|
dependents_list.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
Self {
|
||||||
|
all_tables: all_tables_set,
|
||||||
|
dependents_map,
|
||||||
|
root_tables: sorted_root_tables,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_dependent_children(&self, path: &str) -> Vec<String> {
|
||||||
|
if path.is_empty() {
|
||||||
|
return self.root_tables.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
let path_segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
|
if let Some(last_segment_name) = path_segments.last() {
|
||||||
|
if self.all_tables.contains(*last_segment_name) {
|
||||||
|
return self
|
||||||
|
.dependents_map
|
||||||
|
.get(*last_segment_name)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ... (NavigationState struct and its new(), activate_*, deactivate(), add_char(), remove_char(), move_*, autocomplete_selected(), get_display_input() methods are unchanged) ...
|
||||||
|
pub struct NavigationState {
|
||||||
|
pub active: bool,
|
||||||
|
pub input: String,
|
||||||
|
pub selected_index: Option<usize>,
|
||||||
|
pub filtered_options: Vec<(usize, String)>,
|
||||||
|
pub navigation_type: NavigationType,
|
||||||
|
pub current_path: String,
|
||||||
|
pub graph: Option<TableDependencyGraph>,
|
||||||
|
pub all_options: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NavigationState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
active: false,
|
||||||
|
input: String::new(),
|
||||||
|
selected_index: None,
|
||||||
|
filtered_options: Vec::new(),
|
||||||
|
navigation_type: NavigationType::FindFile,
|
||||||
|
current_path: String::new(),
|
||||||
|
graph: None,
|
||||||
|
all_options: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn activate_find_file(&mut self, options: Vec<String>) {
|
||||||
|
self.active = true;
|
||||||
|
self.navigation_type = NavigationType::FindFile;
|
||||||
|
self.all_options = options;
|
||||||
|
self.input.clear();
|
||||||
|
self.current_path.clear();
|
||||||
|
self.graph = None;
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn activate_table_tree(&mut self, graph: TableDependencyGraph) {
|
||||||
|
self.active = true;
|
||||||
|
self.navigation_type = NavigationType::TableTree;
|
||||||
|
self.graph = Some(graph);
|
||||||
|
self.input.clear();
|
||||||
|
self.current_path.clear();
|
||||||
|
self.update_options_for_path();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deactivate(&mut self) {
|
||||||
|
self.active = false;
|
||||||
|
self.input.clear();
|
||||||
|
self.all_options.clear();
|
||||||
|
self.filtered_options.clear();
|
||||||
|
self.selected_index = None;
|
||||||
|
self.current_path.clear();
|
||||||
|
self.graph = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_char(&mut self, c: char) {
|
||||||
|
match self.navigation_type {
|
||||||
|
NavigationType::FindFile => {
|
||||||
|
self.input.push(c);
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
NavigationType::TableTree => {
|
||||||
|
if c == '/' {
|
||||||
|
if !self.input.is_empty() {
|
||||||
|
if self.current_path.is_empty() {
|
||||||
|
self.current_path = self.input.clone();
|
||||||
|
} else {
|
||||||
|
self.current_path.push('/');
|
||||||
|
self.current_path.push_str(&self.input);
|
||||||
|
}
|
||||||
|
self.input.clear();
|
||||||
|
self.update_options_for_path();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.input.push(c);
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_char(&mut self) {
|
||||||
|
match self.navigation_type {
|
||||||
|
NavigationType::FindFile => {
|
||||||
|
self.input.pop();
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
NavigationType::TableTree => {
|
||||||
|
if self.input.is_empty() {
|
||||||
|
if !self.current_path.is_empty() {
|
||||||
|
if let Some(last_slash_idx) = self.current_path.rfind('/') {
|
||||||
|
self.input = self.current_path[last_slash_idx + 1..].to_string();
|
||||||
|
self.current_path = self.current_path[..last_slash_idx].to_string();
|
||||||
|
} else {
|
||||||
|
self.input = self.current_path.clone();
|
||||||
|
self.current_path.clear();
|
||||||
|
}
|
||||||
|
self.update_options_for_path();
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.input.pop();
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn move_up(&mut self) {
|
||||||
|
if self.filtered_options.is_empty() {
|
||||||
|
self.selected_index = None;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.selected_index = match self.selected_index {
|
||||||
|
Some(0) => Some(self.filtered_options.len() - 1),
|
||||||
|
Some(current) => Some(current - 1),
|
||||||
|
None => Some(self.filtered_options.len() - 1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn move_down(&mut self) {
|
||||||
|
if self.filtered_options.is_empty() {
|
||||||
|
self.selected_index = None;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.selected_index = match self.selected_index {
|
||||||
|
Some(current) if current >= self.filtered_options.len() - 1 => Some(0),
|
||||||
|
Some(current) => Some(current + 1),
|
||||||
|
None => Some(0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_selected_option_str(&self) -> Option<&str> {
|
||||||
|
self.selected_index
|
||||||
|
.and_then(|idx| self.filtered_options.get(idx))
|
||||||
|
.map(|(_, option_str)| option_str.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn autocomplete_selected(&mut self) {
|
||||||
|
if let Some(selected_option_str) = self.get_selected_option_str() {
|
||||||
|
self.input = selected_option_str.to_string();
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_display_input(&self) -> String {
|
||||||
|
match self.navigation_type {
|
||||||
|
NavigationType::FindFile => self.input.clone(),
|
||||||
|
NavigationType::TableTree => {
|
||||||
|
if self.current_path.is_empty() {
|
||||||
|
self.input.clone()
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", self.current_path, self.input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- START FIX ---
|
||||||
|
pub fn get_selected_value(&self) -> Option<String> {
|
||||||
|
match self.navigation_type {
|
||||||
|
NavigationType::FindFile => {
|
||||||
|
// Return the highlighted option, not the raw input buffer.
|
||||||
|
self.get_selected_option_str().map(|s| s.to_string())
|
||||||
|
}
|
||||||
|
NavigationType::TableTree => {
|
||||||
|
self.get_selected_option_str().map(|selected_name| {
|
||||||
|
if self.current_path.is_empty() {
|
||||||
|
selected_name.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", self.current_path, selected_name)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- END FIX ---
|
||||||
|
|
||||||
|
fn update_options_for_path(&mut self) {
|
||||||
|
if let NavigationType::TableTree = self.navigation_type {
|
||||||
|
if let Some(graph) = &self.graph {
|
||||||
|
self.all_options = graph.get_dependent_children(&self.current_path);
|
||||||
|
} else {
|
||||||
|
self.all_options.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.update_filtered_options();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_filtered_options(&mut self) {
|
||||||
|
let filter_text = match self.navigation_type {
|
||||||
|
NavigationType::FindFile => &self.input,
|
||||||
|
NavigationType::TableTree => &self.input,
|
||||||
|
}
|
||||||
|
.to_lowercase();
|
||||||
|
|
||||||
|
if filter_text.is_empty() {
|
||||||
|
self.filtered_options = self
|
||||||
|
.all_options
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, opt)| (i, opt.clone()))
|
||||||
|
.collect();
|
||||||
|
} else {
|
||||||
|
self.filtered_options = self
|
||||||
|
.all_options
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, opt)| opt.to_lowercase().contains(&filter_text))
|
||||||
|
.map(|(i, opt)| (i, opt.clone()))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.filtered_options.is_empty() {
|
||||||
|
self.selected_index = None;
|
||||||
|
} else {
|
||||||
|
self.selected_index = Some(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub async fn handle_command_navigation_event(
|
||||||
|
navigation_state: &mut NavigationState,
|
||||||
|
key: KeyEvent,
|
||||||
|
config: &Config,
|
||||||
|
) -> Result<EventOutcome> {
|
||||||
|
if !navigation_state.active {
|
||||||
|
return Ok(EventOutcome::Ok(String::new()));
|
||||||
|
}
|
||||||
|
|
||||||
|
match key.code {
|
||||||
|
KeyCode::Esc => {
|
||||||
|
navigation_state.deactivate();
|
||||||
|
Ok(EventOutcome::Ok("Navigation cancelled".to_string()))
|
||||||
|
}
|
||||||
|
KeyCode::Tab => {
|
||||||
|
if let Some(selected_opt_str) = navigation_state.get_selected_option_str() {
|
||||||
|
if navigation_state.input == selected_opt_str {
|
||||||
|
if navigation_state.navigation_type == NavigationType::TableTree {
|
||||||
|
let path_before_nav = navigation_state.current_path.clone();
|
||||||
|
let input_before_nav = navigation_state.input.clone();
|
||||||
|
navigation_state.add_char('/');
|
||||||
|
if !(navigation_state.input.is_empty() &&
|
||||||
|
(navigation_state.current_path != path_before_nav || !navigation_state.all_options.is_empty())) {
|
||||||
|
if !navigation_state.input.is_empty() && navigation_state.input != input_before_nav {
|
||||||
|
navigation_state.input = input_before_nav;
|
||||||
|
if navigation_state.current_path != path_before_nav {
|
||||||
|
navigation_state.current_path = path_before_nav;
|
||||||
|
}
|
||||||
|
navigation_state.update_options_for_path();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
navigation_state.autocomplete_selected();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
|
}
|
||||||
|
KeyCode::Backspace => {
|
||||||
|
navigation_state.remove_char();
|
||||||
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
|
}
|
||||||
|
KeyCode::Char(c) => {
|
||||||
|
navigation_state.add_char(c);
|
||||||
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
||||||
|
match action {
|
||||||
|
"move_up" => {
|
||||||
|
navigation_state.move_up();
|
||||||
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
|
}
|
||||||
|
"move_down" => {
|
||||||
|
navigation_state.move_down();
|
||||||
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
|
}
|
||||||
|
"select" => {
|
||||||
|
if let Some(selected_value) = navigation_state.get_selected_value() {
|
||||||
|
let outcome = match navigation_state.navigation_type {
|
||||||
|
// --- START FIX ---
|
||||||
|
NavigationType::FindFile => {
|
||||||
|
// The purpose of this palette is to select a table.
|
||||||
|
// Emit a TableSelected event instead of a generic Ok message.
|
||||||
|
EventOutcome::TableSelected {
|
||||||
|
path: selected_value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- END FIX ---
|
||||||
|
NavigationType::TableTree => {
|
||||||
|
EventOutcome::TableSelected {
|
||||||
|
path: selected_value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
navigation_state.deactivate();
|
||||||
|
Ok(outcome)
|
||||||
|
} else {
|
||||||
|
Ok(EventOutcome::Ok("No selection".to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Ok(EventOutcome::Ok(String::new())),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(EventOutcome::Ok(String::new()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use crate::state::pages::admin::AdminState;
|
|||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::ui::handlers::context::UiContext;
|
use crate::ui::handlers::context::UiContext;
|
||||||
use crate::modes::handlers::event::EventOutcome;
|
use crate::modes::handlers::event::EventOutcome;
|
||||||
|
use crate::modes::general::command_navigation::{handle_command_navigation_event, NavigationState};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
pub async fn handle_navigation_event(
|
pub async fn handle_navigation_event(
|
||||||
@@ -25,7 +26,13 @@ pub async fn handle_navigation_event(
|
|||||||
command_mode: &mut bool,
|
command_mode: &mut bool,
|
||||||
command_input: &mut String,
|
command_input: &mut String,
|
||||||
command_message: &mut String,
|
command_message: &mut String,
|
||||||
|
navigation_state: &mut NavigationState,
|
||||||
) -> Result<EventOutcome> {
|
) -> Result<EventOutcome> {
|
||||||
|
// Handle command navigation first if active
|
||||||
|
if navigation_state.active {
|
||||||
|
return handle_command_navigation_event(navigation_state, key, config).await;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
if let Some(action) = config.get_general_action(key.code, key.modifiers) {
|
||||||
match action {
|
match action {
|
||||||
"move_up" => {
|
"move_up" => {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,10 @@ impl ModeManager {
|
|||||||
event_handler: &EventHandler,
|
event_handler: &EventHandler,
|
||||||
admin_state: &AdminState,
|
admin_state: &AdminState,
|
||||||
) -> AppMode {
|
) -> AppMode {
|
||||||
|
if event_handler.navigation_state.active {
|
||||||
|
return AppMode::General;
|
||||||
|
}
|
||||||
|
|
||||||
if event_handler.command_mode {
|
if event_handler.command_mode {
|
||||||
return AppMode::Command;
|
return AppMode::Command;
|
||||||
}
|
}
|
||||||
@@ -78,12 +82,12 @@ impl ModeManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Mode transition rules
|
// Mode transition rules
|
||||||
pub fn can_enter_command_mode(current_mode: AppMode) -> bool {
|
pub fn can_enter_command_mode(current_mode: AppMode) -> bool {
|
||||||
!matches!(current_mode, AppMode::Edit) // Can't enter from Edit mode
|
!matches!(current_mode, AppMode::Edit)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn can_enter_edit_mode(current_mode: AppMode) -> bool {
|
pub fn can_enter_edit_mode(current_mode: AppMode) -> bool {
|
||||||
matches!(current_mode, AppMode::ReadOnly) // Only from ReadOnly
|
matches!(current_mode, AppMode::ReadOnly)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn can_enter_read_only_mode(current_mode: AppMode) -> bool {
|
pub fn can_enter_read_only_mode(current_mode: AppMode) -> bool {
|
||||||
|
|||||||
@@ -44,8 +44,6 @@ pub async fn handle_highlight_event(
|
|||||||
&mut admin_state.add_table_state,
|
&mut admin_state.add_table_state,
|
||||||
&mut admin_state.add_logic_state,
|
&mut admin_state.add_logic_state,
|
||||||
key_sequence_tracker,
|
key_sequence_tracker,
|
||||||
current_position,
|
|
||||||
total_count,
|
|
||||||
grpc_client,
|
grpc_client,
|
||||||
command_message, // Pass the message buffer
|
command_message, // Pass the message buffer
|
||||||
edit_mode_cooldown,
|
edit_mode_cooldown,
|
||||||
|
|||||||
@@ -1,101 +1,257 @@
|
|||||||
// src/services/grpc_client.rs
|
// src/services/grpc_client.rs
|
||||||
|
|
||||||
use tonic::transport::Channel;
|
use common::proto::multieko2::common::Empty;
|
||||||
use common::proto::multieko2::adresar::adresar_client::AdresarClient;
|
|
||||||
use common::proto::multieko2::adresar::{AdresarResponse, PostAdresarRequest, PutAdresarRequest};
|
|
||||||
use common::proto::multieko2::common::{CountResponse, PositionRequest, Empty};
|
|
||||||
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
|
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
|
||||||
// Import the new request type for table structure
|
use common::proto::multieko2::table_structure::{GetTableStructureRequest, TableStructureResponse};
|
||||||
use common::proto::multieko2::table_structure::{TableStructureResponse, GetTableStructureRequest};
|
|
||||||
use common::proto::multieko2::table_definition::{
|
use common::proto::multieko2::table_definition::{
|
||||||
table_definition_client::TableDefinitionClient,
|
table_definition_client::TableDefinitionClient,
|
||||||
ProfileTreeResponse, PostTableDefinitionRequest, TableDefinitionResponse,
|
PostTableDefinitionRequest, ProfileTreeResponse, TableDefinitionResponse,
|
||||||
};
|
};
|
||||||
use common::proto::multieko2::table_script::{
|
use common::proto::multieko2::table_script::{
|
||||||
table_script_client::TableScriptClient,
|
table_script_client::TableScriptClient,
|
||||||
PostTableScriptRequest, TableScriptResponse,
|
PostTableScriptRequest, TableScriptResponse,
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use common::proto::multieko2::tables_data::{
|
||||||
|
tables_data_client::TablesDataClient,
|
||||||
|
GetTableDataByPositionRequest,
|
||||||
|
GetTableDataRequest, // ADD THIS
|
||||||
|
GetTableDataResponse,
|
||||||
|
DeleteTableDataRequest, // ADD THIS
|
||||||
|
DeleteTableDataResponse, // ADD THIS
|
||||||
|
GetTableDataCountRequest,
|
||||||
|
PostTableDataRequest, PostTableDataResponse, PutTableDataRequest,
|
||||||
|
PutTableDataResponse,
|
||||||
|
};
|
||||||
|
use common::proto::multieko2::search::{
|
||||||
|
searcher_client::SearcherClient, SearchRequest, SearchResponse,
|
||||||
|
};
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use tonic::transport::Channel;
|
||||||
|
use prost_types::Value;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct GrpcClient {
|
pub struct GrpcClient {
|
||||||
adresar_client: AdresarClient<Channel>,
|
|
||||||
table_structure_client: TableStructureServiceClient<Channel>,
|
table_structure_client: TableStructureServiceClient<Channel>,
|
||||||
table_definition_client: TableDefinitionClient<Channel>,
|
table_definition_client: TableDefinitionClient<Channel>,
|
||||||
table_script_client: TableScriptClient<Channel>,
|
table_script_client: TableScriptClient<Channel>,
|
||||||
|
tables_data_client: TablesDataClient<Channel>,
|
||||||
|
search_client: SearcherClient<Channel>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GrpcClient {
|
impl GrpcClient {
|
||||||
pub async fn new() -> Result<Self> {
|
pub async fn new() -> Result<Self> {
|
||||||
let adresar_client = AdresarClient::connect("http://[::1]:50051").await?;
|
let channel = Channel::from_static("http://[::1]:50051")
|
||||||
let table_structure_client = TableStructureServiceClient::connect("http://[::1]:50051").await?;
|
.connect()
|
||||||
let table_definition_client = TableDefinitionClient::connect("http://[::1]:50051").await?;
|
.await
|
||||||
let table_script_client = TableScriptClient::connect("http://[::1]:50051").await?;
|
.context("Failed to create gRPC channel")?;
|
||||||
|
|
||||||
|
let table_structure_client =
|
||||||
|
TableStructureServiceClient::new(channel.clone());
|
||||||
|
let table_definition_client =
|
||||||
|
TableDefinitionClient::new(channel.clone());
|
||||||
|
let table_script_client = TableScriptClient::new(channel.clone());
|
||||||
|
let tables_data_client = TablesDataClient::new(channel.clone());
|
||||||
|
let search_client = SearcherClient::new(channel.clone());
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
adresar_client,
|
|
||||||
table_structure_client,
|
table_structure_client,
|
||||||
table_definition_client,
|
table_definition_client,
|
||||||
table_script_client,
|
table_script_client,
|
||||||
|
tables_data_client,
|
||||||
|
search_client,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_adresar_count(&mut self) -> Result<u64> {
|
|
||||||
let request = tonic::Request::new(Empty::default());
|
|
||||||
let response: CountResponse = self.adresar_client.get_adresar_count(request).await?.into_inner();
|
|
||||||
Ok(response.count as u64)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_adresar_by_position(&mut self, position: u64) -> Result<AdresarResponse> {
|
|
||||||
let request = tonic::Request::new(PositionRequest { position: position as i64 });
|
|
||||||
let response: AdresarResponse = self.adresar_client.get_adresar_by_position(request).await?.into_inner();
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn post_adresar(&mut self, request: PostAdresarRequest) -> Result<tonic::Response<AdresarResponse>> {
|
|
||||||
let request = tonic::Request::new(request);
|
|
||||||
let response = self.adresar_client.post_adresar(request).await?;
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn put_adresar(&mut self, request: PutAdresarRequest) -> Result<tonic::Response<AdresarResponse>> {
|
|
||||||
let request = tonic::Request::new(request);
|
|
||||||
let response = self.adresar_client.put_adresar(request).await?;
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Updated get_table_structure method
|
|
||||||
pub async fn get_table_structure(
|
pub async fn get_table_structure(
|
||||||
&mut self,
|
&mut self,
|
||||||
profile_name: String,
|
profile_name: String,
|
||||||
table_name: String,
|
table_name: String,
|
||||||
) -> Result<TableStructureResponse> {
|
) -> Result<TableStructureResponse> {
|
||||||
// Create the new request type
|
|
||||||
let grpc_request = GetTableStructureRequest {
|
let grpc_request = GetTableStructureRequest {
|
||||||
profile_name,
|
profile_name,
|
||||||
table_name,
|
table_name,
|
||||||
};
|
};
|
||||||
let request = tonic::Request::new(grpc_request);
|
let request = tonic::Request::new(grpc_request);
|
||||||
// Call the new gRPC method
|
let response = self
|
||||||
let response = self.table_structure_client.get_table_structure(request).await?;
|
.table_structure_client
|
||||||
|
.get_table_structure(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC GetTableStructure call failed")?;
|
||||||
Ok(response.into_inner())
|
Ok(response.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_profile_tree(&mut self) -> Result<ProfileTreeResponse> {
|
pub async fn get_profile_tree(
|
||||||
|
&mut self,
|
||||||
|
) -> Result<ProfileTreeResponse> {
|
||||||
let request = tonic::Request::new(Empty::default());
|
let request = tonic::Request::new(Empty::default());
|
||||||
let response = self.table_definition_client.get_profile_tree(request).await?;
|
let response = self
|
||||||
|
.table_definition_client
|
||||||
|
.get_profile_tree(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC GetProfileTree call failed")?;
|
||||||
Ok(response.into_inner())
|
Ok(response.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post_table_definition(&mut self, request: PostTableDefinitionRequest) -> Result<TableDefinitionResponse> {
|
pub async fn post_table_definition(
|
||||||
|
&mut self,
|
||||||
|
request: PostTableDefinitionRequest,
|
||||||
|
) -> Result<TableDefinitionResponse> {
|
||||||
let tonic_request = tonic::Request::new(request);
|
let tonic_request = tonic::Request::new(request);
|
||||||
let response = self.table_definition_client.post_table_definition(tonic_request).await?;
|
let response = self
|
||||||
|
.table_definition_client
|
||||||
|
.post_table_definition(tonic_request)
|
||||||
|
.await
|
||||||
|
.context("gRPC PostTableDefinition call failed")?;
|
||||||
Ok(response.into_inner())
|
Ok(response.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post_table_script(&mut self, request: PostTableScriptRequest) -> Result<TableScriptResponse> {
|
pub async fn post_table_script(
|
||||||
|
&mut self,
|
||||||
|
request: PostTableScriptRequest,
|
||||||
|
) -> Result<TableScriptResponse> {
|
||||||
let tonic_request = tonic::Request::new(request);
|
let tonic_request = tonic::Request::new(request);
|
||||||
let response = self.table_script_client.post_table_script(tonic_request).await?;
|
let response = self
|
||||||
|
.table_script_client
|
||||||
|
.post_table_script(tonic_request)
|
||||||
|
.await
|
||||||
|
.context("gRPC PostTableScript call failed")?;
|
||||||
|
Ok(response.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Existing TablesData methods
|
||||||
|
pub async fn get_table_data_count(
|
||||||
|
&mut self,
|
||||||
|
profile_name: String,
|
||||||
|
table_name: String,
|
||||||
|
) -> Result<u64> {
|
||||||
|
let grpc_request = GetTableDataCountRequest {
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
};
|
||||||
|
let request = tonic::Request::new(grpc_request);
|
||||||
|
let response = self
|
||||||
|
.tables_data_client
|
||||||
|
.get_table_data_count(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC GetTableDataCount call failed")?;
|
||||||
|
Ok(response.into_inner().count as u64)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_table_data_by_position(
|
||||||
|
&mut self,
|
||||||
|
profile_name: String,
|
||||||
|
table_name: String,
|
||||||
|
position: i32,
|
||||||
|
) -> Result<GetTableDataResponse> {
|
||||||
|
let grpc_request = GetTableDataByPositionRequest {
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
position,
|
||||||
|
};
|
||||||
|
let request = tonic::Request::new(grpc_request);
|
||||||
|
let response = self
|
||||||
|
.tables_data_client
|
||||||
|
.get_table_data_by_position(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC GetTableDataByPosition call failed")?;
|
||||||
|
Ok(response.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADD THIS: Missing get_table_data method
|
||||||
|
pub async fn get_table_data(
|
||||||
|
&mut self,
|
||||||
|
profile_name: String,
|
||||||
|
table_name: String,
|
||||||
|
id: i64,
|
||||||
|
) -> Result<GetTableDataResponse> {
|
||||||
|
let grpc_request = GetTableDataRequest {
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
id,
|
||||||
|
};
|
||||||
|
let request = tonic::Request::new(grpc_request);
|
||||||
|
let response = self
|
||||||
|
.tables_data_client
|
||||||
|
.get_table_data(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC GetTableData call failed")?;
|
||||||
|
Ok(response.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADD THIS: Missing delete_table_data method
|
||||||
|
pub async fn delete_table_data(
|
||||||
|
&mut self,
|
||||||
|
profile_name: String,
|
||||||
|
table_name: String,
|
||||||
|
record_id: i64,
|
||||||
|
) -> Result<DeleteTableDataResponse> {
|
||||||
|
let grpc_request = DeleteTableDataRequest {
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
record_id,
|
||||||
|
};
|
||||||
|
let request = tonic::Request::new(grpc_request);
|
||||||
|
let response = self
|
||||||
|
.tables_data_client
|
||||||
|
.delete_table_data(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC DeleteTableData call failed")?;
|
||||||
|
Ok(response.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_table_data(
|
||||||
|
&mut self,
|
||||||
|
profile_name: String,
|
||||||
|
table_name: String,
|
||||||
|
data: HashMap<String, Value>,
|
||||||
|
) -> Result<PostTableDataResponse> {
|
||||||
|
let grpc_request = PostTableDataRequest {
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
let request = tonic::Request::new(grpc_request);
|
||||||
|
let response = self
|
||||||
|
.tables_data_client
|
||||||
|
.post_table_data(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC PostTableData call failed")?;
|
||||||
|
Ok(response.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn put_table_data(
|
||||||
|
&mut self,
|
||||||
|
profile_name: String,
|
||||||
|
table_name: String,
|
||||||
|
id: i64,
|
||||||
|
data: HashMap<String, Value>,
|
||||||
|
) -> Result<PutTableDataResponse> {
|
||||||
|
let grpc_request = PutTableDataRequest {
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
id,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
let request = tonic::Request::new(grpc_request);
|
||||||
|
let response = self
|
||||||
|
.tables_data_client
|
||||||
|
.put_table_data(request)
|
||||||
|
.await
|
||||||
|
.context("gRPC PutTableData call failed")?;
|
||||||
|
Ok(response.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn search_table(
|
||||||
|
&mut self,
|
||||||
|
table_name: String,
|
||||||
|
query: String,
|
||||||
|
) -> Result<SearchResponse> {
|
||||||
|
let request = tonic::Request::new(SearchRequest { table_name, query });
|
||||||
|
let response = self
|
||||||
|
.search_client
|
||||||
|
.search_table(request)
|
||||||
|
.await?;
|
||||||
Ok(response.into_inner())
|
Ok(response.into_inner())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,100 @@
|
|||||||
// src/services/ui_service.rs
|
// src/services/ui_service.rs
|
||||||
|
|
||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::pages::form::FormState;
|
|
||||||
use crate::tui::functions::common::form::SaveOutcome;
|
|
||||||
use crate::state::pages::add_logic::AddLogicState;
|
|
||||||
use crate::state::app::state::AppState;
|
use crate::state::app::state::AppState;
|
||||||
use anyhow::{Context, Result};
|
use crate::state::pages::add_logic::AddLogicState;
|
||||||
|
use crate::state::pages::form::{FieldDefinition, FormState};
|
||||||
|
use crate::tui::functions::common::form::SaveOutcome;
|
||||||
|
use crate::utils::columns::filter_user_columns;
|
||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub struct UiService;
|
pub struct UiService;
|
||||||
|
|
||||||
impl UiService {
|
impl UiService {
|
||||||
|
pub async fn load_table_view(
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
app_state: &mut AppState,
|
||||||
|
profile_name: &str,
|
||||||
|
table_name: &str,
|
||||||
|
) -> Result<FormState> {
|
||||||
|
// 1. & 2. Fetch and Cache Schema - UNCHANGED
|
||||||
|
let table_structure = grpc_client
|
||||||
|
.get_table_structure(profile_name.to_string(), table_name.to_string())
|
||||||
|
.await
|
||||||
|
.context(format!(
|
||||||
|
"Failed to get table structure for {}.{}",
|
||||||
|
profile_name, table_name
|
||||||
|
))?;
|
||||||
|
let cache_key = format!("{}.{}", profile_name, table_name);
|
||||||
|
app_state
|
||||||
|
.schema_cache
|
||||||
|
.insert(cache_key, Arc::new(table_structure.clone()));
|
||||||
|
tracing::info!("Schema for '{}.{}' cached.", profile_name, table_name);
|
||||||
|
|
||||||
|
// --- START: FINAL, SIMPLIFIED, CORRECT LOGIC ---
|
||||||
|
|
||||||
|
// 3a. Create definitions for REGULAR fields first.
|
||||||
|
let mut fields: Vec<FieldDefinition> = table_structure
|
||||||
|
.columns
|
||||||
|
.iter()
|
||||||
|
.filter(|col| {
|
||||||
|
!col.is_primary_key
|
||||||
|
&& col.name != "deleted"
|
||||||
|
&& col.name != "created_at"
|
||||||
|
&& !col.name.ends_with("_id") // Filter out ALL potential links
|
||||||
|
})
|
||||||
|
.map(|col| FieldDefinition {
|
||||||
|
display_name: col.name.clone(),
|
||||||
|
data_key: col.name.clone(),
|
||||||
|
is_link: false,
|
||||||
|
link_target_table: None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// 3b. Now, find and APPEND definitions for LINK fields based on the `_id` convention.
|
||||||
|
let link_fields: Vec<FieldDefinition> = table_structure
|
||||||
|
.columns
|
||||||
|
.iter()
|
||||||
|
.filter(|col| col.name.ends_with("_id")) // Find all foreign key columns
|
||||||
|
.map(|col| {
|
||||||
|
// The table we link to is derived from the column name.
|
||||||
|
// e.g., "test_diacritics_id" -> "test_diacritics"
|
||||||
|
let target_table_base = col
|
||||||
|
.name
|
||||||
|
.strip_suffix("_id")
|
||||||
|
.unwrap_or(&col.name);
|
||||||
|
|
||||||
|
// Find the full table name from the profile tree for display.
|
||||||
|
// e.g., "test_diacritics" -> "2025_test_diacritics"
|
||||||
|
let full_target_table_name = app_state
|
||||||
|
.profile_tree
|
||||||
|
.profiles
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.name == profile_name)
|
||||||
|
.and_then(|p| p.tables.iter().find(|t| t.name.ends_with(target_table_base)))
|
||||||
|
.map_or(target_table_base.to_string(), |t| t.name.clone());
|
||||||
|
|
||||||
|
FieldDefinition {
|
||||||
|
display_name: full_target_table_name.clone(),
|
||||||
|
data_key: col.name.clone(), // The actual FK column name
|
||||||
|
is_link: true,
|
||||||
|
link_target_table: Some(full_target_table_name),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
fields.extend(link_fields); // Append the link fields to the end
|
||||||
|
|
||||||
|
// --- END: FINAL, SIMPLIFIED, CORRECT LOGIC ---
|
||||||
|
|
||||||
|
Ok(FormState::new(
|
||||||
|
profile_name.to_string(),
|
||||||
|
table_name.to_string(),
|
||||||
|
fields,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn initialize_add_logic_table_data(
|
pub async fn initialize_add_logic_table_data(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
add_logic_state: &mut AddLogicState,
|
add_logic_state: &mut AddLogicState,
|
||||||
@@ -82,7 +167,7 @@ impl UiService {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|col| col.name)
|
.map(|col| col.name)
|
||||||
.collect();
|
.collect();
|
||||||
Ok(column_names)
|
Ok(filter_user_columns(column_names))
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!("Failed to fetch columns for {}.{}: {}", profile_name, table_name, e);
|
tracing::warn!("Failed to fetch columns for {}.{}: {}", profile_name, table_name, e);
|
||||||
@@ -91,112 +176,144 @@ impl UiService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn initialize_app_state(
|
// REFACTOR THIS FUNCTION
|
||||||
|
pub async fn initialize_app_state_and_form(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
app_state: &mut AppState,
|
||||||
) -> Result<Vec<String>> {
|
) -> Result<(String, String, Vec<String>)> {
|
||||||
// Fetch profile tree
|
let profile_tree = grpc_client
|
||||||
let profile_tree = grpc_client.get_profile_tree().await.context("Failed to get profile tree")?;
|
.get_profile_tree()
|
||||||
|
.await
|
||||||
|
.context("Failed to get profile tree")?;
|
||||||
app_state.profile_tree = profile_tree;
|
app_state.profile_tree = profile_tree;
|
||||||
|
|
||||||
// TODO for general tables and not hardcoded
|
let initial_profile_name = app_state
|
||||||
let default_profile_name = "default".to_string();
|
.profile_tree
|
||||||
let default_table_name = "2025_customer".to_string();
|
.profiles
|
||||||
|
.first()
|
||||||
|
.map(|p| p.name.clone())
|
||||||
|
.unwrap_or_else(|| "default".to_string());
|
||||||
|
|
||||||
// Fetch table structure for the default table
|
let initial_table_name = app_state
|
||||||
let table_structure = grpc_client
|
.profile_tree
|
||||||
.get_table_structure(default_profile_name, default_table_name)
|
.profiles
|
||||||
.await
|
.first()
|
||||||
.context("Failed to get initial table structure")?;
|
.and_then(|p| p.tables.first().map(|t| t.name.clone()))
|
||||||
|
.unwrap_or_else(|| "2025_company_data1".to_string());
|
||||||
|
|
||||||
// Extract the column names from the response
|
app_state.set_current_view_table(
|
||||||
let column_names: Vec<String> = table_structure
|
initial_profile_name.clone(),
|
||||||
.columns
|
initial_table_name.clone(),
|
||||||
.iter()
|
);
|
||||||
.map(|col| col.name.clone())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
Ok(column_names)
|
// NOW, just call our new central function. This avoids code duplication.
|
||||||
|
let form_state = Self::load_table_view(
|
||||||
|
grpc_client,
|
||||||
|
app_state,
|
||||||
|
&initial_profile_name,
|
||||||
|
&initial_table_name,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// The field names for the UI are derived from the new form_state
|
||||||
|
let field_names = form_state.fields.iter().map(|f| f.display_name.clone()).collect();
|
||||||
|
|
||||||
|
Ok((initial_profile_name, initial_table_name, field_names))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn initialize_adresar_count(
|
pub async fn fetch_and_set_table_count(
|
||||||
|
grpc_client: &mut GrpcClient,
|
||||||
|
form_state: &mut FormState,
|
||||||
|
) -> Result<()> {
|
||||||
|
let total_count = grpc_client
|
||||||
|
.get_table_data_count(
|
||||||
|
form_state.profile_name.clone(),
|
||||||
|
form_state.table_name.clone(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context(format!(
|
||||||
|
"Failed to get count for table {}.{}",
|
||||||
|
form_state.profile_name, form_state.table_name
|
||||||
|
))?;
|
||||||
|
form_state.total_count = total_count;
|
||||||
|
|
||||||
|
if total_count > 0 {
|
||||||
|
form_state.current_position = total_count;
|
||||||
|
} else {
|
||||||
|
form_state.current_position = 1;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn load_table_data_by_position(
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
|
||||||
) -> Result<()> {
|
|
||||||
let total_count = grpc_client.get_adresar_count().await.context("Failed to get adresar count")?;
|
|
||||||
app_state.update_total_count(total_count);
|
|
||||||
app_state.update_current_position(total_count.saturating_add(1)); // Start in new entry mode
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn update_adresar_count(
|
|
||||||
grpc_client: &mut GrpcClient,
|
|
||||||
app_state: &mut AppState,
|
|
||||||
) -> Result<()> {
|
|
||||||
let total_count = grpc_client.get_adresar_count().await.context("Failed to get adresar by position")?;
|
|
||||||
app_state.update_total_count(total_count);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn load_adresar_by_position(
|
|
||||||
grpc_client: &mut GrpcClient,
|
|
||||||
_app_state: &mut AppState,
|
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
position: u64,
|
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
match grpc_client.get_adresar_by_position(position).await {
|
if form_state.current_position == 0 || (form_state.total_count > 0 && form_state.current_position > form_state.total_count) {
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
return Ok(format!(
|
||||||
|
"New entry mode for table {}.{}",
|
||||||
|
form_state.profile_name, form_state.table_name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if form_state.total_count == 0 && form_state.current_position == 1 {
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
return Ok(format!(
|
||||||
|
"New entry mode for empty table {}.{}",
|
||||||
|
form_state.profile_name, form_state.table_name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
match grpc_client
|
||||||
|
.get_table_data_by_position(
|
||||||
|
form_state.profile_name.clone(),
|
||||||
|
form_state.table_name.clone(),
|
||||||
|
form_state.current_position as i32,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
// Set the ID properly
|
// FIX: Pass the current position as the second argument
|
||||||
form_state.id = response.id;
|
form_state.update_from_response(&response.data, form_state.current_position);
|
||||||
|
Ok(format!(
|
||||||
// Update form values dynamically
|
"Loaded entry {}/{} for table {}.{}",
|
||||||
form_state.values = vec![
|
form_state.current_position,
|
||||||
response.firma,
|
form_state.total_count,
|
||||||
response.kz,
|
form_state.profile_name,
|
||||||
response.drc,
|
form_state.table_name
|
||||||
response.ulica,
|
))
|
||||||
response.psc,
|
|
||||||
response.mesto,
|
|
||||||
response.stat,
|
|
||||||
response.banka,
|
|
||||||
response.ucet,
|
|
||||||
response.skladm,
|
|
||||||
response.ico,
|
|
||||||
response.kontakt,
|
|
||||||
response.telefon,
|
|
||||||
response.skladu,
|
|
||||||
response.fax,
|
|
||||||
];
|
|
||||||
|
|
||||||
form_state.has_unsaved_changes = false;
|
|
||||||
Ok(format!("Loaded entry {}", position))
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
Ok(format!("Error loading entry: {}", e))
|
tracing::error!(
|
||||||
|
"Error loading entry {} for table {}.{}: {}",
|
||||||
|
form_state.current_position,
|
||||||
|
form_state.profile_name,
|
||||||
|
form_state.table_name,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
Err(anyhow::anyhow!(
|
||||||
|
"Error loading entry {}: {}",
|
||||||
|
form_state.current_position,
|
||||||
|
e
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handles the consequences of a save operation, like updating counts.
|
|
||||||
pub async fn handle_save_outcome(
|
pub async fn handle_save_outcome(
|
||||||
save_outcome: SaveOutcome,
|
save_outcome: SaveOutcome,
|
||||||
grpc_client: &mut GrpcClient,
|
_grpc_client: &mut GrpcClient,
|
||||||
app_state: &mut AppState,
|
_app_state: &mut AppState,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
match save_outcome {
|
match save_outcome {
|
||||||
SaveOutcome::CreatedNew(new_id) => {
|
SaveOutcome::CreatedNew(new_id) => {
|
||||||
// A new record was created, update the count!
|
form_state.id = new_id;
|
||||||
UiService::update_adresar_count(grpc_client, app_state).await?;
|
|
||||||
// Navigate to the new record (now that count is updated)
|
|
||||||
app_state.update_current_position(app_state.total_count);
|
|
||||||
form_state.id = new_id; // Ensure ID is set (might be redundant if save already did it)
|
|
||||||
}
|
}
|
||||||
SaveOutcome::UpdatedExisting | SaveOutcome::NoChange => {
|
SaveOutcome::UpdatedExisting | SaveOutcome::NoChange => {
|
||||||
// No count update needed for these outcomes
|
// No action needed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,4 +2,5 @@
|
|||||||
|
|
||||||
pub mod state;
|
pub mod state;
|
||||||
pub mod buffer;
|
pub mod buffer;
|
||||||
|
pub mod search;
|
||||||
pub mod highlight;
|
pub mod highlight;
|
||||||
|
|||||||
56
client/src/state/app/search.rs
Normal file
56
client/src/state/app/search.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
// src/state/app/search.rs
|
||||||
|
|
||||||
|
use common::proto::multieko2::search::search_response::Hit;
|
||||||
|
|
||||||
|
/// Holds the complete state for the search palette.
|
||||||
|
pub struct SearchState {
|
||||||
|
/// The name of the table being searched.
|
||||||
|
pub table_name: String,
|
||||||
|
/// The current text entered by the user.
|
||||||
|
pub input: String,
|
||||||
|
/// The position of the cursor within the input text.
|
||||||
|
pub cursor_position: usize,
|
||||||
|
/// The search results returned from the server.
|
||||||
|
pub results: Vec<Hit>,
|
||||||
|
/// The index of the currently selected search result.
|
||||||
|
pub selected_index: usize,
|
||||||
|
/// A flag to indicate if a search is currently in progress.
|
||||||
|
pub is_loading: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SearchState {
|
||||||
|
/// Creates a new SearchState for a given table.
|
||||||
|
pub fn new(table_name: String) -> Self {
|
||||||
|
Self {
|
||||||
|
table_name,
|
||||||
|
input: String::new(),
|
||||||
|
cursor_position: 0,
|
||||||
|
results: Vec::new(),
|
||||||
|
selected_index: 0,
|
||||||
|
is_loading: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the selection to the next item, wrapping around if at the end.
|
||||||
|
pub fn next_result(&mut self) {
|
||||||
|
if !self.results.is_empty() {
|
||||||
|
let next = self.selected_index + 1;
|
||||||
|
self.selected_index = if next >= self.results.len() {
|
||||||
|
0 // Wrap to the start
|
||||||
|
} else {
|
||||||
|
next
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the selection to the previous item, wrapping around if at the beginning.
|
||||||
|
pub fn previous_result(&mut self) {
|
||||||
|
if !self.results.is_empty() {
|
||||||
|
self.selected_index = if self.selected_index == 0 {
|
||||||
|
self.results.len() - 1 // Wrap to the end
|
||||||
|
} else {
|
||||||
|
self.selected_index - 1
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,19 @@
|
|||||||
// src/state/state.rs
|
// src/state/app/state.rs
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
|
||||||
use crate::modes::handlers::mode_manager::AppMode;
|
|
||||||
use crate::ui::handlers::context::DialogPurpose;
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use common::proto::multieko2::table_definition::ProfileTreeResponse;
|
||||||
|
// NEW: Import the types we need for the cache
|
||||||
|
use common::proto::multieko2::table_structure::TableStructureResponse;
|
||||||
|
use crate::modes::handlers::mode_manager::AppMode;
|
||||||
|
use crate::state::app::search::SearchState;
|
||||||
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::env;
|
||||||
|
use std::sync::Arc;
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
// --- DialogState and UiState are unchanged ---
|
||||||
pub struct DialogState {
|
pub struct DialogState {
|
||||||
pub dialog_show: bool,
|
pub dialog_show: bool,
|
||||||
pub dialog_title: String,
|
pub dialog_title: String,
|
||||||
@@ -26,59 +34,75 @@ pub struct UiState {
|
|||||||
pub show_form: bool,
|
pub show_form: bool,
|
||||||
pub show_login: bool,
|
pub show_login: bool,
|
||||||
pub show_register: bool,
|
pub show_register: bool,
|
||||||
|
pub show_search_palette: bool,
|
||||||
pub focus_outside_canvas: bool,
|
pub focus_outside_canvas: bool,
|
||||||
pub dialog: DialogState,
|
pub dialog: DialogState,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DebugState {
|
||||||
|
pub displayed_message: String,
|
||||||
|
pub is_error: bool,
|
||||||
|
pub display_start_time: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
// Core editor state
|
// Core editor state
|
||||||
pub current_dir: String,
|
pub current_dir: String,
|
||||||
pub total_count: u64,
|
|
||||||
pub current_position: u64,
|
|
||||||
pub profile_tree: ProfileTreeResponse,
|
pub profile_tree: ProfileTreeResponse,
|
||||||
pub selected_profile: Option<String>,
|
pub selected_profile: Option<String>,
|
||||||
pub current_mode: AppMode,
|
pub current_mode: AppMode,
|
||||||
|
pub current_view_profile_name: Option<String>,
|
||||||
|
pub current_view_table_name: Option<String>,
|
||||||
|
|
||||||
|
// NEW: The "Rulebook" cache. We use Arc for efficient sharing.
|
||||||
|
pub schema_cache: HashMap<String, Arc<TableStructureResponse>>,
|
||||||
|
|
||||||
pub focused_button_index: usize,
|
pub focused_button_index: usize,
|
||||||
pub pending_table_structure_fetch: Option<(String, String)>,
|
pub pending_table_structure_fetch: Option<(String, String)>,
|
||||||
|
|
||||||
|
pub search_state: Option<SearchState>,
|
||||||
|
|
||||||
// UI preferences
|
// UI preferences
|
||||||
pub ui: UiState,
|
pub ui: UiState,
|
||||||
|
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
pub debug_state: Option<DebugState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub fn new() -> Result<Self> {
|
pub fn new() -> Result<Self> {
|
||||||
let current_dir = env::current_dir()?
|
let current_dir = env::current_dir()?.to_string_lossy().to_string();
|
||||||
.to_string_lossy()
|
|
||||||
.to_string();
|
|
||||||
Ok(AppState {
|
Ok(AppState {
|
||||||
current_dir,
|
current_dir,
|
||||||
total_count: 0,
|
|
||||||
current_position: 0,
|
|
||||||
profile_tree: ProfileTreeResponse::default(),
|
profile_tree: ProfileTreeResponse::default(),
|
||||||
selected_profile: None,
|
selected_profile: None,
|
||||||
|
current_view_profile_name: None,
|
||||||
|
current_view_table_name: None,
|
||||||
current_mode: AppMode::General,
|
current_mode: AppMode::General,
|
||||||
|
schema_cache: HashMap::new(), // NEW: Initialize the cache
|
||||||
focused_button_index: 0,
|
focused_button_index: 0,
|
||||||
pending_table_structure_fetch: None,
|
pending_table_structure_fetch: None,
|
||||||
|
search_state: None,
|
||||||
ui: UiState::default(),
|
ui: UiState::default(),
|
||||||
|
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
debug_state: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Existing methods remain unchanged
|
// --- ALL YOUR EXISTING METHODS ARE UNTOUCHED ---
|
||||||
pub fn update_total_count(&mut self, total_count: u64) {
|
|
||||||
self.total_count = total_count;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_current_position(&mut self, current_position: u64) {
|
|
||||||
self.current_position = current_position;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_mode(&mut self, mode: AppMode) {
|
pub fn update_mode(&mut self, mode: AppMode) {
|
||||||
self.current_mode = mode;
|
self.current_mode = mode;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add dialog helper methods
|
pub fn set_current_view_table(&mut self, profile_name: String, table_name: String) {
|
||||||
/// Shows a dialog with the given title, message, and buttons.
|
self.current_view_profile_name = Some(profile_name);
|
||||||
/// The first button (index 0) is active by default.
|
self.current_view_table_name = Some(table_name);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn show_dialog(
|
pub fn show_dialog(
|
||||||
&mut self,
|
&mut self,
|
||||||
title: &str,
|
title: &str,
|
||||||
@@ -96,19 +120,17 @@ impl AppState {
|
|||||||
self.ui.focus_outside_canvas = true;
|
self.ui.focus_outside_canvas = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shows a dialog specifically for loading states.
|
|
||||||
pub fn show_loading_dialog(&mut self, title: &str, message: &str) {
|
pub fn show_loading_dialog(&mut self, title: &str, message: &str) {
|
||||||
self.ui.dialog.dialog_title = title.to_string();
|
self.ui.dialog.dialog_title = title.to_string();
|
||||||
self.ui.dialog.dialog_message = message.to_string();
|
self.ui.dialog.dialog_message = message.to_string();
|
||||||
self.ui.dialog.dialog_buttons.clear(); // No buttons during loading
|
self.ui.dialog.dialog_buttons.clear();
|
||||||
self.ui.dialog.dialog_active_button_index = 0;
|
self.ui.dialog.dialog_active_button_index = 0;
|
||||||
self.ui.dialog.purpose = None; // Purpose is set when loading finishes
|
self.ui.dialog.purpose = None;
|
||||||
self.ui.dialog.is_loading = true;
|
self.ui.dialog.is_loading = true;
|
||||||
self.ui.dialog.dialog_show = true;
|
self.ui.dialog.dialog_show = true;
|
||||||
self.ui.focus_outside_canvas = true; // Keep focus management consistent
|
self.ui.focus_outside_canvas = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates the content of an existing dialog, typically after loading.
|
|
||||||
pub fn update_dialog_content(
|
pub fn update_dialog_content(
|
||||||
&mut self,
|
&mut self,
|
||||||
message: &str,
|
message: &str,
|
||||||
@@ -118,16 +140,12 @@ impl AppState {
|
|||||||
if self.ui.dialog.dialog_show {
|
if self.ui.dialog.dialog_show {
|
||||||
self.ui.dialog.dialog_message = message.to_string();
|
self.ui.dialog.dialog_message = message.to_string();
|
||||||
self.ui.dialog.dialog_buttons = buttons;
|
self.ui.dialog.dialog_buttons = buttons;
|
||||||
self.ui.dialog.dialog_active_button_index = 0; // Reset focus
|
self.ui.dialog.dialog_active_button_index = 0;
|
||||||
self.ui.dialog.purpose = Some(purpose);
|
self.ui.dialog.purpose = Some(purpose);
|
||||||
self.ui.dialog.is_loading = false; // Loading finished
|
self.ui.dialog.is_loading = false;
|
||||||
// Keep dialog_show = true
|
|
||||||
// Keep focus_outside_canvas = true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Hides the dialog and clears its content.
|
|
||||||
pub fn hide_dialog(&mut self) {
|
pub fn hide_dialog(&mut self) {
|
||||||
self.ui.dialog.dialog_show = false;
|
self.ui.dialog.dialog_show = false;
|
||||||
self.ui.dialog.dialog_title.clear();
|
self.ui.dialog.dialog_title.clear();
|
||||||
@@ -136,32 +154,30 @@ impl AppState {
|
|||||||
self.ui.dialog.dialog_active_button_index = 0;
|
self.ui.dialog.dialog_active_button_index = 0;
|
||||||
self.ui.dialog.purpose = None;
|
self.ui.dialog.purpose = None;
|
||||||
self.ui.focus_outside_canvas = false;
|
self.ui.focus_outside_canvas = false;
|
||||||
|
self.ui.dialog.is_loading = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the active button index, wrapping around if necessary.
|
|
||||||
pub fn next_dialog_button(&mut self) {
|
pub fn next_dialog_button(&mut self) {
|
||||||
if !self.ui.dialog.dialog_buttons.is_empty() {
|
if !self.ui.dialog.dialog_buttons.is_empty() {
|
||||||
let next_index = (self.ui.dialog.dialog_active_button_index + 1)
|
let next_index = (self.ui.dialog.dialog_active_button_index + 1)
|
||||||
% self.ui.dialog.dialog_buttons.len();
|
% self.ui.dialog.dialog_buttons.len();
|
||||||
self.ui.dialog.dialog_active_button_index = next_index; // Use new name
|
self.ui.dialog.dialog_active_button_index = next_index;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the active button index, wrapping around if necessary.
|
|
||||||
pub fn previous_dialog_button(&mut self) {
|
pub fn previous_dialog_button(&mut self) {
|
||||||
if !self.ui.dialog.dialog_buttons.is_empty() {
|
if !self.ui.dialog.dialog_buttons.is_empty() {
|
||||||
let len = self.ui.dialog.dialog_buttons.len();
|
let len = self.ui.dialog.dialog_buttons.len();
|
||||||
let prev_index =
|
let prev_index =
|
||||||
(self.ui.dialog.dialog_active_button_index + len - 1) % len;
|
(self.ui.dialog.dialog_active_button_index + len - 1) % len;
|
||||||
self.ui.dialog.dialog_active_button_index = prev_index; // Use new name
|
self.ui.dialog.dialog_active_button_index = prev_index;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the label of the currently active button, if any.
|
|
||||||
pub fn get_active_dialog_button_label(&self) -> Option<&str> {
|
pub fn get_active_dialog_button_label(&self) -> Option<&str> {
|
||||||
self.ui.dialog
|
self.ui.dialog
|
||||||
.dialog_buttons // Use new name
|
.dialog_buttons
|
||||||
.get(self.ui.dialog.dialog_active_button_index) // Use new name
|
.get(self.ui.dialog.dialog_active_button_index)
|
||||||
.map(|s| s.as_str())
|
.map(|s| s.as_str())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,13 +194,13 @@ impl Default for UiState {
|
|||||||
show_login: false,
|
show_login: false,
|
||||||
show_register: false,
|
show_register: false,
|
||||||
show_buffer_list: true,
|
show_buffer_list: true,
|
||||||
|
show_search_palette: false, // ADDED
|
||||||
focus_outside_canvas: false,
|
focus_outside_canvas: false,
|
||||||
dialog: DialogState::default(),
|
dialog: DialogState::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the Default implementation for DialogState itself
|
|
||||||
impl Default for DialogState {
|
impl Default for DialogState {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
// src/state/canvas_state.rs
|
// src/state/pages/canvas_state.rs
|
||||||
|
|
||||||
|
use common::proto::multieko2::search::search_response::Hit;
|
||||||
|
|
||||||
pub trait CanvasState {
|
pub trait CanvasState {
|
||||||
|
// --- Existing methods (unchanged) ---
|
||||||
fn current_field(&self) -> usize;
|
fn current_field(&self) -> usize;
|
||||||
fn current_cursor_pos(&self) -> usize;
|
fn current_cursor_pos(&self) -> usize;
|
||||||
fn has_unsaved_changes(&self) -> bool;
|
fn has_unsaved_changes(&self) -> bool;
|
||||||
@@ -9,12 +11,22 @@ pub trait CanvasState {
|
|||||||
fn get_current_input(&self) -> &str;
|
fn get_current_input(&self) -> &str;
|
||||||
fn get_current_input_mut(&mut self) -> &mut String;
|
fn get_current_input_mut(&mut self) -> &mut String;
|
||||||
fn fields(&self) -> Vec<&str>;
|
fn fields(&self) -> Vec<&str>;
|
||||||
|
|
||||||
fn set_current_field(&mut self, index: usize);
|
fn set_current_field(&mut self, index: usize);
|
||||||
fn set_current_cursor_pos(&mut self, pos: usize);
|
fn set_current_cursor_pos(&mut self, pos: usize);
|
||||||
fn set_has_unsaved_changes(&mut self, changed: bool);
|
fn set_has_unsaved_changes(&mut self, changed: bool);
|
||||||
|
|
||||||
// --- Autocomplete Support ---
|
|
||||||
fn get_suggestions(&self) -> Option<&[String]>;
|
fn get_suggestions(&self) -> Option<&[String]>;
|
||||||
fn get_selected_suggestion_index(&self) -> Option<usize>;
|
fn get_selected_suggestion_index(&self) -> Option<usize>;
|
||||||
|
fn get_rich_suggestions(&self) -> Option<&[Hit]> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_display_value_for_field(&self, index: usize) -> &str {
|
||||||
|
self.inputs()
|
||||||
|
.get(index)
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
}
|
||||||
|
fn has_display_override(&self, _index: usize) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,109 @@
|
|||||||
// src/state/pages/form.rs
|
// src/state/pages/form.rs
|
||||||
|
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
use ratatui::layout::Rect;
|
|
||||||
use ratatui::Frame;
|
|
||||||
use crate::state::app::highlight::HighlightState;
|
use crate::state::app::highlight::HighlightState;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
|
use common::proto::multieko2::search::search_response::Hit;
|
||||||
|
use ratatui::layout::Rect;
|
||||||
|
use ratatui::Frame;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
fn json_value_to_string(value: &serde_json::Value) -> String {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::String(s) => s.clone(),
|
||||||
|
serde_json::Value::Number(n) => n.to_string(),
|
||||||
|
serde_json::Value::Bool(b) => b.to_string(),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FieldDefinition {
|
||||||
|
pub display_name: String,
|
||||||
|
pub data_key: String,
|
||||||
|
pub is_link: bool,
|
||||||
|
pub link_target_table: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct FormState {
|
pub struct FormState {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub fields: Vec<String>,
|
pub profile_name: String,
|
||||||
|
pub table_name: String,
|
||||||
|
pub total_count: u64,
|
||||||
|
pub current_position: u64,
|
||||||
|
pub fields: Vec<FieldDefinition>,
|
||||||
pub values: Vec<String>,
|
pub values: Vec<String>,
|
||||||
pub current_field: usize,
|
pub current_field: usize,
|
||||||
pub has_unsaved_changes: bool,
|
pub has_unsaved_changes: bool,
|
||||||
pub current_cursor_pos: usize,
|
pub current_cursor_pos: usize,
|
||||||
|
pub autocomplete_active: bool,
|
||||||
|
pub autocomplete_suggestions: Vec<Hit>,
|
||||||
|
pub selected_suggestion_index: Option<usize>,
|
||||||
|
pub autocomplete_loading: bool,
|
||||||
|
pub link_display_map: HashMap<usize, String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FormState {
|
impl FormState {
|
||||||
/// Create a new FormState with dynamic fields.
|
pub fn new(
|
||||||
pub fn new(fields: Vec<String>) -> Self {
|
profile_name: String,
|
||||||
let values = vec![String::new(); fields.len()]; // Initialize values for each field
|
table_name: String,
|
||||||
|
fields: Vec<FieldDefinition>,
|
||||||
|
) -> Self {
|
||||||
|
let values = vec![String::new(); fields.len()];
|
||||||
FormState {
|
FormState {
|
||||||
id: 0,
|
id: 0,
|
||||||
|
profile_name,
|
||||||
|
table_name,
|
||||||
|
total_count: 0,
|
||||||
|
current_position: 1,
|
||||||
fields,
|
fields,
|
||||||
values,
|
values,
|
||||||
current_field: 0,
|
current_field: 0,
|
||||||
has_unsaved_changes: false,
|
has_unsaved_changes: false,
|
||||||
current_cursor_pos: 0,
|
current_cursor_pos: 0,
|
||||||
|
autocomplete_active: false,
|
||||||
|
autocomplete_suggestions: Vec::new(),
|
||||||
|
selected_suggestion_index: None,
|
||||||
|
autocomplete_loading: false,
|
||||||
|
link_display_map: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_display_name_for_hit(&self, hit: &Hit) -> String {
|
||||||
|
if let Ok(content_map) =
|
||||||
|
serde_json::from_str::<HashMap<String, serde_json::Value>>(
|
||||||
|
&hit.content_json,
|
||||||
|
)
|
||||||
|
{
|
||||||
|
const IGNORED_KEYS: &[&str] = &["id", "deleted", "created_at"];
|
||||||
|
let mut keys: Vec<_> = content_map
|
||||||
|
.keys()
|
||||||
|
.filter(|k| !IGNORED_KEYS.contains(&k.as_str()))
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
keys.sort();
|
||||||
|
|
||||||
|
let values: Vec<_> = keys
|
||||||
|
.iter()
|
||||||
|
.map(|key| {
|
||||||
|
content_map
|
||||||
|
.get(key)
|
||||||
|
.map(json_value_to_string)
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.take(1)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let display_part = values.first().cloned().unwrap_or_default();
|
||||||
|
if display_part.is_empty() {
|
||||||
|
format!("ID: {}", hit.id)
|
||||||
|
} else {
|
||||||
|
format!("{} | ID: {}", display_part, hit.id)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
format!("ID: {} (parse error)", hit.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,31 +114,40 @@ impl FormState {
|
|||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
is_edit_mode: bool,
|
is_edit_mode: bool,
|
||||||
highlight_state: &HighlightState,
|
highlight_state: &HighlightState,
|
||||||
total_count: u64,
|
|
||||||
current_position: u64,
|
|
||||||
) {
|
) {
|
||||||
let fields: Vec<&str> = self.fields.iter().map(|s| s.as_str()).collect();
|
let fields_str_slice: Vec<&str> =
|
||||||
let values: Vec<&String> = self.values.iter().collect();
|
self.fields().iter().map(|s| *s).collect();
|
||||||
|
let values_str_slice: Vec<&String> = self.values.iter().collect();
|
||||||
|
|
||||||
crate::components::form::form::render_form(
|
crate::components::form::form::render_form(
|
||||||
f,
|
f,
|
||||||
area,
|
area,
|
||||||
self,
|
self,
|
||||||
&fields,
|
&fields_str_slice,
|
||||||
&self.current_field,
|
&self.current_field,
|
||||||
&values,
|
&values_str_slice,
|
||||||
|
&self.table_name,
|
||||||
theme,
|
theme,
|
||||||
is_edit_mode,
|
is_edit_mode,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
total_count,
|
self.total_count,
|
||||||
current_position,
|
self.current_position,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reset_to_empty(&mut self) {
|
pub fn reset_to_empty(&mut self) {
|
||||||
self.id = 0; // Reset ID to 0 for new entries
|
self.id = 0;
|
||||||
self.values.iter_mut().for_each(|v| v.clear()); // Clear all values
|
self.values.iter_mut().for_each(|v| v.clear());
|
||||||
|
self.current_field = 0;
|
||||||
|
self.current_cursor_pos = 0;
|
||||||
self.has_unsaved_changes = false;
|
self.has_unsaved_changes = false;
|
||||||
|
if self.total_count > 0 {
|
||||||
|
self.current_position = self.total_count + 1;
|
||||||
|
} else {
|
||||||
|
self.current_position = 1;
|
||||||
|
}
|
||||||
|
self.deactivate_autocomplete();
|
||||||
|
self.link_display_map.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_current_input(&self) -> &str {
|
pub fn get_current_input(&self) -> &str {
|
||||||
@@ -70,20 +158,62 @@ impl FormState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_current_input_mut(&mut self) -> &mut String {
|
pub fn get_current_input_mut(&mut self) -> &mut String {
|
||||||
|
self.link_display_map.remove(&self.current_field);
|
||||||
self.values
|
self.values
|
||||||
.get_mut(self.current_field)
|
.get_mut(self.current_field)
|
||||||
.expect("Invalid current_field index")
|
.expect("Invalid current_field index")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_from_response(&mut self, response: common::proto::multieko2::adresar::AdresarResponse) {
|
pub fn update_from_response(
|
||||||
self.id = response.id;
|
&mut self,
|
||||||
self.values = vec![
|
response_data: &HashMap<String, String>,
|
||||||
response.firma, response.kz, response.drc,
|
new_position: u64,
|
||||||
response.ulica, response.psc, response.mesto,
|
) {
|
||||||
response.stat, response.banka, response.ucet,
|
self.values = self
|
||||||
response.skladm, response.ico, response.kontakt,
|
.fields
|
||||||
response.telefon, response.skladu, response.fax,
|
.iter()
|
||||||
];
|
.map(|field_def| {
|
||||||
|
response_data
|
||||||
|
.get(&field_def.data_key)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let id_str_opt = response_data
|
||||||
|
.iter()
|
||||||
|
.find(|(k, _)| k.eq_ignore_ascii_case("id"))
|
||||||
|
.map(|(_, v)| v);
|
||||||
|
|
||||||
|
if let Some(id_str) = id_str_opt {
|
||||||
|
if let Ok(parsed_id) = id_str.parse::<i64>() {
|
||||||
|
self.id = parsed_id;
|
||||||
|
} else {
|
||||||
|
tracing::error!(
|
||||||
|
"Failed to parse 'id' field '{}' for table {}.{}",
|
||||||
|
id_str,
|
||||||
|
self.profile_name,
|
||||||
|
self.table_name
|
||||||
|
);
|
||||||
|
self.id = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.id = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.current_position = new_position;
|
||||||
|
self.has_unsaved_changes = false;
|
||||||
|
self.current_field = 0;
|
||||||
|
self.current_cursor_pos = 0;
|
||||||
|
self.deactivate_autocomplete();
|
||||||
|
self.link_display_map.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deactivate_autocomplete(&mut self) {
|
||||||
|
self.autocomplete_active = false;
|
||||||
|
self.autocomplete_suggestions.clear();
|
||||||
|
self.selected_suggestion_index = None;
|
||||||
|
self.autocomplete_loading = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,58 +221,69 @@ impl CanvasState for FormState {
|
|||||||
fn current_field(&self) -> usize {
|
fn current_field(&self) -> usize {
|
||||||
self.current_field
|
self.current_field
|
||||||
}
|
}
|
||||||
|
|
||||||
fn current_cursor_pos(&self) -> usize {
|
fn current_cursor_pos(&self) -> usize {
|
||||||
self.current_cursor_pos
|
self.current_cursor_pos
|
||||||
}
|
}
|
||||||
|
|
||||||
fn has_unsaved_changes(&self) -> bool {
|
fn has_unsaved_changes(&self) -> bool {
|
||||||
self.has_unsaved_changes
|
self.has_unsaved_changes
|
||||||
}
|
}
|
||||||
|
|
||||||
fn inputs(&self) -> Vec<&String> {
|
fn inputs(&self) -> Vec<&String> {
|
||||||
self.values.iter().collect()
|
self.values.iter().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_current_input(&self) -> &str {
|
fn get_current_input(&self) -> &str {
|
||||||
self.values
|
FormState::get_current_input(self)
|
||||||
.get(self.current_field)
|
}
|
||||||
|
fn get_current_input_mut(&mut self) -> &mut String {
|
||||||
|
FormState::get_current_input_mut(self)
|
||||||
|
}
|
||||||
|
fn fields(&self) -> Vec<&str> {
|
||||||
|
self.fields
|
||||||
|
.iter()
|
||||||
|
.map(|f| f.display_name.as_str())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
fn set_current_field(&mut self, index: usize) {
|
||||||
|
if index < self.fields.len() {
|
||||||
|
self.current_field = index;
|
||||||
|
}
|
||||||
|
self.deactivate_autocomplete();
|
||||||
|
}
|
||||||
|
fn set_current_cursor_pos(&mut self, pos: usize) {
|
||||||
|
self.current_cursor_pos = pos;
|
||||||
|
}
|
||||||
|
fn set_has_unsaved_changes(&mut self, changed: bool) {
|
||||||
|
self.has_unsaved_changes = changed;
|
||||||
|
}
|
||||||
|
fn get_suggestions(&self) -> Option<&[String]> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
fn get_rich_suggestions(&self) -> Option<&[Hit]> {
|
||||||
|
if self.autocomplete_active {
|
||||||
|
Some(&self.autocomplete_suggestions)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn get_selected_suggestion_index(&self) -> Option<usize> {
|
||||||
|
if self.autocomplete_active {
|
||||||
|
self.selected_suggestion_index
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_display_value_for_field(&self, index: usize) -> &str {
|
||||||
|
if let Some(display_text) = self.link_display_map.get(&index) {
|
||||||
|
return display_text.as_str();
|
||||||
|
}
|
||||||
|
self.inputs()
|
||||||
|
.get(index)
|
||||||
.map(|s| s.as_str())
|
.map(|s| s.as_str())
|
||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_current_input_mut(&mut self) -> &mut String {
|
// --- IMPLEMENT THE NEW TRAIT METHOD ---
|
||||||
self.values
|
fn has_display_override(&self, index: usize) -> bool {
|
||||||
.get_mut(self.current_field)
|
self.link_display_map.contains_key(&index)
|
||||||
.expect("Invalid current_field index")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fields(&self) -> Vec<&str> {
|
|
||||||
self.fields.iter().map(|s| s.as_str()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Implement the setter methods ---
|
|
||||||
fn set_current_field(&mut self, index: usize) {
|
|
||||||
if index < self.fields.len() { // Basic bounds check
|
|
||||||
self.current_field = index;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_current_cursor_pos(&mut self, pos: usize) {
|
|
||||||
// Optional: Add validation based on current input length if needed
|
|
||||||
self.current_cursor_pos = pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_has_unsaved_changes(&mut self, changed: bool) {
|
|
||||||
self.has_unsaved_changes = changed;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Autocomplete Support (Not Used for FormState) ---
|
|
||||||
fn get_suggestions(&self) -> Option<&[String]> {
|
|
||||||
None // FormState doesn't provide suggestions
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_selected_suggestion_index(&self) -> Option<usize> {
|
|
||||||
None // FormState doesn't have selected suggestions
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,115 +1,156 @@
|
|||||||
// src/tui/functions/common/form.rs
|
// src/tui/functions/common/form.rs
|
||||||
|
|
||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
|
use crate::state::app::state::AppState; // NEW: Import AppState
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use common::proto::multieko2::adresar::{PostAdresarRequest, PutAdresarRequest};
|
use crate::utils::data_converter; // NEW: Import our translator
|
||||||
use anyhow::Result;
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum SaveOutcome {
|
pub enum SaveOutcome {
|
||||||
NoChange, // Nothing needed saving
|
NoChange,
|
||||||
UpdatedExisting, // An existing record was updated
|
UpdatedExisting,
|
||||||
CreatedNew(i64), // A new record was created (include its new ID)
|
CreatedNew(i64),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shared logic for saving the current form state
|
// MODIFIED save function signature and logic
|
||||||
pub async fn save(
|
pub async fn save(
|
||||||
|
app_state: &AppState, // NEW: Pass in AppState
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
) -> Result<SaveOutcome> {
|
||||||
total_count: u64,
|
|
||||||
) -> Result<SaveOutcome> { // <-- Return SaveOutcome
|
|
||||||
if !form_state.has_unsaved_changes {
|
if !form_state.has_unsaved_changes {
|
||||||
return Ok(SaveOutcome::NoChange); // Early exit if no changes
|
return Ok(SaveOutcome::NoChange);
|
||||||
}
|
}
|
||||||
let is_new = *current_position == total_count + 1;
|
|
||||||
|
|
||||||
let outcome = if is_new {
|
// --- NEW: VALIDATION & CONVERSION STEP ---
|
||||||
let post_request = PostAdresarRequest {
|
let cache_key =
|
||||||
firma: form_state.values[0].clone(),
|
format!("{}.{}", form_state.profile_name, form_state.table_name);
|
||||||
kz: form_state.values[1].clone(),
|
let schema = match app_state.schema_cache.get(&cache_key) {
|
||||||
drc: form_state.values[2].clone(),
|
Some(s) => s,
|
||||||
ulica: form_state.values[3].clone(),
|
None => {
|
||||||
psc: form_state.values[4].clone(),
|
return Err(anyhow!(
|
||||||
mesto: form_state.values[5].clone(),
|
"Schema for table '{}' not found in cache. Cannot save.",
|
||||||
stat: form_state.values[6].clone(),
|
form_state.table_name
|
||||||
banka: form_state.values[7].clone(),
|
));
|
||||||
ucet: form_state.values[8].clone(),
|
}
|
||||||
skladm: form_state.values[9].clone(),
|
|
||||||
ico: form_state.values[10].clone(),
|
|
||||||
kontakt: form_state.values[11].clone(),
|
|
||||||
telefon: form_state.values[12].clone(),
|
|
||||||
skladu: form_state.values[13].clone(),
|
|
||||||
fax: form_state.values[14].clone(),
|
|
||||||
};
|
|
||||||
let response = grpc_client.post_adresar(post_request).await?;
|
|
||||||
let new_id = response.into_inner().id;
|
|
||||||
form_state.id = new_id;
|
|
||||||
SaveOutcome::CreatedNew(new_id) // <-- Return CreatedNew with ID
|
|
||||||
} else {
|
|
||||||
let put_request = PutAdresarRequest {
|
|
||||||
id: form_state.id,
|
|
||||||
firma: form_state.values[0].clone(),
|
|
||||||
kz: form_state.values[1].clone(),
|
|
||||||
drc: form_state.values[2].clone(),
|
|
||||||
ulica: form_state.values[3].clone(),
|
|
||||||
psc: form_state.values[4].clone(),
|
|
||||||
mesto: form_state.values[5].clone(),
|
|
||||||
stat: form_state.values[6].clone(),
|
|
||||||
banka: form_state.values[7].clone(),
|
|
||||||
ucet: form_state.values[8].clone(),
|
|
||||||
skladm: form_state.values[9].clone(),
|
|
||||||
ico: form_state.values[10].clone(),
|
|
||||||
kontakt: form_state.values[11].clone(),
|
|
||||||
telefon: form_state.values[12].clone(),
|
|
||||||
skladu: form_state.values[13].clone(),
|
|
||||||
fax: form_state.values[14].clone(),
|
|
||||||
};
|
|
||||||
let _ = grpc_client.put_adresar(put_request).await?;
|
|
||||||
SaveOutcome::UpdatedExisting
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let data_map: HashMap<String, String> = form_state
|
||||||
|
.fields
|
||||||
|
.iter()
|
||||||
|
.zip(form_state.values.iter())
|
||||||
|
.map(|(field_def, value)| (field_def.data_key.clone(), value.clone()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Use our new translator. It returns a user-friendly error on failure.
|
||||||
|
let converted_data =
|
||||||
|
match data_converter::convert_and_validate_data(&data_map, schema) {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(user_error) => return Err(anyhow!(user_error)),
|
||||||
|
};
|
||||||
|
// --- END OF NEW STEP ---
|
||||||
|
|
||||||
|
let outcome: SaveOutcome;
|
||||||
|
let is_new_entry = form_state.id == 0
|
||||||
|
|| (form_state.total_count > 0
|
||||||
|
&& form_state.current_position > form_state.total_count)
|
||||||
|
|| (form_state.total_count == 0 && form_state.current_position == 1);
|
||||||
|
|
||||||
|
if is_new_entry {
|
||||||
|
let response = grpc_client
|
||||||
|
.post_table_data(
|
||||||
|
form_state.profile_name.clone(),
|
||||||
|
form_state.table_name.clone(),
|
||||||
|
converted_data, // Use the validated & converted data
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("Failed to post new table data")?;
|
||||||
|
|
||||||
|
if response.success {
|
||||||
|
form_state.id = response.inserted_id;
|
||||||
|
form_state.total_count += 1;
|
||||||
|
form_state.current_position = form_state.total_count;
|
||||||
|
outcome = SaveOutcome::CreatedNew(response.inserted_id);
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"Server failed to insert data: {}",
|
||||||
|
response.message
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if form_state.id == 0 {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"Cannot update record: ID is 0, but not classified as new entry."
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let response = grpc_client
|
||||||
|
.put_table_data(
|
||||||
|
form_state.profile_name.clone(),
|
||||||
|
form_state.table_name.clone(),
|
||||||
|
form_state.id,
|
||||||
|
converted_data, // Use the validated & converted data
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("Failed to put (update) table data")?;
|
||||||
|
|
||||||
|
if response.success {
|
||||||
|
outcome = SaveOutcome::UpdatedExisting;
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"Server failed to update data: {}",
|
||||||
|
response.message
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
form_state.has_unsaved_changes = false;
|
form_state.has_unsaved_changes = false;
|
||||||
Ok(outcome)
|
Ok(outcome)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Discard changes since last save
|
|
||||||
pub async fn revert(
|
pub async fn revert(
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState, // Takes &mut FormState to update it
|
||||||
grpc_client: &mut GrpcClient,
|
grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let is_new = *current_position == total_count + 1;
|
if form_state.id == 0 || (form_state.total_count > 0 && form_state.current_position > form_state.total_count) || (form_state.total_count == 0 && form_state.current_position == 1) {
|
||||||
|
let old_total_count = form_state.total_count; // Preserve for correct new position
|
||||||
if is_new {
|
form_state.reset_to_empty(); // reset_to_empty will clear values and set id=0
|
||||||
// Clear all fields for new entries
|
form_state.total_count = old_total_count; // Restore total_count
|
||||||
form_state.values.iter_mut().for_each(|v| *v = String::new());
|
if form_state.total_count > 0 { // Correctly set current_position for new
|
||||||
form_state.has_unsaved_changes = false;
|
form_state.current_position = form_state.total_count + 1;
|
||||||
|
} else {
|
||||||
|
form_state.current_position = 1;
|
||||||
|
}
|
||||||
return Ok("New entry cleared".to_string());
|
return Ok("New entry cleared".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = grpc_client.get_adresar_by_position(*current_position).await?;
|
if form_state.current_position == 0 || form_state.current_position > form_state.total_count {
|
||||||
|
if form_state.total_count > 0 {
|
||||||
|
form_state.current_position = 1;
|
||||||
|
} else {
|
||||||
|
// No records to revert to, effectively a new entry state.
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
return Ok("No saved data to revert to; form cleared.".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Update form fields with saved values
|
let response = grpc_client
|
||||||
form_state.values = vec![
|
.get_table_data_by_position(
|
||||||
data.firma,
|
form_state.profile_name.clone(),
|
||||||
data.kz,
|
form_state.table_name.clone(),
|
||||||
data.drc,
|
form_state.current_position as i32,
|
||||||
data.ulica,
|
)
|
||||||
data.psc,
|
.await
|
||||||
data.mesto,
|
.context(format!(
|
||||||
data.stat,
|
"Failed to get table data by position {} for table {}.{}",
|
||||||
data.banka,
|
form_state.current_position,
|
||||||
data.ucet,
|
form_state.profile_name,
|
||||||
data.skladm,
|
form_state.table_name
|
||||||
data.ico,
|
))?;
|
||||||
data.kontakt,
|
|
||||||
data.telefon,
|
|
||||||
data.skladu,
|
|
||||||
data.fax,
|
|
||||||
];
|
|
||||||
|
|
||||||
form_state.has_unsaved_changes = false;
|
// FIX: Pass the current position as the second argument
|
||||||
|
form_state.update_from_response(&response.data, form_state.current_position);
|
||||||
Ok("Changes discarded, reloaded last saved version".to_string())
|
Ok("Changes discarded, reloaded last saved version".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,15 @@
|
|||||||
// src/tui/functions/form.rs
|
// src/tui/functions/form.rs
|
||||||
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::FormState;
|
||||||
use crate::services::grpc_client::GrpcClient;
|
use crate::services::grpc_client::GrpcClient;
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
|
|
||||||
pub async fn handle_action(
|
pub async fn handle_action(
|
||||||
action: &str,
|
action: &str,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
grpc_client: &mut GrpcClient,
|
_grpc_client: &mut GrpcClient,
|
||||||
current_position: &mut u64,
|
|
||||||
total_count: u64,
|
|
||||||
ideal_cursor_column: &mut usize,
|
ideal_cursor_column: &mut usize,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
// TODO store unsaved changes without deleting form state values
|
|
||||||
// First check for unsaved changes in both cases
|
|
||||||
if form_state.has_unsaved_changes() {
|
if form_state.has_unsaved_changes() {
|
||||||
return Ok(
|
return Ok(
|
||||||
"Unsaved changes. Save (Ctrl+S) or Revert (Ctrl+R) before navigating."
|
"Unsaved changes. Save (Ctrl+S) or Revert (Ctrl+R) before navigating."
|
||||||
@@ -21,71 +17,29 @@ pub async fn handle_action(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let total_count = form_state.total_count;
|
||||||
|
|
||||||
match action {
|
match action {
|
||||||
"previous_entry" => {
|
"previous_entry" => {
|
||||||
let new_position = current_position.saturating_sub(1);
|
// Only decrement if the current position is greater than the first record.
|
||||||
if new_position >= 1 {
|
// This prevents wrapping from 1 to total_count.
|
||||||
*current_position = new_position;
|
// It also correctly handles moving from "New Entry" (total_count + 1) to the last record.
|
||||||
let response = grpc_client.get_adresar_by_position(*current_position).await?;
|
if form_state.current_position > 1 {
|
||||||
|
form_state.current_position -= 1;
|
||||||
// Direct field assignments
|
*ideal_cursor_column = 0;
|
||||||
form_state.id = response.id;
|
|
||||||
form_state.values = vec![
|
|
||||||
response.firma, response.kz, response.drc,
|
|
||||||
response.ulica, response.psc, response.mesto,
|
|
||||||
response.stat, response.banka, response.ucet,
|
|
||||||
response.skladm, response.ico, response.kontakt,
|
|
||||||
response.telefon, response.skladu, response.fax,
|
|
||||||
];
|
|
||||||
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else { 0 };
|
|
||||||
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
|
|
||||||
form_state.has_unsaved_changes = false;
|
|
||||||
|
|
||||||
Ok(format!("Loaded form entry {}", *current_position))
|
|
||||||
} else {
|
|
||||||
Ok("Already at first form entry".into())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"next_entry" => {
|
"next_entry" => {
|
||||||
if *current_position <= total_count {
|
// Only increment if the current position is not yet at the "New Entry" stage.
|
||||||
*current_position += 1;
|
// The "New Entry" position is total_count + 1.
|
||||||
if *current_position <= total_count {
|
// This allows moving from the last record to "New Entry", but stops there.
|
||||||
let response = grpc_client.get_adresar_by_position(*current_position).await?;
|
if form_state.current_position <= total_count {
|
||||||
|
form_state.current_position += 1;
|
||||||
// Direct field assignments
|
*ideal_cursor_column = 0;
|
||||||
form_state.id = response.id;
|
|
||||||
form_state.values = vec![
|
|
||||||
response.firma, response.kz, response.drc,
|
|
||||||
response.ulica, response.psc, response.mesto,
|
|
||||||
response.stat, response.banka, response.ucet,
|
|
||||||
response.skladm, response.ico, response.kontakt,
|
|
||||||
response.telefon, response.skladu, response.fax,
|
|
||||||
];
|
|
||||||
|
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() {
|
|
||||||
current_input.len() - 1
|
|
||||||
} else { 0 };
|
|
||||||
form_state.current_cursor_pos = std::cmp::min(*ideal_cursor_column, max_cursor_pos);
|
|
||||||
form_state.has_unsaved_changes = false;
|
|
||||||
|
|
||||||
Ok(format!("Loaded form entry {}", *current_position))
|
|
||||||
} else {
|
|
||||||
form_state.reset_to_empty();
|
|
||||||
form_state.current_field = 0;
|
|
||||||
form_state.current_cursor_pos = 0;
|
|
||||||
*ideal_cursor_column = 0;
|
|
||||||
Ok("New form entry mode".into())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Ok("Already at last entry".into())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => Err(anyhow!("Unknown form action: {}", action))
|
_ => return Err(anyhow!("Unknown form action: {}", action)),
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(String::new())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,4 +21,3 @@ pub enum DialogPurpose {
|
|||||||
// TODO in the future:
|
// TODO in the future:
|
||||||
// ConfirmQuit,
|
// ConfirmQuit,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// src/ui/handlers/rat_state.rs
|
// client/src/ui/handlers/rat_state.rs
|
||||||
use crossterm::event::{KeyCode, KeyModifiers};
|
use crossterm::event::{KeyCode, KeyModifiers};
|
||||||
use crate::config::binds::config::Config;
|
use crate::config::binds::config::Config;
|
||||||
use crate::state::app::state::UiState;
|
use crate::state::app::state::UiState;
|
||||||
|
|||||||
@@ -1,30 +1,38 @@
|
|||||||
// src/ui/handlers/render.rs
|
// src/ui/handlers/render.rs
|
||||||
|
|
||||||
use crate::components::{
|
use crate::components::{
|
||||||
|
admin::add_logic::render_add_logic,
|
||||||
|
admin::render_add_table,
|
||||||
|
auth::{login::render_login, register::render_register},
|
||||||
|
common::dialog::render_dialog,
|
||||||
|
common::find_file_palette,
|
||||||
|
common::search_palette::render_search_palette,
|
||||||
|
form::form::render_form,
|
||||||
|
handlers::sidebar::{self, calculate_sidebar_layout},
|
||||||
|
intro::intro::render_intro,
|
||||||
render_background,
|
render_background,
|
||||||
render_buffer_list,
|
render_buffer_list,
|
||||||
render_command_line,
|
render_command_line,
|
||||||
render_status_line,
|
render_status_line,
|
||||||
intro::intro::render_intro,
|
|
||||||
handlers::sidebar::{self, calculate_sidebar_layout},
|
|
||||||
form::form::render_form,
|
|
||||||
admin::render_add_table,
|
|
||||||
admin::add_logic::render_add_logic,
|
|
||||||
auth::{login::render_login, register::render_register},
|
|
||||||
};
|
};
|
||||||
use crate::config::colors::themes::Theme;
|
use crate::config::colors::themes::Theme;
|
||||||
use ratatui::layout::{Constraint, Direction, Layout};
|
use crate::modes::general::command_navigation::NavigationState;
|
||||||
use ratatui::Frame;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::app::buffer::BufferState;
|
||||||
|
use crate::state::app::highlight::HighlightState;
|
||||||
|
use crate::state::app::state::AppState;
|
||||||
|
use crate::state::pages::admin::AdminState;
|
||||||
use crate::state::pages::auth::AuthState;
|
use crate::state::pages::auth::AuthState;
|
||||||
use crate::state::pages::auth::LoginState;
|
use crate::state::pages::auth::LoginState;
|
||||||
use crate::state::pages::auth::RegisterState;
|
use crate::state::pages::auth::RegisterState;
|
||||||
|
use crate::state::pages::form::FormState;
|
||||||
use crate::state::pages::intro::IntroState;
|
use crate::state::pages::intro::IntroState;
|
||||||
use crate::state::app::buffer::BufferState;
|
use ratatui::{
|
||||||
use crate::state::app::state::AppState;
|
layout::{Constraint, Direction, Layout},
|
||||||
use crate::state::pages::admin::AdminState;
|
Frame,
|
||||||
use crate::state::app::highlight::HighlightState;
|
};
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub fn render_ui(
|
pub fn render_ui(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
form_state: &mut FormState,
|
form_state: &mut FormState,
|
||||||
@@ -35,56 +43,81 @@ pub fn render_ui(
|
|||||||
admin_state: &mut AdminState,
|
admin_state: &mut AdminState,
|
||||||
buffer_state: &BufferState,
|
buffer_state: &BufferState,
|
||||||
theme: &Theme,
|
theme: &Theme,
|
||||||
is_edit_mode: bool,
|
is_event_handler_edit_mode: bool,
|
||||||
highlight_state: &HighlightState,
|
highlight_state: &HighlightState,
|
||||||
total_count: u64,
|
event_handler_command_input: &str,
|
||||||
current_position: u64,
|
event_handler_command_mode_active: bool,
|
||||||
|
event_handler_command_message: &str,
|
||||||
|
navigation_state: &NavigationState,
|
||||||
current_dir: &str,
|
current_dir: &str,
|
||||||
command_input: &str,
|
|
||||||
command_mode: bool,
|
|
||||||
command_message: &str,
|
|
||||||
current_fps: f64,
|
current_fps: f64,
|
||||||
app_state: &AppState,
|
app_state: &AppState,
|
||||||
) {
|
) {
|
||||||
render_background(f, f.area(), theme);
|
render_background(f, f.area(), theme);
|
||||||
|
|
||||||
// Adjust layout based on whether buffer list is shown
|
// --- START DYNAMIC LAYOUT LOGIC ---
|
||||||
let constraints = if app_state.ui.show_buffer_list {
|
let mut status_line_height = 1;
|
||||||
vec![
|
#[cfg(feature = "ui-debug")]
|
||||||
Constraint::Length(1), // Buffer list
|
{
|
||||||
Constraint::Min(1), // Main content
|
if let Some(debug_state) = &app_state.debug_state {
|
||||||
Constraint::Length(1), // Status line
|
if debug_state.is_error {
|
||||||
Constraint::Length(1), // Command line
|
status_line_height = 4;
|
||||||
]
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- END DYNAMIC LAYOUT LOGIC ---
|
||||||
|
|
||||||
|
const PALETTE_OPTIONS_HEIGHT_FOR_LAYOUT: u16 = 15;
|
||||||
|
|
||||||
|
|
||||||
|
let mut bottom_area_constraints: Vec<Constraint> = vec![Constraint::Length(status_line_height)];
|
||||||
|
let command_palette_area_height = if navigation_state.active {
|
||||||
|
1 + PALETTE_OPTIONS_HEIGHT_FOR_LAYOUT
|
||||||
|
} else if event_handler_command_mode_active {
|
||||||
|
1
|
||||||
} else {
|
} else {
|
||||||
vec![
|
0
|
||||||
Constraint::Min(1), // Main content
|
|
||||||
Constraint::Length(1), // Status line (no buffer list)
|
|
||||||
Constraint::Length(1), // Command line
|
|
||||||
]
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let root = Layout::default()
|
if command_palette_area_height > 0 {
|
||||||
|
bottom_area_constraints.push(Constraint::Length(command_palette_area_height));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut main_layout_constraints = vec![Constraint::Min(1)];
|
||||||
|
if app_state.ui.show_buffer_list {
|
||||||
|
main_layout_constraints.insert(0, Constraint::Length(1));
|
||||||
|
}
|
||||||
|
main_layout_constraints.extend(bottom_area_constraints);
|
||||||
|
|
||||||
|
let root_chunks = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints(constraints)
|
.constraints(main_layout_constraints)
|
||||||
.split(f.area());
|
.split(f.area());
|
||||||
|
|
||||||
let mut buffer_list_area = None;
|
let mut chunk_idx = 0;
|
||||||
let main_content_area;
|
let buffer_list_area = if app_state.ui.show_buffer_list {
|
||||||
let status_line_area;
|
let area = Some(root_chunks[chunk_idx]);
|
||||||
let command_line_area;
|
chunk_idx += 1;
|
||||||
|
area
|
||||||
// Assign areas based on layout
|
|
||||||
if app_state.ui.show_buffer_list {
|
|
||||||
buffer_list_area = Some(root[0]);
|
|
||||||
main_content_area = root[1];
|
|
||||||
status_line_area = root[2];
|
|
||||||
command_line_area = root[3];
|
|
||||||
} else {
|
} else {
|
||||||
main_content_area = root[0];
|
None
|
||||||
status_line_area = root[1];
|
};
|
||||||
command_line_area = root[2];
|
|
||||||
}
|
let main_content_area = root_chunks[chunk_idx];
|
||||||
|
chunk_idx += 1;
|
||||||
|
|
||||||
|
let status_line_area = root_chunks[chunk_idx];
|
||||||
|
chunk_idx += 1;
|
||||||
|
|
||||||
|
let command_render_area = if command_palette_area_height > 0 {
|
||||||
|
if root_chunks.len() > chunk_idx {
|
||||||
|
Some(root_chunks[chunk_idx])
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
if app_state.ui.show_intro {
|
if app_state.ui.show_intro {
|
||||||
render_intro(f, intro_state, main_content_area, theme);
|
render_intro(f, intro_state, main_content_area, theme);
|
||||||
@@ -95,7 +128,7 @@ pub fn render_ui(
|
|||||||
theme,
|
theme,
|
||||||
register_state,
|
register_state,
|
||||||
app_state,
|
app_state,
|
||||||
register_state.current_field < 4,
|
register_state.current_field() < 4,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
);
|
);
|
||||||
} else if app_state.ui.show_add_table {
|
} else if app_state.ui.show_add_table {
|
||||||
@@ -105,7 +138,7 @@ pub fn render_ui(
|
|||||||
theme,
|
theme,
|
||||||
app_state,
|
app_state,
|
||||||
&mut admin_state.add_table_state,
|
&mut admin_state.add_table_state,
|
||||||
login_state.current_field < 3,
|
is_event_handler_edit_mode,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
);
|
);
|
||||||
} else if app_state.ui.show_add_logic {
|
} else if app_state.ui.show_add_logic {
|
||||||
@@ -115,7 +148,7 @@ pub fn render_ui(
|
|||||||
theme,
|
theme,
|
||||||
app_state,
|
app_state,
|
||||||
&mut admin_state.add_logic_state,
|
&mut admin_state.add_logic_state,
|
||||||
is_edit_mode, // Pass the general edit mode status
|
is_event_handler_edit_mode,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
);
|
);
|
||||||
} else if app_state.ui.show_login {
|
} else if app_state.ui.show_login {
|
||||||
@@ -125,7 +158,7 @@ pub fn render_ui(
|
|||||||
theme,
|
theme,
|
||||||
login_state,
|
login_state,
|
||||||
app_state,
|
app_state,
|
||||||
login_state.current_field < 2,
|
login_state.current_field() < 2,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
);
|
);
|
||||||
} else if app_state.ui.show_admin {
|
} else if app_state.ui.show_admin {
|
||||||
@@ -140,70 +173,92 @@ pub fn render_ui(
|
|||||||
&app_state.selected_profile,
|
&app_state.selected_profile,
|
||||||
);
|
);
|
||||||
} else if app_state.ui.show_form {
|
} else if app_state.ui.show_form {
|
||||||
let (sidebar_area, form_area) = calculate_sidebar_layout(
|
let (sidebar_area, form_actual_area) =
|
||||||
app_state.ui.show_sidebar,
|
calculate_sidebar_layout(app_state.ui.show_sidebar, main_content_area);
|
||||||
main_content_area
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Some(sidebar_rect) = sidebar_area {
|
if let Some(sidebar_rect) = sidebar_area {
|
||||||
sidebar::render_sidebar(
|
sidebar::render_sidebar(
|
||||||
f,
|
f,
|
||||||
sidebar_rect,
|
sidebar_rect,
|
||||||
theme,
|
theme,
|
||||||
&app_state.profile_tree,
|
&app_state.profile_tree,
|
||||||
&app_state.selected_profile
|
&app_state.selected_profile,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
let available_width = form_actual_area.width;
|
||||||
// This change makes the form stay stationary when toggling sidebar
|
let form_render_area = if available_width >= 80 {
|
||||||
let available_width = form_area.width;
|
|
||||||
let form_constraint = if available_width >= 80 {
|
|
||||||
// Use main_content_area for centering when enough space
|
|
||||||
Layout::default()
|
Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([Constraint::Min(0), Constraint::Length(80), Constraint::Min(0)])
|
||||||
Constraint::Min(0),
|
.split(form_actual_area)[1]
|
||||||
Constraint::Length(80),
|
|
||||||
Constraint::Min(0),
|
|
||||||
])
|
|
||||||
.split(main_content_area)[1]
|
|
||||||
} else {
|
} else {
|
||||||
// Use form_area (post sidebar) when limited space
|
|
||||||
Layout::default()
|
Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([
|
||||||
Constraint::Min(0),
|
Constraint::Min(0),
|
||||||
Constraint::Length(80.min(available_width)),
|
Constraint::Length(available_width),
|
||||||
Constraint::Min(0),
|
Constraint::Min(0),
|
||||||
])
|
])
|
||||||
.split(form_area)[1]
|
.split(form_actual_area)[1]
|
||||||
};
|
};
|
||||||
|
|
||||||
// Convert fields to &[&str] and values to &[&String]
|
form_state.render(
|
||||||
let fields: Vec<&str> = form_state.fields.iter().map(|s| s.as_str()).collect();
|
|
||||||
let values: Vec<&String> = form_state.values.iter().collect();
|
|
||||||
|
|
||||||
render_form(
|
|
||||||
f,
|
f,
|
||||||
form_constraint,
|
form_render_area,
|
||||||
form_state,
|
|
||||||
&fields,
|
|
||||||
&form_state.current_field,
|
|
||||||
&values,
|
|
||||||
theme,
|
theme,
|
||||||
is_edit_mode,
|
is_event_handler_edit_mode,
|
||||||
highlight_state,
|
highlight_state,
|
||||||
total_count,
|
|
||||||
current_position,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render buffer list if enabled and area is available
|
|
||||||
if let Some(area) = buffer_list_area {
|
if let Some(area) = buffer_list_area {
|
||||||
if app_state.ui.show_buffer_list {
|
render_buffer_list(f, area, theme, buffer_state, app_state);
|
||||||
render_buffer_list(f, area, theme, buffer_state, app_state);
|
}
|
||||||
|
|
||||||
|
render_status_line(
|
||||||
|
f,
|
||||||
|
status_line_area,
|
||||||
|
current_dir,
|
||||||
|
theme,
|
||||||
|
is_event_handler_edit_mode,
|
||||||
|
current_fps,
|
||||||
|
app_state,
|
||||||
|
);
|
||||||
|
|
||||||
|
if let Some(palette_or_command_area) = command_render_area {
|
||||||
|
if navigation_state.active {
|
||||||
|
find_file_palette::render_find_file_palette(
|
||||||
|
f,
|
||||||
|
palette_or_command_area,
|
||||||
|
theme,
|
||||||
|
navigation_state,
|
||||||
|
);
|
||||||
|
} else if event_handler_command_mode_active {
|
||||||
|
render_command_line(
|
||||||
|
f,
|
||||||
|
palette_or_command_area,
|
||||||
|
event_handler_command_input,
|
||||||
|
true,
|
||||||
|
theme,
|
||||||
|
event_handler_command_message,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
render_status_line(f, status_line_area, current_dir, theme, is_edit_mode, current_fps);
|
|
||||||
render_command_line(f, command_line_area, command_input, command_mode, theme, command_message);
|
// This block now correctly handles drawing popups over any view.
|
||||||
|
if app_state.ui.show_search_palette {
|
||||||
|
if let Some(search_state) = &app_state.search_state {
|
||||||
|
render_search_palette(f, f.area(), theme, search_state);
|
||||||
|
}
|
||||||
|
} else if app_state.ui.dialog.dialog_show {
|
||||||
|
render_dialog(
|
||||||
|
f,
|
||||||
|
f.area(),
|
||||||
|
theme,
|
||||||
|
&app_state.ui.dialog.dialog_title,
|
||||||
|
&app_state.ui.dialog.dialog_message,
|
||||||
|
&app_state.ui.dialog.dialog_buttons,
|
||||||
|
app_state.ui.dialog.dialog_active_button_index,
|
||||||
|
app_state.ui.dialog.is_loading,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use crate::modes::common::commands::CommandHandler;
|
|||||||
use crate::modes::handlers::event::{EventHandler, EventOutcome};
|
use crate::modes::handlers::event::{EventHandler, EventOutcome};
|
||||||
use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
|
use crate::modes::handlers::mode_manager::{AppMode, ModeManager};
|
||||||
use crate::state::pages::canvas_state::CanvasState;
|
use crate::state::pages::canvas_state::CanvasState;
|
||||||
use crate::state::pages::form::FormState;
|
use crate::state::pages::form::{FormState, FieldDefinition}; // Import FieldDefinition
|
||||||
use crate::state::pages::auth::AuthState;
|
use crate::state::pages::auth::AuthState;
|
||||||
use crate::state::pages::auth::LoginState;
|
use crate::state::pages::auth::LoginState;
|
||||||
use crate::state::pages::auth::RegisterState;
|
use crate::state::pages::auth::RegisterState;
|
||||||
@@ -23,42 +23,42 @@ use crate::tui::terminal::{EventReader, TerminalCore};
|
|||||||
use crate::ui::handlers::render::render_ui;
|
use crate::ui::handlers::render::render_ui;
|
||||||
use crate::tui::functions::common::login::LoginResult;
|
use crate::tui::functions::common::login::LoginResult;
|
||||||
use crate::tui::functions::common::register::RegisterResult;
|
use crate::tui::functions::common::register::RegisterResult;
|
||||||
// Removed: use crate::tui::functions::common::add_table::handle_save_table_action;
|
use crate::ui::handlers::context::DialogPurpose;
|
||||||
// Removed: use crate::functions::modes::navigation::add_table_nav::SaveTableResultSender;
|
|
||||||
use crate::ui::handlers::context::DialogPurpose; // UiContext removed if not used directly
|
|
||||||
use crate::tui::functions::common::login;
|
use crate::tui::functions::common::login;
|
||||||
use crate::tui::functions::common::register;
|
use crate::tui::functions::common::register;
|
||||||
use std::time::Instant;
|
use crate::utils::columns::filter_user_columns;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{anyhow, Context, Result};
|
||||||
use crossterm::cursor::SetCursorStyle;
|
use crossterm::cursor::SetCursorStyle;
|
||||||
use crossterm::event as crossterm_event;
|
use crossterm::event as crossterm_event;
|
||||||
use tracing::{error, info, warn}; // Added warn
|
use tracing::{error, info, warn};
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
use crate::state::app::state::DebugState;
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
use crate::utils::debug_logger::pop_next_debug_message;
|
||||||
|
|
||||||
pub async fn run_ui() -> Result<()> {
|
pub async fn run_ui() -> Result<()> {
|
||||||
let config = Config::load().context("Failed to load configuration")?;
|
let config = Config::load().context("Failed to load configuration")?;
|
||||||
let theme = Theme::from_str(&config.colors.theme);
|
let theme = Theme::from_str(&config.colors.theme);
|
||||||
let mut terminal = TerminalCore::new().context("Failed to initialize terminal")?;
|
let mut terminal = TerminalCore::new().context("Failed to initialize terminal")?;
|
||||||
let mut grpc_client = GrpcClient::new().await?;
|
let mut grpc_client = GrpcClient::new().await.context("Failed to create GrpcClient")?;
|
||||||
let mut command_handler = CommandHandler::new();
|
let mut command_handler = CommandHandler::new();
|
||||||
|
|
||||||
// --- Channel for Login Results ---
|
let (login_result_sender, mut login_result_receiver) = mpsc::channel::<LoginResult>(1);
|
||||||
let (login_result_sender, mut login_result_receiver) =
|
let (register_result_sender, mut register_result_receiver) = mpsc::channel::<RegisterResult>(1);
|
||||||
mpsc::channel::<LoginResult>(1);
|
let (save_table_result_sender, mut save_table_result_receiver) = mpsc::channel::<Result<String>>(1);
|
||||||
let (register_result_sender, mut register_result_receiver) =
|
let (save_logic_result_sender, _save_logic_result_receiver) = mpsc::channel::<Result<String>>(1);
|
||||||
mpsc::channel::<RegisterResult>(1);
|
|
||||||
let (save_table_result_sender, mut save_table_result_receiver) =
|
|
||||||
mpsc::channel::<Result<String>>(1);
|
|
||||||
let (save_logic_result_sender, _save_logic_result_receiver) = // Prefixed and removed mut
|
|
||||||
mpsc::channel::<Result<String>>(1);
|
|
||||||
|
|
||||||
let mut event_handler = EventHandler::new(
|
let mut event_handler = EventHandler::new(
|
||||||
login_result_sender.clone(),
|
login_result_sender.clone(),
|
||||||
register_result_sender.clone(),
|
register_result_sender.clone(),
|
||||||
save_table_result_sender.clone(),
|
save_table_result_sender.clone(),
|
||||||
save_logic_result_sender.clone(),
|
save_logic_result_sender.clone(),
|
||||||
).await.context("Failed to create event handler")?;
|
grpc_client.clone(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("Failed to create event handler")?;
|
||||||
let event_reader = EventReader::new();
|
let event_reader = EventReader::new();
|
||||||
|
|
||||||
let mut auth_state = AuthState::default();
|
let mut auth_state = AuthState::default();
|
||||||
@@ -69,7 +69,6 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
let mut buffer_state = BufferState::default();
|
let mut buffer_state = BufferState::default();
|
||||||
let mut app_state = AppState::new().context("Failed to create initial app state")?;
|
let mut app_state = AppState::new().context("Failed to create initial app state")?;
|
||||||
|
|
||||||
// --- DATA: Load auth data from file at startup ---
|
|
||||||
let mut auto_logged_in = false;
|
let mut auto_logged_in = false;
|
||||||
match load_auth_data() {
|
match load_auth_data() {
|
||||||
Ok(Some(stored_data)) => {
|
Ok(Some(stored_data)) => {
|
||||||
@@ -87,15 +86,42 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
error!("Failed to load auth data: {}", e);
|
error!("Failed to load auth data: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// --- END DATA ---
|
|
||||||
|
|
||||||
let column_names =
|
let (initial_profile, initial_table, initial_columns_from_service) =
|
||||||
UiService::initialize_app_state(&mut grpc_client, &mut app_state)
|
UiService::initialize_app_state_and_form(&mut grpc_client, &mut app_state)
|
||||||
.await.context("Failed to initialize app state from UI service")?;
|
.await
|
||||||
let mut form_state = FormState::new(column_names);
|
.context("Failed to initialize app state and form")?;
|
||||||
|
|
||||||
UiService::initialize_adresar_count(&mut grpc_client, &mut app_state).await?;
|
let initial_field_defs: Vec<FieldDefinition> = filter_user_columns(initial_columns_from_service)
|
||||||
form_state.reset_to_empty();
|
.into_iter()
|
||||||
|
.map(|col_name| FieldDefinition {
|
||||||
|
display_name: col_name.clone(),
|
||||||
|
data_key: col_name,
|
||||||
|
is_link: false,
|
||||||
|
link_target_table: None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut form_state = FormState::new(
|
||||||
|
initial_profile.clone(),
|
||||||
|
initial_table.clone(),
|
||||||
|
initial_field_defs,
|
||||||
|
);
|
||||||
|
|
||||||
|
UiService::fetch_and_set_table_count(&mut grpc_client, &mut form_state)
|
||||||
|
.await
|
||||||
|
.context(format!(
|
||||||
|
"Failed to fetch initial count for table {}.{}",
|
||||||
|
initial_profile, initial_table
|
||||||
|
))?;
|
||||||
|
|
||||||
|
if form_state.total_count > 0 {
|
||||||
|
if let Err(e) = UiService::load_table_data_by_position(&mut grpc_client, &mut form_state).await {
|
||||||
|
event_handler.command_message = format!("Error loading initial data: {}", e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
form_state.reset_to_empty();
|
||||||
|
}
|
||||||
|
|
||||||
if auto_logged_in {
|
if auto_logged_in {
|
||||||
buffer_state.history = vec![AppView::Form];
|
buffer_state.history = vec![AppView::Form];
|
||||||
@@ -106,9 +132,173 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
let mut last_frame_time = Instant::now();
|
let mut last_frame_time = Instant::now();
|
||||||
let mut current_fps = 0.0;
|
let mut current_fps = 0.0;
|
||||||
let mut needs_redraw = true;
|
let mut needs_redraw = true;
|
||||||
|
let mut prev_view_profile_name = app_state.current_view_profile_name.clone();
|
||||||
|
let mut prev_view_table_name = app_state.current_view_table_name.clone();
|
||||||
|
let mut table_just_switched = false;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
// --- Synchronize UI View from Active Buffer ---
|
let position_before_event = form_state.current_position;
|
||||||
|
let mut event_processed = false;
|
||||||
|
|
||||||
|
// --- CHANNEL RECEIVERS ---
|
||||||
|
|
||||||
|
// For main search palette
|
||||||
|
match event_handler.search_result_receiver.try_recv() {
|
||||||
|
Ok(hits) => {
|
||||||
|
info!("--- 4. Main loop received message from channel. ---");
|
||||||
|
if let Some(search_state) = app_state.search_state.as_mut() {
|
||||||
|
search_state.results = hits;
|
||||||
|
search_state.is_loading = false;
|
||||||
|
}
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => {
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Search result channel disconnected!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- ADDED: For live form autocomplete ---
|
||||||
|
match event_handler.autocomplete_result_receiver.try_recv() {
|
||||||
|
Ok(hits) => {
|
||||||
|
if form_state.autocomplete_active {
|
||||||
|
form_state.autocomplete_suggestions = hits;
|
||||||
|
form_state.autocomplete_loading = false;
|
||||||
|
if !form_state.autocomplete_suggestions.is_empty() {
|
||||||
|
form_state.selected_suggestion_index = Some(0);
|
||||||
|
} else {
|
||||||
|
form_state.selected_suggestion_index = None;
|
||||||
|
}
|
||||||
|
event_handler.command_message = format!("Found {} suggestions.", form_state.autocomplete_suggestions.len());
|
||||||
|
}
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => {}
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Autocomplete result channel disconnected!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if app_state.ui.show_search_palette {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
if crossterm_event::poll(std::time::Duration::from_millis(1))? {
|
||||||
|
let event = event_reader.read_event().context("Failed to read terminal event")?;
|
||||||
|
event_processed = true;
|
||||||
|
let event_outcome_result = event_handler.handle_event(
|
||||||
|
event,
|
||||||
|
&config,
|
||||||
|
&mut terminal,
|
||||||
|
&mut command_handler,
|
||||||
|
&mut form_state,
|
||||||
|
&mut auth_state,
|
||||||
|
&mut login_state,
|
||||||
|
&mut register_state,
|
||||||
|
&mut intro_state,
|
||||||
|
&mut admin_state,
|
||||||
|
&mut buffer_state,
|
||||||
|
&mut app_state,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
let mut should_exit = false;
|
||||||
|
match event_outcome_result {
|
||||||
|
Ok(outcome) => match outcome {
|
||||||
|
EventOutcome::Ok(message) => {
|
||||||
|
if !message.is_empty() {
|
||||||
|
event_handler.command_message = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventOutcome::Exit(message) => {
|
||||||
|
event_handler.command_message = message;
|
||||||
|
should_exit = true;
|
||||||
|
}
|
||||||
|
EventOutcome::DataSaved(save_outcome, message) => {
|
||||||
|
event_handler.command_message = message;
|
||||||
|
if let Err(e) = UiService::handle_save_outcome(
|
||||||
|
save_outcome,
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut app_state,
|
||||||
|
&mut form_state,
|
||||||
|
).await {
|
||||||
|
event_handler.command_message =
|
||||||
|
format!("Error handling save outcome: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventOutcome::ButtonSelected { .. } => {}
|
||||||
|
EventOutcome::TableSelected { path } => {
|
||||||
|
let parts: Vec<&str> = path.split('/').collect();
|
||||||
|
if parts.len() == 2 {
|
||||||
|
let profile_name = parts[0].to_string();
|
||||||
|
let table_name = parts[1].to_string();
|
||||||
|
|
||||||
|
app_state.set_current_view_table(profile_name, table_name);
|
||||||
|
buffer_state.update_history(AppView::Form);
|
||||||
|
event_handler.command_message = format!("Loading table: {}", path);
|
||||||
|
} else {
|
||||||
|
event_handler.command_message = format!("Invalid table path: {}", path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
event_handler.command_message = format!("Error: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if should_exit {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match login_result_receiver.try_recv() {
|
||||||
|
Ok(result) => {
|
||||||
|
if login::handle_login_result(result, &mut app_state, &mut auth_state, &mut login_state) {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => {}
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Login result channel disconnected unexpectedly.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match register_result_receiver.try_recv() {
|
||||||
|
Ok(result) => {
|
||||||
|
if register::handle_registration_result(result, &mut app_state, &mut register_state) {
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => {}
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Register result channel disconnected unexpectedly.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match save_table_result_receiver.try_recv() {
|
||||||
|
Ok(result) => {
|
||||||
|
app_state.hide_dialog();
|
||||||
|
match result {
|
||||||
|
Ok(ref success_message) => {
|
||||||
|
app_state.show_dialog(
|
||||||
|
"Save Successful",
|
||||||
|
success_message,
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::SaveTableSuccess,
|
||||||
|
);
|
||||||
|
admin_state.add_table_state.has_unsaved_changes = false;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
event_handler.command_message = format!("Save failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => {}
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
error!("Save table result channel disconnected unexpectedly.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(active_view) = buffer_state.get_active_view() {
|
if let Some(active_view) = buffer_state.get_active_view() {
|
||||||
app_state.ui.show_intro = false;
|
app_state.ui.show_intro = false;
|
||||||
app_state.ui.show_login = false;
|
app_state.ui.show_login = false;
|
||||||
@@ -139,11 +329,11 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
admin_state.set_profiles(profile_names);
|
admin_state.set_profiles(profile_names);
|
||||||
|
|
||||||
if admin_state.current_focus == AdminFocus::default() ||
|
if admin_state.current_focus == AdminFocus::default() ||
|
||||||
!matches!(admin_state.current_focus,
|
!matches!(admin_state.current_focus,
|
||||||
AdminFocus::InsideProfilesList |
|
AdminFocus::InsideProfilesList |
|
||||||
AdminFocus::Tables | AdminFocus::InsideTablesList |
|
AdminFocus::Tables | AdminFocus::InsideTablesList |
|
||||||
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3) {
|
AdminFocus::Button1 | AdminFocus::Button2 | AdminFocus::Button3) {
|
||||||
admin_state.current_focus = AdminFocus::ProfilesPane;
|
admin_state.current_focus = AdminFocus::ProfilesPane;
|
||||||
}
|
}
|
||||||
if admin_state.profile_list_state.selected().is_none() && !app_state.profile_tree.profiles.is_empty() {
|
if admin_state.profile_list_state.selected().is_none() && !app_state.profile_tree.profiles.is_empty() {
|
||||||
admin_state.profile_list_state.select(Some(0));
|
admin_state.profile_list_state.select(Some(0));
|
||||||
@@ -155,20 +345,110 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
AppView::Scratch => {}
|
AppView::Scratch => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// --- End Synchronization ---
|
|
||||||
|
|
||||||
// --- Handle Pending Table Structure Fetches ---
|
if app_state.ui.show_form {
|
||||||
|
let current_view_profile = app_state.current_view_profile_name.clone();
|
||||||
|
let current_view_table = app_state.current_view_table_name.clone();
|
||||||
|
|
||||||
|
// This condition correctly detects a table switch.
|
||||||
|
if prev_view_profile_name != current_view_profile
|
||||||
|
|| prev_view_table_name != current_view_table
|
||||||
|
{
|
||||||
|
if let (Some(prof_name), Some(tbl_name)) =
|
||||||
|
(current_view_profile.as_ref(), current_view_table.as_ref())
|
||||||
|
{
|
||||||
|
// --- START OF REFACTORED LOGIC ---
|
||||||
|
app_state.show_loading_dialog(
|
||||||
|
"Loading Table",
|
||||||
|
&format!("Fetching data for {}.{}...", prof_name, tbl_name),
|
||||||
|
);
|
||||||
|
needs_redraw = true;
|
||||||
|
|
||||||
|
// 1. Call our new, central function. It handles fetching AND caching.
|
||||||
|
match UiService::load_table_view(
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut app_state,
|
||||||
|
prof_name,
|
||||||
|
tbl_name,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(mut new_form_state) => {
|
||||||
|
// 2. The function succeeded, we have a new FormState.
|
||||||
|
// Now, fetch its data.
|
||||||
|
if let Err(e) = UiService::fetch_and_set_table_count(
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut new_form_state,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
// Handle count fetching error
|
||||||
|
app_state.update_dialog_content(
|
||||||
|
&format!("Error fetching count: {}", e),
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::LoginFailed, // Or a more appropriate purpose
|
||||||
|
);
|
||||||
|
} else if new_form_state.total_count > 0 {
|
||||||
|
// If there are records, load the first/last one
|
||||||
|
if let Err(e) = UiService::load_table_data_by_position(
|
||||||
|
&mut grpc_client,
|
||||||
|
&mut new_form_state,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
// Handle data loading error
|
||||||
|
app_state.update_dialog_content(
|
||||||
|
&format!("Error loading data: {}", e),
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::LoginFailed, // Or a more appropriate purpose
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Success! Hide the loading dialog.
|
||||||
|
app_state.hide_dialog();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No records, so just reset to an empty form.
|
||||||
|
new_form_state.reset_to_empty();
|
||||||
|
app_state.hide_dialog();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. CRITICAL: Replace the old form_state with the new one.
|
||||||
|
form_state = new_form_state;
|
||||||
|
|
||||||
|
// 4. Update our tracking variables.
|
||||||
|
prev_view_profile_name = current_view_profile;
|
||||||
|
prev_view_table_name = current_view_table;
|
||||||
|
table_just_switched = true;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
// This handles errors from load_table_view (e.g., schema fetch failed)
|
||||||
|
app_state.update_dialog_content(
|
||||||
|
&format!("Error loading table: {}", e),
|
||||||
|
vec!["OK".to_string()],
|
||||||
|
DialogPurpose::LoginFailed, // Or a more appropriate purpose
|
||||||
|
);
|
||||||
|
// Revert the view change in app_state to avoid a loop
|
||||||
|
app_state.current_view_profile_name =
|
||||||
|
prev_view_profile_name.clone();
|
||||||
|
app_state.current_view_table_name =
|
||||||
|
prev_view_table_name.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- END OF REFACTORED LOGIC ---
|
||||||
|
}
|
||||||
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if let Some((profile_name, table_name)) = app_state.pending_table_structure_fetch.take() {
|
if let Some((profile_name, table_name)) = app_state.pending_table_structure_fetch.take() {
|
||||||
if app_state.ui.show_add_logic {
|
if app_state.ui.show_add_logic {
|
||||||
// Ensure admin_state.add_logic_state matches the pending fetch
|
|
||||||
if admin_state.add_logic_state.profile_name == profile_name &&
|
if admin_state.add_logic_state.profile_name == profile_name &&
|
||||||
admin_state.add_logic_state.selected_table_name.as_deref() == Some(table_name.as_str()) {
|
admin_state.add_logic_state.selected_table_name.as_deref() == Some(table_name.as_str()) {
|
||||||
|
|
||||||
info!("Fetching table structure for {}.{}", profile_name, table_name);
|
info!("Fetching table structure for {}.{}", profile_name, table_name);
|
||||||
let fetch_message = UiService::initialize_add_logic_table_data(
|
let fetch_message = UiService::initialize_add_logic_table_data(
|
||||||
&mut grpc_client,
|
&mut grpc_client,
|
||||||
&mut admin_state.add_logic_state,
|
&mut admin_state.add_logic_state,
|
||||||
&app_state.profile_tree, // Pass the profile tree
|
&app_state.profile_tree,
|
||||||
).await.unwrap_or_else(|e| {
|
).await.unwrap_or_else(|e| {
|
||||||
error!("Error initializing add_logic_table_data: {}", e);
|
error!("Error initializing add_logic_table_data: {}", e);
|
||||||
format!("Error fetching table structure: {}", e)
|
format!("Error fetching table structure: {}", e)
|
||||||
@@ -196,35 +476,6 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 3. Draw UI ---
|
|
||||||
if needs_redraw {
|
|
||||||
terminal.draw(|f| {
|
|
||||||
render_ui(
|
|
||||||
f,
|
|
||||||
&mut form_state,
|
|
||||||
&mut auth_state,
|
|
||||||
&login_state,
|
|
||||||
®ister_state,
|
|
||||||
&intro_state,
|
|
||||||
&mut admin_state,
|
|
||||||
&buffer_state,
|
|
||||||
&theme,
|
|
||||||
event_handler.is_edit_mode,
|
|
||||||
&event_handler.highlight_state,
|
|
||||||
app_state.total_count,
|
|
||||||
app_state.current_position,
|
|
||||||
&app_state.current_dir,
|
|
||||||
&event_handler.command_input,
|
|
||||||
event_handler.command_mode,
|
|
||||||
&event_handler.command_message,
|
|
||||||
current_fps,
|
|
||||||
&app_state,
|
|
||||||
);
|
|
||||||
}).context("Terminal draw call failed")?;
|
|
||||||
needs_redraw = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Handle Pending Column Autocomplete for Table Selection ---
|
|
||||||
if let Some(table_name) = admin_state.add_logic_state.script_editor_awaiting_column_autocomplete.clone() {
|
if let Some(table_name) = admin_state.add_logic_state.script_editor_awaiting_column_autocomplete.clone() {
|
||||||
if app_state.ui.show_add_logic {
|
if app_state.ui.show_add_logic {
|
||||||
let profile_name = admin_state.add_logic_state.profile_name.clone();
|
let profile_name = admin_state.add_logic_state.profile_name.clone();
|
||||||
@@ -247,208 +498,56 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Cursor Visibility Logic ---
|
let position_changed = form_state.current_position != position_before_event;
|
||||||
let current_mode = ModeManager::derive_mode(&app_state, &event_handler, &admin_state);
|
|
||||||
match current_mode {
|
|
||||||
AppMode::Edit => { terminal.show_cursor()?; }
|
|
||||||
AppMode::Highlight => { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.show_cursor()?; }
|
|
||||||
AppMode::ReadOnly => {
|
|
||||||
if !app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; }
|
|
||||||
else { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; }
|
|
||||||
terminal.show_cursor().context("Failed to show cursor in ReadOnly mode")?;
|
|
||||||
}
|
|
||||||
AppMode::General => {
|
|
||||||
if app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor()?; }
|
|
||||||
else { terminal.hide_cursor()?; }
|
|
||||||
}
|
|
||||||
AppMode::Command => { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor().context("Failed to show cursor in Command mode")?; }
|
|
||||||
}
|
|
||||||
// --- End Cursor Visibility Logic ---
|
|
||||||
|
|
||||||
let total_count = app_state.total_count;
|
|
||||||
let mut current_position = app_state.current_position;
|
|
||||||
let position_before_event = current_position;
|
|
||||||
if app_state.ui.dialog.is_loading {
|
|
||||||
needs_redraw = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 1. Handle Terminal Events ---
|
|
||||||
let mut event_outcome_result = Ok(EventOutcome::Ok(String::new()));
|
|
||||||
let mut event_processed = false;
|
|
||||||
if crossterm_event::poll(std::time::Duration::from_millis(1))? {
|
|
||||||
let event = event_reader.read_event().context("Failed to read terminal event")?;
|
|
||||||
event_processed = true;
|
|
||||||
event_outcome_result = event_handler.handle_event(
|
|
||||||
event,
|
|
||||||
&config,
|
|
||||||
&mut terminal,
|
|
||||||
&mut grpc_client,
|
|
||||||
&mut command_handler,
|
|
||||||
&mut form_state,
|
|
||||||
&mut auth_state,
|
|
||||||
&mut login_state,
|
|
||||||
&mut register_state,
|
|
||||||
&mut intro_state,
|
|
||||||
&mut admin_state,
|
|
||||||
&mut buffer_state,
|
|
||||||
&mut app_state,
|
|
||||||
total_count,
|
|
||||||
&mut current_position,
|
|
||||||
).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
if event_processed {
|
|
||||||
needs_redraw = true;
|
|
||||||
}
|
|
||||||
app_state.current_position = current_position;
|
|
||||||
|
|
||||||
// --- Check for Login Results from Channel ---
|
|
||||||
match login_result_receiver.try_recv() {
|
|
||||||
Ok(result) => {
|
|
||||||
if login::handle_login_result(result, &mut app_state, &mut auth_state, &mut login_state) {
|
|
||||||
needs_redraw = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
|
|
||||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
|
||||||
error!("Login result channel disconnected unexpectedly.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Check for Register Results from Channel ---
|
|
||||||
match register_result_receiver.try_recv() {
|
|
||||||
Ok(result) => {
|
|
||||||
if register::handle_registration_result(result, &mut app_state, &mut register_state) {
|
|
||||||
needs_redraw = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(mpsc::error::TryRecvError::Empty) => { /* No message waiting */ }
|
|
||||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
|
||||||
error!("Register result channel disconnected unexpectedly.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// --- Check for Save Table Results ---
|
|
||||||
match save_table_result_receiver.try_recv() {
|
|
||||||
Ok(result) => {
|
|
||||||
app_state.hide_dialog();
|
|
||||||
match result {
|
|
||||||
Ok(ref success_message) => {
|
|
||||||
app_state.show_dialog(
|
|
||||||
"Save Successful",
|
|
||||||
success_message,
|
|
||||||
vec!["OK".to_string()],
|
|
||||||
DialogPurpose::SaveTableSuccess,
|
|
||||||
);
|
|
||||||
admin_state.add_table_state.has_unsaved_changes = false;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
event_handler.command_message = format!("Save failed: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
needs_redraw = true;
|
|
||||||
}
|
|
||||||
Err(mpsc::error::TryRecvError::Empty) => {}
|
|
||||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
|
||||||
error!("Save table result channel disconnected unexpectedly.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Centralized Consequence Handling ---
|
|
||||||
let mut should_exit = false;
|
|
||||||
match event_outcome_result {
|
|
||||||
Ok(outcome) => match outcome {
|
|
||||||
EventOutcome::Ok(_message) => {
|
|
||||||
// Message is often set directly in event_handler.command_message
|
|
||||||
}
|
|
||||||
EventOutcome::Exit(message) => {
|
|
||||||
event_handler.command_message = message;
|
|
||||||
should_exit = true;
|
|
||||||
}
|
|
||||||
EventOutcome::DataSaved(save_outcome, message) => {
|
|
||||||
event_handler.command_message = message;
|
|
||||||
if let Err(e) = UiService::handle_save_outcome(
|
|
||||||
save_outcome,
|
|
||||||
&mut grpc_client,
|
|
||||||
&mut app_state,
|
|
||||||
&mut form_state,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
event_handler.command_message =
|
|
||||||
format!("Error handling save outcome: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
EventOutcome::ButtonSelected { context: _, index: _ } => {
|
|
||||||
// Handled within event_handler or specific navigation modules
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => {
|
|
||||||
event_handler.command_message = format!("Error: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// --- End Consequence Handling ---
|
|
||||||
|
|
||||||
// --- Position Change Handling ---
|
|
||||||
let position_changed = app_state.current_position != position_before_event;
|
|
||||||
let current_total_count = app_state.total_count; // Use current total_count
|
|
||||||
let mut position_logic_needs_redraw = false;
|
let mut position_logic_needs_redraw = false;
|
||||||
|
|
||||||
if app_state.ui.show_form {
|
if app_state.ui.show_form && !table_just_switched {
|
||||||
if position_changed && !event_handler.is_edit_mode {
|
if position_changed && !event_handler.is_edit_mode {
|
||||||
let current_input = form_state.get_current_input();
|
|
||||||
let max_cursor_pos = if !current_input.is_empty() { current_input.len() - 1 } else { 0 };
|
|
||||||
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
|
||||||
position_logic_needs_redraw = true;
|
position_logic_needs_redraw = true;
|
||||||
|
|
||||||
if app_state.current_position > current_total_count + 1 {
|
if form_state.current_position > form_state.total_count {
|
||||||
app_state.current_position = current_total_count + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if app_state.current_position > current_total_count {
|
|
||||||
form_state.reset_to_empty();
|
form_state.reset_to_empty();
|
||||||
form_state.current_field = 0;
|
event_handler.command_message = format!("New entry for {}.{}", form_state.profile_name, form_state.table_name);
|
||||||
} else if app_state.current_position >= 1 && app_state.current_position <= current_total_count {
|
} else {
|
||||||
let current_position_to_load = app_state.current_position;
|
match UiService::load_table_data_by_position(&mut grpc_client, &mut form_state).await {
|
||||||
let load_message = UiService::load_adresar_by_position(
|
Ok(load_message) => {
|
||||||
&mut grpc_client,
|
if event_handler.command_message.is_empty() || !load_message.starts_with("Error") {
|
||||||
&mut app_state,
|
event_handler.command_message = load_message;
|
||||||
&mut form_state,
|
}
|
||||||
current_position_to_load,
|
}
|
||||||
)
|
Err(e) => {
|
||||||
.await.with_context(|| format!("Failed to load adresar by position: {}", current_position_to_load))?;
|
event_handler.command_message = format!("Error loading data: {}", e);
|
||||||
|
}
|
||||||
let current_input_after_load = form_state.get_current_input();
|
|
||||||
let max_cursor_pos_after_load = if !event_handler.is_edit_mode && !current_input_after_load.is_empty() {
|
|
||||||
current_input_after_load.len() - 1
|
|
||||||
} else {
|
|
||||||
current_input_after_load.len()
|
|
||||||
};
|
|
||||||
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos_after_load);
|
|
||||||
|
|
||||||
if !load_message.starts_with("Loaded entry") || event_handler.command_message.is_empty() {
|
|
||||||
event_handler.command_message = load_message;
|
|
||||||
}
|
}
|
||||||
} else { // current_position is 0 or invalid
|
|
||||||
app_state.current_position = 1.min(current_total_count + 1);
|
|
||||||
if app_state.current_position > current_total_count { // Handles empty db case
|
|
||||||
form_state.reset_to_empty();
|
|
||||||
form_state.current_field = 0;
|
|
||||||
}
|
|
||||||
// If db is not empty, this will trigger load in next iteration if position changed to 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let current_input_after_load_str = form_state.get_current_input();
|
||||||
|
let current_input_len_after_load = current_input_after_load_str.chars().count();
|
||||||
|
let max_cursor_pos = if current_input_len_after_load > 0 {
|
||||||
|
current_input_len_after_load.saturating_sub(1)
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
|
|
||||||
} else if !position_changed && !event_handler.is_edit_mode {
|
} else if !position_changed && !event_handler.is_edit_mode {
|
||||||
let current_input = form_state.get_current_input();
|
let current_input_str = form_state.get_current_input();
|
||||||
let max_cursor_pos = if !current_input.is_empty() { current_input.len() - 1 } else { 0 };
|
let current_input_len = current_input_str.chars().count();
|
||||||
|
let max_cursor_pos = if current_input_len > 0 {
|
||||||
|
current_input_len.saturating_sub(1)
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
form_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
}
|
}
|
||||||
} else if app_state.ui.show_register {
|
} else if app_state.ui.show_register {
|
||||||
if !event_handler.is_edit_mode {
|
if !event_handler.is_edit_mode {
|
||||||
let current_input = register_state.get_current_input();
|
let current_input = register_state.get_current_input();
|
||||||
let max_cursor_pos = if !current_input.is_empty() { current_input.len() - 1 } else { 0 };
|
let max_cursor_pos = if !current_input.is_empty() { current_input.len() - 1 } else { 0 };
|
||||||
register_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
register_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
}
|
}
|
||||||
} else if app_state.ui.show_login {
|
} else if app_state.ui.show_login {
|
||||||
if !event_handler.is_edit_mode {
|
if !event_handler.is_edit_mode {
|
||||||
let current_input = login_state.get_current_input();
|
let current_input = login_state.get_current_input();
|
||||||
let max_cursor_pos = if !current_input.is_empty() { current_input.len() - 1 } else { 0 };
|
let max_cursor_pos = if !current_input.is_empty() { current_input.len() - 1 } else { 0 };
|
||||||
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
login_state.current_cursor_pos = event_handler.ideal_cursor_column.min(max_cursor_pos);
|
||||||
@@ -458,18 +557,78 @@ pub async fn run_ui() -> Result<()> {
|
|||||||
if position_logic_needs_redraw {
|
if position_logic_needs_redraw {
|
||||||
needs_redraw = true;
|
needs_redraw = true;
|
||||||
}
|
}
|
||||||
// --- End Position Change Handling ---
|
|
||||||
|
|
||||||
if should_exit {
|
if app_state.ui.dialog.is_loading {
|
||||||
return Ok(());
|
needs_redraw = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "ui-debug")]
|
||||||
|
{
|
||||||
|
let can_display_next = match &app_state.debug_state {
|
||||||
|
Some(current) => current.display_start_time.elapsed() >= Duration::from_secs(2),
|
||||||
|
None => true,
|
||||||
|
};
|
||||||
|
|
||||||
|
if can_display_next {
|
||||||
|
if let Some((new_message, is_error)) = pop_next_debug_message() {
|
||||||
|
app_state.debug_state = Some(DebugState {
|
||||||
|
displayed_message: new_message,
|
||||||
|
is_error,
|
||||||
|
display_start_time: Instant::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if event_processed || needs_redraw || position_changed {
|
||||||
|
let current_mode = ModeManager::derive_mode(&app_state, &event_handler, &admin_state);
|
||||||
|
match current_mode {
|
||||||
|
AppMode::Edit => { terminal.show_cursor()?; }
|
||||||
|
AppMode::Highlight => { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; terminal.show_cursor()?; }
|
||||||
|
AppMode::ReadOnly => {
|
||||||
|
if !app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyBlock)?; }
|
||||||
|
else { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; }
|
||||||
|
terminal.show_cursor().context("Failed to show cursor in ReadOnly mode")?;
|
||||||
|
}
|
||||||
|
AppMode::General => {
|
||||||
|
if app_state.ui.focus_outside_canvas { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor()?; }
|
||||||
|
else { terminal.hide_cursor()?; }
|
||||||
|
}
|
||||||
|
AppMode::Command => { terminal.set_cursor_style(SetCursorStyle::SteadyUnderScore)?; terminal.show_cursor().context("Failed to show cursor in Command mode")?; }
|
||||||
|
}
|
||||||
|
|
||||||
|
terminal.draw(|f| {
|
||||||
|
render_ui(
|
||||||
|
f,
|
||||||
|
&mut form_state,
|
||||||
|
&mut auth_state,
|
||||||
|
&login_state,
|
||||||
|
®ister_state,
|
||||||
|
&intro_state,
|
||||||
|
&mut admin_state,
|
||||||
|
&buffer_state,
|
||||||
|
&theme,
|
||||||
|
event_handler.is_edit_mode,
|
||||||
|
&event_handler.highlight_state,
|
||||||
|
&event_handler.command_input,
|
||||||
|
event_handler.command_mode,
|
||||||
|
&event_handler.command_message,
|
||||||
|
&event_handler.navigation_state,
|
||||||
|
&app_state.current_dir,
|
||||||
|
current_fps,
|
||||||
|
&app_state,
|
||||||
|
);
|
||||||
|
}).context("Terminal draw call failed")?;
|
||||||
|
needs_redraw = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- FPS Calculation ---
|
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
let frame_duration = now.duration_since(last_frame_time);
|
let frame_duration = now.duration_since(last_frame_time);
|
||||||
last_frame_time = now;
|
last_frame_time = now;
|
||||||
if frame_duration.as_secs_f64() > 1e-6 { // Avoid division by zero
|
if frame_duration.as_secs_f64() > 1e-6 {
|
||||||
current_fps = 1.0 / frame_duration.as_secs_f64();
|
current_fps = 1.0 / frame_duration.as_secs_f64();
|
||||||
}
|
}
|
||||||
} // End main loop
|
|
||||||
|
table_just_switched = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
14
client/src/utils/columns.rs
Normal file
14
client/src/utils/columns.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// src/utils/columns.rs
|
||||||
|
pub fn is_system_column(column_name: &str) -> bool {
|
||||||
|
match column_name {
|
||||||
|
"id" | "deleted" | "created_at" => true,
|
||||||
|
name if name.ends_with("_id") => true,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn filter_user_columns(all_columns: Vec<String>) -> Vec<String> {
|
||||||
|
all_columns.into_iter()
|
||||||
|
.filter(|col| !is_system_column(col))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
50
client/src/utils/data_converter.rs
Normal file
50
client/src/utils/data_converter.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
// src/utils/data_converter.rs
|
||||||
|
|
||||||
|
use common::proto::multieko2::table_structure::TableStructureResponse;
|
||||||
|
use prost_types::{value::Kind, NullValue, Value};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub fn convert_and_validate_data(
|
||||||
|
data: &HashMap<String, String>,
|
||||||
|
schema: &TableStructureResponse,
|
||||||
|
) -> Result<HashMap<String, Value>, String> {
|
||||||
|
let type_map: HashMap<_, _> = schema
|
||||||
|
.columns
|
||||||
|
.iter()
|
||||||
|
.map(|col| (col.name.as_str(), col.data_type.as_str()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
data.iter()
|
||||||
|
.map(|(key, str_value)| {
|
||||||
|
let expected_type = type_map.get(key.as_str()).unwrap_or(&"TEXT");
|
||||||
|
|
||||||
|
let kind = if str_value.is_empty() {
|
||||||
|
// TODO: Use the correct enum variant
|
||||||
|
Kind::NullValue(NullValue::NullValue.into())
|
||||||
|
} else {
|
||||||
|
// Attempt to parse the string based on the expected type
|
||||||
|
match *expected_type {
|
||||||
|
"BOOL" => match str_value.to_lowercase().parse::<bool>() {
|
||||||
|
Ok(v) => Kind::BoolValue(v),
|
||||||
|
Err(_) => return Err(format!("Invalid boolean for '{}': must be 'true' or 'false'", key)),
|
||||||
|
},
|
||||||
|
"INT8" | "INT4" | "INT2" | "SERIAL" | "BIGSERIAL" => {
|
||||||
|
match str_value.parse::<f64>() {
|
||||||
|
Ok(v) => Kind::NumberValue(v),
|
||||||
|
Err(_) => return Err(format!("Invalid number for '{}': must be a whole number", key)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"NUMERIC" | "FLOAT4" | "FLOAT8" => match str_value.parse::<f64>() {
|
||||||
|
Ok(v) => Kind::NumberValue(v),
|
||||||
|
Err(_) => return Err(format!("Invalid decimal for '{}': must be a number", key)),
|
||||||
|
},
|
||||||
|
"TIMESTAMPTZ" | "DATE" | "TIME" | "TEXT" | "VARCHAR" | "UUID" => {
|
||||||
|
Kind::StringValue(str_value.clone())
|
||||||
|
}
|
||||||
|
_ => Kind::StringValue(str_value.clone()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok((key.clone(), Value { kind: Some(kind) }))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
46
client/src/utils/debug_logger.rs
Normal file
46
client/src/utils/debug_logger.rs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
// client/src/utils/debug_logger.rs
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use std::collections::VecDeque; // <-- FIX: Import VecDeque
|
||||||
|
use std::io;
|
||||||
|
use std::sync::{Arc, Mutex}; // <-- FIX: Import Mutex
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref UI_DEBUG_BUFFER: Arc<Mutex<VecDeque<(String, bool)>>> =
|
||||||
|
Arc::new(Mutex::new(VecDeque::from([(String::from("Logger initialized..."), false)])));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct UiDebugWriter;
|
||||||
|
|
||||||
|
impl Default for UiDebugWriter {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UiDebugWriter {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl io::Write for UiDebugWriter {
|
||||||
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
|
let mut buffer = UI_DEBUG_BUFFER.lock().unwrap();
|
||||||
|
let message = String::from_utf8_lossy(buf);
|
||||||
|
let trimmed_message = message.trim().to_string();
|
||||||
|
let is_error = trimmed_message.starts_with("ERROR");
|
||||||
|
// Add the new message to the back of the queue
|
||||||
|
buffer.push_back((trimmed_message, is_error));
|
||||||
|
Ok(buf.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A public function to pop the next message from the front of the queue.
|
||||||
|
pub fn pop_next_debug_message() -> Option<(String, bool)> {
|
||||||
|
UI_DEBUG_BUFFER.lock().unwrap().pop_front()
|
||||||
|
}
|
||||||
9
client/src/utils/mod.rs
Normal file
9
client/src/utils/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
// src/utils/mod.rs
|
||||||
|
|
||||||
|
pub mod columns;
|
||||||
|
pub mod debug_logger;
|
||||||
|
pub mod data_converter;
|
||||||
|
|
||||||
|
pub use columns::*;
|
||||||
|
pub use debug_logger::*;
|
||||||
|
pub use data_converter::*;
|
||||||
262
client/tests/form/gui/form_tests.rs
Normal file
262
client/tests/form/gui/form_tests.rs
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
// client/tests/form_tests.rs
|
||||||
|
use rstest::{fixture, rstest};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use client::state::pages::form::{FormState, FieldDefinition};
|
||||||
|
use client::state::pages::canvas_state::CanvasState;
|
||||||
|
|
||||||
|
#[fixture]
|
||||||
|
fn test_form_state() -> FormState {
|
||||||
|
let fields = vec![
|
||||||
|
FieldDefinition {
|
||||||
|
display_name: "Company".to_string(),
|
||||||
|
data_key: "firma".to_string(),
|
||||||
|
is_link: false,
|
||||||
|
link_target_table: None,
|
||||||
|
},
|
||||||
|
FieldDefinition {
|
||||||
|
display_name: "Phone".to_string(),
|
||||||
|
data_key: "telefon".to_string(),
|
||||||
|
is_link: false,
|
||||||
|
link_target_table: None,
|
||||||
|
},
|
||||||
|
FieldDefinition {
|
||||||
|
display_name: "Email".to_string(),
|
||||||
|
data_key: "email".to_string(),
|
||||||
|
is_link: false,
|
||||||
|
link_target_table: None,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
FormState::new("test_profile".to_string(), "test_table".to_string(), fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[fixture]
|
||||||
|
fn test_form_data() -> HashMap<String, String> {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), "Test Company".to_string());
|
||||||
|
data.insert("telefon".to_string(), "+421123456789".to_string());
|
||||||
|
data.insert("email".to_string(), "test@example.com".to_string());
|
||||||
|
data
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_state_creation(test_form_state: FormState) {
|
||||||
|
assert_eq!(test_form_state.profile_name, "test_profile");
|
||||||
|
assert_eq!(test_form_state.table_name, "test_table");
|
||||||
|
assert_eq!(test_form_state.fields.len(), 3);
|
||||||
|
assert_eq!(test_form_state.current_field(), 0);
|
||||||
|
assert!(!test_form_state.has_unsaved_changes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_field_navigation(mut test_form_state: FormState) {
|
||||||
|
// Test initial field
|
||||||
|
assert_eq!(test_form_state.current_field(), 0);
|
||||||
|
|
||||||
|
// Test navigation to next field
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
assert_eq!(test_form_state.current_field(), 1);
|
||||||
|
|
||||||
|
// Test navigation to last field
|
||||||
|
test_form_state.set_current_field(2);
|
||||||
|
assert_eq!(test_form_state.current_field(), 2);
|
||||||
|
|
||||||
|
// Test invalid field (should not crash)
|
||||||
|
test_form_state.set_current_field(999);
|
||||||
|
assert_eq!(test_form_state.current_field(), 2); // Should stay at valid field
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_data_entry(mut test_form_state: FormState) {
|
||||||
|
// Test entering data in first field
|
||||||
|
*test_form_state.get_current_input_mut() = "Test Company".to_string();
|
||||||
|
test_form_state.set_has_unsaved_changes(true);
|
||||||
|
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "Test Company");
|
||||||
|
assert!(test_form_state.has_unsaved_changes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_field_switching_with_data(mut test_form_state: FormState) {
|
||||||
|
// Enter data in first field
|
||||||
|
*test_form_state.get_current_input_mut() = "Company Name".to_string();
|
||||||
|
|
||||||
|
// Switch to second field
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
*test_form_state.get_current_input_mut() = "+421123456789".to_string();
|
||||||
|
|
||||||
|
// Switch back to first field
|
||||||
|
test_form_state.set_current_field(0);
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "Company Name");
|
||||||
|
|
||||||
|
// Switch to second field again
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "+421123456789");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_reset_functionality(mut test_form_state: FormState) {
|
||||||
|
// Add some data
|
||||||
|
test_form_state.set_current_field(0);
|
||||||
|
*test_form_state.get_current_input_mut() = "Test Company".to_string();
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
*test_form_state.get_current_input_mut() = "+421123456789".to_string();
|
||||||
|
test_form_state.set_has_unsaved_changes(true);
|
||||||
|
test_form_state.id = 123;
|
||||||
|
test_form_state.current_position = 5;
|
||||||
|
|
||||||
|
// Reset the form
|
||||||
|
test_form_state.reset_to_empty();
|
||||||
|
|
||||||
|
// Verify reset
|
||||||
|
assert_eq!(test_form_state.id, 0);
|
||||||
|
assert!(!test_form_state.has_unsaved_changes());
|
||||||
|
assert_eq!(test_form_state.current_field(), 0);
|
||||||
|
|
||||||
|
// Check all fields are empty
|
||||||
|
for i in 0..test_form_state.fields.len() {
|
||||||
|
test_form_state.set_current_field(i);
|
||||||
|
assert!(test_form_state.get_current_input().is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_update_from_response(mut test_form_state: FormState, test_form_data: HashMap<String, String>) {
|
||||||
|
let position = 3;
|
||||||
|
|
||||||
|
// Update form with response data
|
||||||
|
test_form_state.update_from_response(&test_form_data, position);
|
||||||
|
|
||||||
|
// Verify data was loaded
|
||||||
|
assert_eq!(test_form_state.current_position, position);
|
||||||
|
assert!(!test_form_state.has_unsaved_changes());
|
||||||
|
assert_eq!(test_form_state.current_field(), 0);
|
||||||
|
|
||||||
|
// Check field values
|
||||||
|
test_form_state.set_current_field(0);
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "Test Company");
|
||||||
|
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "+421123456789");
|
||||||
|
|
||||||
|
test_form_state.set_current_field(2);
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "test@example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_cursor_position(mut test_form_state: FormState) {
|
||||||
|
// Test initial cursor position
|
||||||
|
assert_eq!(test_form_state.current_cursor_pos(), 0);
|
||||||
|
|
||||||
|
// Add some text
|
||||||
|
*test_form_state.get_current_input_mut() = "Test Company".to_string();
|
||||||
|
|
||||||
|
// Test cursor positioning
|
||||||
|
test_form_state.set_current_cursor_pos(5);
|
||||||
|
assert_eq!(test_form_state.current_cursor_pos(), 5);
|
||||||
|
|
||||||
|
// Test cursor bounds
|
||||||
|
test_form_state.set_current_cursor_pos(999);
|
||||||
|
// Should be clamped to text length
|
||||||
|
assert!(test_form_state.current_cursor_pos() <= "Test Company".len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_field_display_names(test_form_state: FormState) {
|
||||||
|
let field_names = test_form_state.fields();
|
||||||
|
|
||||||
|
assert_eq!(field_names.len(), 3);
|
||||||
|
assert_eq!(field_names[0], "Company");
|
||||||
|
assert_eq!(field_names[1], "Phone");
|
||||||
|
assert_eq!(field_names[2], "Email");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_inputs_vector(mut test_form_state: FormState) {
|
||||||
|
// Add data to fields
|
||||||
|
test_form_state.set_current_field(0);
|
||||||
|
*test_form_state.get_current_input_mut() = "Company A".to_string();
|
||||||
|
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
*test_form_state.get_current_input_mut() = "123456789".to_string();
|
||||||
|
|
||||||
|
test_form_state.set_current_field(2);
|
||||||
|
*test_form_state.get_current_input_mut() = "test@test.com".to_string();
|
||||||
|
|
||||||
|
// Get inputs vector
|
||||||
|
let inputs = test_form_state.inputs();
|
||||||
|
|
||||||
|
assert_eq!(inputs.len(), 3);
|
||||||
|
assert_eq!(inputs[0], "Company A");
|
||||||
|
assert_eq!(inputs[1], "123456789");
|
||||||
|
assert_eq!(inputs[2], "test@test.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_position_management(mut test_form_state: FormState) {
|
||||||
|
// Test initial position
|
||||||
|
assert_eq!(test_form_state.current_position, 1);
|
||||||
|
assert_eq!(test_form_state.total_count, 0);
|
||||||
|
|
||||||
|
// Set some values
|
||||||
|
test_form_state.total_count = 10;
|
||||||
|
test_form_state.current_position = 5;
|
||||||
|
|
||||||
|
assert_eq!(test_form_state.current_position, 5);
|
||||||
|
assert_eq!(test_form_state.total_count, 10);
|
||||||
|
|
||||||
|
// Test reset affects position
|
||||||
|
test_form_state.reset_to_empty();
|
||||||
|
assert_eq!(test_form_state.current_position, 11); // total_count + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_autocomplete_state(mut test_form_state: FormState) {
|
||||||
|
// Test initial autocomplete state
|
||||||
|
assert!(!test_form_state.autocomplete_active);
|
||||||
|
assert!(test_form_state.autocomplete_suggestions.is_empty());
|
||||||
|
assert!(test_form_state.selected_suggestion_index.is_none());
|
||||||
|
|
||||||
|
// Test deactivating autocomplete
|
||||||
|
test_form_state.autocomplete_active = true;
|
||||||
|
test_form_state.deactivate_autocomplete();
|
||||||
|
|
||||||
|
assert!(!test_form_state.autocomplete_active);
|
||||||
|
assert!(test_form_state.autocomplete_suggestions.is_empty());
|
||||||
|
assert!(test_form_state.selected_suggestion_index.is_none());
|
||||||
|
assert!(!test_form_state.autocomplete_loading);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_empty_data_handling(mut test_form_state: FormState) {
|
||||||
|
let empty_data = HashMap::new();
|
||||||
|
|
||||||
|
// Update with empty data
|
||||||
|
test_form_state.update_from_response(&empty_data, 1);
|
||||||
|
|
||||||
|
// All fields should be empty
|
||||||
|
for i in 0..test_form_state.fields.len() {
|
||||||
|
test_form_state.set_current_field(i);
|
||||||
|
assert!(test_form_state.get_current_input().is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
fn test_form_partial_data_handling(mut test_form_state: FormState) {
|
||||||
|
let mut partial_data = HashMap::new();
|
||||||
|
partial_data.insert("firma".to_string(), "Partial Company".to_string());
|
||||||
|
// Intentionally missing telefon and email
|
||||||
|
|
||||||
|
test_form_state.update_from_response(&partial_data, 1);
|
||||||
|
|
||||||
|
// First field should have data
|
||||||
|
test_form_state.set_current_field(0);
|
||||||
|
assert_eq!(test_form_state.get_current_input(), "Partial Company");
|
||||||
|
|
||||||
|
// Other fields should be empty
|
||||||
|
test_form_state.set_current_field(1);
|
||||||
|
assert!(test_form_state.get_current_input().is_empty());
|
||||||
|
|
||||||
|
test_form_state.set_current_field(2);
|
||||||
|
assert!(test_form_state.get_current_input().is_empty());
|
||||||
|
}
|
||||||
1
client/tests/form/gui/mod.rs
Normal file
1
client/tests/form/gui/mod.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
pub mod form_tests;
|
||||||
2
client/tests/form/mod.rs
Normal file
2
client/tests/form/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod gui;
|
||||||
|
pub mod requests;
|
||||||
1019
client/tests/form/requests/form_request_tests.rs
Normal file
1019
client/tests/form/requests/form_request_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
267
client/tests/form/requests/form_request_tests2.rs
Normal file
267
client/tests/form/requests/form_request_tests2.rs
Normal file
@@ -0,0 +1,267 @@
|
|||||||
|
// ========================================================================
|
||||||
|
// ROBUST WORKFLOW AND INTEGRATION TESTS
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_partial_update_preserves_other_fields(
|
||||||
|
#[future] populated_test_context: FormTestContext,
|
||||||
|
) {
|
||||||
|
let mut context = populated_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Create a record with multiple fields
|
||||||
|
let mut initial_data = context.create_test_form_data();
|
||||||
|
let original_email = "preserve.this@email.com";
|
||||||
|
initial_data.insert(
|
||||||
|
"email".to_string(),
|
||||||
|
create_string_value(original_email),
|
||||||
|
);
|
||||||
|
|
||||||
|
let post_res = context
|
||||||
|
.client
|
||||||
|
.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
initial_data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Setup: Failed to create record for partial update test");
|
||||||
|
let created_id = post_res.inserted_id;
|
||||||
|
println!("Partial Update Test: Created record ID {}", created_id);
|
||||||
|
|
||||||
|
// 2. Update only ONE field
|
||||||
|
let mut partial_update = HashMap::new();
|
||||||
|
let updated_firma = "Partially Updated Inc.";
|
||||||
|
partial_update.insert(
|
||||||
|
"firma".to_string(),
|
||||||
|
create_string_value(updated_firma),
|
||||||
|
);
|
||||||
|
|
||||||
|
context
|
||||||
|
.client
|
||||||
|
.put_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
created_id,
|
||||||
|
partial_update,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Partial update failed");
|
||||||
|
println!("Partial Update Test: Updated only 'firma' field");
|
||||||
|
|
||||||
|
// 3. Get the record back and verify ALL fields
|
||||||
|
let get_res = context
|
||||||
|
.client
|
||||||
|
.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
created_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to get record after partial update");
|
||||||
|
|
||||||
|
let final_data = get_res.data;
|
||||||
|
assert_eq!(
|
||||||
|
final_data.get("firma").unwrap(),
|
||||||
|
updated_firma,
|
||||||
|
"The 'firma' field should be updated"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
final_data.get("email").unwrap(),
|
||||||
|
original_email,
|
||||||
|
"The 'email' field should have been preserved"
|
||||||
|
);
|
||||||
|
println!("Partial Update Test: Verified other fields were preserved. OK.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_data_edge_cases_and_unicode(
|
||||||
|
#[future] form_test_context: FormTestContext,
|
||||||
|
) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
let edge_case_strings = vec![
|
||||||
|
("Unicode", "José María González, Москва, 北京市"),
|
||||||
|
("Emoji", "🚀 Tech Company 🌟"),
|
||||||
|
("Quotes", "Quote\"Test'Apostrophe"),
|
||||||
|
("Symbols", "Price: $1,000.50 (50% off!)"),
|
||||||
|
("Empty", ""),
|
||||||
|
("Whitespace", " "),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, test_string) in edge_case_strings {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value(test_string));
|
||||||
|
data.insert(
|
||||||
|
"kz".to_string(),
|
||||||
|
create_string_value(&format!("EDGE-{}", case_name)),
|
||||||
|
);
|
||||||
|
|
||||||
|
let post_res = context
|
||||||
|
.client
|
||||||
|
.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect(&format!("POST should succeed for case: {}", case_name));
|
||||||
|
let created_id = post_res.inserted_id;
|
||||||
|
|
||||||
|
let get_res = context
|
||||||
|
.client
|
||||||
|
.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
created_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect(&format!(
|
||||||
|
"GET should succeed for case: {}",
|
||||||
|
case_name
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
get_res.data.get("firma").unwrap(),
|
||||||
|
test_string,
|
||||||
|
"Data should be identical after round-trip for case: {}",
|
||||||
|
case_name
|
||||||
|
);
|
||||||
|
println!("Edge Case Test: '{}' passed.", case_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_numeric_and_null_edge_cases(
|
||||||
|
#[future] form_test_context: FormTestContext,
|
||||||
|
) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Test NULL value
|
||||||
|
let mut null_data = HashMap::new();
|
||||||
|
null_data.insert(
|
||||||
|
"firma".to_string(),
|
||||||
|
create_string_value("Company With Null Phone"),
|
||||||
|
);
|
||||||
|
null_data.insert("telefon".to_string(), create_null_value());
|
||||||
|
let post_res_null = context
|
||||||
|
.client
|
||||||
|
.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
null_data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("POST with NULL value should succeed");
|
||||||
|
let get_res_null = context
|
||||||
|
.client
|
||||||
|
.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
post_res_null.inserted_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
// Depending on DB, NULL may come back as empty string or be absent.
|
||||||
|
// The important part is that the operation doesn't fail.
|
||||||
|
assert!(
|
||||||
|
get_res_null.data.get("telefon").unwrap_or(&"".to_string()).is_empty(),
|
||||||
|
"NULL value should result in an empty or absent field"
|
||||||
|
);
|
||||||
|
println!("Edge Case Test: NULL value handled correctly. OK.");
|
||||||
|
|
||||||
|
// 2. Test Zero value for a numeric field (assuming 'age' is numeric)
|
||||||
|
let mut zero_data = HashMap::new();
|
||||||
|
zero_data.insert(
|
||||||
|
"firma".to_string(),
|
||||||
|
create_string_value("Newborn Company"),
|
||||||
|
);
|
||||||
|
// Assuming 'age' is a field in your actual table definition
|
||||||
|
// zero_data.insert("age".to_string(), create_number_value(0.0));
|
||||||
|
// let post_res_zero = context.client.post_table_data(...).await.expect("POST with zero should succeed");
|
||||||
|
// ... then get and verify it's "0"
|
||||||
|
println!("Edge Case Test: Zero value test skipped (uncomment if 'age' field exists).");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_concurrent_updates_on_same_record(
|
||||||
|
#[future] populated_test_context: FormTestContext,
|
||||||
|
) {
|
||||||
|
let mut context = populated_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Create a single record to be updated by all tasks
|
||||||
|
let initial_data = context.create_minimal_form_data();
|
||||||
|
let post_res = context
|
||||||
|
.client
|
||||||
|
.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
initial_data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Setup: Failed to create record for concurrency test");
|
||||||
|
let record_id = post_res.inserted_id;
|
||||||
|
println!("Concurrency Test: Target record ID is {}", record_id);
|
||||||
|
|
||||||
|
// 2. Spawn multiple concurrent UPDATE operations
|
||||||
|
let mut handles = Vec::new();
|
||||||
|
let num_concurrent_tasks = 5;
|
||||||
|
let mut final_values = Vec::new();
|
||||||
|
|
||||||
|
for i in 0..num_concurrent_tasks {
|
||||||
|
let mut client_clone = context.client.clone();
|
||||||
|
let profile_name = context.profile_name.clone();
|
||||||
|
let table_name = context.table_name.clone();
|
||||||
|
let final_value = format!("Concurrent Update {}", i);
|
||||||
|
final_values.push(final_value.clone());
|
||||||
|
|
||||||
|
let handle = tokio::spawn(async move {
|
||||||
|
let mut update_data = HashMap::new();
|
||||||
|
update_data.insert(
|
||||||
|
"firma".to_string(),
|
||||||
|
create_string_value(&final_value),
|
||||||
|
);
|
||||||
|
client_clone
|
||||||
|
.put_table_data(profile_name, table_name, record_id, update_data)
|
||||||
|
.await
|
||||||
|
});
|
||||||
|
handles.push(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Wait for all tasks to complete and check for panics
|
||||||
|
let results = futures::future::join_all(handles).await;
|
||||||
|
assert!(
|
||||||
|
results.iter().all(|r| r.is_ok()),
|
||||||
|
"No concurrent task should panic"
|
||||||
|
);
|
||||||
|
println!("Concurrency Test: All update tasks completed without panicking.");
|
||||||
|
|
||||||
|
// 4. Get the final state of the record
|
||||||
|
let final_get_res = context
|
||||||
|
.client
|
||||||
|
.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Should be able to get the record after concurrent updates");
|
||||||
|
|
||||||
|
let final_firma = final_get_res.data.get("firma").unwrap();
|
||||||
|
assert!(
|
||||||
|
final_values.contains(final_firma),
|
||||||
|
"The final state '{}' must be one of the states set by the tasks",
|
||||||
|
final_firma
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
"Concurrency Test: Final state is '{}', which is a valid outcome. OK.",
|
||||||
|
final_firma
|
||||||
|
);
|
||||||
|
}
|
||||||
727
client/tests/form/requests/form_request_tests3.rs
Normal file
727
client/tests/form/requests/form_request_tests3.rs
Normal file
@@ -0,0 +1,727 @@
|
|||||||
|
// form_request_tests3.rs - Comprehensive and Robust Testing
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// STEEL SCRIPT VALIDATION TESTS (HIGHEST PRIORITY)
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_steel_script_validation_success(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test with data that should pass script validation
|
||||||
|
// Assuming there's a script that validates 'kz' field to start with "KZ" and be 5 chars
|
||||||
|
let mut valid_data = HashMap::new();
|
||||||
|
valid_data.insert("firma".to_string(), create_string_value("Script Test Company"));
|
||||||
|
valid_data.insert("kz".to_string(), create_string_value("KZ123"));
|
||||||
|
valid_data.insert("telefon".to_string(), create_string_value("+421123456789"));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
valid_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
assert!(response.success, "Valid data should pass script validation");
|
||||||
|
println!("Script Validation Test: Valid data passed - ID {}", response.inserted_id);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(status) = e.downcast_ref::<Status>() {
|
||||||
|
if status.code() == tonic::Code::Unavailable {
|
||||||
|
println!("Script validation test skipped - backend not available");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// If there are no scripts configured, this might still work
|
||||||
|
println!("Script validation test: {}", status.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_steel_script_validation_failure(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test with data that should fail script validation
|
||||||
|
let invalid_script_data = vec![
|
||||||
|
("TooShort", "KZ12"), // Too short
|
||||||
|
("TooLong", "KZ12345"), // Too long
|
||||||
|
("WrongPrefix", "AB123"), // Wrong prefix
|
||||||
|
("NoPrefix", "12345"), // No prefix
|
||||||
|
("Empty", ""), // Empty
|
||||||
|
];
|
||||||
|
|
||||||
|
for (test_case, invalid_kz) in invalid_script_data {
|
||||||
|
let mut invalid_data = HashMap::new();
|
||||||
|
invalid_data.insert("firma".to_string(), create_string_value("Script Fail Company"));
|
||||||
|
invalid_data.insert("kz".to_string(), create_string_value(invalid_kz));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
invalid_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(_) => {
|
||||||
|
println!("Script Validation Test: {} passed (no validation script configured)", test_case);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(status) = e.downcast_ref::<Status>() {
|
||||||
|
assert_eq!(status.code(), tonic::Code::InvalidArgument,
|
||||||
|
"Script validation failure should return InvalidArgument for case: {}", test_case);
|
||||||
|
println!("Script Validation Test: {} correctly failed - {}", test_case, status.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_steel_script_validation_on_update(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Create a valid record first
|
||||||
|
let mut initial_data = HashMap::new();
|
||||||
|
initial_data.insert("firma".to_string(), create_string_value("Update Script Test"));
|
||||||
|
initial_data.insert("kz".to_string(), create_string_value("KZ123"));
|
||||||
|
|
||||||
|
let post_result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
initial_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
if let Ok(post_response) = post_result {
|
||||||
|
let record_id = post_response.inserted_id;
|
||||||
|
|
||||||
|
// 2. Try to update with invalid data
|
||||||
|
let mut invalid_update = HashMap::new();
|
||||||
|
invalid_update.insert("kz".to_string(), create_string_value("INVALID"));
|
||||||
|
|
||||||
|
let update_result = context.client.put_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
invalid_update,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match update_result {
|
||||||
|
Ok(_) => {
|
||||||
|
println!("Script Validation on Update: No validation script configured for updates");
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(status) = e.downcast_ref::<Status>() {
|
||||||
|
assert_eq!(status.code(), tonic::Code::InvalidArgument,
|
||||||
|
"Update with invalid data should fail script validation");
|
||||||
|
println!("Script Validation on Update: Correctly rejected invalid update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// COMPREHENSIVE DATA TYPE TESTS
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_boolean_data_type(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test valid boolean values
|
||||||
|
let boolean_test_cases = vec![
|
||||||
|
("true", true),
|
||||||
|
("false", false),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, bool_value) in boolean_test_cases {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value("Boolean Test Company"));
|
||||||
|
// Assuming there's a boolean field called 'active'
|
||||||
|
data.insert("active".to_string(), create_bool_value(bool_value));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
println!("Boolean Test: {} value succeeded", case_name);
|
||||||
|
|
||||||
|
// Verify the value round-trip
|
||||||
|
if let Ok(get_response) = context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
response.inserted_id,
|
||||||
|
).await {
|
||||||
|
if let Some(retrieved_value) = get_response.data.get("active") {
|
||||||
|
println!("Boolean Test: {} round-trip value: {}", case_name, retrieved_value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("Boolean Test: {} failed (field may not exist): {}", case_name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_numeric_data_types(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test various numeric values
|
||||||
|
let numeric_test_cases = vec![
|
||||||
|
("Zero", 0.0),
|
||||||
|
("Positive", 123.45),
|
||||||
|
("Negative", -67.89),
|
||||||
|
("Large", 999999.99),
|
||||||
|
("SmallDecimal", 0.01),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, numeric_value) in numeric_test_cases {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value("Numeric Test Company"));
|
||||||
|
// Assuming there's a numeric field called 'price' or 'amount'
|
||||||
|
data.insert("amount".to_string(), create_number_value(numeric_value));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
println!("Numeric Test: {} ({}) succeeded", case_name, numeric_value);
|
||||||
|
|
||||||
|
// Verify round-trip
|
||||||
|
if let Ok(get_response) = context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
response.inserted_id,
|
||||||
|
).await {
|
||||||
|
if let Some(retrieved_value) = get_response.data.get("amount") {
|
||||||
|
println!("Numeric Test: {} round-trip value: {}", case_name, retrieved_value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("Numeric Test: {} failed (field may not exist): {}", case_name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_timestamp_data_type(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test various timestamp formats
|
||||||
|
let timestamp_test_cases = vec![
|
||||||
|
("ISO8601", "2024-01-15T10:30:00Z"),
|
||||||
|
("WithTimezone", "2024-01-15T10:30:00+01:00"),
|
||||||
|
("WithMilliseconds", "2024-01-15T10:30:00.123Z"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, timestamp_str) in timestamp_test_cases {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value("Timestamp Test Company"));
|
||||||
|
// Assuming there's a timestamp field called 'created_at'
|
||||||
|
data.insert("created_at".to_string(), create_string_value(timestamp_str));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
println!("Timestamp Test: {} succeeded", case_name);
|
||||||
|
|
||||||
|
// Verify round-trip
|
||||||
|
if let Ok(get_response) = context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
response.inserted_id,
|
||||||
|
).await {
|
||||||
|
if let Some(retrieved_value) = get_response.data.get("created_at") {
|
||||||
|
println!("Timestamp Test: {} round-trip value: {}", case_name, retrieved_value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("Timestamp Test: {} failed (field may not exist): {}", case_name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_invalid_data_types(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test invalid data type combinations
|
||||||
|
let invalid_type_cases = vec![
|
||||||
|
("StringForNumber", "amount", create_string_value("not-a-number")),
|
||||||
|
("NumberForBoolean", "active", create_number_value(123.0)),
|
||||||
|
("StringForBoolean", "active", create_string_value("maybe")),
|
||||||
|
("InvalidTimestamp", "created_at", create_string_value("not-a-date")),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, field_name, invalid_value) in invalid_type_cases {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value("Invalid Type Test"));
|
||||||
|
data.insert(field_name.to_string(), invalid_value);
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(_) => {
|
||||||
|
println!("Invalid Type Test: {} passed (no type validation or field doesn't exist)", case_name);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(status) = e.downcast_ref::<Status>() {
|
||||||
|
assert_eq!(status.code(), tonic::Code::InvalidArgument,
|
||||||
|
"Invalid data type should return InvalidArgument for case: {}", case_name);
|
||||||
|
println!("Invalid Type Test: {} correctly rejected - {}", case_name, status.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// FOREIGN KEY RELATIONSHIP TESTS
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_foreign_key_valid_relationship(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Create a parent record first (e.g., company)
|
||||||
|
let mut parent_data = HashMap::new();
|
||||||
|
parent_data.insert("firma".to_string(), create_string_value("Parent Company"));
|
||||||
|
|
||||||
|
let parent_result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
"companies".to_string(), // Assuming companies table exists
|
||||||
|
parent_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
if let Ok(parent_response) = parent_result {
|
||||||
|
let parent_id = parent_response.inserted_id;
|
||||||
|
|
||||||
|
// 2. Create a child record that references the parent
|
||||||
|
let mut child_data = HashMap::new();
|
||||||
|
child_data.insert("name".to_string(), create_string_value("Child Record"));
|
||||||
|
child_data.insert("company_id".to_string(), create_number_value(parent_id as f64));
|
||||||
|
|
||||||
|
let child_result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
"contacts".to_string(), // Assuming contacts table exists
|
||||||
|
child_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match child_result {
|
||||||
|
Ok(child_response) => {
|
||||||
|
assert!(child_response.success, "Valid foreign key relationship should succeed");
|
||||||
|
println!("Foreign Key Test: Valid relationship created - Parent ID: {}, Child ID: {}",
|
||||||
|
parent_id, child_response.inserted_id);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("Foreign Key Test: Failed (tables may not exist or no FK constraint): {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("Foreign Key Test: Could not create parent record");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_foreign_key_invalid_relationship(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Try to create a child record with non-existent parent ID
|
||||||
|
let mut invalid_child_data = HashMap::new();
|
||||||
|
invalid_child_data.insert("name".to_string(), create_string_value("Orphan Record"));
|
||||||
|
invalid_child_data.insert("company_id".to_string(), create_number_value(99999.0)); // Non-existent ID
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
"contacts".to_string(),
|
||||||
|
invalid_child_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(_) => {
|
||||||
|
println!("Foreign Key Test: Invalid relationship passed (no FK constraint configured)");
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(status) = e.downcast_ref::<Status>() {
|
||||||
|
// Could be InvalidArgument or NotFound depending on implementation
|
||||||
|
assert!(matches!(status.code(), tonic::Code::InvalidArgument | tonic::Code::NotFound),
|
||||||
|
"Invalid foreign key should return InvalidArgument or NotFound");
|
||||||
|
println!("Foreign Key Test: Invalid relationship correctly rejected - {}", status.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// DELETED RECORD INTERACTION TESTS
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_update_deleted_record_behavior(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Create a record
|
||||||
|
let initial_data = context.create_test_form_data();
|
||||||
|
let post_result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
initial_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
if let Ok(post_response) = post_result {
|
||||||
|
let record_id = post_response.inserted_id;
|
||||||
|
println!("Deleted Record Test: Created record ID {}", record_id);
|
||||||
|
|
||||||
|
// 2. Delete the record (soft delete)
|
||||||
|
let delete_result = context.client.delete_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
assert!(delete_result.is_ok(), "Delete should succeed");
|
||||||
|
println!("Deleted Record Test: Soft-deleted record {}", record_id);
|
||||||
|
|
||||||
|
// 3. Try to UPDATE the deleted record
|
||||||
|
let mut update_data = HashMap::new();
|
||||||
|
update_data.insert("firma".to_string(), create_string_value("Updated Deleted Record"));
|
||||||
|
|
||||||
|
let update_result = context.client.put_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
update_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match update_result {
|
||||||
|
Ok(_) => {
|
||||||
|
// This might be a bug - updating deleted records should probably fail
|
||||||
|
println!("Deleted Record Test: UPDATE on deleted record succeeded (potential bug?)");
|
||||||
|
|
||||||
|
// Check if the record is still considered deleted
|
||||||
|
let get_result = context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
if get_result.is_err() {
|
||||||
|
println!("Deleted Record Test: Record still appears deleted after update");
|
||||||
|
} else {
|
||||||
|
println!("Deleted Record Test: Record appears to be undeleted after update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(status) = e.downcast_ref::<Status>() {
|
||||||
|
assert_eq!(status.code(), tonic::Code::NotFound,
|
||||||
|
"UPDATE on deleted record should return NotFound");
|
||||||
|
println!("Deleted Record Test: UPDATE correctly rejected on deleted record");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_delete_already_deleted_record(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// 1. Create and delete a record
|
||||||
|
let initial_data = context.create_test_form_data();
|
||||||
|
let post_result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
initial_data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
if let Ok(post_response) = post_result {
|
||||||
|
let record_id = post_response.inserted_id;
|
||||||
|
|
||||||
|
// First deletion
|
||||||
|
let delete_result1 = context.client.delete_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
).await;
|
||||||
|
assert!(delete_result1.is_ok(), "First delete should succeed");
|
||||||
|
|
||||||
|
// Second deletion (idempotent)
|
||||||
|
let delete_result2 = context.client.delete_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
assert!(delete_result2.is_ok(), "Second delete should succeed (idempotent)");
|
||||||
|
if let Ok(response) = delete_result2 {
|
||||||
|
assert!(response.success, "Delete should report success even for already-deleted record");
|
||||||
|
}
|
||||||
|
println!("Double Delete Test: Both deletions succeeded (idempotent behavior)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// VALIDATION AND BOUNDARY TESTS
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_large_data_handling(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test with very large string values
|
||||||
|
let large_string = "A".repeat(10000); // 10KB string
|
||||||
|
let very_large_string = "B".repeat(100000); // 100KB string
|
||||||
|
|
||||||
|
let test_cases = vec![
|
||||||
|
("Large", large_string),
|
||||||
|
("VeryLarge", very_large_string),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, large_value) in test_cases {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value(&large_value));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
println!("Large Data Test: {} string handled successfully", case_name);
|
||||||
|
|
||||||
|
// Verify round-trip
|
||||||
|
if let Ok(get_response) = context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
response.inserted_id,
|
||||||
|
).await {
|
||||||
|
if let Some(retrieved_value) = get_response.data.get("firma") {
|
||||||
|
assert_eq!(retrieved_value.len(), large_value.len(),
|
||||||
|
"Large string should survive round-trip for case: {}", case_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("Large Data Test: {} failed (may hit size limits): {}", case_name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_sql_injection_attempts(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test potential SQL injection strings
|
||||||
|
let injection_attempts = vec![
|
||||||
|
("SingleQuote", "'; DROP TABLE users; --"),
|
||||||
|
("DoubleQuote", "\"; DROP TABLE users; --"),
|
||||||
|
("Union", "' UNION SELECT * FROM users --"),
|
||||||
|
("Comment", "/* malicious comment */"),
|
||||||
|
("Semicolon", "; DELETE FROM users;"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (case_name, injection_string) in injection_attempts {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value(injection_string));
|
||||||
|
data.insert("kz".to_string(), create_string_value("KZ123"));
|
||||||
|
|
||||||
|
let result = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {
|
||||||
|
println!("SQL Injection Test: {} handled safely (parameterized queries)", case_name);
|
||||||
|
|
||||||
|
// Verify the malicious string was stored as-is (not executed)
|
||||||
|
if let Ok(get_response) = context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
response.inserted_id,
|
||||||
|
).await {
|
||||||
|
if let Some(retrieved_value) = get_response.data.get("firma") {
|
||||||
|
assert_eq!(retrieved_value, injection_string,
|
||||||
|
"Injection string should be stored literally for case: {}", case_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("SQL Injection Test: {} rejected: {}", case_name, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_concurrent_operations_with_same_data(#[future] form_test_context: FormTestContext) {
|
||||||
|
let context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
// Test multiple concurrent operations with identical data
|
||||||
|
let mut handles = Vec::new();
|
||||||
|
let num_tasks = 10;
|
||||||
|
|
||||||
|
for i in 0..num_tasks {
|
||||||
|
let mut context_clone = context.clone();
|
||||||
|
let handle = tokio::spawn(async move {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value("Concurrent Identical"));
|
||||||
|
data.insert("kz".to_string(), create_string_value(&format!("SAME{:02}", i)));
|
||||||
|
|
||||||
|
context_clone.client.post_table_data(
|
||||||
|
context_clone.profile_name,
|
||||||
|
context_clone.table_name,
|
||||||
|
data,
|
||||||
|
).await
|
||||||
|
});
|
||||||
|
handles.push(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all to complete
|
||||||
|
let mut success_count = 0;
|
||||||
|
let mut inserted_ids = Vec::new();
|
||||||
|
|
||||||
|
for (i, handle) in handles.into_iter().enumerate() {
|
||||||
|
match handle.await {
|
||||||
|
Ok(Ok(response)) => {
|
||||||
|
success_count += 1;
|
||||||
|
inserted_ids.push(response.inserted_id);
|
||||||
|
println!("Concurrent Identical Data: Task {} succeeded with ID {}", i, response.inserted_id);
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
println!("Concurrent Identical Data: Task {} failed: {}", i, e);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
println!("Concurrent Identical Data: Task {} panicked: {}", i, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(success_count > 0, "At least some concurrent operations should succeed");
|
||||||
|
|
||||||
|
// Verify all IDs are unique
|
||||||
|
let unique_ids: std::collections::HashSet<_> = inserted_ids.iter().collect();
|
||||||
|
assert_eq!(unique_ids.len(), inserted_ids.len(), "All inserted IDs should be unique");
|
||||||
|
|
||||||
|
println!("Concurrent Identical Data: {}/{} operations succeeded with unique IDs",
|
||||||
|
success_count, num_tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// PERFORMANCE AND STRESS TESTS
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_bulk_operations_performance(#[future] form_test_context: FormTestContext) {
|
||||||
|
let mut context = form_test_context.await;
|
||||||
|
skip_if_backend_unavailable!();
|
||||||
|
|
||||||
|
let operation_count = 50;
|
||||||
|
let start_time = std::time::Instant::now();
|
||||||
|
|
||||||
|
let mut successful_operations = 0;
|
||||||
|
let mut created_ids = Vec::new();
|
||||||
|
|
||||||
|
// Bulk create
|
||||||
|
for i in 0..operation_count {
|
||||||
|
let mut data = HashMap::new();
|
||||||
|
data.insert("firma".to_string(), create_string_value(&format!("Bulk Company {}", i)));
|
||||||
|
data.insert("kz".to_string(), create_string_value(&format!("BLK{:02}", i)));
|
||||||
|
|
||||||
|
if let Ok(response) = context.client.post_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
data,
|
||||||
|
).await {
|
||||||
|
successful_operations += 1;
|
||||||
|
created_ids.push(response.inserted_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let create_duration = start_time.elapsed();
|
||||||
|
println!("Bulk Performance: Created {} records in {:?}", successful_operations, create_duration);
|
||||||
|
|
||||||
|
// Bulk read
|
||||||
|
let read_start = std::time::Instant::now();
|
||||||
|
let mut successful_reads = 0;
|
||||||
|
|
||||||
|
for &record_id in &created_ids {
|
||||||
|
if context.client.get_table_data(
|
||||||
|
context.profile_name.clone(),
|
||||||
|
context.table_name.clone(),
|
||||||
|
record_id,
|
||||||
|
).await.is_ok() {
|
||||||
|
successful_reads += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let read_duration = read_start.elapsed();
|
||||||
|
println!("Bulk Performance: Read {} records in {:?}", successful_reads, read_duration);
|
||||||
|
|
||||||
|
// Performance assertions
|
||||||
|
assert!(successful_operations > operation_count * 8 / 10,
|
||||||
|
"At least 80% of operations should succeed");
|
||||||
|
assert!(create_duration.as_secs() < 60,
|
||||||
|
"Bulk operations should complete in reasonable time");
|
||||||
|
|
||||||
|
println!("Bulk Performance Test: {}/{} creates, {}/{} reads successful",
|
||||||
|
successful_operations, operation_count, successful_reads, created_ids.len());
|
||||||
|
}
|
||||||
1
client/tests/form/requests/mod.rs
Normal file
1
client/tests/form/requests/mod.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
pub mod form_request_tests;
|
||||||
3
client/tests/mod.rs
Normal file
3
client/tests/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
// tests/mod.rs
|
||||||
|
|
||||||
|
pub mod form;
|
||||||
@@ -5,9 +5,14 @@ edition.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
prost-types = { workspace = true }
|
||||||
|
|
||||||
tonic = "0.13.0"
|
tonic = "0.13.0"
|
||||||
prost = "0.13.5"
|
prost = "0.13.5"
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
|
|
||||||
|
# Search
|
||||||
|
tantivy = { workspace = true }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
tonic-build = "0.13.0"
|
tonic-build = "0.13.0"
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
"proto/table_definition.proto",
|
"proto/table_definition.proto",
|
||||||
"proto/tables_data.proto",
|
"proto/tables_data.proto",
|
||||||
"proto/table_script.proto",
|
"proto/table_script.proto",
|
||||||
|
"proto/search.proto",
|
||||||
],
|
],
|
||||||
&["proto"],
|
&["proto"],
|
||||||
)?;
|
)?;
|
||||||
|
|||||||
20
common/proto/search.proto
Normal file
20
common/proto/search.proto
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
// In common/proto/search.proto
|
||||||
|
syntax = "proto3";
|
||||||
|
package multieko2.search;
|
||||||
|
|
||||||
|
service Searcher {
|
||||||
|
rpc SearchTable(SearchRequest) returns (SearchResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
message SearchRequest {
|
||||||
|
string table_name = 1;
|
||||||
|
string query = 2;
|
||||||
|
}
|
||||||
|
message SearchResponse {
|
||||||
|
message Hit {
|
||||||
|
int64 id = 1; // PostgreSQL row ID
|
||||||
|
float score = 2;
|
||||||
|
string content_json = 3;
|
||||||
|
}
|
||||||
|
repeated Hit hits = 1;
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ syntax = "proto3";
|
|||||||
package multieko2.tables_data;
|
package multieko2.tables_data;
|
||||||
|
|
||||||
import "common.proto";
|
import "common.proto";
|
||||||
|
import "google/protobuf/struct.proto";
|
||||||
|
|
||||||
service TablesData {
|
service TablesData {
|
||||||
rpc PostTableData (PostTableDataRequest) returns (PostTableDataResponse);
|
rpc PostTableData (PostTableDataRequest) returns (PostTableDataResponse);
|
||||||
@@ -16,7 +17,7 @@ service TablesData {
|
|||||||
message PostTableDataRequest {
|
message PostTableDataRequest {
|
||||||
string profile_name = 1;
|
string profile_name = 1;
|
||||||
string table_name = 2;
|
string table_name = 2;
|
||||||
map<string, string> data = 3;
|
map<string, google.protobuf.Value> data = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
message PostTableDataResponse {
|
message PostTableDataResponse {
|
||||||
@@ -29,7 +30,7 @@ message PutTableDataRequest {
|
|||||||
string profile_name = 1;
|
string profile_name = 1;
|
||||||
string table_name = 2;
|
string table_name = 2;
|
||||||
int64 id = 3;
|
int64 id = 3;
|
||||||
map<string, string> data = 4;
|
map<string, google.protobuf.Value> data = 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
message PutTableDataResponse {
|
message PutTableDataResponse {
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
// common/src/lib.rs
|
// common/src/lib.rs
|
||||||
|
|
||||||
|
pub mod search;
|
||||||
|
|
||||||
pub mod proto {
|
pub mod proto {
|
||||||
pub mod multieko2 {
|
pub mod multieko2 {
|
||||||
pub mod adresar {
|
pub mod adresar {
|
||||||
@@ -25,6 +28,9 @@ pub mod proto {
|
|||||||
pub mod table_script {
|
pub mod table_script {
|
||||||
include!("proto/multieko2.table_script.rs");
|
include!("proto/multieko2.table_script.rs");
|
||||||
}
|
}
|
||||||
|
pub mod search {
|
||||||
|
include!("proto/multieko2.search.rs");
|
||||||
|
}
|
||||||
pub const FILE_DESCRIPTOR_SET: &[u8] =
|
pub const FILE_DESCRIPTOR_SET: &[u8] =
|
||||||
include_bytes!("proto/descriptor.bin");
|
include_bytes!("proto/descriptor.bin");
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
317
common/src/proto/multieko2.search.rs
Normal file
317
common/src/proto/multieko2.search.rs
Normal file
@@ -0,0 +1,317 @@
|
|||||||
|
// This file is @generated by prost-build.
|
||||||
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
|
pub struct SearchRequest {
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
pub table_name: ::prost::alloc::string::String,
|
||||||
|
#[prost(string, tag = "2")]
|
||||||
|
pub query: ::prost::alloc::string::String,
|
||||||
|
}
|
||||||
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
|
pub struct SearchResponse {
|
||||||
|
#[prost(message, repeated, tag = "1")]
|
||||||
|
pub hits: ::prost::alloc::vec::Vec<search_response::Hit>,
|
||||||
|
}
|
||||||
|
/// Nested message and enum types in `SearchResponse`.
|
||||||
|
pub mod search_response {
|
||||||
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
|
pub struct Hit {
|
||||||
|
/// PostgreSQL row ID
|
||||||
|
#[prost(int64, tag = "1")]
|
||||||
|
pub id: i64,
|
||||||
|
#[prost(float, tag = "2")]
|
||||||
|
pub score: f32,
|
||||||
|
#[prost(string, tag = "3")]
|
||||||
|
pub content_json: ::prost::alloc::string::String,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Generated client implementations.
|
||||||
|
pub mod searcher_client {
|
||||||
|
#![allow(
|
||||||
|
unused_variables,
|
||||||
|
dead_code,
|
||||||
|
missing_docs,
|
||||||
|
clippy::wildcard_imports,
|
||||||
|
clippy::let_unit_value,
|
||||||
|
)]
|
||||||
|
use tonic::codegen::*;
|
||||||
|
use tonic::codegen::http::Uri;
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SearcherClient<T> {
|
||||||
|
inner: tonic::client::Grpc<T>,
|
||||||
|
}
|
||||||
|
impl SearcherClient<tonic::transport::Channel> {
|
||||||
|
/// Attempt to create a new client by connecting to a given endpoint.
|
||||||
|
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
|
||||||
|
where
|
||||||
|
D: TryInto<tonic::transport::Endpoint>,
|
||||||
|
D::Error: Into<StdError>,
|
||||||
|
{
|
||||||
|
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
|
||||||
|
Ok(Self::new(conn))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> SearcherClient<T>
|
||||||
|
where
|
||||||
|
T: tonic::client::GrpcService<tonic::body::Body>,
|
||||||
|
T::Error: Into<StdError>,
|
||||||
|
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
|
||||||
|
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
|
||||||
|
{
|
||||||
|
pub fn new(inner: T) -> Self {
|
||||||
|
let inner = tonic::client::Grpc::new(inner);
|
||||||
|
Self { inner }
|
||||||
|
}
|
||||||
|
pub fn with_origin(inner: T, origin: Uri) -> Self {
|
||||||
|
let inner = tonic::client::Grpc::with_origin(inner, origin);
|
||||||
|
Self { inner }
|
||||||
|
}
|
||||||
|
pub fn with_interceptor<F>(
|
||||||
|
inner: T,
|
||||||
|
interceptor: F,
|
||||||
|
) -> SearcherClient<InterceptedService<T, F>>
|
||||||
|
where
|
||||||
|
F: tonic::service::Interceptor,
|
||||||
|
T::ResponseBody: Default,
|
||||||
|
T: tonic::codegen::Service<
|
||||||
|
http::Request<tonic::body::Body>,
|
||||||
|
Response = http::Response<
|
||||||
|
<T as tonic::client::GrpcService<tonic::body::Body>>::ResponseBody,
|
||||||
|
>,
|
||||||
|
>,
|
||||||
|
<T as tonic::codegen::Service<
|
||||||
|
http::Request<tonic::body::Body>,
|
||||||
|
>>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
|
||||||
|
{
|
||||||
|
SearcherClient::new(InterceptedService::new(inner, interceptor))
|
||||||
|
}
|
||||||
|
/// Compress requests with the given encoding.
|
||||||
|
///
|
||||||
|
/// This requires the server to support it otherwise it might respond with an
|
||||||
|
/// error.
|
||||||
|
#[must_use]
|
||||||
|
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.inner = self.inner.send_compressed(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Enable decompressing responses.
|
||||||
|
#[must_use]
|
||||||
|
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.inner = self.inner.accept_compressed(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of a decoded message.
|
||||||
|
///
|
||||||
|
/// Default: `4MB`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.inner = self.inner.max_decoding_message_size(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of an encoded message.
|
||||||
|
///
|
||||||
|
/// Default: `usize::MAX`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.inner = self.inner.max_encoding_message_size(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub async fn search_table(
|
||||||
|
&mut self,
|
||||||
|
request: impl tonic::IntoRequest<super::SearchRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::SearchResponse>, tonic::Status> {
|
||||||
|
self.inner
|
||||||
|
.ready()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tonic::Status::unknown(
|
||||||
|
format!("Service was not ready: {}", e.into()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let path = http::uri::PathAndQuery::from_static(
|
||||||
|
"/multieko2.search.Searcher/SearchTable",
|
||||||
|
);
|
||||||
|
let mut req = request.into_request();
|
||||||
|
req.extensions_mut()
|
||||||
|
.insert(GrpcMethod::new("multieko2.search.Searcher", "SearchTable"));
|
||||||
|
self.inner.unary(req, path, codec).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Generated server implementations.
|
||||||
|
pub mod searcher_server {
|
||||||
|
#![allow(
|
||||||
|
unused_variables,
|
||||||
|
dead_code,
|
||||||
|
missing_docs,
|
||||||
|
clippy::wildcard_imports,
|
||||||
|
clippy::let_unit_value,
|
||||||
|
)]
|
||||||
|
use tonic::codegen::*;
|
||||||
|
/// Generated trait containing gRPC methods that should be implemented for use with SearcherServer.
|
||||||
|
#[async_trait]
|
||||||
|
pub trait Searcher: std::marker::Send + std::marker::Sync + 'static {
|
||||||
|
async fn search_table(
|
||||||
|
&self,
|
||||||
|
request: tonic::Request<super::SearchRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::SearchResponse>, tonic::Status>;
|
||||||
|
}
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct SearcherServer<T> {
|
||||||
|
inner: Arc<T>,
|
||||||
|
accept_compression_encodings: EnabledCompressionEncodings,
|
||||||
|
send_compression_encodings: EnabledCompressionEncodings,
|
||||||
|
max_decoding_message_size: Option<usize>,
|
||||||
|
max_encoding_message_size: Option<usize>,
|
||||||
|
}
|
||||||
|
impl<T> SearcherServer<T> {
|
||||||
|
pub fn new(inner: T) -> Self {
|
||||||
|
Self::from_arc(Arc::new(inner))
|
||||||
|
}
|
||||||
|
pub fn from_arc(inner: Arc<T>) -> Self {
|
||||||
|
Self {
|
||||||
|
inner,
|
||||||
|
accept_compression_encodings: Default::default(),
|
||||||
|
send_compression_encodings: Default::default(),
|
||||||
|
max_decoding_message_size: None,
|
||||||
|
max_encoding_message_size: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn with_interceptor<F>(
|
||||||
|
inner: T,
|
||||||
|
interceptor: F,
|
||||||
|
) -> InterceptedService<Self, F>
|
||||||
|
where
|
||||||
|
F: tonic::service::Interceptor,
|
||||||
|
{
|
||||||
|
InterceptedService::new(Self::new(inner), interceptor)
|
||||||
|
}
|
||||||
|
/// Enable decompressing requests with the given encoding.
|
||||||
|
#[must_use]
|
||||||
|
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.accept_compression_encodings.enable(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Compress responses with the given encoding, if the client supports it.
|
||||||
|
#[must_use]
|
||||||
|
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.send_compression_encodings.enable(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of a decoded message.
|
||||||
|
///
|
||||||
|
/// Default: `4MB`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.max_decoding_message_size = Some(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of an encoded message.
|
||||||
|
///
|
||||||
|
/// Default: `usize::MAX`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.max_encoding_message_size = Some(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T, B> tonic::codegen::Service<http::Request<B>> for SearcherServer<T>
|
||||||
|
where
|
||||||
|
T: Searcher,
|
||||||
|
B: Body + std::marker::Send + 'static,
|
||||||
|
B::Error: Into<StdError> + std::marker::Send + 'static,
|
||||||
|
{
|
||||||
|
type Response = http::Response<tonic::body::Body>;
|
||||||
|
type Error = std::convert::Infallible;
|
||||||
|
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||||
|
fn poll_ready(
|
||||||
|
&mut self,
|
||||||
|
_cx: &mut Context<'_>,
|
||||||
|
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||||
|
match req.uri().path() {
|
||||||
|
"/multieko2.search.Searcher/SearchTable" => {
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
struct SearchTableSvc<T: Searcher>(pub Arc<T>);
|
||||||
|
impl<T: Searcher> tonic::server::UnaryService<super::SearchRequest>
|
||||||
|
for SearchTableSvc<T> {
|
||||||
|
type Response = super::SearchResponse;
|
||||||
|
type Future = BoxFuture<
|
||||||
|
tonic::Response<Self::Response>,
|
||||||
|
tonic::Status,
|
||||||
|
>;
|
||||||
|
fn call(
|
||||||
|
&mut self,
|
||||||
|
request: tonic::Request<super::SearchRequest>,
|
||||||
|
) -> Self::Future {
|
||||||
|
let inner = Arc::clone(&self.0);
|
||||||
|
let fut = async move {
|
||||||
|
<T as Searcher>::search_table(&inner, request).await
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let accept_compression_encodings = self.accept_compression_encodings;
|
||||||
|
let send_compression_encodings = self.send_compression_encodings;
|
||||||
|
let max_decoding_message_size = self.max_decoding_message_size;
|
||||||
|
let max_encoding_message_size = self.max_encoding_message_size;
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
let fut = async move {
|
||||||
|
let method = SearchTableSvc(inner);
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let mut grpc = tonic::server::Grpc::new(codec)
|
||||||
|
.apply_compression_config(
|
||||||
|
accept_compression_encodings,
|
||||||
|
send_compression_encodings,
|
||||||
|
)
|
||||||
|
.apply_max_message_size_config(
|
||||||
|
max_decoding_message_size,
|
||||||
|
max_encoding_message_size,
|
||||||
|
);
|
||||||
|
let res = grpc.unary(method, req).await;
|
||||||
|
Ok(res)
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut response = http::Response::new(
|
||||||
|
tonic::body::Body::default(),
|
||||||
|
);
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers
|
||||||
|
.insert(
|
||||||
|
tonic::Status::GRPC_STATUS,
|
||||||
|
(tonic::Code::Unimplemented as i32).into(),
|
||||||
|
);
|
||||||
|
headers
|
||||||
|
.insert(
|
||||||
|
http::header::CONTENT_TYPE,
|
||||||
|
tonic::metadata::GRPC_CONTENT_TYPE,
|
||||||
|
);
|
||||||
|
Ok(response)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> Clone for SearcherServer<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
Self {
|
||||||
|
inner,
|
||||||
|
accept_compression_encodings: self.accept_compression_encodings,
|
||||||
|
send_compression_encodings: self.send_compression_encodings,
|
||||||
|
max_decoding_message_size: self.max_decoding_message_size,
|
||||||
|
max_encoding_message_size: self.max_encoding_message_size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Generated gRPC service name
|
||||||
|
pub const SERVICE_NAME: &str = "multieko2.search.Searcher";
|
||||||
|
impl<T> tonic::server::NamedService for SearcherServer<T> {
|
||||||
|
const NAME: &'static str = SERVICE_NAME;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,10 +5,10 @@ pub struct PostTableDataRequest {
|
|||||||
pub profile_name: ::prost::alloc::string::String,
|
pub profile_name: ::prost::alloc::string::String,
|
||||||
#[prost(string, tag = "2")]
|
#[prost(string, tag = "2")]
|
||||||
pub table_name: ::prost::alloc::string::String,
|
pub table_name: ::prost::alloc::string::String,
|
||||||
#[prost(map = "string, string", tag = "3")]
|
#[prost(map = "string, message", tag = "3")]
|
||||||
pub data: ::std::collections::HashMap<
|
pub data: ::std::collections::HashMap<
|
||||||
::prost::alloc::string::String,
|
::prost::alloc::string::String,
|
||||||
::prost::alloc::string::String,
|
::prost_types::Value,
|
||||||
>,
|
>,
|
||||||
}
|
}
|
||||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
@@ -28,10 +28,10 @@ pub struct PutTableDataRequest {
|
|||||||
pub table_name: ::prost::alloc::string::String,
|
pub table_name: ::prost::alloc::string::String,
|
||||||
#[prost(int64, tag = "3")]
|
#[prost(int64, tag = "3")]
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
#[prost(map = "string, string", tag = "4")]
|
#[prost(map = "string, message", tag = "4")]
|
||||||
pub data: ::std::collections::HashMap<
|
pub data: ::std::collections::HashMap<
|
||||||
::prost::alloc::string::String,
|
::prost::alloc::string::String,
|
||||||
::prost::alloc::string::String,
|
::prost_types::Value,
|
||||||
>,
|
>,
|
||||||
}
|
}
|
||||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||||
|
|||||||
78
common/src/search.rs
Normal file
78
common/src/search.rs
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
// common/src/search.rs
|
||||||
|
|
||||||
|
use tantivy::schema::*;
|
||||||
|
use tantivy::tokenizer::*;
|
||||||
|
use tantivy::Index;
|
||||||
|
|
||||||
|
/// Creates a hybrid Slovak search schema with optimized prefix fields.
|
||||||
|
pub fn create_search_schema() -> Schema {
|
||||||
|
let mut schema_builder = Schema::builder();
|
||||||
|
|
||||||
|
schema_builder.add_u64_field("pg_id", INDEXED | STORED);
|
||||||
|
|
||||||
|
// FIELD 1: For prefixes (1-4 chars).
|
||||||
|
let short_prefix_indexing = TextFieldIndexing::default()
|
||||||
|
.set_tokenizer("slovak_prefix_edge")
|
||||||
|
.set_index_option(IndexRecordOption::WithFreqsAndPositions);
|
||||||
|
let short_prefix_options = TextOptions::default()
|
||||||
|
.set_indexing_options(short_prefix_indexing)
|
||||||
|
.set_stored();
|
||||||
|
schema_builder.add_text_field("prefix_edge", short_prefix_options);
|
||||||
|
|
||||||
|
// FIELD 2: For the full word.
|
||||||
|
let full_word_indexing = TextFieldIndexing::default()
|
||||||
|
.set_tokenizer("slovak_prefix_full")
|
||||||
|
.set_index_option(IndexRecordOption::WithFreqsAndPositions);
|
||||||
|
let full_word_options = TextOptions::default()
|
||||||
|
.set_indexing_options(full_word_indexing)
|
||||||
|
.set_stored();
|
||||||
|
schema_builder.add_text_field("prefix_full", full_word_options);
|
||||||
|
|
||||||
|
// NGRAM FIELD: For substring matching.
|
||||||
|
let ngram_field_indexing = TextFieldIndexing::default()
|
||||||
|
.set_tokenizer("slovak_ngram")
|
||||||
|
.set_index_option(IndexRecordOption::WithFreqsAndPositions);
|
||||||
|
let ngram_options = TextOptions::default()
|
||||||
|
.set_indexing_options(ngram_field_indexing)
|
||||||
|
.set_stored();
|
||||||
|
schema_builder.add_text_field("text_ngram", ngram_options);
|
||||||
|
|
||||||
|
schema_builder.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Registers all necessary Slovak tokenizers with the index.
|
||||||
|
///
|
||||||
|
/// This must be called by ANY process that opens the index
|
||||||
|
/// to ensure the tokenizers are loaded into memory.
|
||||||
|
pub fn register_slovak_tokenizers(index: &Index) -> tantivy::Result<()> {
|
||||||
|
let tokenizer_manager = index.tokenizers();
|
||||||
|
|
||||||
|
// TOKENIZER for `prefix_edge`: Edge N-gram (1-4 chars)
|
||||||
|
let edge_tokenizer =
|
||||||
|
TextAnalyzer::builder(NgramTokenizer::new(1, 4, true)?)
|
||||||
|
.filter(RemoveLongFilter::limit(40))
|
||||||
|
.filter(LowerCaser)
|
||||||
|
.filter(AsciiFoldingFilter)
|
||||||
|
.build();
|
||||||
|
tokenizer_manager.register("slovak_prefix_edge", edge_tokenizer);
|
||||||
|
|
||||||
|
// TOKENIZER for `prefix_full`: Simple word tokenizer
|
||||||
|
let full_tokenizer =
|
||||||
|
TextAnalyzer::builder(SimpleTokenizer::default())
|
||||||
|
.filter(RemoveLongFilter::limit(40))
|
||||||
|
.filter(LowerCaser)
|
||||||
|
.filter(AsciiFoldingFilter)
|
||||||
|
.build();
|
||||||
|
tokenizer_manager.register("slovak_prefix_full", full_tokenizer);
|
||||||
|
|
||||||
|
// NGRAM TOKENIZER: For substring matching.
|
||||||
|
let ngram_tokenizer =
|
||||||
|
TextAnalyzer::builder(NgramTokenizer::new(3, 3, false)?)
|
||||||
|
.filter(RemoveLongFilter::limit(40))
|
||||||
|
.filter(LowerCaser)
|
||||||
|
.filter(AsciiFoldingFilter)
|
||||||
|
.build();
|
||||||
|
tokenizer_manager.register("slovak_ngram", ngram_tokenizer);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
19
search/Cargo.toml
Normal file
19
search/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "search"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license = "AGPL-3.0-or-later"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
prost = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
tonic = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
tantivy = { workspace = true }
|
||||||
|
|
||||||
|
common = { path = "../common" }
|
||||||
|
tonic-reflection = "0.13.1"
|
||||||
|
sqlx = { version = "0.8.6", features = ["postgres"] }
|
||||||
302
search/src/lib.rs
Normal file
302
search/src/lib.rs
Normal file
@@ -0,0 +1,302 @@
|
|||||||
|
// src/lib.rs
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::Path;
|
||||||
|
use tantivy::collector::TopDocs;
|
||||||
|
use tantivy::query::{
|
||||||
|
BooleanQuery, BoostQuery, FuzzyTermQuery, Occur, Query, QueryParser,
|
||||||
|
TermQuery,
|
||||||
|
};
|
||||||
|
use tantivy::schema::{IndexRecordOption, Value};
|
||||||
|
use tantivy::{Index, TantivyDocument, Term};
|
||||||
|
use tonic::{Request, Response, Status};
|
||||||
|
|
||||||
|
use common::proto::multieko2::search::{
|
||||||
|
search_response::Hit, SearchRequest, SearchResponse,
|
||||||
|
};
|
||||||
|
pub use common::proto::multieko2::search::searcher_server::SearcherServer;
|
||||||
|
use common::proto::multieko2::search::searcher_server::Searcher;
|
||||||
|
use common::search::register_slovak_tokenizers;
|
||||||
|
use sqlx::{PgPool, Row};
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
// We need to hold the database pool in our service struct.
|
||||||
|
pub struct SearcherService {
|
||||||
|
pub pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalize_slovak_text function remains unchanged...
|
||||||
|
fn normalize_slovak_text(text: &str) -> String {
|
||||||
|
// ... function content is unchanged ...
|
||||||
|
text.chars()
|
||||||
|
.map(|c| match c {
|
||||||
|
'á' | 'à' | 'â' | 'ä' | 'ă' | 'ā' => 'a',
|
||||||
|
'Á' | 'À' | 'Â' | 'Ä' | 'Ă' | 'Ā' => 'A',
|
||||||
|
'é' | 'è' | 'ê' | 'ë' | 'ě' | 'ē' => 'e',
|
||||||
|
'É' | 'È' | 'Ê' | 'Ë' | 'Ě' | 'Ē' => 'E',
|
||||||
|
'í' | 'ì' | 'î' | 'ï' | 'ī' => 'i',
|
||||||
|
'Í' | 'Ì' | 'Î' | 'Ï' | 'Ī' => 'I',
|
||||||
|
'ó' | 'ò' | 'ô' | 'ö' | 'ō' | 'ő' => 'o',
|
||||||
|
'Ó' | 'Ò' | 'Ô' | 'Ö' | 'Ō' | 'Ő' => 'O',
|
||||||
|
'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ű' => 'u',
|
||||||
|
'Ú' | 'Ù' | 'Û' | 'Ü' | 'Ū' | 'Ű' => 'U',
|
||||||
|
'ý' | 'ỳ' | 'ŷ' | 'ÿ' => 'y',
|
||||||
|
'Ý' | 'Ỳ' | 'Ŷ' | 'Ÿ' => 'Y',
|
||||||
|
'č' => 'c',
|
||||||
|
'Č' => 'C',
|
||||||
|
'ď' => 'd',
|
||||||
|
'Ď' => 'D',
|
||||||
|
'ľ' => 'l',
|
||||||
|
'Ľ' => 'L',
|
||||||
|
'ň' => 'n',
|
||||||
|
'Ň' => 'N',
|
||||||
|
'ř' => 'r',
|
||||||
|
'Ř' => 'R',
|
||||||
|
'š' => 's',
|
||||||
|
'Š' => 'S',
|
||||||
|
'ť' => 't',
|
||||||
|
'Ť' => 'T',
|
||||||
|
'ž' => 'z',
|
||||||
|
'Ž' => 'Z',
|
||||||
|
_ => c,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl Searcher for SearcherService {
|
||||||
|
async fn search_table(
|
||||||
|
&self,
|
||||||
|
request: Request<SearchRequest>,
|
||||||
|
) -> Result<Response<SearchResponse>, Status> {
|
||||||
|
let req = request.into_inner();
|
||||||
|
let table_name = req.table_name;
|
||||||
|
let query_str = req.query;
|
||||||
|
|
||||||
|
// --- MODIFIED LOGIC ---
|
||||||
|
// If the query is empty, fetch the 5 most recent records.
|
||||||
|
if query_str.trim().is_empty() {
|
||||||
|
info!(
|
||||||
|
"Empty query for table '{}'. Fetching default results.",
|
||||||
|
table_name
|
||||||
|
);
|
||||||
|
let qualified_table = format!("gen.\"{}\"", table_name);
|
||||||
|
let sql = format!(
|
||||||
|
"SELECT id, to_jsonb(t) AS data FROM {} t ORDER BY id DESC LIMIT 5",
|
||||||
|
qualified_table
|
||||||
|
);
|
||||||
|
|
||||||
|
let rows = sqlx::query(&sql)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
Status::internal(format!(
|
||||||
|
"DB query for default results failed: {}",
|
||||||
|
e
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let hits: Vec<Hit> = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|row| {
|
||||||
|
let id: i64 = row.try_get("id").unwrap_or_default();
|
||||||
|
let json_data: serde_json::Value =
|
||||||
|
row.try_get("data").unwrap_or_default();
|
||||||
|
Hit {
|
||||||
|
id,
|
||||||
|
// Score is 0.0 as this is not a relevance-ranked search
|
||||||
|
score: 0.0,
|
||||||
|
content_json: json_data.to_string(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
info!("--- SERVER: Successfully processed empty query. Returning {} default hits. ---", hits.len());
|
||||||
|
return Ok(Response::new(SearchResponse { hits }));
|
||||||
|
}
|
||||||
|
// --- END OF MODIFIED LOGIC ---
|
||||||
|
|
||||||
|
let index_path = Path::new("./tantivy_indexes").join(&table_name);
|
||||||
|
if !index_path.exists() {
|
||||||
|
return Err(Status::not_found(format!(
|
||||||
|
"No search index found for table '{}'",
|
||||||
|
table_name
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = Index::open_in_dir(&index_path)
|
||||||
|
.map_err(|e| Status::internal(format!("Failed to open index: {}", e)))?;
|
||||||
|
|
||||||
|
register_slovak_tokenizers(&index).map_err(|e| {
|
||||||
|
Status::internal(format!("Failed to register Slovak tokenizers: {}", e))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let reader = index.reader().map_err(|e| {
|
||||||
|
Status::internal(format!("Failed to create index reader: {}", e))
|
||||||
|
})?;
|
||||||
|
let searcher = reader.searcher();
|
||||||
|
let schema = index.schema();
|
||||||
|
|
||||||
|
let pg_id_field = schema.get_field("pg_id").map_err(|_| {
|
||||||
|
Status::internal("Schema is missing the 'pg_id' field.")
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// --- Query Building Logic (no changes here) ---
|
||||||
|
let prefix_edge_field = schema.get_field("prefix_edge").unwrap();
|
||||||
|
let prefix_full_field = schema.get_field("prefix_full").unwrap();
|
||||||
|
let text_ngram_field = schema.get_field("text_ngram").unwrap();
|
||||||
|
let normalized_query = normalize_slovak_text(&query_str);
|
||||||
|
let words: Vec<&str> = normalized_query.split_whitespace().collect();
|
||||||
|
if words.is_empty() {
|
||||||
|
return Ok(Response::new(SearchResponse { hits: vec![] }));
|
||||||
|
}
|
||||||
|
let mut query_layers: Vec<(Occur, Box<dyn Query>)> = Vec::new();
|
||||||
|
// ... all your query building layers remain exactly the same ...
|
||||||
|
// ===============================
|
||||||
|
// LAYER 1: PREFIX MATCHING (HIGHEST PRIORITY, Boost: 4.0)
|
||||||
|
// ===============================
|
||||||
|
{
|
||||||
|
let mut must_clauses: Vec<(Occur, Box<dyn Query>)> = Vec::new();
|
||||||
|
for word in &words {
|
||||||
|
let edge_term =
|
||||||
|
Term::from_field_text(prefix_edge_field, word);
|
||||||
|
let full_term =
|
||||||
|
Term::from_field_text(prefix_full_field, word);
|
||||||
|
|
||||||
|
let per_word_query = BooleanQuery::new(vec![
|
||||||
|
(
|
||||||
|
Occur::Should,
|
||||||
|
Box::new(TermQuery::new(
|
||||||
|
edge_term,
|
||||||
|
IndexRecordOption::Basic,
|
||||||
|
)),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
Occur::Should,
|
||||||
|
Box::new(TermQuery::new(
|
||||||
|
full_term,
|
||||||
|
IndexRecordOption::Basic,
|
||||||
|
)),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
must_clauses.push((Occur::Must, Box::new(per_word_query) as Box<dyn Query>));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !must_clauses.is_empty() {
|
||||||
|
let prefix_query = BooleanQuery::new(must_clauses);
|
||||||
|
let boosted_query =
|
||||||
|
BoostQuery::new(Box::new(prefix_query), 4.0);
|
||||||
|
query_layers.push((Occur::Should, Box::new(boosted_query)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===============================
|
||||||
|
// LAYER 2: FUZZY MATCHING (HIGH PRIORITY, Boost: 3.0)
|
||||||
|
// ===============================
|
||||||
|
{
|
||||||
|
let last_word = words.last().unwrap();
|
||||||
|
let fuzzy_term =
|
||||||
|
Term::from_field_text(prefix_full_field, last_word);
|
||||||
|
let fuzzy_query = FuzzyTermQuery::new(fuzzy_term, 2, true);
|
||||||
|
let boosted_query = BoostQuery::new(Box::new(fuzzy_query), 3.0);
|
||||||
|
query_layers.push((Occur::Should, Box::new(boosted_query)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===============================
|
||||||
|
// LAYER 3: PHRASE MATCHING WITH SLOP (MEDIUM PRIORITY, Boost: 2.0)
|
||||||
|
// ===============================
|
||||||
|
if words.len() > 1 {
|
||||||
|
let slop_parser =
|
||||||
|
QueryParser::for_index(&index, vec![prefix_full_field]);
|
||||||
|
let slop_query_str = format!("\"{}\"~3", normalized_query);
|
||||||
|
if let Ok(slop_query) = slop_parser.parse_query(&slop_query_str) {
|
||||||
|
let boosted_query = BoostQuery::new(slop_query, 2.0);
|
||||||
|
query_layers.push((Occur::Should, Box::new(boosted_query)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===============================
|
||||||
|
// LAYER 4: NGRAM SUBSTRING MATCHING (LOWEST PRIORITY, Boost: 1.0)
|
||||||
|
// ===============================
|
||||||
|
{
|
||||||
|
let ngram_parser =
|
||||||
|
QueryParser::for_index(&index, vec![text_ngram_field]);
|
||||||
|
if let Ok(ngram_query) =
|
||||||
|
ngram_parser.parse_query(&normalized_query)
|
||||||
|
{
|
||||||
|
let boosted_query = BoostQuery::new(ngram_query, 1.0);
|
||||||
|
query_layers.push((Occur::Should, Box::new(boosted_query)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let master_query = BooleanQuery::new(query_layers);
|
||||||
|
// --- End of Query Building Logic ---
|
||||||
|
|
||||||
|
let top_docs = searcher
|
||||||
|
.search(&master_query, &TopDocs::with_limit(100))
|
||||||
|
.map_err(|e| Status::internal(format!("Search failed: {}", e)))?;
|
||||||
|
|
||||||
|
if top_docs.is_empty() {
|
||||||
|
return Ok(Response::new(SearchResponse { hits: vec![] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- NEW LOGIC: Fetch from DB and combine results ---
|
||||||
|
|
||||||
|
// Step 1: Extract (score, pg_id) from Tantivy results.
|
||||||
|
let mut scored_ids: Vec<(f32, u64)> = Vec::new();
|
||||||
|
for (score, doc_address) in top_docs {
|
||||||
|
let doc: TantivyDocument = searcher.doc(doc_address).map_err(|e| {
|
||||||
|
Status::internal(format!("Failed to retrieve document: {}", e))
|
||||||
|
})?;
|
||||||
|
if let Some(pg_id_value) = doc.get_first(pg_id_field) {
|
||||||
|
if let Some(pg_id) = pg_id_value.as_u64() {
|
||||||
|
scored_ids.push((score, pg_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Fetch all corresponding rows from Postgres in a single query.
|
||||||
|
let pg_ids: Vec<i64> =
|
||||||
|
scored_ids.iter().map(|(_, id)| *id as i64).collect();
|
||||||
|
let qualified_table = format!("gen.\"{}\"", table_name);
|
||||||
|
let query_str = format!(
|
||||||
|
"SELECT id, to_jsonb(t) AS data FROM {} t WHERE id = ANY($1)",
|
||||||
|
qualified_table
|
||||||
|
);
|
||||||
|
|
||||||
|
let rows = sqlx::query(&query_str)
|
||||||
|
.bind(&pg_ids)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
Status::internal(format!("Database query failed: {}", e))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Step 3: Map the database results by ID for quick lookup.
|
||||||
|
let mut content_map: HashMap<i64, String> = HashMap::new();
|
||||||
|
for row in rows {
|
||||||
|
let id: i64 = row.try_get("id").unwrap_or(0);
|
||||||
|
let json_data: serde_json::Value =
|
||||||
|
row.try_get("data").unwrap_or(serde_json::Value::Null);
|
||||||
|
content_map.insert(id, json_data.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 4: Build the final response, combining Tantivy scores with PG content.
|
||||||
|
let hits: Vec<Hit> = scored_ids
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(score, pg_id)| {
|
||||||
|
content_map
|
||||||
|
.get(&(pg_id as i64))
|
||||||
|
.map(|content_json| Hit {
|
||||||
|
id: pg_id as i64,
|
||||||
|
score,
|
||||||
|
content_json: content_json.clone(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
info!("--- SERVER: Successfully processed search. Returning {} hits. ---", hits.len());
|
||||||
|
|
||||||
|
let response = SearchResponse { hits };
|
||||||
|
Ok(Response::new(response))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,13 +6,17 @@ license = "AGPL-3.0-or-later"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
|
search = { path = "../search" }
|
||||||
|
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
tantivy = { workspace = true }
|
||||||
|
prost-types = { workspace = true }
|
||||||
chrono = { version = "0.4.40", features = ["serde"] }
|
chrono = { version = "0.4.40", features = ["serde"] }
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
prost = "0.13.5"
|
prost = "0.13.5"
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_json = "1.0.140"
|
serde_json = "1.0.140"
|
||||||
sqlx = { version = "0.8.5", features = ["chrono", "postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "uuid"] }
|
sqlx = { version = "0.8.5", features = ["chrono", "postgres", "runtime-tokio", "runtime-tokio-native-tls", "rust_decimal", "time", "uuid"] }
|
||||||
tokio = { version = "1.44.2", features = ["full", "macros"] }
|
tokio = { version = "1.44.2", features = ["full", "macros"] }
|
||||||
tonic = "0.13.0"
|
tonic = "0.13.0"
|
||||||
tonic-reflection = "0.13.0"
|
tonic-reflection = "0.13.0"
|
||||||
@@ -28,6 +32,9 @@ bcrypt = "0.17.0"
|
|||||||
validator = { version = "0.20.0", features = ["derive"] }
|
validator = { version = "0.20.0", features = ["derive"] }
|
||||||
uuid = { version = "1.16.0", features = ["serde", "v4"] }
|
uuid = { version = "1.16.0", features = ["serde", "v4"] }
|
||||||
jsonwebtoken = "9.3.1"
|
jsonwebtoken = "9.3.1"
|
||||||
|
rust-stemmers = "1.2.0"
|
||||||
|
rust_decimal = { version = "1.37.2", features = ["maths", "serde"] }
|
||||||
|
rust_decimal_macros = "1.37.1"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "server"
|
name = "server"
|
||||||
@@ -37,3 +44,5 @@ path = "src/lib.rs"
|
|||||||
tokio = { version = "1.44", features = ["full", "test-util"] }
|
tokio = { version = "1.44", features = ["full", "test-util"] }
|
||||||
rstest = "0.25.0"
|
rstest = "0.25.0"
|
||||||
lazy_static = "1.5.0"
|
lazy_static = "1.5.0"
|
||||||
|
rand = "0.9.1"
|
||||||
|
futures = "0.3.31"
|
||||||
|
|||||||
13
server/Makefile
Normal file
13
server/Makefile
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
# Makefile
|
||||||
|
|
||||||
|
test: reset_db run_tests
|
||||||
|
|
||||||
|
reset_db:
|
||||||
|
@echo "Resetting test database..."
|
||||||
|
@./scripts/reset_test_db.sh
|
||||||
|
|
||||||
|
run_tests:
|
||||||
|
@echo "Running tests..."
|
||||||
|
@cargo test --test mod -- --test-threads=1
|
||||||
|
|
||||||
|
.PHONY: test
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
-- Add migration script here
|
|
||||||
CREATE TABLE adresar (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
firma TEXT NOT NULL,
|
|
||||||
kz TEXT,
|
|
||||||
drc TEXT,
|
|
||||||
ulica TEXT,
|
|
||||||
psc TEXT,
|
|
||||||
mesto TEXT,
|
|
||||||
stat TEXT,
|
|
||||||
banka TEXT,
|
|
||||||
ucet TEXT,
|
|
||||||
skladm TEXT,
|
|
||||||
ico TEXT,
|
|
||||||
kontakt TEXT,
|
|
||||||
telefon TEXT,
|
|
||||||
skladu TEXT,
|
|
||||||
fax TEXT,
|
|
||||||
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX idx_adresar_firma ON adresar (firma);
|
|
||||||
CREATE INDEX idx_adresar_mesto ON adresar (mesto);
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
-- Add migration script here
|
|
||||||
CREATE TABLE uctovnictvo (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
adresar_id BIGINT NOT NULL REFERENCES adresar(id), -- Link to adresar table
|
|
||||||
c_dokladu TEXT NOT NULL,
|
|
||||||
datum DATE NOT NULL,
|
|
||||||
c_faktury TEXT NOT NULL,
|
|
||||||
obsah TEXT,
|
|
||||||
stredisko TEXT,
|
|
||||||
c_uctu TEXT,
|
|
||||||
md TEXT,
|
|
||||||
identif TEXT,
|
|
||||||
poznanka TEXT,
|
|
||||||
firma TEXT NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX idx_uctovnictvo_adresar_id ON uctovnictvo (adresar_id);
|
|
||||||
CREATE INDEX idx_uctovnictvo_firma ON uctovnictvo (firma);
|
|
||||||
CREATE INDEX idx_uctovnictvo_c_dokladu ON uctovnictvo (c_dokladu);
|
|
||||||
CREATE INDEX idx_uctovnictvo_poznanka ON uctovnictvo (poznanka);
|
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
-- Add migration script here
|
-- Add migration script here
|
||||||
CREATE TABLE profiles (
|
CREATE TABLE schemas (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
name TEXT NOT NULL UNIQUE,
|
name TEXT NOT NULL UNIQUE,
|
||||||
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
|
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
description TEXT,
|
||||||
|
is_active BOOLEAN DEFAULT TRUE
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Create default profile for existing data
|
-- Create default profile for existing data
|
||||||
INSERT INTO profiles (name) VALUES ('default');
|
INSERT INTO schemas (name) VALUES ('default');
|
||||||
|
CREATE SCHEMA IF NOT EXISTS "default";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
-- Main table definitions
|
-- Main table definitions
|
||||||
|
|
||||||
CREATE TABLE table_definitions (
|
CREATE TABLE table_definitions (
|
||||||
id BIGSERIAL PRIMARY KEY,
|
id BIGSERIAL PRIMARY KEY,
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
@@ -6,7 +7,7 @@ CREATE TABLE table_definitions (
|
|||||||
columns JSONB NOT NULL,
|
columns JSONB NOT NULL,
|
||||||
indexes JSONB NOT NULL,
|
indexes JSONB NOT NULL,
|
||||||
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
||||||
profile_id BIGINT NOT NULL REFERENCES profiles(id) DEFAULT 1
|
schema_id BIGINT NOT NULL REFERENCES schemas(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Relationship table for multiple links
|
-- Relationship table for multiple links
|
||||||
@@ -18,9 +19,10 @@ CREATE TABLE table_definition_links (
|
|||||||
PRIMARY KEY (source_table_id, linked_table_id)
|
PRIMARY KEY (source_table_id, linked_table_id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Create composite unique index for profile+table combination
|
-- Create composite unique index for schema+table combination
|
||||||
CREATE UNIQUE INDEX idx_table_definitions_profile_table
|
CREATE UNIQUE INDEX idx_table_definitions_schema_table
|
||||||
ON table_definitions (profile_id, table_name);
|
ON table_definitions (schema_id, table_name);
|
||||||
|
|
||||||
CREATE INDEX idx_links_source ON table_definition_links (source_table_id);
|
CREATE INDEX idx_links_source ON table_definition_links (source_table_id);
|
||||||
CREATE INDEX idx_links_target ON table_definition_links (linked_table_id);
|
CREATE INDEX idx_links_target ON table_definition_links (linked_table_id);
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ CREATE TABLE table_scripts (
|
|||||||
script TEXT NOT NULL,
|
script TEXT NOT NULL,
|
||||||
description TEXT,
|
description TEXT,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
profile_id BIGINT NOT NULL REFERENCES profiles(id) DEFAULT 1,
|
schema_id BIGINT NOT NULL REFERENCES schemas(id),
|
||||||
UNIQUE(table_definitions_id, target_column)
|
UNIQUE(table_definitions_id, target_column)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
9
server/scripts/reset_test_db.sh
Executable file
9
server/scripts/reset_test_db.sh
Executable file
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# scripts/reset_test_db.sh
|
||||||
|
|
||||||
|
DATABASE_URL=${TEST_DATABASE_URL:-"postgres://multi_psql_dev:3@localhost:5432/multi_rust_test"}
|
||||||
|
|
||||||
|
echo "Reset db script"
|
||||||
|
yes | sqlx database drop --database-url "$DATABASE_URL"
|
||||||
|
sqlx database create --database-url "$DATABASE_URL"
|
||||||
|
echo "Test database reset complete."
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
❯ grpcurl -plaintext -d '{"id": 1}' localhost:50051 multieko2.adresar.Adresar/GetAdresar
|
|
||||||
{
|
|
||||||
"id": "1",
|
|
||||||
"firma": "Updated Firma",
|
|
||||||
"kz": "Updated KZ",
|
|
||||||
"drc": "Updated DRC",
|
|
||||||
"ulica": "Updated Ulica",
|
|
||||||
"psc": "Updated PSC",
|
|
||||||
"mesto": "Updated Mesto",
|
|
||||||
"stat": "Updated Stat",
|
|
||||||
"banka": "Updated Banka",
|
|
||||||
"ucet": "Updated Ucet",
|
|
||||||
"skladm": "Updated Skladm",
|
|
||||||
"ico": "Updated ICO",
|
|
||||||
"kontakt": "Updated Kontakt",
|
|
||||||
"telefon": "Updated Telefon",
|
|
||||||
"skladu": "Updated Skladu",
|
|
||||||
"fax": "Updated Fax"
|
|
||||||
}
|
|
||||||
❯ grpcurl -plaintext -d '{"id": 2}' localhost:50051 multieko2.adresar.Adresar/GetAdresar
|
|
||||||
{
|
|
||||||
"id": "2",
|
|
||||||
"firma": "asdfasf",
|
|
||||||
"kz": " ",
|
|
||||||
"drc": " ",
|
|
||||||
"ulica": " ",
|
|
||||||
"psc": "sdfasdf",
|
|
||||||
"mesto": "asf",
|
|
||||||
"stat": "as",
|
|
||||||
"banka": "df",
|
|
||||||
"ucet": "asf",
|
|
||||||
"skladm": "f",
|
|
||||||
"ico": "f",
|
|
||||||
"kontakt": "f",
|
|
||||||
"telefon": "f",
|
|
||||||
"skladu": "f",
|
|
||||||
"fax": " "
|
|
||||||
}
|
|
||||||
❯ grpcurl -plaintext -d '{"id": 1}' localhost:50051 multieko2.adresar.Adresar/DeleteAdresar
|
|
||||||
{
|
|
||||||
"success": true
|
|
||||||
}
|
|
||||||
❯ grpcurl -plaintext -d '{"id": 1}' localhost:50051 multieko2.adresar.Adresar/GetAdresar
|
|
||||||
ERROR:
|
|
||||||
Code: NotFound
|
|
||||||
Message: no rows returned by a query that expected to return at least one row
|
|
||||||
❯ grpcurl -plaintext -d '{"id": 2}' localhost:50051 multieko2.adresar.Adresar/GetAdresar
|
|
||||||
{
|
|
||||||
"id": "2",
|
|
||||||
"firma": "asdfasf",
|
|
||||||
"kz": " ",
|
|
||||||
"drc": " ",
|
|
||||||
"ulica": " ",
|
|
||||||
"psc": "sdfasdf",
|
|
||||||
"mesto": "asf",
|
|
||||||
"stat": "as",
|
|
||||||
"banka": "df",
|
|
||||||
"ucet": "asf",
|
|
||||||
"skladm": "f",
|
|
||||||
"ico": "f",
|
|
||||||
"kontakt": "f",
|
|
||||||
"telefon": "f",
|
|
||||||
"skladu": "f",
|
|
||||||
"fax": " "
|
|
||||||
}
|
|
||||||
|
|
||||||
❯ grpcurl -plaintext -d '{
|
|
||||||
"firma": "New Firma",
|
|
||||||
"kz": "New KZ",
|
|
||||||
"drc": "New DRC",
|
|
||||||
"ulica": "New Ulica",
|
|
||||||
"psc": "New PSC",
|
|
||||||
"mesto": "New Mesto",
|
|
||||||
"stat": "New Stat",
|
|
||||||
"banka": "New Banka",
|
|
||||||
"ucet": "New Ucet",
|
|
||||||
"skladm": "New Skladm",
|
|
||||||
"ico": "New ICO",
|
|
||||||
"kontakt": "New Kontakt",
|
|
||||||
"telefon": "New Telefon",
|
|
||||||
"skladu": "New Skladu",
|
|
||||||
"fax": "New Fax"
|
|
||||||
}' localhost:50051 multieko2.adresar.Adresar/PostAdresar
|
|
||||||
{
|
|
||||||
"id": "43",
|
|
||||||
"firma": "New Firma",
|
|
||||||
"kz": "New KZ",
|
|
||||||
"drc": "New DRC",
|
|
||||||
"ulica": "New Ulica",
|
|
||||||
"psc": "New PSC",
|
|
||||||
"mesto": "New Mesto",
|
|
||||||
"stat": "New Stat",
|
|
||||||
"banka": "New Banka",
|
|
||||||
"ucet": "New Ucet",
|
|
||||||
"skladm": "New Skladm",
|
|
||||||
"ico": "New ICO",
|
|
||||||
"kontakt": "New Kontakt",
|
|
||||||
"telefon": "New Telefon",
|
|
||||||
"skladu": "New Skladu",
|
|
||||||
"fax": "New Fax"
|
|
||||||
}
|
|
||||||
❯ grpcurl -plaintext -d '{
|
|
||||||
"id": 43,
|
|
||||||
"firma": "Updated Firma",
|
|
||||||
"kz": "Updated KZ",
|
|
||||||
"drc": "Updated DRC",
|
|
||||||
"ulica": "Updated Ulica",
|
|
||||||
"psc": "Updated PSC",
|
|
||||||
"mesto": "Updated Mesto",
|
|
||||||
"stat": "Updated Stat",
|
|
||||||
"banka": "Updated Banka",
|
|
||||||
"ucet": "Updated Ucet",
|
|
||||||
"skladm": "Updated Skladm",
|
|
||||||
"ico": "Updated ICO",
|
|
||||||
"kontakt": "Updated Kontakt",
|
|
||||||
"telefon": "Updated Telefon",
|
|
||||||
"skladu": "Updated Skladu",
|
|
||||||
"fax": "Updated Fax"
|
|
||||||
}' localhost:50051 multieko2.adresar.Adresar/PutAdresar
|
|
||||||
{
|
|
||||||
"id": "43",
|
|
||||||
"firma": "Updated Firma",
|
|
||||||
"kz": "Updated KZ",
|
|
||||||
"drc": "Updated DRC",
|
|
||||||
"ulica": "Updated Ulica",
|
|
||||||
"psc": "Updated PSC",
|
|
||||||
"mesto": "Updated Mesto",
|
|
||||||
"stat": "Updated Stat",
|
|
||||||
"banka": "Updated Banka",
|
|
||||||
"ucet": "Updated Ucet",
|
|
||||||
"skladm": "Updated Skladm",
|
|
||||||
"ico": "Updated ICO",
|
|
||||||
"kontakt": "Updated Kontakt",
|
|
||||||
"telefon": "Updated Telefon",
|
|
||||||
"skladu": "Updated Skladu",
|
|
||||||
"fax": "Updated Fax"
|
|
||||||
}
|
|
||||||
❯ grpcurl -plaintext -d '{"id": 43}' localhost:50051 multieko2.adresar.Adresar/GetAdresar
|
|
||||||
{
|
|
||||||
"id": "43",
|
|
||||||
"firma": "Updated Firma",
|
|
||||||
"kz": "Updated KZ",
|
|
||||||
"drc": "Updated DRC",
|
|
||||||
"ulica": "Updated Ulica",
|
|
||||||
"psc": "Updated PSC",
|
|
||||||
"mesto": "Updated Mesto",
|
|
||||||
"stat": "Updated Stat",
|
|
||||||
"banka": "Updated Banka",
|
|
||||||
"ucet": "Updated Ucet",
|
|
||||||
"skladm": "Updated Skladm",
|
|
||||||
"ico": "Updated ICO",
|
|
||||||
"kontakt": "Updated Kontakt",
|
|
||||||
"telefon": "Updated Telefon",
|
|
||||||
"skladu": "Updated Skladu",
|
|
||||||
"fax": "Updated Fax"
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
|
|
||||||
# TOTAL items in the adresar
|
|
||||||
❯ grpcurl -plaintext localhost:50051 multieko2.adresar.Adresar/GetAdresarCount
|
|
||||||
{
|
|
||||||
"count": "5"
|
|
||||||
}
|
|
||||||
# Item at this count. If there are 43 items, number 1 is the first item
|
|
||||||
❯ grpcurl -plaintext -d '{"position": 1}' localhost:50051 multieko2.adresar.Adresar/GetAdresarByPosition
|
|
||||||
{
|
|
||||||
"id": "1",
|
|
||||||
"firma": "ks555",
|
|
||||||
"kz": "f",
|
|
||||||
"drc": "asdf",
|
|
||||||
"ulica": "as",
|
|
||||||
"psc": "f",
|
|
||||||
"mesto": "asf",
|
|
||||||
"stat": "as",
|
|
||||||
"banka": "fa",
|
|
||||||
"telefon": "a",
|
|
||||||
"skladu": "fd",
|
|
||||||
"fax": "asf"
|
|
||||||
}
|
|
||||||
# Item fetched by id. The first item was created and marked as deleted, therefore number 1 in ids shouldnt be fetched.
|
|
||||||
❯ grpcurl -plaintext -d '{"id": 1}' localhost:50051 multieko2.adresar.Adresar/GetAdresar
|
|
||||||
ERROR:
|
|
||||||
Code: NotFound
|
|
||||||
Message: no rows returned by a query that expected to return at least one row
|
|
||||||
╭─ ~ ············································· 69 ✘
|
|
||||||
╰─
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
// src/adresar/handlers.rs
|
|
||||||
|
|
||||||
pub mod post_adresar;
|
|
||||||
pub mod get_adresar;
|
|
||||||
pub mod put_adresar;
|
|
||||||
pub mod delete_adresar;
|
|
||||||
pub mod get_adresar_count;
|
|
||||||
pub mod get_adresar_by_position;
|
|
||||||
|
|
||||||
pub use post_adresar::post_adresar;
|
|
||||||
pub use get_adresar::get_adresar;
|
|
||||||
pub use put_adresar::put_adresar;
|
|
||||||
pub use delete_adresar::delete_adresar;
|
|
||||||
pub use get_adresar_count::get_adresar_count;
|
|
||||||
pub use get_adresar_by_position::get_adresar_by_position;
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
// src/adresar/handlers/delete_adresar.rs
|
|
||||||
use tonic::Status;
|
|
||||||
use sqlx::PgPool;
|
|
||||||
use common::proto::multieko2::adresar::{DeleteAdresarRequest, DeleteAdresarResponse};
|
|
||||||
|
|
||||||
pub async fn delete_adresar(
|
|
||||||
db_pool: &PgPool,
|
|
||||||
request: DeleteAdresarRequest,
|
|
||||||
) -> Result<DeleteAdresarResponse, Status> {
|
|
||||||
let rows_affected = sqlx::query!(
|
|
||||||
r#"
|
|
||||||
UPDATE adresar
|
|
||||||
SET deleted = true
|
|
||||||
WHERE id = $1 AND deleted = false
|
|
||||||
"#,
|
|
||||||
request.id
|
|
||||||
)
|
|
||||||
.execute(db_pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| Status::internal(e.to_string()))?
|
|
||||||
.rows_affected();
|
|
||||||
|
|
||||||
Ok(DeleteAdresarResponse {
|
|
||||||
success: rows_affected > 0,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
// src/adresar/handlers/get_adresar.rs
|
|
||||||
use tonic::Status;
|
|
||||||
use sqlx::PgPool;
|
|
||||||
use crate::adresar::models::Adresar;
|
|
||||||
use common::proto::multieko2::adresar::{GetAdresarRequest, AdresarResponse};
|
|
||||||
|
|
||||||
pub async fn get_adresar(
|
|
||||||
db_pool: &PgPool,
|
|
||||||
request: GetAdresarRequest,
|
|
||||||
) -> Result<AdresarResponse, Status> {
|
|
||||||
let adresar = sqlx::query_as!(
|
|
||||||
Adresar,
|
|
||||||
r#"
|
|
||||||
SELECT
|
|
||||||
id,
|
|
||||||
deleted,
|
|
||||||
firma,
|
|
||||||
kz,
|
|
||||||
drc,
|
|
||||||
ulica,
|
|
||||||
psc,
|
|
||||||
mesto,
|
|
||||||
stat,
|
|
||||||
banka,
|
|
||||||
ucet,
|
|
||||||
skladm,
|
|
||||||
ico,
|
|
||||||
kontakt,
|
|
||||||
telefon,
|
|
||||||
skladu,
|
|
||||||
fax
|
|
||||||
FROM adresar
|
|
||||||
WHERE id = $1 AND deleted = false
|
|
||||||
"#,
|
|
||||||
request.id
|
|
||||||
)
|
|
||||||
.fetch_one(db_pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| match e {
|
|
||||||
sqlx::Error::RowNotFound => Status::not_found("Record not found"),
|
|
||||||
_ => Status::internal(format!("Database error: {}", e)),
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(AdresarResponse {
|
|
||||||
id: adresar.id,
|
|
||||||
firma: adresar.firma,
|
|
||||||
kz: adresar.kz.unwrap_or_default(),
|
|
||||||
drc: adresar.drc.unwrap_or_default(),
|
|
||||||
ulica: adresar.ulica.unwrap_or_default(),
|
|
||||||
psc: adresar.psc.unwrap_or_default(),
|
|
||||||
mesto: adresar.mesto.unwrap_or_default(),
|
|
||||||
stat: adresar.stat.unwrap_or_default(),
|
|
||||||
banka: adresar.banka.unwrap_or_default(),
|
|
||||||
ucet: adresar.ucet.unwrap_or_default(),
|
|
||||||
skladm: adresar.skladm.unwrap_or_default(),
|
|
||||||
ico: adresar.ico.unwrap_or_default(),
|
|
||||||
kontakt: adresar.kontakt.unwrap_or_default(),
|
|
||||||
telefon: adresar.telefon.unwrap_or_default(),
|
|
||||||
skladu: adresar.skladu.unwrap_or_default(),
|
|
||||||
fax: adresar.fax.unwrap_or_default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
// src/adresar/handlers/get_adresar_by_position.rs
|
|
||||||
use tonic::{Status};
|
|
||||||
use sqlx::PgPool;
|
|
||||||
use common::proto::multieko2::adresar::{AdresarResponse, GetAdresarRequest};
|
|
||||||
use common::proto::multieko2::common::PositionRequest;
|
|
||||||
use super::get_adresar;
|
|
||||||
|
|
||||||
pub async fn get_adresar_by_position(
|
|
||||||
db_pool: &PgPool,
|
|
||||||
request: PositionRequest,
|
|
||||||
) -> Result<AdresarResponse, Status> {
|
|
||||||
if request.position < 1 {
|
|
||||||
return Err(Status::invalid_argument("Position must be at least 1"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find the ID of the Nth non-deleted record
|
|
||||||
let id: i64 = sqlx::query_scalar!(
|
|
||||||
r#"
|
|
||||||
SELECT id
|
|
||||||
FROM adresar
|
|
||||||
WHERE deleted = FALSE
|
|
||||||
ORDER BY id ASC
|
|
||||||
OFFSET $1
|
|
||||||
LIMIT 1
|
|
||||||
"#,
|
|
||||||
request.position - 1
|
|
||||||
)
|
|
||||||
.fetch_optional(db_pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| Status::internal(e.to_string()))?
|
|
||||||
.ok_or_else(|| Status::not_found("Position out of bounds"))?;
|
|
||||||
|
|
||||||
// Now fetch the complete record using the existing get_adresar function
|
|
||||||
get_adresar(db_pool, GetAdresarRequest { id }).await
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
// src/adresar/handlers/get_adresar_count.rs
|
|
||||||
use tonic::Status;
|
|
||||||
use sqlx::PgPool;
|
|
||||||
use common::proto::multieko2::common::{CountResponse, Empty};
|
|
||||||
|
|
||||||
pub async fn get_adresar_count(
|
|
||||||
db_pool: &PgPool,
|
|
||||||
_request: Empty,
|
|
||||||
) -> Result<CountResponse, Status> {
|
|
||||||
let count: i64 = sqlx::query_scalar!(
|
|
||||||
r#"
|
|
||||||
SELECT COUNT(*) AS count
|
|
||||||
FROM adresar
|
|
||||||
WHERE deleted = FALSE
|
|
||||||
"#
|
|
||||||
)
|
|
||||||
.fetch_one(db_pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| Status::internal(e.to_string()))?
|
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
Ok(CountResponse { count })
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
// src/adresar/handlers/post_adresar.rs
|
|
||||||
use tonic::Status;
|
|
||||||
use sqlx::PgPool;
|
|
||||||
use crate::adresar::models::Adresar;
|
|
||||||
use common::proto::multieko2::adresar::{PostAdresarRequest, AdresarResponse};
|
|
||||||
|
|
||||||
// Helper function to sanitize inputs
|
|
||||||
fn sanitize_input(input: &str) -> Option<String> {
|
|
||||||
let trimmed = input.trim().to_string();
|
|
||||||
if trimmed.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(trimmed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn post_adresar(
|
|
||||||
db_pool: &PgPool,
|
|
||||||
mut request: PostAdresarRequest,
|
|
||||||
) -> Result<AdresarResponse, Status> {
|
|
||||||
request.firma = request.firma.trim().to_string();
|
|
||||||
if request.firma.is_empty() {
|
|
||||||
return Err(Status::invalid_argument("Firma je povinne pole"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanitize optional fields
|
|
||||||
let kz = sanitize_input(&request.kz);
|
|
||||||
let drc = sanitize_input(&request.drc);
|
|
||||||
let ulica = sanitize_input(&request.ulica);
|
|
||||||
let psc = sanitize_input(&request.psc);
|
|
||||||
let mesto = sanitize_input(&request.mesto);
|
|
||||||
let stat = sanitize_input(&request.stat);
|
|
||||||
let banka = sanitize_input(&request.banka);
|
|
||||||
let ucet = sanitize_input(&request.ucet);
|
|
||||||
let skladm = sanitize_input(&request.skladm);
|
|
||||||
let ico = sanitize_input(&request.ico);
|
|
||||||
let kontakt = sanitize_input(&request.kontakt);
|
|
||||||
let telefon = sanitize_input(&request.telefon);
|
|
||||||
let skladu = sanitize_input(&request.skladu);
|
|
||||||
let fax = sanitize_input(&request.fax);
|
|
||||||
|
|
||||||
let adresar = sqlx::query_as!(
|
|
||||||
Adresar,
|
|
||||||
r#"
|
|
||||||
INSERT INTO adresar (
|
|
||||||
firma, kz, drc, ulica, psc, mesto, stat, banka, ucet,
|
|
||||||
skladm, ico, kontakt, telefon, skladu, fax, deleted
|
|
||||||
)
|
|
||||||
VALUES (
|
|
||||||
$1, $2, $3, $4, $5, $6, $7, $8, $9,
|
|
||||||
$10, $11, $12, $13, $14, $15, $16
|
|
||||||
)
|
|
||||||
RETURNING
|
|
||||||
id, deleted, firma, kz, drc, ulica, psc, mesto, stat,
|
|
||||||
banka, ucet, skladm, ico, kontakt, telefon, skladu, fax
|
|
||||||
"#,
|
|
||||||
request.firma,
|
|
||||||
kz,
|
|
||||||
drc,
|
|
||||||
ulica,
|
|
||||||
psc,
|
|
||||||
mesto,
|
|
||||||
stat,
|
|
||||||
banka,
|
|
||||||
ucet,
|
|
||||||
skladm,
|
|
||||||
ico,
|
|
||||||
kontakt,
|
|
||||||
telefon,
|
|
||||||
skladu,
|
|
||||||
fax,
|
|
||||||
false
|
|
||||||
)
|
|
||||||
.fetch_one(db_pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| Status::internal(e.to_string()))?;
|
|
||||||
|
|
||||||
Ok(AdresarResponse {
|
|
||||||
id: adresar.id,
|
|
||||||
// Do not include `deleted` in the response since it's not
|
|
||||||
// defined in the proto message.
|
|
||||||
firma: adresar.firma,
|
|
||||||
kz: adresar.kz.unwrap_or_default(),
|
|
||||||
drc: adresar.drc.unwrap_or_default(),
|
|
||||||
ulica: adresar.ulica.unwrap_or_default(),
|
|
||||||
psc: adresar.psc.unwrap_or_default(),
|
|
||||||
mesto: adresar.mesto.unwrap_or_default(),
|
|
||||||
stat: adresar.stat.unwrap_or_default(),
|
|
||||||
banka: adresar.banka.unwrap_or_default(),
|
|
||||||
ucet: adresar.ucet.unwrap_or_default(),
|
|
||||||
skladm: adresar.skladm.unwrap_or_default(),
|
|
||||||
ico: adresar.ico.unwrap_or_default(),
|
|
||||||
kontakt: adresar.kontakt.unwrap_or_default(),
|
|
||||||
telefon: adresar.telefon.unwrap_or_default(),
|
|
||||||
skladu: adresar.skladu.unwrap_or_default(),
|
|
||||||
fax: adresar.fax.unwrap_or_default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
// src/adresar/handlers/put_adresar.rs
|
|
||||||
use tonic::Status;
|
|
||||||
use sqlx::PgPool;
|
|
||||||
use crate::adresar::models::Adresar;
|
|
||||||
use common::proto::multieko2::adresar::{PutAdresarRequest, AdresarResponse};
|
|
||||||
|
|
||||||
// Add the same sanitize_input helper as in POST handler
|
|
||||||
fn sanitize_input(input: &str) -> Option<String> {
|
|
||||||
let trimmed = input.trim().to_string();
|
|
||||||
if trimmed.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(trimmed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn put_adresar(
|
|
||||||
db_pool: &PgPool,
|
|
||||||
mut request: PutAdresarRequest,
|
|
||||||
) -> Result<AdresarResponse, Status> {
|
|
||||||
// Add validation for required fields like in POST
|
|
||||||
request.firma = request.firma.trim().to_string();
|
|
||||||
if request.firma.is_empty() {
|
|
||||||
return Err(Status::invalid_argument("Firma je povinne pole"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanitize optional fields like in POST
|
|
||||||
let kz = sanitize_input(&request.kz);
|
|
||||||
let drc = sanitize_input(&request.drc);
|
|
||||||
let ulica = sanitize_input(&request.ulica);
|
|
||||||
let psc = sanitize_input(&request.psc);
|
|
||||||
let mesto = sanitize_input(&request.mesto);
|
|
||||||
let stat = sanitize_input(&request.stat);
|
|
||||||
let banka = sanitize_input(&request.banka);
|
|
||||||
let ucet = sanitize_input(&request.ucet);
|
|
||||||
let skladm = sanitize_input(&request.skladm);
|
|
||||||
let ico = sanitize_input(&request.ico);
|
|
||||||
let kontakt = sanitize_input(&request.kontakt);
|
|
||||||
let telefon = sanitize_input(&request.telefon);
|
|
||||||
let skladu = sanitize_input(&request.skladu);
|
|
||||||
let fax = sanitize_input(&request.fax);
|
|
||||||
|
|
||||||
let adresar = sqlx::query_as!(
|
|
||||||
Adresar,
|
|
||||||
r#"
|
|
||||||
UPDATE adresar
|
|
||||||
SET
|
|
||||||
firma = $2,
|
|
||||||
kz = $3,
|
|
||||||
drc = $4,
|
|
||||||
ulica = $5,
|
|
||||||
psc = $6,
|
|
||||||
mesto = $7,
|
|
||||||
stat = $8,
|
|
||||||
banka = $9,
|
|
||||||
ucet = $10,
|
|
||||||
skladm = $11,
|
|
||||||
ico = $12,
|
|
||||||
kontakt = $13,
|
|
||||||
telefon = $14,
|
|
||||||
skladu = $15,
|
|
||||||
fax = $16
|
|
||||||
WHERE id = $1 AND deleted = FALSE
|
|
||||||
RETURNING
|
|
||||||
id,
|
|
||||||
deleted,
|
|
||||||
firma,
|
|
||||||
kz,
|
|
||||||
drc,
|
|
||||||
ulica,
|
|
||||||
psc,
|
|
||||||
mesto,
|
|
||||||
stat,
|
|
||||||
banka,
|
|
||||||
ucet,
|
|
||||||
skladm,
|
|
||||||
ico,
|
|
||||||
kontakt,
|
|
||||||
telefon,
|
|
||||||
skladu,
|
|
||||||
fax
|
|
||||||
"#,
|
|
||||||
request.id,
|
|
||||||
request.firma,
|
|
||||||
kz,
|
|
||||||
drc,
|
|
||||||
ulica,
|
|
||||||
psc,
|
|
||||||
mesto,
|
|
||||||
stat,
|
|
||||||
banka,
|
|
||||||
ucet,
|
|
||||||
skladm,
|
|
||||||
ico,
|
|
||||||
kontakt,
|
|
||||||
telefon,
|
|
||||||
skladu,
|
|
||||||
fax
|
|
||||||
)
|
|
||||||
.fetch_one(db_pool)
|
|
||||||
.await
|
|
||||||
.map_err(|e| Status::internal(e.to_string()))?;
|
|
||||||
|
|
||||||
Ok(AdresarResponse {
|
|
||||||
id: adresar.id,
|
|
||||||
firma: adresar.firma,
|
|
||||||
kz: adresar.kz.unwrap_or_default(),
|
|
||||||
drc: adresar.drc.unwrap_or_default(),
|
|
||||||
ulica: adresar.ulica.unwrap_or_default(),
|
|
||||||
psc: adresar.psc.unwrap_or_default(),
|
|
||||||
mesto: adresar.mesto.unwrap_or_default(),
|
|
||||||
stat: adresar.stat.unwrap_or_default(),
|
|
||||||
banka: adresar.banka.unwrap_or_default(),
|
|
||||||
ucet: adresar.ucet.unwrap_or_default(),
|
|
||||||
skladm: adresar.skladm.unwrap_or_default(),
|
|
||||||
ico: adresar.ico.unwrap_or_default(),
|
|
||||||
kontakt: adresar.kontakt.unwrap_or_default(),
|
|
||||||
telefon: adresar.telefon.unwrap_or_default(),
|
|
||||||
skladu: adresar.skladu.unwrap_or_default(),
|
|
||||||
fax: adresar.fax.unwrap_or_default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
// src/adresar/mod.rs
|
|
||||||
|
|
||||||
pub mod models;
|
|
||||||
pub mod handlers;
|
|
||||||
|
|
||||||
// #[cfg(test)]
|
|
||||||
// pub mod tests;
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
// src/adresar/models.rs
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
|
||||||
pub struct Adresar {
|
|
||||||
pub id: i64,
|
|
||||||
pub deleted: bool,
|
|
||||||
pub firma: String,
|
|
||||||
pub kz: Option<String>,
|
|
||||||
pub drc: Option<String>,
|
|
||||||
pub ulica: Option<String>,
|
|
||||||
pub psc: Option<String>,
|
|
||||||
pub mesto: Option<String>,
|
|
||||||
pub stat: Option<String>,
|
|
||||||
pub banka: Option<String>,
|
|
||||||
pub ucet: Option<String>,
|
|
||||||
pub skladm: Option<String>,
|
|
||||||
pub ico: Option<String>,
|
|
||||||
pub kontakt: Option<String>,
|
|
||||||
pub telefon: Option<String>,
|
|
||||||
pub skladu: Option<String>,
|
|
||||||
pub fax: Option<String>,
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,8 @@
|
|||||||
use tower::ServiceBuilder;
|
use tower::ServiceBuilder;
|
||||||
use crate::auth::logic::rbac;
|
use crate::auth::logic::rbac;
|
||||||
|
|
||||||
|
// TODO redesign this, adresar and uctovnictvo are nonexistent, but we are keeping this code for
|
||||||
|
// the reference. Please adjust in the future rbac.
|
||||||
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
// ... existing setup code ...
|
// ... existing setup code ...
|
||||||
|
|
||||||
|
|||||||
137
server/src/indexer.rs
Normal file
137
server/src/indexer.rs
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
// server/src/indexer.rs
|
||||||
|
|
||||||
|
use sqlx::{PgPool, Row};
|
||||||
|
use tantivy::schema::Term;
|
||||||
|
use tantivy::{doc, IndexWriter};
|
||||||
|
use tokio::sync::mpsc::Receiver;
|
||||||
|
use tracing::{error, info, warn};
|
||||||
|
use tantivy::schema::Schema;
|
||||||
|
use crate::search_schema;
|
||||||
|
|
||||||
|
/// Defines the commands that can be sent to the indexer task.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum IndexCommand {
|
||||||
|
/// Add a new document or update an existing one.
|
||||||
|
AddOrUpdate(IndexCommandData),
|
||||||
|
/// Remove a document from the index.
|
||||||
|
Delete(IndexCommandData),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct IndexCommandData {
|
||||||
|
pub table_name: String,
|
||||||
|
pub row_id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The main loop for the background indexer task.
|
||||||
|
pub async fn indexer_task(pool: PgPool, mut receiver: Receiver<IndexCommand>) {
|
||||||
|
info!("Background indexer task started.");
|
||||||
|
while let Some(command) = receiver.recv().await {
|
||||||
|
info!("Indexer received command: {:?}", command);
|
||||||
|
let result = match command {
|
||||||
|
IndexCommand::AddOrUpdate(data) => {
|
||||||
|
handle_add_or_update(&pool, data).await
|
||||||
|
}
|
||||||
|
IndexCommand::Delete(data) => handle_delete(&pool, data).await,
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(e) = result {
|
||||||
|
error!("Failed to process index command: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
warn!("Indexer channel closed. Task is shutting down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles adding or updating a document in a Tantivy index.
|
||||||
|
async fn handle_add_or_update(
|
||||||
|
pool: &PgPool,
|
||||||
|
data: IndexCommandData,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let qualified_table = format!("gen.\"{}\"", data.table_name);
|
||||||
|
let query_str = format!(
|
||||||
|
"SELECT to_jsonb(t) AS data FROM {} t WHERE id = $1",
|
||||||
|
qualified_table
|
||||||
|
);
|
||||||
|
let row = sqlx::query(&query_str)
|
||||||
|
.bind(data.row_id)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
let json_data: serde_json::Value = row.try_get("data")?;
|
||||||
|
let slovak_text = extract_text_content(&json_data);
|
||||||
|
|
||||||
|
let (mut writer, schema) = get_index_writer(&data.table_name)?;
|
||||||
|
let pg_id_field = schema.get_field("pg_id").unwrap();
|
||||||
|
let prefix_edge_field = schema.get_field("prefix_edge").unwrap();
|
||||||
|
let prefix_full_field = schema.get_field("prefix_full").unwrap();
|
||||||
|
let text_ngram_field = schema.get_field("text_ngram").unwrap();
|
||||||
|
|
||||||
|
let id_term = Term::from_field_u64(pg_id_field, data.row_id as u64);
|
||||||
|
writer.delete_term(id_term);
|
||||||
|
|
||||||
|
writer.add_document(doc!(
|
||||||
|
pg_id_field => data.row_id as u64,
|
||||||
|
prefix_edge_field => slovak_text.clone(),
|
||||||
|
prefix_full_field => slovak_text.clone(),
|
||||||
|
text_ngram_field => slovak_text
|
||||||
|
))?;
|
||||||
|
|
||||||
|
writer.commit()?;
|
||||||
|
info!(
|
||||||
|
"Successfully indexed document id:{} for table:{}",
|
||||||
|
data.row_id, data.table_name
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles deleting a document from a Tantivy index.
|
||||||
|
async fn handle_delete(
|
||||||
|
_pool: &PgPool,
|
||||||
|
data: IndexCommandData,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let (mut writer, schema) = get_index_writer(&data.table_name)?;
|
||||||
|
let pg_id_field = schema.get_field("pg_id").unwrap();
|
||||||
|
|
||||||
|
let id_term = Term::from_field_u64(pg_id_field, data.row_id as u64);
|
||||||
|
writer.delete_term(id_term);
|
||||||
|
writer.commit()?;
|
||||||
|
|
||||||
|
info!(
|
||||||
|
"Successfully deleted document id:{} from table:{}",
|
||||||
|
data.row_id, data.table_name
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper to get or create an index and return its writer and schema.
|
||||||
|
fn get_index_writer(
|
||||||
|
table_name: &str,
|
||||||
|
) -> anyhow::Result<(IndexWriter, Schema)> {
|
||||||
|
let index = search_schema::get_or_create_index(table_name)?;
|
||||||
|
let schema = index.schema();
|
||||||
|
let writer = index.writer(100_000_000)?; // 100MB heap
|
||||||
|
Ok((writer, schema))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract all text content from a JSON object for indexing
|
||||||
|
fn extract_text_content(json_data: &serde_json::Value) -> String {
|
||||||
|
let mut full_text = String::new();
|
||||||
|
|
||||||
|
if let Some(obj) = json_data.as_object() {
|
||||||
|
for value in obj.values() {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::String(s) => {
|
||||||
|
full_text.push_str(s);
|
||||||
|
full_text.push(' ');
|
||||||
|
}
|
||||||
|
serde_json::Value::Number(n) => {
|
||||||
|
full_text.push_str(&n.to_string());
|
||||||
|
full_text.push(' ');
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
full_text.trim().to_string()
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
// src/lib.rs
|
// src/lib.rs
|
||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
|
pub mod indexer;
|
||||||
|
pub mod search_schema;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod adresar;
|
|
||||||
pub mod uctovnictvo;
|
|
||||||
pub mod shared;
|
pub mod shared;
|
||||||
pub mod table_structure;
|
pub mod table_structure;
|
||||||
pub mod table_definition;
|
pub mod table_definition;
|
||||||
|
|||||||
26
server/src/search_schema.rs
Normal file
26
server/src/search_schema.rs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
// server/src/search_schema.rs
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use tantivy::Index;
|
||||||
|
|
||||||
|
// Re-export the functions from the common crate.
|
||||||
|
// This makes them available as `crate::search_schema::create_search_schema`, etc.
|
||||||
|
pub use common::search::{create_search_schema, register_slovak_tokenizers};
|
||||||
|
|
||||||
|
/// Gets an existing index or creates a new one.
|
||||||
|
/// This function now uses the shared logic from the `common` crate.
|
||||||
|
pub fn get_or_create_index(table_name: &str) -> tantivy::Result<Index> {
|
||||||
|
let index_path = Path::new("./tantivy_indexes").join(table_name);
|
||||||
|
std::fs::create_dir_all(&index_path)?;
|
||||||
|
|
||||||
|
let index = if index_path.join("meta.json").exists() {
|
||||||
|
Index::open_in_dir(&index_path)?
|
||||||
|
} else {
|
||||||
|
let schema = create_search_schema();
|
||||||
|
Index::create_in_dir(&index_path, schema)?
|
||||||
|
};
|
||||||
|
|
||||||
|
// This now calls the single, authoritative function from `common`.
|
||||||
|
register_slovak_tokenizers(&index)?;
|
||||||
|
Ok(index)
|
||||||
|
}
|
||||||
@@ -1,4 +1,2 @@
|
|||||||
// src/server/handlers.rs
|
// src/server/handlers.rs
|
||||||
pub use crate::server::services::adresar_service::AdresarService;
|
|
||||||
pub use crate::server::services::uctovnictvo_service::UctovnictvoService;
|
|
||||||
pub use crate::server::services::table_structure_service::TableStructureHandler;
|
pub use crate::server::services::table_structure_service::TableStructureHandler;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
// src/server/run.rs
|
|
||||||
use tonic::transport::Server;
|
use tonic::transport::Server;
|
||||||
use tonic_reflection::server::Builder as ReflectionBuilder;
|
use tonic_reflection::server::Builder as ReflectionBuilder;
|
||||||
|
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use crate::indexer::{indexer_task, IndexCommand};
|
||||||
|
|
||||||
use common::proto::multieko2::FILE_DESCRIPTOR_SET;
|
use common::proto::multieko2::FILE_DESCRIPTOR_SET;
|
||||||
use crate::server::services::{
|
use crate::server::services::{
|
||||||
AdresarService,
|
|
||||||
UctovnictvoService,
|
|
||||||
TableStructureHandler,
|
TableStructureHandler,
|
||||||
TableDefinitionService,
|
TableDefinitionService,
|
||||||
TablesDataService,
|
TablesDataService,
|
||||||
@@ -13,39 +13,51 @@ use crate::server::services::{
|
|||||||
AuthServiceImpl
|
AuthServiceImpl
|
||||||
};
|
};
|
||||||
use common::proto::multieko2::{
|
use common::proto::multieko2::{
|
||||||
adresar::adresar_server::AdresarServer,
|
|
||||||
uctovnictvo::uctovnictvo_server::UctovnictvoServer,
|
|
||||||
table_structure::table_structure_service_server::TableStructureServiceServer,
|
table_structure::table_structure_service_server::TableStructureServiceServer,
|
||||||
table_definition::table_definition_server::TableDefinitionServer,
|
table_definition::table_definition_server::TableDefinitionServer,
|
||||||
tables_data::tables_data_server::TablesDataServer,
|
tables_data::tables_data_server::TablesDataServer,
|
||||||
table_script::table_script_server::TableScriptServer,
|
table_script::table_script_server::TableScriptServer,
|
||||||
auth::auth_service_server::AuthServiceServer
|
auth::auth_service_server::AuthServiceServer
|
||||||
};
|
};
|
||||||
|
use search::{SearcherService, SearcherServer};
|
||||||
|
|
||||||
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
pub async fn run_server(db_pool: sqlx::PgPool) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
// Initialize JWT for authentication
|
// Initialize JWT for authentication
|
||||||
crate::auth::logic::jwt::init_jwt()?;
|
crate::auth::logic::jwt::init_jwt()?;
|
||||||
|
|
||||||
let addr = "[::1]:50051".parse()?;
|
let addr = "[::1]:50051".parse()?;
|
||||||
|
println!("Unified Server listening on {}", addr);
|
||||||
|
|
||||||
|
// 1. Create the MPSC channel for indexer commands
|
||||||
|
let (indexer_tx, indexer_rx) = mpsc::channel::<IndexCommand>(100); // Buffer of 100 messages
|
||||||
|
|
||||||
|
// 2. Spawn the background indexer task
|
||||||
|
let indexer_pool = db_pool.clone();
|
||||||
|
tokio::spawn(indexer_task(indexer_pool, indexer_rx));
|
||||||
|
|
||||||
let reflection_service = ReflectionBuilder::configure()
|
let reflection_service = ReflectionBuilder::configure()
|
||||||
.register_encoded_file_descriptor_set(FILE_DESCRIPTOR_SET)
|
.register_encoded_file_descriptor_set(FILE_DESCRIPTOR_SET)
|
||||||
.build_v1()?;
|
.build_v1()?;
|
||||||
|
|
||||||
// Initialize services
|
// Initialize services, passing the indexer sender to the relevant ones
|
||||||
let table_definition_service = TableDefinitionService { db_pool: db_pool.clone() };
|
let table_definition_service = TableDefinitionService { db_pool: db_pool.clone() };
|
||||||
let tables_data_service = TablesDataService { db_pool: db_pool.clone() };
|
let tables_data_service = TablesDataService {
|
||||||
|
db_pool: db_pool.clone(),
|
||||||
|
indexer_tx: indexer_tx.clone(),
|
||||||
|
};
|
||||||
let table_script_service = TableScriptService { db_pool: db_pool.clone() };
|
let table_script_service = TableScriptService { db_pool: db_pool.clone() };
|
||||||
let auth_service = AuthServiceImpl { db_pool: db_pool.clone() };
|
let auth_service = AuthServiceImpl { db_pool: db_pool.clone() };
|
||||||
|
|
||||||
|
// MODIFIED: Instantiate SearcherService with the database pool
|
||||||
|
let search_service = SearcherService { pool: db_pool.clone() };
|
||||||
|
|
||||||
Server::builder()
|
Server::builder()
|
||||||
.add_service(AdresarServer::new(AdresarService { db_pool: db_pool.clone() }))
|
|
||||||
.add_service(UctovnictvoServer::new(UctovnictvoService { db_pool: db_pool.clone() }))
|
|
||||||
.add_service(TableStructureServiceServer::new(TableStructureHandler { db_pool: db_pool.clone() }))
|
.add_service(TableStructureServiceServer::new(TableStructureHandler { db_pool: db_pool.clone() }))
|
||||||
.add_service(TableDefinitionServer::new(table_definition_service))
|
.add_service(TableDefinitionServer::new(table_definition_service))
|
||||||
.add_service(TablesDataServer::new(tables_data_service))
|
.add_service(TablesDataServer::new(tables_data_service))
|
||||||
.add_service(TableScriptServer::new(table_script_service))
|
.add_service(TableScriptServer::new(table_script_service))
|
||||||
.add_service(AuthServiceServer::new(auth_service))
|
.add_service(AuthServiceServer::new(auth_service))
|
||||||
|
.add_service(SearcherServer::new(search_service))
|
||||||
.add_service(reflection_service)
|
.add_service(reflection_service)
|
||||||
.serve(addr)
|
.serve(addr)
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
// src/server/services/adresar_service.rs
|
|
||||||
use tonic::{Request, Response, Status};
|
|
||||||
use common::proto::multieko2::adresar::{
|
|
||||||
adresar_server::Adresar,
|
|
||||||
PostAdresarRequest, AdresarResponse, GetAdresarRequest, PutAdresarRequest,
|
|
||||||
DeleteAdresarRequest, DeleteAdresarResponse,
|
|
||||||
};
|
|
||||||
use common::proto::multieko2::common::{Empty, CountResponse, PositionRequest};
|
|
||||||
use crate::adresar::handlers::{
|
|
||||||
post_adresar, get_adresar, put_adresar, delete_adresar,
|
|
||||||
get_adresar_count, get_adresar_by_position,
|
|
||||||
};
|
|
||||||
use sqlx::PgPool;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct AdresarService {
|
|
||||||
pub db_pool: PgPool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tonic::async_trait]
|
|
||||||
impl Adresar for AdresarService {
|
|
||||||
async fn post_adresar(
|
|
||||||
&self,
|
|
||||||
request: Request<PostAdresarRequest>,
|
|
||||||
) -> Result<Response<AdresarResponse>, Status> {
|
|
||||||
let response = post_adresar(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_adresar(
|
|
||||||
&self,
|
|
||||||
request: Request<GetAdresarRequest>,
|
|
||||||
) -> Result<Response<AdresarResponse>, Status> {
|
|
||||||
let response = get_adresar(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn put_adresar(
|
|
||||||
&self,
|
|
||||||
request: Request<PutAdresarRequest>,
|
|
||||||
) -> Result<Response<AdresarResponse>, Status> {
|
|
||||||
let response = put_adresar(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_adresar(
|
|
||||||
&self,
|
|
||||||
request: Request<DeleteAdresarRequest>,
|
|
||||||
) -> Result<Response<DeleteAdresarResponse>, Status> {
|
|
||||||
let response = delete_adresar(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_adresar_count(
|
|
||||||
&self,
|
|
||||||
request: Request<Empty>,
|
|
||||||
) -> Result<Response<CountResponse>, Status> {
|
|
||||||
let response = get_adresar_count(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_adresar_by_position(
|
|
||||||
&self,
|
|
||||||
request: Request<PositionRequest>,
|
|
||||||
) -> Result<Response<AdresarResponse>, Status> {
|
|
||||||
let response = get_adresar_by_position(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,12 @@
|
|||||||
// src/server/services/mod.rs
|
// src/server/services/mod.rs
|
||||||
|
|
||||||
pub mod adresar_service;
|
|
||||||
pub mod table_structure_service;
|
pub mod table_structure_service;
|
||||||
pub mod uctovnictvo_service;
|
|
||||||
pub mod table_definition_service;
|
pub mod table_definition_service;
|
||||||
pub mod tables_data_service;
|
pub mod tables_data_service;
|
||||||
pub mod table_script_service;
|
pub mod table_script_service;
|
||||||
pub mod auth_service;
|
pub mod auth_service;
|
||||||
|
|
||||||
pub use adresar_service::AdresarService;
|
|
||||||
pub use table_structure_service::TableStructureHandler;
|
pub use table_structure_service::TableStructureHandler;
|
||||||
pub use uctovnictvo_service::UctovnictvoService;
|
|
||||||
pub use table_definition_service::TableDefinitionService;
|
pub use table_definition_service::TableDefinitionService;
|
||||||
pub use tables_data_service::TablesDataService;
|
pub use tables_data_service::TablesDataService;
|
||||||
pub use table_script_service::TableScriptService;
|
pub use table_script_service::TableScriptService;
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
// src/server/services/tables_data_service.rs
|
// src/server/services/tables_data_service.rs
|
||||||
|
|
||||||
use tonic::{Request, Response, Status};
|
use tonic::{Request, Response, Status};
|
||||||
|
// Add these imports
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
use crate::indexer::IndexCommand;
|
||||||
|
|
||||||
use common::proto::multieko2::tables_data::tables_data_server::TablesData;
|
use common::proto::multieko2::tables_data::tables_data_server::TablesData;
|
||||||
use common::proto::multieko2::common::CountResponse;
|
use common::proto::multieko2::common::CountResponse;
|
||||||
use common::proto::multieko2::tables_data::{
|
use common::proto::multieko2::tables_data::{
|
||||||
@@ -15,6 +20,8 @@ use sqlx::PgPool;
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct TablesDataService {
|
pub struct TablesDataService {
|
||||||
pub db_pool: PgPool,
|
pub db_pool: PgPool,
|
||||||
|
// MODIFIED: Add the sender field
|
||||||
|
pub indexer_tx: mpsc::Sender<IndexCommand>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tonic::async_trait]
|
#[tonic::async_trait]
|
||||||
@@ -24,25 +31,37 @@ impl TablesData for TablesDataService {
|
|||||||
request: Request<PostTableDataRequest>,
|
request: Request<PostTableDataRequest>,
|
||||||
) -> Result<Response<PostTableDataResponse>, Status> {
|
) -> Result<Response<PostTableDataResponse>, Status> {
|
||||||
let request = request.into_inner();
|
let request = request.into_inner();
|
||||||
let response = post_table_data(&self.db_pool, request).await?;
|
// MODIFIED: Pass the indexer_tx to the handler
|
||||||
|
let response = post_table_data(
|
||||||
|
&self.db_pool,
|
||||||
|
request,
|
||||||
|
&self.indexer_tx,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
Ok(Response::new(response))
|
Ok(Response::new(response))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add the new method implementation
|
|
||||||
async fn put_table_data(
|
async fn put_table_data(
|
||||||
&self,
|
&self,
|
||||||
request: Request<PutTableDataRequest>,
|
request: Request<PutTableDataRequest>,
|
||||||
) -> Result<Response<PutTableDataResponse>, Status> {
|
) -> Result<Response<PutTableDataResponse>, Status> {
|
||||||
let request = request.into_inner();
|
let request = request.into_inner();
|
||||||
let response = put_table_data(&self.db_pool, request).await?;
|
let response = put_table_data(
|
||||||
|
&self.db_pool,
|
||||||
|
request,
|
||||||
|
&self.indexer_tx,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
Ok(Response::new(response))
|
Ok(Response::new(response))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ...and delete_table_data
|
||||||
async fn delete_table_data(
|
async fn delete_table_data(
|
||||||
&self,
|
&self,
|
||||||
request: Request<DeleteTableDataRequest>,
|
request: Request<DeleteTableDataRequest>,
|
||||||
) -> Result<Response<DeleteTableDataResponse>, Status> {
|
) -> Result<Response<DeleteTableDataResponse>, Status> {
|
||||||
let request = request.into_inner();
|
let request = request.into_inner();
|
||||||
|
// TODO: Update delete_table_data handler to accept and use indexer_tx
|
||||||
let response = delete_table_data(&self.db_pool, request).await?;
|
let response = delete_table_data(&self.db_pool, request).await?;
|
||||||
Ok(Response::new(response))
|
Ok(Response::new(response))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
// src/server/services/uctovnictvo_service.rs
|
|
||||||
use tonic::{Request, Response, Status};
|
|
||||||
use common::proto::multieko2::uctovnictvo::{
|
|
||||||
uctovnictvo_server::Uctovnictvo,
|
|
||||||
PostUctovnictvoRequest, UctovnictvoResponse, GetUctovnictvoRequest, PutUctovnictvoRequest,
|
|
||||||
};
|
|
||||||
use crate::uctovnictvo::handlers::{
|
|
||||||
post_uctovnictvo, get_uctovnictvo, get_uctovnictvo_count,
|
|
||||||
get_uctovnictvo_by_position, put_uctovnictvo,
|
|
||||||
};
|
|
||||||
use common::proto::multieko2::common::{Empty, CountResponse, PositionRequest};
|
|
||||||
use sqlx::PgPool;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct UctovnictvoService {
|
|
||||||
pub db_pool: PgPool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tonic::async_trait]
|
|
||||||
impl Uctovnictvo for UctovnictvoService {
|
|
||||||
async fn post_uctovnictvo(
|
|
||||||
&self,
|
|
||||||
request: Request<PostUctovnictvoRequest>,
|
|
||||||
) -> Result<Response<UctovnictvoResponse>, Status> {
|
|
||||||
let response = post_uctovnictvo(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_uctovnictvo(
|
|
||||||
&self,
|
|
||||||
request: Request<GetUctovnictvoRequest>,
|
|
||||||
) -> Result<Response<UctovnictvoResponse>, Status> {
|
|
||||||
let response = get_uctovnictvo(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_uctovnictvo_count(
|
|
||||||
&self,
|
|
||||||
request: Request<Empty>,
|
|
||||||
) -> Result<Response<CountResponse>, Status> {
|
|
||||||
let response = get_uctovnictvo_count(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_uctovnictvo_by_position(
|
|
||||||
&self,
|
|
||||||
request: Request<PositionRequest>,
|
|
||||||
) -> Result<Response<UctovnictvoResponse>, Status> {
|
|
||||||
let response = get_uctovnictvo_by_position(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn put_uctovnictvo(
|
|
||||||
&self,
|
|
||||||
request: Request<PutUctovnictvoRequest>,
|
|
||||||
) -> Result<Response<UctovnictvoResponse>, Status> {
|
|
||||||
let response = put_uctovnictvo(&self.db_pool, request.into_inner()).await?;
|
|
||||||
Ok(Response::new(response))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
// src/shared/mod.rs
|
// src/shared/mod.rs
|
||||||
pub mod date_utils;
|
pub mod date_utils;
|
||||||
|
pub mod schema_qualifier;
|
||||||
|
|||||||
50
server/src/shared/schema_qualifier.rs
Normal file
50
server/src/shared/schema_qualifier.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
// src/shared/schema_qualifier.rs
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use tonic::Status;
|
||||||
|
|
||||||
|
// TODO in the future, remove database query on every request and implement caching for scalable
|
||||||
|
// solution with many data and requests
|
||||||
|
|
||||||
|
/// Qualifies a table name by checking for its existence in the table_definitions table.
|
||||||
|
/// This is the robust, "source of truth" approach.
|
||||||
|
///
|
||||||
|
/// Rules:
|
||||||
|
/// - If a table is found in `table_definitions`, it is qualified with the 'gen' schema.
|
||||||
|
/// - Otherwise, it is assumed to be a system table in the 'public' schema.
|
||||||
|
pub async fn qualify_table_name(
|
||||||
|
db_pool: &PgPool,
|
||||||
|
profile_name: &str,
|
||||||
|
table_name: &str,
|
||||||
|
) -> Result<String, Status> {
|
||||||
|
// Check if a definition exists for this table in the given profile.
|
||||||
|
let definition_exists = sqlx::query!(
|
||||||
|
r#"SELECT EXISTS (
|
||||||
|
SELECT 1 FROM table_definitions td
|
||||||
|
JOIN schemas s ON td.schema_id = s.id
|
||||||
|
WHERE s.name = $1 AND td.table_name = $2
|
||||||
|
)"#,
|
||||||
|
profile_name,
|
||||||
|
table_name
|
||||||
|
)
|
||||||
|
.fetch_one(db_pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Status::internal(format!("Schema lookup failed: {}", e)))?
|
||||||
|
.exists
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
if definition_exists {
|
||||||
|
Ok(format!("\"{}\".\"{}\"", profile_name, table_name))
|
||||||
|
} else {
|
||||||
|
// It's not a user-defined table, so it must be a system table in 'public.
|
||||||
|
Ok(format!("\"{}\"", table_name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Qualifies table names for data operations
|
||||||
|
pub async fn qualify_table_name_for_data(
|
||||||
|
db_pool: &PgPool,
|
||||||
|
profile_name: &str,
|
||||||
|
table_name: &str,
|
||||||
|
) -> Result<String, Status> {
|
||||||
|
qualify_table_name(db_pool, profile_name, table_name).await
|
||||||
|
}
|
||||||
190
server/src/steel/server/decimal_math.rs
Normal file
190
server/src/steel/server/decimal_math.rs
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
// src/steel/server/decimal_math.rs
|
||||||
|
use rust_decimal::prelude::*;
|
||||||
|
use rust_decimal::MathematicalOps;
|
||||||
|
use steel::rvals::SteelVal;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum DecimalMathError {
|
||||||
|
#[error("Invalid decimal format: {0}")]
|
||||||
|
InvalidDecimal(String),
|
||||||
|
#[error("Math operation failed: {0}")]
|
||||||
|
MathError(String),
|
||||||
|
#[error("Division by zero")]
|
||||||
|
DivisionByZero,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts a SteelVal to a Decimal
|
||||||
|
fn steel_val_to_decimal(val: &SteelVal) -> Result<Decimal, DecimalMathError> {
|
||||||
|
match val {
|
||||||
|
SteelVal::StringV(s) => {
|
||||||
|
Decimal::from_str(&s.to_string())
|
||||||
|
.map_err(|e| DecimalMathError::InvalidDecimal(format!("{}: {}", s, e)))
|
||||||
|
}
|
||||||
|
SteelVal::NumV(n) => {
|
||||||
|
Decimal::try_from(*n)
|
||||||
|
.map_err(|e| DecimalMathError::InvalidDecimal(format!("{}: {}", n, e)))
|
||||||
|
}
|
||||||
|
SteelVal::IntV(i) => {
|
||||||
|
Ok(Decimal::from(*i))
|
||||||
|
}
|
||||||
|
_ => Err(DecimalMathError::InvalidDecimal(format!("Unsupported type: {:?}", val)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts a Decimal back to a SteelVal string
|
||||||
|
fn decimal_to_steel_val(decimal: Decimal) -> SteelVal {
|
||||||
|
SteelVal::StringV(decimal.to_string().into())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Basic arithmetic operations
|
||||||
|
pub fn decimal_add(a: String, b: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok((a_dec + b_dec).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_sub(a: String, b: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok((a_dec - b_dec).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_mul(a: String, b: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok((a_dec * b_dec).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_div(a: String, b: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
|
||||||
|
if b_dec.is_zero() {
|
||||||
|
return Err("Division by zero".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((a_dec / b_dec).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advanced mathematical functions (requires maths feature)
|
||||||
|
pub fn decimal_pow(base: String, exp: String) -> Result<String, String> {
|
||||||
|
let base_dec = Decimal::from_str(&base).map_err(|e| format!("Invalid decimal '{}': {}", base, e))?;
|
||||||
|
let exp_dec = Decimal::from_str(&exp).map_err(|e| format!("Invalid decimal '{}': {}", exp, e))?;
|
||||||
|
|
||||||
|
base_dec.checked_powd(exp_dec)
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Power operation failed or overflowed".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_sqrt(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.sqrt()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Square root failed (negative number?)".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_ln(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.checked_ln()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Natural log failed (non-positive number?)".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_log10(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.checked_log10()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Log10 failed (non-positive number?)".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_exp(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.checked_exp()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Exponential failed or overflowed".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trigonometric functions (input in radians)
|
||||||
|
pub fn decimal_sin(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.checked_sin()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Sine calculation failed or overflowed".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_cos(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.checked_cos()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Cosine calculation failed or overflowed".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_tan(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
|
||||||
|
a_dec.checked_tan()
|
||||||
|
.map(|result| result.to_string())
|
||||||
|
.ok_or_else(|| "Tangent calculation failed or overflowed".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comparison functions
|
||||||
|
pub fn decimal_gt(a: String, b: String) -> Result<bool, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec > b_dec)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_lt(a: String, b: String) -> Result<bool, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec < b_dec)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_eq(a: String, b: String) -> Result<bool, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec == b_dec)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
pub fn decimal_abs(a: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
Ok(a_dec.abs().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_round(a: String, places: i32) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
Ok(a_dec.round_dp(places as u32).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_min(a: String, b: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec.min(b_dec).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_max(a: String, b: String) -> Result<String, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec.max(b_dec).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_gte(a: String, b: String) -> Result<bool, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec >= b_dec)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decimal_lte(a: String, b: String) -> Result<bool, String> {
|
||||||
|
let a_dec = Decimal::from_str(&a).map_err(|e| format!("Invalid decimal '{}': {}", a, e))?;
|
||||||
|
let b_dec = Decimal::from_str(&b).map_err(|e| format!("Invalid decimal '{}': {}", b, e))?;
|
||||||
|
Ok(a_dec <= b_dec)
|
||||||
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
// src/steel/server/execution.rs
|
// Updated src/steel/server/execution.rs
|
||||||
use steel::steel_vm::engine::Engine;
|
use steel::steel_vm::engine::Engine;
|
||||||
use steel::steel_vm::register_fn::RegisterFn;
|
use steel::steel_vm::register_fn::RegisterFn;
|
||||||
use steel::rvals::SteelVal;
|
use steel::rvals::SteelVal;
|
||||||
use super::functions::SteelContext;
|
use super::functions::SteelContext;
|
||||||
|
use super::decimal_math::*;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
@@ -33,6 +34,24 @@ pub fn execute_script(
|
|||||||
let mut vm = Engine::new();
|
let mut vm = Engine::new();
|
||||||
let context = Arc::new(context);
|
let context = Arc::new(context);
|
||||||
|
|
||||||
|
// Register existing Steel functions
|
||||||
|
register_steel_functions(&mut vm, context.clone());
|
||||||
|
|
||||||
|
// Register all decimal math functions
|
||||||
|
register_decimal_math_functions(&mut vm);
|
||||||
|
|
||||||
|
// Execute script and process results
|
||||||
|
let results = vm.compile_and_run_raw_program(script)
|
||||||
|
.map_err(|e| ExecutionError::RuntimeError(e.to_string()))?;
|
||||||
|
|
||||||
|
// Convert results to target type
|
||||||
|
match target_type {
|
||||||
|
"STRINGS" => process_string_results(results),
|
||||||
|
_ => Err(ExecutionError::UnsupportedType(target_type.into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn register_steel_functions(vm: &mut Engine, context: Arc<SteelContext>) {
|
||||||
// Register steel_get_column with row context
|
// Register steel_get_column with row context
|
||||||
vm.register_fn("steel_get_column", {
|
vm.register_fn("steel_get_column", {
|
||||||
let ctx = context.clone();
|
let ctx = context.clone();
|
||||||
@@ -59,27 +78,101 @@ pub fn execute_script(
|
|||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Execute script and process results
|
fn register_decimal_math_functions(vm: &mut Engine) {
|
||||||
let results = vm.compile_and_run_raw_program(script)
|
// Basic arithmetic operations
|
||||||
.map_err(|e| ExecutionError::RuntimeError(e.to_string()))?;
|
vm.register_fn("decimal-add", decimal_add);
|
||||||
|
vm.register_fn("decimal-sub", decimal_sub);
|
||||||
|
vm.register_fn("decimal-mul", decimal_mul);
|
||||||
|
vm.register_fn("decimal-div", decimal_div);
|
||||||
|
|
||||||
// Convert results to target type
|
// Advanced mathematical functions
|
||||||
match target_type {
|
vm.register_fn("decimal-pow", decimal_pow);
|
||||||
"STRINGS" => process_string_results(results),
|
vm.register_fn("decimal-sqrt", decimal_sqrt);
|
||||||
_ => Err(ExecutionError::UnsupportedType(target_type.into()))
|
vm.register_fn("decimal-ln", decimal_ln);
|
||||||
}
|
vm.register_fn("decimal-log10", decimal_log10);
|
||||||
|
vm.register_fn("decimal-exp", decimal_exp);
|
||||||
|
|
||||||
|
// Trigonometric functions
|
||||||
|
vm.register_fn("decimal-sin", decimal_sin);
|
||||||
|
vm.register_fn("decimal-cos", decimal_cos);
|
||||||
|
vm.register_fn("decimal-tan", decimal_tan);
|
||||||
|
|
||||||
|
// Comparison functions
|
||||||
|
vm.register_fn("decimal-gt", decimal_gt);
|
||||||
|
vm.register_fn("decimal-lt", decimal_lt);
|
||||||
|
vm.register_fn("decimal-eq", decimal_eq);
|
||||||
|
|
||||||
|
// Utility functions
|
||||||
|
vm.register_fn("decimal-abs", decimal_abs);
|
||||||
|
vm.register_fn("decimal-round", decimal_round);
|
||||||
|
vm.register_fn("decimal-min", decimal_min);
|
||||||
|
vm.register_fn("decimal-max", decimal_max);
|
||||||
|
|
||||||
|
// Additional convenience functions
|
||||||
|
vm.register_fn("decimal-zero", || "0".to_string());
|
||||||
|
vm.register_fn("decimal-one", || "1".to_string());
|
||||||
|
vm.register_fn("decimal-pi", || "3.1415926535897932384626433833".to_string());
|
||||||
|
vm.register_fn("decimal-e", || "2.7182818284590452353602874714".to_string());
|
||||||
|
|
||||||
|
// Type conversion helpers
|
||||||
|
vm.register_fn("to-decimal", |s: String| -> Result<String, String> {
|
||||||
|
use rust_decimal::prelude::*;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
Decimal::from_str(&s)
|
||||||
|
.map(|d| d.to_string())
|
||||||
|
.map_err(|e| format!("Invalid decimal: {}", e))
|
||||||
|
});
|
||||||
|
|
||||||
|
// Financial functions
|
||||||
|
vm.register_fn("decimal-percentage", |amount: String, percentage: String| -> Result<String, String> {
|
||||||
|
use rust_decimal::prelude::*;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
let amount_dec = Decimal::from_str(&amount)
|
||||||
|
.map_err(|e| format!("Invalid amount: {}", e))?;
|
||||||
|
let percentage_dec = Decimal::from_str(&percentage)
|
||||||
|
.map_err(|e| format!("Invalid percentage: {}", e))?;
|
||||||
|
let hundred = Decimal::from(100);
|
||||||
|
|
||||||
|
Ok((amount_dec * percentage_dec / hundred).to_string())
|
||||||
|
});
|
||||||
|
|
||||||
|
vm.register_fn("decimal-compound", |principal: String, rate: String, time: String| -> Result<String, String> {
|
||||||
|
use rust_decimal::prelude::*;
|
||||||
|
use rust_decimal::MathematicalOps;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
let principal_dec = Decimal::from_str(&principal)
|
||||||
|
.map_err(|e| format!("Invalid principal: {}", e))?;
|
||||||
|
let rate_dec = Decimal::from_str(&rate)
|
||||||
|
.map_err(|e| format!("Invalid rate: {}", e))?;
|
||||||
|
let time_dec = Decimal::from_str(&time)
|
||||||
|
.map_err(|e| format!("Invalid time: {}", e))?;
|
||||||
|
|
||||||
|
let one = Decimal::ONE;
|
||||||
|
let compound_factor = (one + rate_dec).checked_powd(time_dec)
|
||||||
|
.ok_or("Compound calculation overflow")?;
|
||||||
|
|
||||||
|
Ok((principal_dec * compound_factor).to_string())
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_string_results(results: Vec<SteelVal>) -> Result<Value, ExecutionError> {
|
fn process_string_results(results: Vec<SteelVal>) -> Result<Value, ExecutionError> {
|
||||||
let mut strings = Vec::new();
|
let mut strings = Vec::new();
|
||||||
for result in results {
|
for result in results {
|
||||||
if let SteelVal::StringV(s) = result {
|
match result {
|
||||||
strings.push(s.to_string());
|
SteelVal::StringV(s) => strings.push(s.to_string()),
|
||||||
} else {
|
SteelVal::NumV(n) => strings.push(n.to_string()),
|
||||||
return Err(ExecutionError::TypeConversionError(
|
SteelVal::IntV(i) => strings.push(i.to_string()),
|
||||||
format!("Expected string, got {:?}", result)
|
SteelVal::BoolV(b) => strings.push(b.to_string()),
|
||||||
));
|
_ => {
|
||||||
|
return Err(ExecutionError::TypeConversionError(
|
||||||
|
format!("Expected string-convertible type, got {:?}", result)
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Value::Strings(strings))
|
Ok(Value::Strings(strings))
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ pub enum FunctionError {
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct SteelContext {
|
pub struct SteelContext {
|
||||||
pub current_table: String,
|
pub current_table: String,
|
||||||
pub profile_id: i64,
|
pub schema_id: i64,
|
||||||
|
pub schema_name: String,
|
||||||
pub row_data: HashMap<String, String>,
|
pub row_data: HashMap<String, String>,
|
||||||
pub db_pool: Arc<PgPool>,
|
pub db_pool: Arc<PgPool>,
|
||||||
}
|
}
|
||||||
@@ -30,8 +31,8 @@ impl SteelContext {
|
|||||||
pub async fn get_related_table_name(&self, base_name: &str) -> Result<String, FunctionError> {
|
pub async fn get_related_table_name(&self, base_name: &str) -> Result<String, FunctionError> {
|
||||||
let table_def = sqlx::query!(
|
let table_def = sqlx::query!(
|
||||||
r#"SELECT table_name FROM table_definitions
|
r#"SELECT table_name FROM table_definitions
|
||||||
WHERE profile_id = $1 AND table_name LIKE $2"#,
|
WHERE schema_id = $1 AND table_name LIKE $2"#,
|
||||||
self.profile_id,
|
self.schema_id,
|
||||||
format!("%_{}", base_name)
|
format!("%_{}", base_name)
|
||||||
)
|
)
|
||||||
.fetch_optional(&*self.db_pool)
|
.fetch_optional(&*self.db_pool)
|
||||||
@@ -66,7 +67,7 @@ impl SteelContext {
|
|||||||
|
|
||||||
// Add quotes around the table name
|
// Add quotes around the table name
|
||||||
sqlx::query_scalar::<_, String>(
|
sqlx::query_scalar::<_, String>(
|
||||||
&format!("SELECT {} FROM \"{}\" WHERE id = $1", column, actual_table)
|
&format!("SELECT {} FROM \"{}\".\"{}\" WHERE id = $1", column, self.schema_name, actual_table)
|
||||||
)
|
)
|
||||||
.bind(fk_value.parse::<i64>().map_err(|_|
|
.bind(fk_value.parse::<i64>().map_err(|_|
|
||||||
SteelVal::StringV("Invalid foreign key format".into()))?)
|
SteelVal::StringV("Invalid foreign key format".into()))?)
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
pub mod execution;
|
pub mod execution;
|
||||||
pub mod syntax_parser;
|
pub mod syntax_parser;
|
||||||
pub mod functions;
|
pub mod functions;
|
||||||
|
pub mod decimal_math;
|
||||||
|
|
||||||
pub use execution::*;
|
pub use execution::*;
|
||||||
pub use syntax_parser::*;
|
pub use syntax_parser::*;
|
||||||
pub use functions::*;
|
pub use functions::*;
|
||||||
|
pub use decimal_math::*;
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user