Compare commits

...

17 Commits

Author SHA1 Message Date
filipriec
3dfa922b9e unimportant change 2025-06-17 10:27:22 +02:00
filipriec
248d54a30f accpeting now null in the post table data as nothing 2025-06-16 22:51:05 +02:00
filipriec
b30fef4ccd post doesnt work, but refactored code displays the autocomplete at least, needs fix 2025-06-16 16:42:25 +02:00
filipriec
a9c4527318 complete redesign oh how client is displaying data 2025-06-16 16:10:24 +02:00
filipriec
c31f08d5b8 fixing post with links 2025-06-16 14:42:49 +02:00
filipriec
9e0fa9ddb1 autocomplete now autocompleting data not just id 2025-06-16 11:54:54 +02:00
filipriec
8fcd28832d better answer parsing 2025-06-16 11:14:04 +02:00
filipriec
cccf029464 autocomplete is now perfectc 2025-06-16 10:52:28 +02:00
filipriec
512e7fb9e7 suggestions in the dropdown menu now works amazingly well 2025-06-15 23:11:27 +02:00
filipriec
0e69df8282 empty search is now allowed 2025-06-15 18:36:01 +02:00
filipriec
eb5532c200 finally works as i wanted it to 2025-06-15 14:23:19 +02:00
filipriec
49ed1dfe33 trash 2025-06-15 13:52:43 +02:00
filipriec
62d1c3f7f5 suggestion works, but not exactly, needs more stuff 2025-06-15 13:35:45 +02:00
filipriec
b49dce3334 dropdown is being triggered 2025-06-15 12:15:25 +02:00
filipriec
8ace9bc4d1 links are now in the get method of the backend 2025-06-14 18:09:30 +02:00
filipriec
ce490007ed fixing server responses, now push data links fixed 2025-06-14 17:39:59 +02:00
filipriec
eb96c64e26 links to the other tables 2025-06-14 12:47:59 +02:00
32 changed files with 1567 additions and 712 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/target /target
.env .env
/tantivy_indexes /tantivy_indexes
server/tantivy_indexes

3
Cargo.lock generated
View File

@@ -449,6 +449,7 @@ dependencies = [
"dotenvy", "dotenvy",
"lazy_static", "lazy_static",
"prost", "prost",
"prost-types",
"ratatui", "ratatui",
"serde", "serde",
"serde_json", "serde_json",
@@ -487,6 +488,7 @@ name = "common"
version = "0.3.13" version = "0.3.13"
dependencies = [ dependencies = [
"prost", "prost",
"prost-types",
"serde", "serde",
"tantivy", "tantivy",
"tonic", "tonic",
@@ -2843,6 +2845,7 @@ dependencies = [
"jsonwebtoken", "jsonwebtoken",
"lazy_static", "lazy_static",
"prost", "prost",
"prost-types",
"regex", "regex",
"rstest", "rstest",
"rust-stemmers", "rust-stemmers",

View File

@@ -24,6 +24,7 @@ tokio = { version = "1.44.2", features = ["full"] }
tonic = "0.13.0" tonic = "0.13.0"
prost = "0.13.5" prost = "0.13.5"
async-trait = "0.1.88" async-trait = "0.1.88"
prost-types = "0.13.0"
# Data Handling & Serialization # Data Handling & Serialization
serde = { version = "1.0.219", features = ["derive"] } serde = { version = "1.0.219", features = ["derive"] }

View File

@@ -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"

View File

@@ -70,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"]

View File

@@ -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);
}

View File

@@ -1,36 +1,37 @@
// src/components/form/form.rs // src/components/form/form.rs
use crate::components::common::autocomplete; // <--- ADD THIS IMPORT
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; // <--- CHANGE THIS IMPORT
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_param: &impl CanvasState, form_state: &FormState, // <--- CHANGE THIS to the concrete type
fields: &[&str], fields: &[&str],
current_field_idx: &usize, current_field_idx: &usize,
inputs: &[&String], inputs: &[&String],
table_name: &str, // This parameter receives the correct table name 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,
) { ) {
// Use the dynamic `table_name` parameter for the title instead of a hardcoded string.
let card_title = format!(" {} ", table_name); 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(card_title) // Use the dynamic title .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);
@@ -42,10 +43,7 @@ pub fn render_form(
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);
let count_position_text = if total_count == 0 && current_position == 1 { let count_position_text = if total_count == 0 && current_position == 1 {
@@ -54,19 +52,22 @@ pub fn render_form(
format!("Total: {} | New Entry ({})", total_count, current_position) format!("Total: {} | New Entry ({})", total_count, current_position)
} else if total_count == 0 && current_position > 1 { } else if total_count == 0 && current_position > 1 {
format!("Total: 0 | New Entry ({})", current_position) format!("Total: 0 | New Entry ({})", current_position)
} } else {
else { format!(
format!("Total: {} | Position: {}/{}", total_count, current_position, total_count) "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]);
render_canvas( // Get the active field's rect from render_canvas
let active_field_rect = render_canvas(
f, f,
main_layout[1], main_layout[1],
form_state_param, form_state,
fields, fields,
current_field_idx, current_field_idx,
inputs, inputs,
@@ -74,4 +75,41 @@ pub fn render_form(
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,
);
}
}
}
}
} }

View File

@@ -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
} }

View File

@@ -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,6 +29,7 @@ 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,
) )

View File

