Skip to main content

aylis_data/
events.rs

1//! Os eventos com estrutura do [`Field`] e do [`ClientDataSet`](crate::ClientDataSet): o
2//! pedido chega em JSON no `EventArgs::Text`, e cada um tem o registro dele no acesso tipado
3//! ([`GetTextRequest`], [`SetTextRequest`], [`MasterChange`], [`ServerQuery`]), para o
4//! handler receber o valor já lido nas 8 linguagens. As ajudas [`get_text`] e [`set_text`]
5//! respondem os do `Field` a partir do handler por nome (`ui, sender, args`).
6//!
7//! ```ignore
8//! pub fn field1_get_text(ui: &mut Ui, sender: ComponentId, args: &EventArgs) {
9//!     aylis_data::get_text(ui, sender, args, |v| match v.as_i64() {
10//!         Some(1) => "Aberto".into(),
11//!         Some(2) => "Faturado".into(),
12//!         _ => v.to_string(),
13//!     });
14//! }
15//!
16//! pub fn field1_set_text(ui: &mut Ui, sender: ComponentId, args: &EventArgs) {
17//!     aylis_data::set_text(ui, sender, args, |t| match t {
18//!         "Aberto" => Ok(1.into()),
19//!         "Faturado" => Ok(2.into()),
20//!         _ => Err(format!("situação desconhecida: {t}")),
21//!     });
22//! }
23//! ```
24
25use aylis_core::{ComponentId, EventArg, EventArgs, EventValue, PropKind, PropValue, RecordInfo, Ui};
26use serde_json::Value as Json;
27
28use crate::field::{Field, FieldType};
29use crate::handle::data_set;
30use crate::value::Value;
31
32/// O registro do pedido do `Field.on_get_text`: o campo e os valores que esperam o texto de
33/// exibição, cada um no texto canônico ([`value_text`]: `1`, `2024-05-01`, `SP`).
34pub const GET_TEXT_REQUEST_RECORD: RecordInfo =
35    RecordInfo { name: "GetTextRequest", fields: &[("field", PropKind::String), ("values", PropKind::List)] };
36
37/// O registro do pedido do `Field.on_set_text`: o campo e o texto digitado.
38pub const SET_TEXT_REQUEST_RECORD: RecordInfo =
39    RecordInfo { name: "SetTextRequest", fields: &[("field", PropKind::String), ("text", PropKind::String)] };
40
41/// Um campo e o valor dele, no texto canônico (os valores do mestre no `on_master_change`).
42pub const FIELD_VALUE_RECORD: RecordInfo =
43    RecordInfo { name: "FieldValue", fields: &[("field", PropKind::String), ("value", PropKind::String)] };
44
45/// O registro do `ClientDataSet.on_master_change`: os campos do mestre ligados ao detalhe
46/// (o `master_fields`) com o valor do registro atual do mestre.
47pub const MASTER_CHANGE_RECORD: RecordInfo =
48    RecordInfo { name: "MasterChange", fields: &[("values", PropKind::RecordList(&FIELD_VALUE_RECORD))] };
49
50/// O registro do `ClientDataSet.on_server_query` (veja [`ServerQuery`]).
51pub const SERVER_QUERY_RECORD: RecordInfo = RecordInfo {
52    name: "ServerQuery",
53    fields: &[
54        ("kind", PropKind::Enum(&["filter", "sort", "locate"])),
55        ("index", PropKind::String),
56        ("filter", PropKind::String),
57        ("loaded", PropKind::Int),
58        ("field", PropKind::String),
59        ("value", PropKind::String),
60    ],
61};
62
63/// O valor no texto canônico dos eventos: o número, a data ISO, o texto como é; nulo é vazio.
64/// É também a chave dos textos que o `on_get_text` devolve (o backend pode mandar `1` ou
65/// `"1"`: os dois valem para o mesmo valor).
66pub fn value_text(value: &Value) -> String {
67    value.to_string()
68}
69
70/// O JSON do `args` (texto, ou valor texto).
71fn json_of(args: &EventArgs) -> Option<Json> {
72    let text = match args {
73        EventArgs::Text(t) => t.as_str(),
74        EventArgs::Value(PropValue::String(t)) => t.as_str(),
75        _ => return None,
76    };
77    serde_json::from_str(text).ok()
78}
79
80fn text(json: &Json, key: &str) -> String {
81    match &json[key] {
82        Json::String(s) => s.clone(),
83        Json::Null => String::new(),
84        other => other.to_string(),
85    }
86}
87
88/// O pedido do `on_get_text`: os valores (no texto canônico) que esperam o texto de exibição.
89#[derive(Clone, Debug, Default, PartialEq)]
90pub struct GetTextRequest {
91    pub field: String,
92    pub values: Vec<String>,
93}
94
95impl GetTextRequest {
96    pub fn to_json(&self) -> String {
97        serde_json::json!({ "field": self.field, "values": self.values }).to_string()
98    }
99}
100
101impl EventValue for GetTextRequest {
102    const ARG: EventArg = EventArg::Value(PropKind::Record(&GET_TEXT_REQUEST_RECORD));
103    fn from_args(args: &EventArgs) -> Option<Self> {
104        let json = json_of(args)?;
105        let values = json["values"].as_array().map(|a| a.iter().map(|v| if let Json::String(s) = v { s.clone() } else { v.to_string() }).collect());
106        Some(GetTextRequest { field: text(&json, "field"), values: values.unwrap_or_default() })
107    }
108}
109
110/// O pedido do `on_set_text`: o texto digitado no campo.
111#[derive(Clone, Debug, Default, PartialEq)]
112pub struct SetTextRequest {
113    pub field: String,
114    pub text: String,
115}
116
117impl SetTextRequest {
118    pub fn to_json(&self) -> String {
119        serde_json::json!({ "field": self.field, "text": self.text }).to_string()
120    }
121}
122
123impl EventValue for SetTextRequest {
124    const ARG: EventArg = EventArg::Value(PropKind::Record(&SET_TEXT_REQUEST_RECORD));
125    fn from_args(args: &EventArgs) -> Option<Self> {
126        let json = json_of(args)?;
127        Some(SetTextRequest { field: text(&json, "field"), text: text(&json, "text") })
128    }
129}
130
131/// Um campo e o valor dele, no texto canônico.
132#[derive(Clone, Debug, Default, PartialEq)]
133pub struct FieldValue {
134    pub field: String,
135    pub value: String,
136}
137
138/// O `on_master_change`: o mestre mudou de registro, e estes são os valores dos campos dele
139/// ligados ao detalhe (para o backend carregar os detalhes sob demanda).
140#[derive(Clone, Debug, Default, PartialEq)]
141pub struct MasterChange {
142    pub values: Vec<FieldValue>,
143}
144
145impl MasterChange {
146    /// O valor de um campo do mestre (sem diferença de maiúsculas).
147    pub fn get(&self, field: &str) -> Option<&str> {
148        self.values.iter().find(|v| v.field.eq_ignore_ascii_case(field)).map(|v| v.value.as_str())
149    }
150
151    pub fn to_json(&self) -> String {
152        let values: Vec<Json> = self.values.iter().map(|v| serde_json::json!({ "field": v.field, "value": v.value })).collect();
153        serde_json::json!({ "values": values }).to_string()
154    }
155}
156
157impl EventValue for MasterChange {
158    const ARG: EventArg = EventArg::Value(PropKind::Record(&MASTER_CHANGE_RECORD));
159    fn from_args(args: &EventArgs) -> Option<Self> {
160        let json = json_of(args)?;
161        let values = json["values"]
162            .as_array()
163            .into_iter()
164            .flatten()
165            .map(|v| FieldValue { field: text(v, "field"), value: text(v, "value") })
166            .collect();
167        Some(MasterChange { values })
168    }
169}
170
171/// O `on_server_query`: com só parte da consulta carregada, ordenar, filtrar ou localizar pede
172/// ao backend que refaça a consulta.
173#[derive(Clone, Debug, Default, PartialEq)]
174pub struct ServerQuery {
175    /// `sort` (ordenar), `filter` (filtrar) ou `locate` (localizar).
176    pub kind: String,
177    /// A ordem pedida (`cliente;total desc`; vazio: a de chegada).
178    pub index: String,
179    /// O filtro em vigor (vazio: sem filtro).
180    pub filter: String,
181    /// Quantos registros estão carregados.
182    pub loaded: i64,
183    /// Só no `locate`: o campo e o valor procurados (no texto canônico).
184    pub field: String,
185    pub value: String,
186}
187
188impl ServerQuery {
189    pub fn to_json(&self) -> String {
190        serde_json::json!({
191            "kind": self.kind,
192            "index": self.index,
193            "filter": self.filter,
194            "loaded": self.loaded,
195            "field": self.field,
196            "value": self.value,
197        })
198        .to_string()
199    }
200}
201
202impl EventValue for ServerQuery {
203    const ARG: EventArg = EventArg::Value(PropKind::Record(&SERVER_QUERY_RECORD));
204    fn from_args(args: &EventArgs) -> Option<Self> {
205        let json = json_of(args)?;
206        Some(ServerQuery {
207            kind: text(&json, "kind"),
208            index: text(&json, "index"),
209            filter: text(&json, "filter"),
210            loaded: json["loaded"].as_i64().unwrap_or_default(),
211            field: text(&json, "field"),
212            value: text(&json, "value"),
213        })
214    }
215}
216
217/// Um valor no texto canônico de volta ao tipo do campo.
218pub(crate) fn value_from_text(text: &str, field: &Field) -> Result<Value, String> {
219    let json = match field.field_type {
220        // Número, lógico e bytes: o texto é o JSON deles.
221        FieldType::Integer | FieldType::AutoInc | FieldType::Boolean | FieldType::Blob => {
222            serde_json::from_str(text).unwrap_or_else(|_| Json::String(text.to_string()))
223        }
224        _ => Json::String(text.to_string()),
225    };
226    if text.is_empty() && field.field_type != FieldType::String && field.field_type != FieldType::Memo {
227        return Ok(Value::Null);
228    }
229    crate::json::json_to_value(&json, field)
230}
231
232/// Responde um `on_get_text`: o texto de exibição de cada valor pedido (o grid e os
233/// controles de dados repintam com eles).
234pub fn get_text(ui: &mut Ui, field: ComponentId, args: &EventArgs, text: impl Fn(&Value) -> String) {
235    let Some(request) = GetTextRequest::from_args(args) else { return };
236    let Some(cds) = ui.parent(field) else { return };
237    let Some(f) = ui.get::<Field>(field) else { return };
238    let texts: Vec<(Value, String)> = request
239        .values
240        .iter()
241        .filter_map(|v| value_from_text(v, f).ok())
242        .map(|v| {
243            let t = text(&v);
244            (v, t)
245        })
246        .collect();
247    let _ = data_set(ui, cds).set_field_texts(&request.field, texts);
248}
249
250/// Responde um `on_set_text`: o texto digitado vira o valor do campo, ou a mensagem de
251/// erro marca o campo (o `post` recusa enquanto houver).
252pub fn set_text(ui: &mut Ui, field: ComponentId, args: &EventArgs, value: impl Fn(&str) -> Result<Value, String>) {
253    let Some(request) = SetTextRequest::from_args(args) else { return };
254    let Some(cds) = ui.parent(field) else { return };
255    let mut ds = data_set(ui, cds);
256    match value(&request.text) {
257        Ok(v) => {
258            let _ = ds.set_value(&request.field, v);
259        }
260        Err(message) => {
261            let _ = ds.set_field_error(&request.field, Some(message));
262        }
263    }
264}