@@ -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,6 +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,
app_state: &AppState,
) -> Result<EventOutcome> { ) -> Result<EventOutcome> {
match action { match action {
"save" | "revert" => { "save" | "revert" => {
@@ -26,10 +28,11 @@ 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,
).await; ).await;
match save_result { match save_result {
Ok(save_outcome) => { Ok(save_outcome) => {
let message = match save_outcome { let message = match save_outcome {
@@ -47,7 +50,7 @@ pub async fn execute_common_action<S: CanvasState + Any>(
form_state, form_state,
grpc_client, grpc_client,
).await; ).await;
match revert_result { match revert_result {
Ok(message) => Ok(EventOutcome::Ok(message)), Ok(message) => Ok(EventOutcome::Ok(message)),
Err(e) => Err(e), Err(e) => Err(e),

View File

@@ -32,6 +32,7 @@ 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,
).await.context("Register save action failed")?; ).await.context("Register save action failed")?;
@@ -52,6 +53,7 @@ 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,
).await?; ).await?;

View File

@@ -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).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))
} }

View File

@@ -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,6 +117,7 @@ async fn process_command(
}, },
"save" => { "save" => {
let outcome = save( let outcome = save(
app_state,
form_state, form_state,
grpc_client, grpc_client,
).await?; ).await?;

View File

@@ -47,7 +47,7 @@ use crossterm::cursor::SetCursorStyle;
use crossterm::event::{Event, KeyCode, KeyEvent}; use crossterm::event::{Event, KeyCode, KeyEvent};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio::sync::mpsc::unbounded_channel; use tokio::sync::mpsc::unbounded_channel;
use tracing::{info, error}; use tracing::{error, info};
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventOutcome { pub enum EventOutcome {
@@ -85,6 +85,9 @@ pub struct EventHandler {
pub navigation_state: NavigationState, pub navigation_state: NavigationState,
pub search_result_sender: mpsc::UnboundedSender<Vec<Hit>>, pub search_result_sender: mpsc::UnboundedSender<Vec<Hit>>,
pub search_result_receiver: mpsc::UnboundedReceiver<Vec<Hit>>, pub search_result_receiver: mpsc::UnboundedReceiver<Vec<Hit>>,
// --- ADDED FOR LIVE AUTOCOMPLETE ---
pub autocomplete_result_sender: mpsc::UnboundedSender<Vec<Hit>>,
pub autocomplete_result_receiver: mpsc::UnboundedReceiver<Vec<Hit>>,
} }
impl EventHandler { impl EventHandler {
@@ -96,6 +99,7 @@ impl EventHandler {
grpc_client: GrpcClient, grpc_client: GrpcClient,
) -> Result<Self> { ) -> Result<Self> {
let (search_tx, search_rx) = unbounded_channel(); let (search_tx, search_rx) = unbounded_channel();
let (autocomplete_tx, autocomplete_rx) = unbounded_channel(); // ADDED
Ok(EventHandler { Ok(EventHandler {
command_mode: false, command_mode: false,
command_input: String::new(), command_input: String::new(),
@@ -114,6 +118,9 @@ impl EventHandler {
navigation_state: NavigationState::new(), navigation_state: NavigationState::new(),
search_result_sender: search_tx, search_result_sender: search_tx,
search_result_receiver: search_rx, search_result_receiver: search_rx,
// --- ADDED ---
autocomplete_result_sender: autocomplete_tx,
autocomplete_result_receiver: autocomplete_rx,
}) })
} }
@@ -143,19 +150,28 @@ impl EventHandler {
outcome_message = "Search cancelled".to_string(); outcome_message = "Search cancelled".to_string();
} }
KeyCode::Enter => { KeyCode::Enter => {
if let Some(selected_hit) = search_state.results.get(search_state.selected_index) { if let Some(selected_hit) =
if let Ok(data) = serde_json::from_str::<std::collections::HashMap<String, String>>(&selected_hit.content_json) { search_state.results.get(search_state.selected_index)
{
if let Ok(data) = serde_json::from_str::<
std::collections::HashMap<String, String>,
>(&selected_hit.content_json)
{
let detached_pos = form_state.total_count + 2; let detached_pos = form_state.total_count + 2;
form_state.update_from_response(&data, detached_pos); form_state
.update_from_response(&data, detached_pos);
} }
should_close = true; should_close = true;
outcome_message = format!("Loaded record ID {}", selected_hit.id); outcome_message =
format!("Loaded record ID {}", selected_hit.id);
} }
} }
KeyCode::Up => search_state.previous_result(), KeyCode::Up => search_state.previous_result(),
KeyCode::Down => search_state.next_result(), KeyCode::Down => search_state.next_result(),
KeyCode::Char(c) => { KeyCode::Char(c) => {
search_state.input.insert(search_state.cursor_position, c); search_state
.input
.insert(search_state.cursor_position, c);
search_state.cursor_position += 1; search_state.cursor_position += 1;
trigger_search = true; trigger_search = true;
} }
@@ -167,10 +183,12 @@ impl EventHandler {
} }
} }
KeyCode::Left => { KeyCode::Left => {
search_state.cursor_position = search_state.cursor_position.saturating_sub(1); search_state.cursor_position =
search_state.cursor_position.saturating_sub(1);
} }
KeyCode::Right => { KeyCode::Right => {
if search_state.cursor_position < search_state.input.len() { if search_state.cursor_position < search_state.input.len()
{
search_state.cursor_position += 1; search_state.cursor_position += 1;
} }
} }
@@ -188,13 +206,19 @@ impl EventHandler {
let sender = self.search_result_sender.clone(); let sender = self.search_result_sender.clone();
let mut grpc_client = self.grpc_client.clone(); let mut grpc_client = self.grpc_client.clone();
info!("--- 1. Spawning search task for query: '{}' ---", query); info!(
"--- 1. Spawning search task for query: '{}' ---",
query
);
// We now move the grpc_client into the task, just like with login. // We now move the grpc_client into the task, just like with login.
tokio::spawn(async move { tokio::spawn(async move {
info!("--- 2. Background task started. ---"); info!("--- 2. Background task started. ---");
match grpc_client.search_table(table_name, query).await { match grpc_client.search_table(table_name, query).await {
Ok(response) => { Ok(response) => {
info!("--- 3a. gRPC call successful. Found {} hits. ---", response.hits.len()); info!(
"--- 3a. gRPC call successful. Found {} hits. ---",
response.hits.len()
);
let _ = sender.send(response.hits); let _ = sender.send(response.hits);
} }
Err(e) => { Err(e) => {
@@ -237,22 +261,33 @@ impl EventHandler {
if app_state.ui.show_search_palette { if app_state.ui.show_search_palette {
if let Event::Key(key_event) = event { if let Event::Key(key_event) = event {
// The call no longer passes grpc_client // The call no longer passes grpc_client
return self.handle_search_palette_event(key_event, form_state, app_state).await; return self
.handle_search_palette_event(
key_event,
form_state,
app_state,
)
.await;
} }
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
let mut current_mode = ModeManager::derive_mode(app_state, self, admin_state); let mut current_mode =
ModeManager::derive_mode(app_state, self, admin_state);
if current_mode == AppMode::General && self.navigation_state.active { if current_mode == AppMode::General && self.navigation_state.active {
if let Event::Key(key_event) = event { if let Event::Key(key_event) = event {
let outcome = let outcome = handle_command_navigation_event(
handle_command_navigation_event(&mut self.navigation_state, key_event, config) &mut self.navigation_state,
.await?; key_event,
config,
)
.await?;
if !self.navigation_state.active { if !self.navigation_state.active {
self.command_message = outcome.get_message_if_ok(); self.command_message = outcome.get_message_if_ok();
current_mode = ModeManager::derive_mode(app_state, self, admin_state); current_mode =
ModeManager::derive_mode(app_state, self, admin_state);
} }
app_state.update_mode(current_mode); app_state.update_mode(current_mode);
return Ok(outcome); return Ok(outcome);
@@ -265,23 +300,39 @@ impl EventHandler {
let current_view = { let current_view = {
let ui = &app_state.ui; let ui = &app_state.ui;
if ui.show_intro { AppView::Intro } if ui.show_intro {
else if ui.show_login { AppView::Login } AppView::Intro
else if ui.show_register { AppView::Register } } else if ui.show_login {
else if ui.show_admin { AppView::Admin } AppView::Login
else if ui.show_add_logic { AppView::AddLogic } } else if ui.show_register {
else if ui.show_add_table { AppView::AddTable } AppView::Register
else if ui.show_form { AppView::Form } } else if ui.show_admin {
else { AppView::Scratch } AppView::Admin
} else if ui.show_add_logic {
AppView::AddLogic
} else if ui.show_add_table {
AppView::AddTable
} else if ui.show_form {
AppView::Form
} else {
AppView::Scratch
}
}; };
buffer_state.update_history(current_view); buffer_state.update_history(current_view);
if app_state.ui.dialog.dialog_show { if app_state.ui.dialog.dialog_show {
if let Event::Key(key_event) = event { if let Event::Key(key_event) = event {
if let Some(dialog_result) = dialog::handle_dialog_event( if let Some(dialog_result) = dialog::handle_dialog_event(
&Event::Key(key_event), config, app_state, login_state, &Event::Key(key_event),
register_state, buffer_state, admin_state, config,
).await { app_state,
login_state,
register_state,
buffer_state,
admin_state,
)
.await
{
return dialog_result; return dialog_result;
} }
} else if let Event::Resize(_, _) = event { } else if let Event::Resize(_, _) = event {
@@ -293,45 +344,88 @@ impl EventHandler {
let key_code = key_event.code; let key_code = key_event.code;
let modifiers = key_event.modifiers; let modifiers = key_event.modifiers;
if UiStateHandler::toggle_sidebar(&mut app_state.ui, config, key_code, modifiers) { if UiStateHandler::toggle_sidebar(
let message = format!("Sidebar {}", if app_state.ui.show_sidebar { "shown" } else { "hidden" }); &mut app_state.ui,
config,
key_code,
modifiers,
) {
let message = format!(
"Sidebar {}",
if app_state.ui.show_sidebar {
"shown"
} else {
"hidden"
}
);
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
if UiStateHandler::toggle_buffer_list(&mut app_state.ui, config, key_code, modifiers) { if UiStateHandler::toggle_buffer_list(
let message = format!("Buffer {}", if app_state.ui.show_buffer_list { "shown" } else { "hidden" }); &mut app_state.ui,
config,
key_code,
modifiers,
) {
let message = format!(
"Buffer {}",
if app_state.ui.show_buffer_list {
"shown"
} else {
"hidden"
}
);
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
if !matches!(current_mode, AppMode::Edit | AppMode::Command) { if !matches!(current_mode, AppMode::Edit | AppMode::Command) {
if let Some(action) = config.get_action_for_key_in_mode(&config.keybindings.global, key_code, modifiers) { if let Some(action) = config.get_action_for_key_in_mode(
&config.keybindings.global,
key_code,
modifiers,
) {
match action { match action {
"next_buffer" => { "next_buffer" => {
if buffer::switch_buffer(buffer_state, true) { if buffer::switch_buffer(buffer_state, true) {
return Ok(EventOutcome::Ok("Switched to next buffer".to_string())); return Ok(EventOutcome::Ok(
"Switched to next buffer".to_string(),
));
} }
} }
"previous_buffer" => { "previous_buffer" => {
if buffer::switch_buffer(buffer_state, false) { if buffer::switch_buffer(buffer_state, false) {
return Ok(EventOutcome::Ok("Switched to previous buffer".to_string())); return Ok(EventOutcome::Ok(
"Switched to previous buffer".to_string(),
));
} }
} }
"close_buffer" => { "close_buffer" => {
let current_table_name = app_state.current_view_table_name.as_deref(); let current_table_name =
let message = buffer_state.close_buffer_with_intro_fallback(current_table_name); app_state.current_view_table_name.as_deref();
let message = buffer_state
.close_buffer_with_intro_fallback(
current_table_name,
);
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
_ => {} _ => {}
} }
} }
if let Some(action) = config.get_general_action(key_code, modifiers) { if let Some(action) =
config.get_general_action(key_code, modifiers)
{
if action == "open_search" { if action == "open_search" {
if app_state.ui.show_form { if app_state.ui.show_form {
if let Some(table_name) = app_state.current_view_table_name.clone() { if let Some(table_name) =
app_state.current_view_table_name.clone()
{
app_state.ui.show_search_palette = true; app_state.ui.show_search_palette = true;
app_state.search_state = Some(SearchState::new(table_name)); app_state.search_state =
Some(SearchState::new(table_name));
app_state.ui.focus_outside_canvas = true; app_state.ui.focus_outside_canvas = true;
return Ok(EventOutcome::Ok("Search palette opened".to_string())); return Ok(EventOutcome::Ok(
"Search palette opened".to_string(),
));
} }
} }
} }
@@ -340,9 +434,20 @@ impl EventHandler {
match current_mode { match current_mode {
AppMode::General => { AppMode::General => {
if app_state.ui.show_admin && auth_state.role.as_deref() == Some("admin") { if app_state.ui.show_admin
if admin_nav::handle_admin_navigation(key_event, config, app_state, admin_state, buffer_state, &mut self.command_message) { && auth_state.role.as_deref() == Some("admin")
return Ok(EventOutcome::Ok(self.command_message.clone())); {
if admin_nav::handle_admin_navigation(
key_event,
config,
app_state,
admin_state,
buffer_state,
&mut self.command_message,
) {
return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
@@ -350,10 +455,19 @@ impl EventHandler {
let client_clone = self.grpc_client.clone(); let client_clone = self.grpc_client.clone();
let sender_clone = self.save_logic_result_sender.clone(); let sender_clone = self.save_logic_result_sender.clone();
if add_logic_nav::handle_add_logic_navigation( if add_logic_nav::handle_add_logic_navigation(
key_event, config, app_state, &mut admin_state.add_logic_state, key_event,
&mut self.is_edit_mode, buffer_state, client_clone, sender_clone, &mut self.command_message, config,
app_state,
&mut admin_state.add_logic_state,
&mut self.is_edit_mode,
buffer_state,
client_clone,
sender_clone,
&mut self.command_message,
) { ) {
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
@@ -361,44 +475,96 @@ impl EventHandler {
let client_clone = self.grpc_client.clone(); let client_clone = self.grpc_client.clone();
let sender_clone = self.save_table_result_sender.clone(); let sender_clone = self.save_table_result_sender.clone();
if add_table_nav::handle_add_table_navigation( if add_table_nav::handle_add_table_navigation(
key_event, config, app_state, &mut admin_state.add_table_state, key_event,
client_clone, sender_clone, &mut self.command_message, config,
app_state,
&mut admin_state.add_table_state,
client_clone,
sender_clone,
&mut self.command_message,
) { ) {
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
let nav_outcome = navigation::handle_navigation_event( let nav_outcome = navigation::handle_navigation_event(
key_event, config, form_state, app_state, login_state, register_state, key_event,
intro_state, admin_state, &mut self.command_mode, &mut self.command_input, config,
&mut self.command_message, &mut self.navigation_state, form_state,
).await; app_state,
login_state,
register_state,
intro_state,
admin_state,
&mut self.command_mode,
&mut self.command_input,
&mut self.command_message,
&mut self.navigation_state,
)
.await;
match nav_outcome { match nav_outcome {
Ok(EventOutcome::ButtonSelected { context, index }) => { Ok(EventOutcome::ButtonSelected { context, index }) => {
let message = match context { let message = match context {
UiContext::Intro => { UiContext::Intro => {
intro::handle_intro_selection(app_state, buffer_state, index); intro::handle_intro_selection(
if app_state.ui.show_admin && !app_state.profile_tree.profiles.is_empty() { app_state,
admin_state.profile_list_state.select(Some(0)); buffer_state,
index,
);
if app_state.ui.show_admin
&& !app_state
.profile_tree
.profiles
.is_empty()
{
admin_state
.profile_list_state
.select(Some(0));
} }
format!("Intro Option {} selected", index) format!("Intro Option {} selected", index)
} }
UiContext::Login => match index { UiContext::Login => match index {
0 => login::initiate_login(login_state, app_state, self.auth_client.clone(), self.login_result_sender.clone()), 0 => login::initiate_login(
1 => login::back_to_main(login_state, app_state, buffer_state).await, login_state,
app_state,
self.auth_client.clone(),
self.login_result_sender.clone(),
),
1 => login::back_to_main(
login_state,
app_state,
buffer_state,
)
.await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),
}, },
UiContext::Register => match index { UiContext::Register => match index {
0 => register::initiate_registration(register_state, app_state, self.auth_client.clone(), self.register_result_sender.clone()), 0 => register::initiate_registration(
1 => register::back_to_login(register_state, app_state, buffer_state).await, register_state,
app_state,
self.auth_client.clone(),
self.register_result_sender.clone(),
),
1 => register::back_to_login(
register_state,
app_state,
buffer_state,
)
.await,
_ => "Invalid Login Option".to_string(), _ => "Invalid Login Option".to_string(),
}, },
UiContext::Admin => { UiContext::Admin => {
admin::handle_admin_selection(app_state, admin_state); admin::handle_admin_selection(
app_state,
admin_state,
);
format!("Admin Option {} selected", index) format!("Admin Option {} selected", index)
} }
UiContext::Dialog => "Internal error: Unexpected dialog state".to_string(), UiContext::Dialog => "Internal error: Unexpected dialog state"
.to_string(),
}; };
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
@@ -450,34 +616,46 @@ impl EventHandler {
return Ok(EventOutcome::Ok(String::new())); return Ok(EventOutcome::Ok(String::new()));
} }
if let Some(action) = config.get_common_action(key_code, modifiers) { if let Some(action) =
config.get_common_action(key_code, modifiers)
{
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit"
| "revert" => {
return common_mode::handle_core_action( return common_mode::handle_core_action(
action, form_state, auth_state, login_state, register_state, action,
&mut self.grpc_client, &mut self.auth_client, terminal, app_state, form_state,
).await; auth_state,
login_state,
register_state,
&mut self.grpc_client,
&mut self.auth_client,
terminal,
app_state,
)
.await;
} }
_ => {} _ => {}
} }
} }
let (_should_exit, message) = read_only::handle_read_only_event( let (_should_exit, message) =
app_state, read_only::handle_read_only_event(
key_event, app_state,
config, key_event,
form_state, config,
login_state, form_state,
register_state, login_state,
&mut admin_state.add_table_state, register_state,
&mut admin_state.add_logic_state, &mut admin_state.add_table_state,
&mut self.key_sequence_tracker, &mut admin_state.add_logic_state,
&mut self.grpc_client, // <-- FIX 1 &mut self.key_sequence_tracker,
&mut self.command_message, &mut self.grpc_client, // <-- FIX 1
&mut self.edit_mode_cooldown, &mut self.command_message,
&mut self.ideal_cursor_column, &mut self.edit_mode_cooldown,
) &mut self.ideal_cursor_column,
.await?; )
.await?;
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
@@ -496,33 +674,45 @@ impl EventHandler {
return Ok(EventOutcome::Ok("".to_string())); return Ok(EventOutcome::Ok("".to_string()));
} }
let (_should_exit, message) = read_only::handle_read_only_event( let (_should_exit, message) =
app_state, read_only::handle_read_only_event(
key_event, app_state,
config, key_event,
form_state, config,
login_state, form_state,
register_state, login_state,
&mut admin_state.add_table_state, register_state,
&mut admin_state.add_logic_state, &mut admin_state.add_table_state,
&mut self.key_sequence_tracker, &mut admin_state.add_logic_state,
&mut self.grpc_client, // <-- FIX 2 &mut self.key_sequence_tracker,
&mut self.command_message, &mut self.grpc_client, // <-- FIX 2
&mut self.edit_mode_cooldown, &mut self.command_message,
&mut self.ideal_cursor_column, &mut self.edit_mode_cooldown,
) &mut self.ideal_cursor_column,
.await?; )
.await?;
return Ok(EventOutcome::Ok(message)); return Ok(EventOutcome::Ok(message));
} }
AppMode::Edit => { AppMode::Edit => {
if let Some(action) = config.get_common_action(key_code, modifiers) { if let Some(action) =
config.get_common_action(key_code, modifiers)
{
match action { match action {
"save" | "force_quit" | "save_and_quit" | "revert" => { "save" | "force_quit" | "save_and_quit"
| "revert" => {
return common_mode::handle_core_action( return common_mode::handle_core_action(
action, form_state, auth_state, login_state, register_state, action,
&mut self.grpc_client, &mut self.auth_client, terminal, app_state, // <-- FIX 3 form_state,
).await; auth_state,
login_state,
register_state,
&mut self.grpc_client,
&mut self.auth_client,
terminal,
app_state,
)
.await;
} }
_ => {} _ => {}
} }
@@ -530,11 +720,20 @@ impl EventHandler {
let mut current_position = form_state.current_position; let mut current_position = form_state.current_position;
let total_count = form_state.total_count; let total_count = form_state.total_count;
// --- MODIFIED: Pass `self` instead of `grpc_client` ---
let edit_result = edit::handle_edit_event( let edit_result = edit::handle_edit_event(
key_event, config, form_state, login_state, register_state, admin_state, key_event,
&mut self.ideal_cursor_column, &mut current_position, total_count, config,
&mut self.grpc_client, app_state, // <-- FIX 4 form_state,
).await; login_state,
register_state,
admin_state,
&mut current_position,
total_count,
self,
app_state,
)
.await;
match edit_result { match edit_result {
Ok(edit::EditEventOutcome::ExitEditMode) => { Ok(edit::EditEventOutcome::ExitEditMode) => {
@@ -551,14 +750,22 @@ impl EventHandler {
target_state.set_current_cursor_pos(new_pos); target_state.set_current_cursor_pos(new_pos);
self.ideal_cursor_column = new_pos; self.ideal_cursor_column = new_pos;
} }
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
Ok(edit::EditEventOutcome::Message(msg)) => { Ok(edit::EditEventOutcome::Message(msg)) => {
if !msg.is_empty() { self.command_message = msg; } if !msg.is_empty() {
self.command_message = msg;
}
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok(self.command_message.clone())); return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
}
Err(e) => {
return Err(e.into());
} }
Err(e) => { return Err(e.into()); }
} }
} }
@@ -568,21 +775,38 @@ impl EventHandler {
self.command_message.clear(); self.command_message.clear();
self.command_mode = false; self.command_mode = false;
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok("Exited command mode".to_string())); return Ok(EventOutcome::Ok(
"Exited command mode".to_string(),
));
} }
if config.is_command_execute(key_code, modifiers) { if config.is_command_execute(key_code, modifiers) {
let mut current_position = form_state.current_position; let mut current_position = form_state.current_position;
let total_count = form_state.total_count; let total_count = form_state.total_count;
let outcome = command_mode::handle_command_event( let outcome = command_mode::handle_command_event(
key_event, config, app_state, login_state, register_state, form_state, key_event,
&mut self.command_input, &mut self.command_message, &mut self.grpc_client, // <-- FIX 5 config,
command_handler, terminal, &mut current_position, total_count, app_state,
).await?; login_state,
register_state,
form_state,
&mut self.command_input,
&mut self.command_message,
&mut self.grpc_client, // <-- FIX 5
command_handler,
terminal,
&mut current_position,
total_count,
)
.await?;
form_state.current_position = current_position; form_state.current_position = current_position;
self.command_mode = false; self.command_mode = false;
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
let new_mode = ModeManager::derive_mode(app_state, self, admin_state); let new_mode = ModeManager::derive_mode(
app_state,
self,
admin_state,
);
app_state.update_mode(new_mode); app_state.update_mode(new_mode);
return Ok(outcome); return Ok(outcome);
} }
@@ -596,37 +820,59 @@ impl EventHandler {
if let KeyCode::Char(c) = key_code { if let KeyCode::Char(c) = key_code {
if c == 'f' { if c == 'f' {
self.key_sequence_tracker.add_key(key_code); self.key_sequence_tracker.add_key(key_code);
let sequence = self.key_sequence_tracker.get_sequence(); let sequence =
self.key_sequence_tracker.get_sequence();
if config.matches_key_sequence_generalized(&sequence) == Some("find_file_palette_toggle") { if config.matches_key_sequence_generalized(
if app_state.ui.show_form || app_state.ui.show_intro { &sequence,
let mut all_table_paths: Vec<String> = app_state ) == Some("find_file_palette_toggle")
.profile_tree {
.profiles if app_state.ui.show_form
.iter() || app_state.ui.show_intro
.flat_map(|profile| { {
profile.tables.iter().map(move |table| { let mut all_table_paths: Vec<String> =
format!("{}/{}", profile.name, table.name) app_state
.profile_tree
.profiles
.iter()
.flat_map(|profile| {
profile.tables.iter().map(
move |table| {
format!(
"{}/{}",
profile.name,
table.name
)
},
)
}) })
}) .collect();
.collect();
all_table_paths.sort(); all_table_paths.sort();
self.navigation_state.activate_find_file(all_table_paths); self.navigation_state
.activate_find_file(all_table_paths);
self.command_mode = false; self.command_mode = false;
self.command_input.clear(); self.command_input.clear();
self.command_message.clear(); self.command_message.clear();
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
return Ok(EventOutcome::Ok("Table selection palette activated".to_string())); return Ok(EventOutcome::Ok(
"Table selection palette activated"
.to_string(),
));
} else { } else {
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
self.command_input.push('f'); self.command_input.push('f');
if sequence.len() > 1 && sequence[0] == KeyCode::Char('f') { if sequence.len() > 1
&& sequence[0] == KeyCode::Char('f')
{
self.command_input.push('f'); self.command_input.push('f');
} }
self.command_message = "Find File not available in this view.".to_string(); self.command_message = "Find File not available in this view."
return Ok(EventOutcome::Ok(self.command_message.clone())); .to_string();
return Ok(EventOutcome::Ok(
self.command_message.clone(),
));
} }
} }
@@ -635,7 +881,9 @@ impl EventHandler {
} }
} }
if c != 'f' && !self.key_sequence_tracker.current_sequence.is_empty() { if c != 'f'
&& !self.key_sequence_tracker.current_sequence.is_empty()
{
self.key_sequence_tracker.reset(); self.key_sequence_tracker.reset();
} }

View File

@@ -1,7 +1,6 @@
// src/services/grpc_client.rs // src/services/grpc_client.rs
use tonic::transport::Channel; use common::proto::multieko2::common::Empty;
use common::proto::multieko2::common::{CountResponse, Empty};
use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient; use common::proto::multieko2::table_structure::table_structure_service_client::TableStructureServiceClient;
use common::proto::multieko2::table_structure::{GetTableStructureRequest, TableStructureResponse}; use common::proto::multieko2::table_structure::{GetTableStructureRequest, TableStructureResponse};
use common::proto::multieko2::table_definition::{ use common::proto::multieko2::table_definition::{
@@ -23,8 +22,10 @@ use common::proto::multieko2::tables_data::{
use common::proto::multieko2::search::{ use common::proto::multieko2::search::{
searcher_client::SearcherClient, SearchRequest, SearchResponse, searcher_client::SearcherClient, SearchRequest, SearchResponse,
}; };
use anyhow::{Context, Result}; // Added Context use anyhow::{Context, Result};
use std::collections::HashMap; // NEW use std::collections::HashMap;
use tonic::transport::Channel;
use prost_types::Value;
#[derive(Clone)] #[derive(Clone)]
pub struct GrpcClient { pub struct GrpcClient {
@@ -48,7 +49,6 @@ impl GrpcClient {
TableDefinitionClient::new(channel.clone()); TableDefinitionClient::new(channel.clone());
let table_script_client = TableScriptClient::new(channel.clone()); let table_script_client = TableScriptClient::new(channel.clone());
let tables_data_client = TablesDataClient::new(channel.clone()); let tables_data_client = TablesDataClient::new(channel.clone());
// NEW: Instantiate the search client
let search_client = SearcherClient::new(channel.clone()); let search_client = SearcherClient::new(channel.clone());
Ok(Self { Ok(Self {
@@ -56,7 +56,7 @@ impl GrpcClient {
table_definition_client, table_definition_client,
table_script_client, table_script_client,
tables_data_client, tables_data_client,
search_client, // NEW search_client,
}) })
} }
@@ -135,7 +135,7 @@ impl GrpcClient {
Ok(response.into_inner().count as u64) Ok(response.into_inner().count as u64)
} }
pub async fn get_table_data_by_position( pub async fn get_table_data_by_position(
&mut self, &mut self,
profile_name: String, profile_name: String,
table_name: String, table_name: String,
@@ -159,12 +159,14 @@ impl GrpcClient {
&mut self, &mut self,
profile_name: String, profile_name: String,
table_name: String, table_name: String,
data: HashMap<String, String>, // CHANGE THIS: Accept the pre-converted data
data: HashMap<String, Value>,
) -> Result<PostTableDataResponse> { ) -> Result<PostTableDataResponse> {
// The conversion logic is now gone from here.
let grpc_request = PostTableDataRequest { let grpc_request = PostTableDataRequest {
profile_name, profile_name,
table_name, table_name,
data, data, // This is now the correct type
}; };
let request = tonic::Request::new(grpc_request); let request = tonic::Request::new(grpc_request);
let response = self let response = self
@@ -180,13 +182,15 @@ impl GrpcClient {
profile_name: String, profile_name: String,
table_name: String, table_name: String,
id: i64, id: i64,
data: HashMap<String, String>, // CHANGE THIS: Accept the pre-converted data
data: HashMap<String, Value>,
) -> Result<PutTableDataResponse> { ) -> Result<PutTableDataResponse> {
// The conversion logic is now gone from here.
let grpc_request = PutTableDataRequest { let grpc_request = PutTableDataRequest {
profile_name, profile_name,
table_name, table_name,
id, id,
data, data, // This is now the correct type
}; };
let request = tonic::Request::new(grpc_request); let request = tonic::Request::new(grpc_request);
let response = self let response = self

View File

@@ -1,16 +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 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 crate::utils::columns::filter_user_columns;
use anyhow::{Context, Result}; 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,
@@ -92,6 +176,7 @@ impl UiService {
} }
} }
// REFACTOR THIS FUNCTION
pub async fn initialize_app_state_and_form( pub async fn initialize_app_state_and_form(
grpc_client: &mut GrpcClient, grpc_client: &mut GrpcClient,
app_state: &mut AppState, app_state: &mut AppState,
@@ -102,7 +187,6 @@ impl UiService {
.context("Failed to get profile tree")?; .context("Failed to get profile tree")?;
app_state.profile_tree = profile_tree; app_state.profile_tree = profile_tree;
// Determine initial table to load (e.g., first table of first profile, or a default)
let initial_profile_name = app_state let initial_profile_name = app_state
.profile_tree .profile_tree
.profiles .profiles
@@ -115,33 +199,26 @@ impl UiService {
.profiles .profiles
.first() .first()
.and_then(|p| p.tables.first().map(|t| t.name.clone())) .and_then(|p| p.tables.first().map(|t| t.name.clone()))
.unwrap_or_else(|| "2025_company_data1".to_string()); // Fallback if no tables .unwrap_or_else(|| "2025_company_data1".to_string());
app_state.set_current_view_table( app_state.set_current_view_table(
initial_profile_name.clone(), initial_profile_name.clone(),
initial_table_name.clone(), initial_table_name.clone(),
); );
let table_structure = grpc_client // NOW, just call our new central function. This avoids code duplication.
.get_table_structure( let form_state = Self::load_table_view(
initial_profile_name.clone(), grpc_client,
initial_table_name.clone(), app_state,
) &initial_profile_name,
.await &initial_table_name,
.context(format!( )
"Failed to get initial table structure for {}.{}", .await?;
initial_profile_name, initial_table_name
))?;
let column_names: Vec<String> = table_structure // The field names for the UI are derived from the new form_state
.columns let field_names = form_state.fields.iter().map(|f| f.display_name.clone()).collect();
.iter()
.map(|col| col.name.clone())
.collect();
let filtered_columns = filter_user_columns(column_names); Ok((initial_profile_name, initial_table_name, field_names))
Ok((initial_profile_name, initial_table_name, filtered_columns))
} }
pub async fn fetch_and_set_table_count( pub async fn fetch_and_set_table_count(

View File

@@ -1,15 +1,19 @@
// src/state/app/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 crate::state::app::search::SearchState; // ADDED
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")] #[cfg(feature = "ui-debug")]
use std::time::Instant; use std::time::Instant;
// --- YOUR EXISTING DIALOGSTATE IS UNTOUCHED --- // --- 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,
@@ -30,7 +34,7 @@ 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, // ADDED pub show_search_palette: bool,
pub focus_outside_canvas: bool, pub focus_outside_canvas: bool,
pub dialog: DialogState, pub dialog: DialogState,
} }
@@ -52,10 +56,12 @@ pub struct AppState {
pub current_view_profile_name: Option<String>, pub current_view_profile_name: Option<String>,
pub current_view_table_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)>,
// ADDED: State for the search palette
pub search_state: Option<SearchState>, pub search_state: Option<SearchState>,
// UI preferences // UI preferences
@@ -67,9 +73,7 @@ pub struct AppState {
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,
profile_tree: ProfileTreeResponse::default(), profile_tree: ProfileTreeResponse::default(),
@@ -77,9 +81,10 @@ impl AppState {
current_view_profile_name: None, current_view_profile_name: None,
current_view_table_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, // ADDED search_state: None,
ui: UiState::default(), ui: UiState::default(),
#[cfg(feature = "ui-debug")] #[cfg(feature = "ui-debug")]

View File

@@ -1,6 +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;
@@ -8,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
}
} }

View File

@@ -1,30 +1,54 @@
// src/state/pages/form.rs // src/state/pages/form.rs
use std::collections::HashMap;
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 profile_name: String, pub profile_name: String,
pub table_name: String, pub table_name: String,
pub total_count: u64, pub total_count: u64,
pub current_position: u64, pub current_position: u64,
pub fields: Vec<String>, 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 {
pub fn new( pub fn new(
profile_name: String, profile_name: String,
table_name: String, table_name: String,
fields: Vec<String>, fields: Vec<FieldDefinition>,
) -> Self { ) -> Self {
let values = vec![String::new(); fields.len()]; let values = vec![String::new(); fields.len()];
FormState { FormState {
@@ -38,10 +62,51 @@ impl FormState {
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)
} }
} }
// This signature is now correct and only deals with form-related state.
pub fn render( pub fn render(
&self, &self,
f: &mut Frame, f: &mut Frame,
@@ -51,7 +116,7 @@ impl FormState {
highlight_state: &HighlightState, highlight_state: &HighlightState,
) { ) {
let fields_str_slice: Vec<&str> = let fields_str_slice: Vec<&str> =
self.fields.iter().map(|s| s.as_str()).collect(); self.fields().iter().map(|s| *s).collect();
let values_str_slice: Vec<&String> = self.values.iter().collect(); let values_str_slice: Vec<&String> = self.values.iter().collect();
crate::components::form::form::render_form( crate::components::form::form::render_form(
@@ -70,7 +135,6 @@ impl FormState {
); );
} }
// ... other methods are unchanged ...
pub fn reset_to_empty(&mut self) { pub fn reset_to_empty(&mut self) {
self.id = 0; self.id = 0;
self.values.iter_mut().for_each(|v| v.clear()); self.values.iter_mut().for_each(|v| v.clear());
@@ -82,6 +146,8 @@ impl FormState {
} else { } else {
self.current_position = 1; 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 {
@@ -92,6 +158,7 @@ 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")
@@ -102,13 +169,16 @@ impl FormState {
response_data: &HashMap<String, String>, response_data: &HashMap<String, String>,
new_position: u64, new_position: u64,
) { ) {
self.values = self.fields.iter().map(|field_from_schema| { self.values = self
response_data .fields
.iter() .iter()
.find(|(key_from_data, _)| key_from_data.eq_ignore_ascii_case(field_from_schema)) .map(|field_def| {
.map(|(_, value)| value.clone()) response_data
.unwrap_or_default() .get(&field_def.data_key)
}).collect(); .cloned()
.unwrap_or_default()
})
.collect();
let id_str_opt = response_data let id_str_opt = response_data
.iter() .iter()
@@ -119,7 +189,12 @@ impl FormState {
if let Ok(parsed_id) = id_str.parse::<i64>() { if let Ok(parsed_id) = id_str.parse::<i64>() {
self.id = parsed_id; self.id = parsed_id;
} else { } else {
tracing::error!( "Failed to parse 'id' field '{}' for table {}.{}", id_str, self.profile_name, self.table_name); tracing::error!(
"Failed to parse 'id' field '{}' for table {}.{}",
id_str,
self.profile_name,
self.table_name
);
self.id = 0; self.id = 0;
} }
} else { } else {
@@ -130,6 +205,15 @@ impl FormState {
self.has_unsaved_changes = false; self.has_unsaved_changes = false;
self.current_field = 0; self.current_field = 0;
self.current_cursor_pos = 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;
} }
} }
@@ -137,50 +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 {
FormState::get_current_input(self) FormState::get_current_input(self)
} }
fn get_current_input_mut(&mut self) -> &mut String { fn get_current_input_mut(&mut self) -> &mut String {
FormState::get_current_input_mut(self) FormState::get_current_input_mut(self)
} }
fn fields(&self) -> Vec<&str> { fn fields(&self) -> Vec<&str> {
self.fields.iter().map(|s| s.as_str()).collect() self.fields
.iter()
.map(|f| f.display_name.as_str())
.collect()
} }
fn set_current_field(&mut self, index: usize) { fn set_current_field(&mut self, index: usize) {
if index < self.fields.len() { if index < self.fields.len() {
self.current_field = index; self.current_field = index;
} }
self.deactivate_autocomplete();
} }
fn set_current_cursor_pos(&mut self, pos: usize) { fn set_current_cursor_pos(&mut self, pos: usize) {
self.current_cursor_pos = pos; self.current_cursor_pos = pos;
} }
fn set_has_unsaved_changes(&mut self, changed: bool) { fn set_has_unsaved_changes(&mut self, changed: bool) {
self.has_unsaved_changes = changed; self.has_unsaved_changes = changed;
} }
fn get_suggestions(&self) -> Option<&[String]> { fn get_suggestions(&self) -> Option<&[String]> {
None 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> { fn get_selected_suggestion_index(&self) -> Option<usize> {
None 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())
.unwrap_or("")
}
// --- IMPLEMENT THE NEW TRAIT METHOD ---
fn has_display_override(&self, index: usize) -> bool {
self.link_display_map.contains_key(&index)
} }
} }

View File

@@ -1,19 +1,22 @@
// 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 anyhow::{Context, Result}; // Added Context use crate::utils::data_converter; // NEW: Import our translator
use std::collections::HashMap; // NEW 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, NoChange,
UpdatedExisting, UpdatedExisting,
CreatedNew(i64), // Keep the ID CreatedNew(i64),
} }
// MODIFIED save function // 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,
) -> Result<SaveOutcome> { ) -> Result<SaveOutcome> {
@@ -21,42 +24,64 @@ pub async fn save(
return Ok(SaveOutcome::NoChange); return Ok(SaveOutcome::NoChange);
} }
let data_map: HashMap<String, String> = form_state.fields.iter() // --- NEW: VALIDATION & CONVERSION STEP ---
let cache_key =
format!("{}.{}", form_state.profile_name, form_state.table_name);
let schema = match app_state.schema_cache.get(&cache_key) {
Some(s) => s,
None => {
return Err(anyhow!(
"Schema for table '{}' not found in cache. Cannot save.",
form_state.table_name
));
}
};
let data_map: HashMap<String, String> = form_state
.fields
.iter()
.zip(form_state.values.iter()) .zip(form_state.values.iter())
.map(|(field, value)| (field.clone(), value.clone())) .map(|(field_def, value)| (field_def.data_key.clone(), value.clone()))
.collect(); .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 outcome: SaveOutcome;
let is_new_entry = form_state.id == 0
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) ; || (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 { if is_new_entry {
let response = grpc_client let response = grpc_client
.post_table_data( .post_table_data(
form_state.profile_name.clone(), form_state.profile_name.clone(),
form_state.table_name.clone(), form_state.table_name.clone(),
data_map, converted_data, // Use the validated & converted data
) )
.await .await
.context("Failed to post new table data")?; .context("Failed to post new table data")?;
if response.success { if response.success {
form_state.id = response.inserted_id; form_state.id = response.inserted_id;
// After creating a new entry, total_count increases, and current_position becomes this new total_count
form_state.total_count += 1; form_state.total_count += 1;
form_state.current_position = form_state.total_count; form_state.current_position = form_state.total_count;
outcome = SaveOutcome::CreatedNew(response.inserted_id); outcome = SaveOutcome::CreatedNew(response.inserted_id);
} else { } else {
return Err(anyhow::anyhow!( return Err(anyhow!(
"Server failed to insert data: {}", "Server failed to insert data: {}",
response.message response.message
)); ));
} }
} else { } else {
// This assumes form_state.id is valid for an existing record
if form_state.id == 0 { if form_state.id == 0 {
return Err(anyhow::anyhow!( return Err(anyhow!(
"Cannot update record: ID is 0, but not classified as new entry." "Cannot update record: ID is 0, but not classified as new entry."
)); ));
} }
@@ -65,7 +90,7 @@ pub async fn save(
form_state.profile_name.clone(), form_state.profile_name.clone(),
form_state.table_name.clone(), form_state.table_name.clone(),
form_state.id, form_state.id,
data_map, converted_data, // Use the validated & converted data
) )
.await .await
.context("Failed to put (update) table data")?; .context("Failed to put (update) table data")?;
@@ -73,7 +98,7 @@ pub async fn save(
if response.success { if response.success {
outcome = SaveOutcome::UpdatedExisting; outcome = SaveOutcome::UpdatedExisting;
} else { } else {
return Err(anyhow::anyhow!( return Err(anyhow!(
"Server failed to update data: {}", "Server failed to update data: {}",
response.message response.message
)); ));

View File

@@ -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;
@@ -92,12 +92,20 @@ pub async fn run_ui() -> Result<()> {
.await .await
.context("Failed to initialize app state and form")?; .context("Failed to initialize app state and form")?;
let filtered_columns = filter_user_columns(initial_columns_from_service); let initial_field_defs: Vec<FieldDefinition> = filter_user_columns(initial_columns_from_service)
.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( let mut form_state = FormState::new(
initial_profile.clone(), initial_profile.clone(),
initial_table.clone(), initial_table.clone(),
filtered_columns, initial_field_defs,
); );
UiService::fetch_and_set_table_count(&mut grpc_client, &mut form_state) UiService::fetch_and_set_table_count(&mut grpc_client, &mut form_state)
@@ -132,6 +140,9 @@ pub async fn run_ui() -> Result<()> {
let position_before_event = form_state.current_position; let position_before_event = form_state.current_position;
let mut event_processed = false; let mut event_processed = false;
// --- CHANNEL RECEIVERS ---
// For main search palette
match event_handler.search_result_receiver.try_recv() { match event_handler.search_result_receiver.try_recv() {
Ok(hits) => { Ok(hits) => {
info!("--- 4. Main loop received message from channel. ---"); info!("--- 4. Main loop received message from channel. ---");
@@ -147,6 +158,29 @@ pub async fn run_ui() -> Result<()> {
error!("Search result channel 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 { if app_state.ui.show_search_palette {
needs_redraw = true; needs_redraw = true;
} }
@@ -316,83 +350,91 @@ pub async fn run_ui() -> Result<()> {
let current_view_profile = app_state.current_view_profile_name.clone(); let current_view_profile = app_state.current_view_profile_name.clone();
let current_view_table = app_state.current_view_table_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 if prev_view_profile_name != current_view_profile
|| prev_view_table_name != current_view_table || prev_view_table_name != current_view_table
{ {
if let (Some(prof_name), Some(tbl_name)) = if let (Some(prof_name), Some(tbl_name)) =
(current_view_profile.as_ref(), current_view_table.as_ref()) (current_view_profile.as_ref(), current_view_table.as_ref())
{ {
// --- START OF REFACTORED LOGIC ---
app_state.show_loading_dialog( app_state.show_loading_dialog(
"Loading Table", "Loading Table",
&format!("Fetching data for {}.{}...", prof_name, tbl_name), &format!("Fetching data for {}.{}...", prof_name, tbl_name),
); );
needs_redraw = true; needs_redraw = true;
match grpc_client // 1. Call our new, central function. It handles fetching AND caching.
.get_table_structure(prof_name.clone(), tbl_name.clone()) match UiService::load_table_view(
.await &mut grpc_client,
&mut app_state,
prof_name,
tbl_name,
)
.await
{ {
Ok(structure_response) => { Ok(mut new_form_state) => {
let new_columns: Vec<String> = structure_response // 2. The function succeeded, we have a new FormState.
.columns // Now, fetch its data.
.iter()
.map(|c| c.name.clone())
.collect();
let filtered_columns = filter_user_columns(new_columns);
form_state = FormState::new(
prof_name.clone(),
tbl_name.clone(),
filtered_columns,
);
if let Err(e) = UiService::fetch_and_set_table_count( if let Err(e) = UiService::fetch_and_set_table_count(
&mut grpc_client, &mut grpc_client,
&mut form_state, &mut new_form_state,
) )
.await .await
{ {
// Handle count fetching error
app_state.update_dialog_content( app_state.update_dialog_content(
&format!("Error fetching count: {}", e), &format!("Error fetching count: {}", e),
vec!["OK".to_string()], vec!["OK".to_string()],
DialogPurpose::LoginFailed, DialogPurpose::LoginFailed, // Or a more appropriate purpose
); );
} else if form_state.total_count > 0 { } 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( if let Err(e) = UiService::load_table_data_by_position(
&mut grpc_client, &mut grpc_client,
&mut form_state, &mut new_form_state,
) )
.await .await
{ {
// Handle data loading error
app_state.update_dialog_content( app_state.update_dialog_content(
&format!("Error loading data: {}", e), &format!("Error loading data: {}", e),
vec!["OK".to_string()], vec!["OK".to_string()],
DialogPurpose::LoginFailed, DialogPurpose::LoginFailed, // Or a more appropriate purpose
); );
} else { } else {
// Success! Hide the loading dialog.
app_state.hide_dialog(); app_state.hide_dialog();
} }
} else { } else {
form_state.reset_to_empty(); // No records, so just reset to an empty form.
new_form_state.reset_to_empty();
app_state.hide_dialog(); 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_profile_name = current_view_profile;
prev_view_table_name = current_view_table; prev_view_table_name = current_view_table;
table_just_switched = true; table_just_switched = true;
} }
Err(e) => { Err(e) => {
// This handles errors from load_table_view (e.g., schema fetch failed)
app_state.update_dialog_content( app_state.update_dialog_content(
&format!("Error fetching table structure: {}", e), &format!("Error loading table: {}", e),
vec!["OK".to_string()], vec!["OK".to_string()],
DialogPurpose::LoginFailed, DialogPurpose::LoginFailed, // Or a more appropriate purpose
); );
// Revert the view change in app_state to avoid a loop
app_state.current_view_profile_name = app_state.current_view_profile_name =
prev_view_profile_name.clone(); prev_view_profile_name.clone();
app_state.current_view_table_name = app_state.current_view_table_name =
prev_view_table_name.clone(); prev_view_table_name.clone();
} }
} }
// --- END OF REFACTORED LOGIC ---
} }
needs_redraw = true; needs_redraw = true;
} }

View 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()
}

View File

@@ -2,5 +2,8 @@
pub mod columns; pub mod columns;
pub mod debug_logger; pub mod debug_logger;
pub mod data_converter;
pub use columns::*; pub use columns::*;
pub use debug_logger::*; pub use debug_logger::*;
pub use data_converter::*;

View File

@@ -5,6 +5,8 @@ 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"] }

View File

@@ -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 {

Binary file not shown.

View File

@@ -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)]

View File

@@ -25,7 +25,7 @@ pub struct SearcherService {
pub pool: PgPool, pub pool: PgPool,
} }
// Normalize diacritics in queries (no changes here) // normalize_slovak_text function remains unchanged...
fn normalize_slovak_text(text: &str) -> String { fn normalize_slovak_text(text: &str) -> String {
// ... function content is unchanged ... // ... function content is unchanged ...
text.chars() text.chars()
@@ -73,9 +73,48 @@ impl Searcher for SearcherService {
let table_name = req.table_name; let table_name = req.table_name;
let query_str = req.query; let query_str = req.query;
// --- MODIFIED LOGIC ---
// If the query is empty, fetch the 5 most recent records.
if query_str.trim().is_empty() { if query_str.trim().is_empty() {
return Err(Status::invalid_argument("Query cannot be 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); let index_path = Path::new("./tantivy_indexes").join(&table_name);
if !index_path.exists() { if !index_path.exists() {
@@ -98,15 +137,6 @@ impl Searcher for SearcherService {
let searcher = reader.searcher(); let searcher = reader.searcher();
let schema = index.schema(); let schema = index.schema();
let prefix_edge_field = schema.get_field("prefix_edge").map_err(|_| {
Status::internal("Schema is missing the 'prefix_edge' field.")
})?;
let prefix_full_field = schema.get_field("prefix_full").map_err(|_| {
Status::internal("Schema is missing the 'prefix_full' field.")
})?;
let text_ngram_field = schema.get_field("text_ngram").map_err(|_| {
Status::internal("Schema is missing the 'text_ngram' field.")
})?;
let pg_id_field = schema.get_field("pg_id").map_err(|_| { let pg_id_field = schema.get_field("pg_id").map_err(|_| {
Status::internal("Schema is missing the 'pg_id' field.") Status::internal("Schema is missing the 'pg_id' field.")
})?; })?;

View File

@@ -10,6 +10,7 @@ search = { path = "../search" }
anyhow = { workspace = true } anyhow = { workspace = true }
tantivy = { 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"

View File

@@ -1,9 +1,10 @@
// src/tables_data/handlers/get_table_data.rs // src/tables_data/handlers/get_table_data.rs
use tonic::Status; use tonic::Status;
use sqlx::{PgPool, Row}; use sqlx::{PgPool, Row};
use std::collections::HashMap; use std::collections::HashMap;
use common::proto::multieko2::tables_data::{GetTableDataRequest, GetTableDataResponse}; use common::proto::multieko2::tables_data::{GetTableDataRequest, GetTableDataResponse};
use crate::shared::schema_qualifier::qualify_table_name_for_data; // Import schema qualifier use crate::shared::schema_qualifier::qualify_table_name_for_data;
pub async fn get_table_data( pub async fn get_table_data(
db_pool: &PgPool, db_pool: &PgPool,
@@ -48,27 +49,44 @@ pub async fn get_table_data(
return Err(Status::internal("Invalid column format")); return Err(Status::internal("Invalid column format"));
} }
let name = parts[0].trim_matches('"').to_string(); let name = parts[0].trim_matches('"').to_string();
let sql_type = parts[1].to_string(); user_columns.push(name);
user_columns.push((name, sql_type));
} }
// Prepare all columns (system + user-defined) // --- START OF FIX ---
let system_columns = vec![
("id".to_string(), "BIGINT".to_string()),
("deleted".to_string(), "BOOLEAN".to_string()),
];
let all_columns: Vec<(String, String)> = system_columns
.into_iter()
.chain(user_columns.into_iter())
.collect();
// Build SELECT clause with COALESCE and type casting // 1. Get all foreign key columns for this table
let columns_clause = all_columns let fk_columns_query = sqlx::query!(
r#"SELECT ltd.table_name
FROM table_definition_links tdl
JOIN table_definitions ltd ON tdl.linked_table_id = ltd.id
WHERE tdl.source_table_id = $1"#,
table_def.id
)
.fetch_all(db_pool)
.await
.map_err(|e| Status::internal(format!("Foreign key lookup error: {}", e)))?;
// 2. Build the list of foreign key column names
let mut foreign_key_columns = Vec::new();
for fk in fk_columns_query {
let base_name = fk.table_name.split_once('_').map_or(fk.table_name.as_str(), |(_, rest)| rest);
foreign_key_columns.push(format!("{}_id", base_name));
}
// 3. Prepare a complete list of all columns to select
let mut all_column_names = vec!["id".to_string(), "deleted".to_string()];
all_column_names.extend(user_columns);
all_column_names.extend(foreign_key_columns);
// 4. Build the SELECT clause with all columns
let columns_clause = all_column_names
.iter() .iter()
.map(|(name, _)| format!("COALESCE(\"{0}\"::TEXT, '') AS \"{0}\"", name)) .map(|name| format!("COALESCE(\"{0}\"::TEXT, '') AS \"{0}\"", name))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
// --- END OF FIX ---
// Qualify table name with schema // Qualify table name with schema
let qualified_table = qualify_table_name_for_data(&table_name)?; let qualified_table = qualify_table_name_for_data(&table_name)?;
@@ -87,7 +105,6 @@ pub async fn get_table_data(
Ok(row) => row, Ok(row) => row,
Err(sqlx::Error::RowNotFound) => return Err(Status::not_found("Record not found")), Err(sqlx::Error::RowNotFound) => return Err(Status::not_found("Record not found")),
Err(e) => { Err(e) => {
// Handle "relation does not exist" error specifically
if let Some(db_err) = e.as_database_error() { if let Some(db_err) = e.as_database_error() {
if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) { if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) {
return Err(Status::internal(format!( return Err(Status::internal(format!(
@@ -100,9 +117,9 @@ pub async fn get_table_data(
} }
}; };
// Build response data // Build response data from the complete list of columns
let mut data = HashMap::new(); let mut data = HashMap::new();
for (column_name, _) in &all_columns { for column_name in &all_column_names {
let value: String = row let value: String = row
.try_get(column_name.as_str()) .try_get(column_name.as_str())
.map_err(|e| Status::internal(format!("Failed to get column {}: {}", column_name, e)))?; .map_err(|e| Status::internal(format!("Failed to get column {}: {}", column_name, e)))?;

View File

@@ -8,16 +8,15 @@ use common::proto::multieko2::tables_data::{PostTableDataRequest, PostTableDataR
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use crate::shared::schema_qualifier::qualify_table_name_for_data; use crate::shared::schema_qualifier::qualify_table_name_for_data;
use prost_types::value::Kind; // NEW: Import the Kind enum
use crate::steel::server::execution::{self, Value}; use crate::steel::server::execution::{self, Value};
use crate::steel::server::functions::SteelContext; use crate::steel::server::functions::SteelContext;
// Add these imports
use crate::indexer::{IndexCommand, IndexCommandData}; use crate::indexer::{IndexCommand, IndexCommandData};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tracing::error; use tracing::error;
// MODIFIED: Function signature now accepts the indexer sender
pub async fn post_table_data( pub async fn post_table_data(
db_pool: &PgPool, db_pool: &PgPool,
request: PostTableDataRequest, request: PostTableDataRequest,
@@ -25,11 +24,6 @@ pub async fn post_table_data(
) -> Result<PostTableDataResponse, Status> { ) -> Result<PostTableDataResponse, Status> {
let profile_name = request.profile_name; let profile_name = request.profile_name;
let table_name = request.table_name; let table_name = request.table_name;
let mut data = HashMap::new();
for (key, value) in request.data {
data.insert(key, value.trim().to_string());
}
// Lookup profile // Lookup profile
let profile = sqlx::query!( let profile = sqlx::query!(
@@ -85,7 +79,7 @@ pub async fn post_table_data(
// Build system columns with foreign keys // Build system columns with foreign keys
let mut system_columns = vec!["deleted".to_string()]; let mut system_columns = vec!["deleted".to_string()];
for fk in fk_columns { for fk in fk_columns {
let base_name = fk.table_name.split('_').last().unwrap_or(&fk.table_name); let base_name = fk.table_name.split_once('_').map_or(fk.table_name.as_str(), |(_, rest)| rest);
system_columns.push(format!("{}_id", base_name)); system_columns.push(format!("{}_id", base_name));
} }
@@ -94,13 +88,32 @@ pub async fn post_table_data(
// Validate all data columns // Validate all data columns
let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect(); let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect();
for key in data.keys() { for key in request.data.keys() {
if !system_columns_set.contains(key.as_str()) && if !system_columns_set.contains(key.as_str()) &&
!user_columns.contains(&&key.to_string()) { !user_columns.contains(&&key.to_string()) {
return Err(Status::invalid_argument(format!("Invalid column: {}", key))); return Err(Status::invalid_argument(format!("Invalid column: {}", key)));
} }
} }
// ========================================================================
// FIX #1: SCRIPT VALIDATION LOOP
// This loop now correctly handles JSON `null` (which becomes `None`).
// ========================================================================
let mut string_data_for_scripts = HashMap::new();
for (key, proto_value) in &request.data {
let str_val = match &proto_value.kind {
Some(Kind::StringValue(s)) => s.clone(),
Some(Kind::NumberValue(n)) => n.to_string(),
Some(Kind::BoolValue(b)) => b.to_string(),
// This now correctly skips both protobuf `NULL` and JSON `null`.
Some(Kind::NullValue(_)) | None => continue,
Some(Kind::StructValue(_)) | Some(Kind::ListValue(_)) => {
return Err(Status::invalid_argument(format!("Unsupported type for script validation in column '{}'", key)));
}
};
string_data_for_scripts.insert(key.clone(), str_val);
}
// Validate Steel scripts // Validate Steel scripts
let scripts = sqlx::query!( let scripts = sqlx::query!(
"SELECT target_column, script FROM table_scripts WHERE table_definitions_id = $1", "SELECT target_column, script FROM table_scripts WHERE table_definitions_id = $1",
@@ -113,21 +126,18 @@ pub async fn post_table_data(
for script_record in scripts { for script_record in scripts {
let target_column = script_record.target_column; let target_column = script_record.target_column;
// Ensure target column exists in submitted data let user_value = string_data_for_scripts.get(&target_column)
let user_value = data.get(&target_column)
.ok_or_else(|| Status::invalid_argument( .ok_or_else(|| Status::invalid_argument(
format!("Script target column '{}' is required", target_column) format!("Script target column '{}' is required", target_column)
))?; ))?;
// Create execution context
let context = SteelContext { let context = SteelContext {
current_table: table_name.clone(), // Keep base name for scripts current_table: table_name.clone(),
profile_id, profile_id,
row_data: data.clone(), row_data: string_data_for_scripts.clone(),
db_pool: Arc::new(db_pool.clone()), db_pool: Arc::new(db_pool.clone()),
}; };
// Execute validation script
let script_result = execution::execute_script( let script_result = execution::execute_script(
script_record.script, script_record.script,
"STRINGS", "STRINGS",
@@ -138,7 +148,6 @@ pub async fn post_table_data(
format!("Script execution failed for '{}': {}", target_column, e) format!("Script execution failed for '{}': {}", target_column, e)
))?; ))?;
// Validate script output
let Value::Strings(mut script_output) = script_result else { let Value::Strings(mut script_output) = script_result else {
return Err(Status::internal("Script must return string values")); return Err(Status::internal("Script must return string values"));
}; };
@@ -160,11 +169,16 @@ pub async fn post_table_data(
let mut placeholders = Vec::new(); let mut placeholders = Vec::new();
let mut param_idx = 1; let mut param_idx = 1;
for (col, value) in data { // ========================================================================
// FIX #2: DATABASE INSERTION LOOP
// This loop now correctly handles JSON `null` (which becomes `None`)
// without crashing and correctly inserts a SQL NULL.
// ========================================================================
for (col, proto_value) in request.data {
let sql_type = if system_columns_set.contains(col.as_str()) { let sql_type = if system_columns_set.contains(col.as_str()) {
match col.as_str() { match col.as_str() {
"deleted" => "BOOLEAN", "deleted" => "BOOLEAN",
_ if col.ends_with("_id") => "BIGINT", // Handle foreign keys _ if col.ends_with("_id") => "BIGINT",
_ => return Err(Status::invalid_argument("Invalid system column")), _ => return Err(Status::invalid_argument("Invalid system column")),
} }
} else { } else {
@@ -174,36 +188,65 @@ pub async fn post_table_data(
.ok_or_else(|| Status::invalid_argument(format!("Column not found: {}", col)))? .ok_or_else(|| Status::invalid_argument(format!("Column not found: {}", col)))?
}; };
// Check for `None` (from JSON null) or `Some(NullValue)` first.
let kind = match &proto_value.kind {
None | Some(Kind::NullValue(_)) => {
// It's a null value. Add the correct SQL NULL type and continue.
match sql_type {
"BOOLEAN" => params.add(None::<bool>),
"TEXT" | "VARCHAR(15)" | "VARCHAR(255)" => params.add(None::<String>),
"TIMESTAMPTZ" => params.add(None::<DateTime<Utc>>),
"BIGINT" => params.add(None::<i64>),
_ => return Err(Status::invalid_argument(format!("Unsupported type for null value: {}", sql_type))),
}.map_err(|e| Status::internal(format!("Failed to add null parameter for {}: {}", col, e)))?;
columns_list.push(format!("\"{}\"", col));
placeholders.push(format!("${}", param_idx));
param_idx += 1;
continue; // Skip to the next column in the loop
}
// If it's not null, just pass the inner `Kind` through.
Some(k) => k,
};
// From here, we know `kind` is not a null type.
match sql_type { match sql_type {
"TEXT" | "VARCHAR(15)" | "VARCHAR(255)" => { "TEXT" | "VARCHAR(15)" | "VARCHAR(255)" => {
if let Some(max_len) = sql_type.strip_prefix("VARCHAR(") if let Kind::StringValue(value) = kind {
.and_then(|s| s.strip_suffix(')')) if let Some(max_len) = sql_type.strip_prefix("VARCHAR(").and_then(|s| s.strip_suffix(')')).and_then(|s| s.parse::<usize>().ok()) {
.and_then(|s| s.parse::<usize>().ok()) if value.len() > max_len {
{ return Err(Status::internal(format!("Value too long for {}", col)));
if value.len() > max_len { }
return Err(Status::internal(format!("Value too long for {}", col)));
} }
params.add(value).map_err(|e| Status::invalid_argument(format!("Failed to add text parameter for {}: {}", col, e)))?;
} else {
return Err(Status::invalid_argument(format!("Expected string for column '{}'", col)));
} }
params.add(value)
.map_err(|e| Status::invalid_argument(format!("Failed to add text parameter for {}: {}", col, e)))?;
}, },
"BOOLEAN" => { "BOOLEAN" => {
let val = value.parse::<bool>() if let Kind::BoolValue(val) = kind {
.map_err(|_| Status::invalid_argument(format!("Invalid boolean for {}", col)))?; params.add(val).map_err(|e| Status::invalid_argument(format!("Failed to add boolean parameter for {}: {}", col, e)))?;
params.add(val) } else {
.map_err(|e| Status::invalid_argument(format!("Failed to add boolean parameter for {}: {}", col, e)))?; return Err(Status::invalid_argument(format!("Expected boolean for column '{}'", col)));
}
}, },
"TIMESTAMPTZ" => { "TIMESTAMPTZ" => {
let dt = DateTime::parse_from_rfc3339(&value) if let Kind::StringValue(value) = kind {
.map_err(|_| Status::invalid_argument(format!("Invalid timestamp for {}", col)))?; let dt = DateTime::parse_from_rfc3339(value).map_err(|_| Status::invalid_argument(format!("Invalid timestamp for {}", col)))?;
params.add(dt.with_timezone(&Utc)) params.add(dt.with_timezone(&Utc)).map_err(|e| Status::invalid_argument(format!("Failed to add timestamp parameter for {}: {}", col, e)))?;
.map_err(|e| Status::invalid_argument(format!("Failed to add timestamp parameter for {}: {}", col, e)))?; } else {
return Err(Status::invalid_argument(format!("Expected ISO 8601 string for column '{}'", col)));
}
}, },
"BIGINT" => { "BIGINT" => {
let val = value.parse::<i64>() if let Kind::NumberValue(val) = kind {
.map_err(|_| Status::invalid_argument(format!("Invalid integer for {}", col)))?; if val.fract() != 0.0 {
params.add(val) return Err(Status::invalid_argument(format!("Expected integer for column '{}', but got a float", col)));
.map_err(|e| Status::invalid_argument(format!("Failed to add integer parameter for {}: {}", col, e)))?; }
params.add(*val as i64).map_err(|e| Status::invalid_argument(format!("Failed to add integer parameter for {}: {}", col, e)))?;
} else {
return Err(Status::invalid_argument(format!("Expected number for column '{}'", col)));
}
}, },
_ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))), _ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))),
} }
@@ -227,7 +270,6 @@ pub async fn post_table_data(
placeholders.join(", ") placeholders.join(", ")
); );
// Execute query with enhanced error handling
let result = sqlx::query_scalar_with::<_, i64, _>(&sql, params) let result = sqlx::query_scalar_with::<_, i64, _>(&sql, params)
.fetch_one(db_pool) .fetch_one(db_pool)
.await; .await;
@@ -235,7 +277,6 @@ pub async fn post_table_data(
let inserted_id = match result { let inserted_id = match result {
Ok(id) => id, Ok(id) => id,
Err(e) => { Err(e) => {
// Handle "relation does not exist" error specifically
if let Some(db_err) = e.as_database_error() { if let Some(db_err) = e.as_database_error() {
if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) { if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) {
return Err(Status::internal(format!( return Err(Status::internal(format!(
@@ -248,15 +289,12 @@ pub async fn post_table_data(
} }
}; };
// After a successful insert, send a command to the indexer.
let command = IndexCommand::AddOrUpdate(IndexCommandData { let command = IndexCommand::AddOrUpdate(IndexCommandData {
table_name: table_name.clone(), table_name: table_name.clone(),
row_id: inserted_id, row_id: inserted_id,
}); });
if let Err(e) = indexer_tx.send(command).await { if let Err(e) = indexer_tx.send(command).await {
// If sending fails, the DB is updated but the index will be stale.
// This is a critical situation to log and monitor.
error!( error!(
"CRITICAL: DB insert for table '{}' (id: {}) succeeded but failed to queue for indexing: {}. Search index is now inconsistent.", "CRITICAL: DB insert for table '{}' (id: {}) succeeded but failed to queue for indexing: {}. Search index is now inconsistent.",
table_name, inserted_id, e table_name, inserted_id, e

View File

@@ -4,8 +4,8 @@ use sqlx::{PgPool, Arguments, Postgres};
use sqlx::postgres::PgArguments; use sqlx::postgres::PgArguments;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use common::proto::multieko2::tables_data::{PutTableDataRequest, PutTableDataResponse}; use common::proto::multieko2::tables_data::{PutTableDataRequest, PutTableDataResponse};
use std::collections::HashMap; use crate::shared::schema_qualifier::qualify_table_name_for_data;
use crate::shared::schema_qualifier::qualify_table_name_for_data; // Import schema qualifier use prost_types::value::Kind;
pub async fn put_table_data( pub async fn put_table_data(
db_pool: &PgPool, db_pool: &PgPool,
@@ -15,20 +15,9 @@ pub async fn put_table_data(
let table_name = request.table_name; let table_name = request.table_name;
let record_id = request.id; let record_id = request.id;
// Preprocess and validate data // If no data is provided to update, it's an invalid request.
let mut processed_data = HashMap::new(); if request.data.is_empty() {
let mut null_fields = Vec::new(); return Err(Status::invalid_argument("No fields provided to update."));
// CORRECTED: Generic handling for all fields.
// Any field with an empty string will be added to the null_fields list.
// The special, hardcoded logic for "firma" has been removed.
for (key, value) in request.data {
let trimmed = value.trim().to_string();
if trimmed.is_empty() {
null_fields.push(key);
} else {
processed_data.insert(key, trimmed);
}
} }
// Lookup profile // Lookup profile
@@ -70,14 +59,29 @@ pub async fn put_table_data(
columns.push((name, sql_type)); columns.push((name, sql_type));
} }
// CORRECTED: "firma" is not a system column. // Get all foreign key columns for this table (needed for validation)
// It should be treated as a user-defined column. let fk_columns = sqlx::query!(
let system_columns = ["deleted"]; r#"SELECT ltd.table_name
FROM table_definition_links tdl
JOIN table_definitions ltd ON tdl.linked_table_id = ltd.id
WHERE tdl.source_table_id = $1"#,
table_def.id
)
.fetch_all(db_pool)
.await
.map_err(|e| Status::internal(format!("Foreign key lookup error: {}", e)))?;
let mut system_columns = vec!["deleted".to_string()];
for fk in fk_columns {
let base_name = fk.table_name.split_once('_').map_or(fk.table_name.as_str(), |(_, rest)| rest);
system_columns.push(format!("{}_id", base_name));
}
let system_columns_set: std::collections::HashSet<_> = system_columns.iter().map(|s| s.as_str()).collect();
let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect(); let user_columns: Vec<&String> = columns.iter().map(|(name, _)| name).collect();
// Validate input columns // Validate input columns
for key in processed_data.keys() { for key in request.data.keys() {
if !system_columns.contains(&key.as_str()) && !user_columns.contains(&key) { if !system_columns_set.contains(key.as_str()) && !user_columns.contains(&key) {
return Err(Status::invalid_argument(format!("Invalid column: {}", key))); return Err(Status::invalid_argument(format!("Invalid column: {}", key)));
} }
} }
@@ -87,54 +91,65 @@ pub async fn put_table_data(
let mut set_clauses = Vec::new(); let mut set_clauses = Vec::new();
let mut param_idx = 1; let mut param_idx = 1;
// Add data parameters for non-empty fields for (col, proto_value) in request.data {
for (col, value) in &processed_data { let sql_type = if system_columns_set.contains(col.as_str()) {
// CORRECTED: The logic for "firma" is removed from this match.
// It will now fall through to the `else` block and have its type
// correctly looked up from the `columns` vector.
let sql_type = if system_columns.contains(&col.as_str()) {
match col.as_str() { match col.as_str() {
"deleted" => "BOOLEAN", "deleted" => "BOOLEAN",
_ if col.ends_with("_id") => "BIGINT",
_ => return Err(Status::invalid_argument("Invalid system column")), _ => return Err(Status::invalid_argument("Invalid system column")),
} }
} else { } else {
columns.iter() columns.iter()
.find(|(name, _)| name == col) .find(|(name, _)| name == &col)
.map(|(_, sql_type)| sql_type.as_str()) .map(|(_, sql_type)| sql_type.as_str())
.ok_or_else(|| Status::invalid_argument(format!("Column not found: {}", col)))? .ok_or_else(|| Status::invalid_argument(format!("Column not found: {}", col)))?
}; };
// A provided value cannot be null or empty in a PUT request.
// To clear a field, it should be set to an empty string "" for text,
// or a specific value for other types if needed (though typically not done).
// For now, we reject nulls.
let kind = proto_value.kind.ok_or_else(|| {
Status::invalid_argument(format!("Value for column '{}' cannot be empty in a PUT request. To clear a text field, send an empty string.", col))
})?;
match sql_type { match sql_type {
"TEXT" | "VARCHAR(15)" | "VARCHAR(255)" => { "TEXT" | "VARCHAR(15)" | "VARCHAR(255)" => {
if let Some(max_len) = sql_type.strip_prefix("VARCHAR(") if let Kind::StringValue(value) = kind {
.and_then(|s| s.strip_suffix(')')) params.add(value)
.and_then(|s| s.parse::<usize>().ok()) .map_err(|e| Status::internal(format!("Failed to add text parameter for {}: {}", col, e)))?;
{ } else {
if value.len() > max_len { return Err(Status::invalid_argument(format!("Expected string for column '{}'", col)));
return Err(Status::internal(format!("Value too long for {}", col)));
}
} }
params.add(value)
.map_err(|e| Status::internal(format!("Failed to add text parameter for {}: {}", col, e)))?;
}, },
"BOOLEAN" => { "BOOLEAN" => {
let val = value.parse::<bool>() if let Kind::BoolValue(val) = kind {
.map_err(|_| Status::invalid_argument(format!("Invalid boolean for {}", col)))?; params.add(val)
params.add(val) .map_err(|e| Status::internal(format!("Failed to add boolean parameter for {}: {}", col, e)))?;
.map_err(|e| Status::internal(format!("Failed to add boolean parameter for {}: {}", col, e)))?; } else {
return Err(Status::invalid_argument(format!("Expected boolean for column '{}'", col)));
}
}, },
"TIMESTAMPTZ" => { "TIMESTAMPTZ" => {
let dt = DateTime::parse_from_rfc3339(value) if let Kind::StringValue(value) = kind {
.map_err(|_| Status::invalid_argument(format!("Invalid timestamp for {}", col)))?; let dt = DateTime::parse_from_rfc3339(&value)
params.add(dt.with_timezone(&Utc)) .map_err(|_| Status::invalid_argument(format!("Invalid timestamp for {}", col)))?;
.map_err(|e| Status::internal(format!("Failed to add timestamp parameter for {}: {}", col, e)))?; params.add(dt.with_timezone(&Utc))
.map_err(|e| Status::internal(format!("Failed to add timestamp parameter for {}: {}", col, e)))?;
} else {
return Err(Status::invalid_argument(format!("Expected ISO 8601 string for column '{}'", col)));
}
}, },
// ADDED: BIGINT handling for completeness, if needed for other columns.
"BIGINT" => { "BIGINT" => {
let val = value.parse::<i64>() if let Kind::NumberValue(val) = kind {
.map_err(|_| Status::invalid_argument(format!("Invalid integer for {}", col)))?; if val.fract() != 0.0 {
params.add(val) return Err(Status::invalid_argument(format!("Expected integer for column '{}', but got a float", col)));
.map_err(|e| Status::internal(format!("Failed to add integer parameter for {}: {}", col, e)))?; }
params.add(val as i64)
.map_err(|e| Status::internal(format!("Failed to add integer parameter for {}: {}", col, e)))?;
} else {
return Err(Status::invalid_argument(format!("Expected number for column '{}'", col)));
}
}, },
_ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))), _ => return Err(Status::invalid_argument(format!("Unsupported type {}", sql_type))),
} }
@@ -143,27 +158,10 @@ pub async fn put_table_data(
param_idx += 1; param_idx += 1;
} }
// Add NULL clauses for empty fields
for field in null_fields {
// Make sure the field is valid
if !system_columns.contains(&field.as_str()) && !user_columns.contains(&&field) {
return Err(Status::invalid_argument(format!("Invalid column to set NULL: {}", field)));
}
set_clauses.push(format!("\"{}\" = NULL", field));
}
// Ensure we have at least one field to update
if set_clauses.is_empty() {
return Err(Status::invalid_argument("No valid fields to update"));
}
// Add ID parameter at the end
params.add(record_id) params.add(record_id)
.map_err(|e| Status::internal(format!("Failed to add record_id parameter: {}", e)))?; .map_err(|e| Status::internal(format!("Failed to add record_id parameter: {}", e)))?;
// Qualify table name with schema
let qualified_table = qualify_table_name_for_data(&table_name)?; let qualified_table = qualify_table_name_for_data(&table_name)?;
let set_clause = set_clauses.join(", "); let set_clause = set_clauses.join(", ");
let sql = format!( let sql = format!(
"UPDATE {} SET {} WHERE id = ${} AND deleted = FALSE RETURNING id", "UPDATE {} SET {} WHERE id = ${} AND deleted = FALSE RETURNING id",
@@ -184,7 +182,6 @@ pub async fn put_table_data(
}), }),
Ok(None) => Err(Status::not_found("Record not found or already deleted")), Ok(None) => Err(Status::not_found("Record not found or already deleted")),
Err(e) => { Err(e) => {
// Handle "relation does not exist" error specifically
if let Some(db_err) = e.as_database_error() { if let Some(db_err) = e.as_database_error() {
if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) { if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) {
return Err(Status::internal(format!( return Err(Status::internal(format!(