Skip to main content

aylis_data/
field.rs

1//! [`Field`]: a definição de uma coluna do dataset.
2//! É um componente filho do `ClientDataSet`, então aparece
3//! no arquivo de layout e no designer.
4
5use std::cell::RefCell;
6
7use aylis_core::messages::{t, tf};
8use aylis_core::platform::LocaleInfo;
9use aylis_core::{Component, ComponentId, Error, PropEnum, PropInfo, PropKind, PropValue, Result, TextAlign};
10
11use crate::expr::Expr;
12use crate::mask::Mask;
13
14use crate::format::{date_time_pattern, format_date_time, format_number, parse_date_time, parse_number, plain_number, split};
15use crate::value::{Date, DateTime, Decimal, Rounding, Time, Timestamp, Value};
16
17/// Tipo do campo; define como o valor é guardado, exibido e editado.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub enum FieldType {
20    #[default]
21    String,
22    /// Texto longo.
23    Memo,
24    Integer,
25    Float,
26    /// Dinheiro: decimal exato com `scale` casas.
27    Currency,
28    Boolean,
29    Date,
30    Time,
31    DateTime,
32    Blob,
33    /// Inteiro gerado pelo backend; somente leitura. Registros novos recebem um número
34    /// provisório negativo até o backend devolver o definitivo.
35    AutoInc,
36    /// Um instante (a hora do pedido, a última alteração): guardado em UTC, mostrado e
37    /// digitado no horário local de quem vê.
38    Timestamp,
39}
40
41impl FieldType {
42    pub const ALL: [FieldType; 12] = [
43        FieldType::String,
44        FieldType::Memo,
45        FieldType::Integer,
46        FieldType::Float,
47        FieldType::Currency,
48        FieldType::Boolean,
49        FieldType::Date,
50        FieldType::Time,
51        FieldType::DateTime,
52        FieldType::Blob,
53        FieldType::AutoInc,
54        FieldType::Timestamp,
55    ];
56
57    pub fn is_numeric(self) -> bool {
58        matches!(self, FieldType::Integer | FieldType::Float | FieldType::Currency | FieldType::AutoInc)
59    }
60}
61
62impl PropEnum for FieldType {
63    const NAMES: &'static [&'static str] =
64        &["string", "memo", "integer", "float", "currency", "boolean", "date", "time", "datetime", "blob", "auto_inc", "timestamp"];
65
66    fn from_index(index: usize) -> Option<Self> {
67        FieldType::ALL.get(index).copied()
68    }
69
70    fn index(self) -> usize {
71        self as usize
72    }
73}
74
75/// De onde vem o valor do campo.
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77pub enum FieldKind {
78    /// Dado do registro (vem do backend e volta no delta).
79    #[default]
80    Data,
81    /// Calculado a partir dos outros campos (`expression` ou `on_calculate`); não vai no
82    /// delta.
83    Calculated,
84    /// Buscado em outro dataset (`lookup_data_set`): o `key_fields` deste registro é
85    /// procurado no `lookup_key_fields` de lá e o resultado é o `lookup_result_field`.
86    Lookup,
87}
88
89impl PropEnum for FieldKind {
90    const NAMES: &'static [&'static str] = &["data", "calculated", "lookup"];
91
92    fn from_index(index: usize) -> Option<Self> {
93        [FieldKind::Data, FieldKind::Calculated, FieldKind::Lookup].get(index).copied()
94    }
95
96    fn index(self) -> usize {
97        self as usize
98    }
99}
100
101/// Maiúsculas/minúsculas forçadas na digitação (como `CharCase`).
102#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103pub enum CharCase {
104    #[default]
105    Normal,
106    Upper,
107    Lower,
108}
109
110impl PropEnum for CharCase {
111    const NAMES: &'static [&'static str] = &["normal", "upper", "lower"];
112
113    fn from_index(index: usize) -> Option<Self> {
114        [CharCase::Normal, CharCase::Upper, CharCase::Lower].get(index).copied()
115    }
116
117    fn index(self) -> usize {
118        self as usize
119    }
120}
121
122pub type GetTextFn = dyn Fn(&Value, bool) -> String;
123pub type SetTextFn = dyn Fn(&str) -> std::result::Result<Value, String>;
124pub type ValidateFn = dyn Fn(&Value) -> std::result::Result<(), String>;
125/// Cálculo em Rust: recebe uma função que lê os outros campos do registro.
126pub type CalculateFn = dyn Fn(&dyn Fn(&str) -> Value) -> Value;
127
128/// Definição de um campo.
129///
130/// ```ignore
131/// ui.add(Field::new("limite", FieldType::Currency).label("Limite").format("R$ #,##0.00").min(0.0), cds);
132/// ```
133pub struct Field {
134    /// Nome da coluna. Vazio = usa o nome do componente.
135    pub field_name: String,
136    /// O tipo do valor: `string`, `memo`, `integer`, `float`, `currency`, `boolean`, `date`,
137    /// `time`, `datetime`, `blob`, `auto_inc` ou `timestamp`.
138    pub field_type: FieldType,
139    /// Tamanho máximo (texto). 0 = sem limite.
140    pub size: usize,
141    /// Casas decimais de `currency`.
142    pub scale: u8,
143    /// Como um valor com mais casas é arredondado para `scale` (ao gravar, vindo da tela, do
144    /// backend ou de uma expressão, e ao mostrar): metade para cima (o padrão), bancário,
145    /// truncar ou para cima.
146    pub rounding: Rounding,
147    /// O título do campo nas grades e nos rótulos; vazio: o nome do campo.
148    pub display_label: String,
149    /// Largura sugerida para grids, em unidades lógicas. 0 = automática.
150    pub display_width: f32,
151    /// Como o valor aparece (`R$ #,##0.00`, `dd/mm/yyyy`); vazio: o padrão do tipo e do idioma.
152    pub display_format: String,
153    /// Como um número aparece durante a edição; vazio: o `display_format`.
154    pub edit_format: String,
155    /// `None` = conforme o tipo (números à direita).
156    pub alignment: Option<TextAlign>,
157    /// Não aceita gravar o registro com o campo vazio.
158    pub required: bool,
159    /// Os controles ligados mostram, mas não deixam editar.
160    pub read_only: bool,
161    /// Aparece nas grades; desligado, a coluna some (o valor continua no registro).
162    pub visible: bool,
163    /// O menor valor aceito (números); vazio: sem limite.
164    pub min: Option<f64>,
165    /// O maior valor aceito (números); vazio: sem limite.
166    pub max: Option<f64>,
167    /// Valor inicial de registros novos, em texto (lido com as regras do tipo).
168    pub default_value: String,
169    /// Textos para verdadeiro;falso (campos lógicos), como `DisplayValues`.
170    pub display_values: String,
171    /// Maiúsculas (`upper`) ou minúsculas (`lower`) forçadas no valor; `normal`: como digitado.
172    pub char_case: CharCase,
173    /// De onde vem o valor: `data` (do registro), `calculated` (a `expression`) ou `lookup`
174    /// (procurado em outro dataset).
175    pub kind: FieldKind,
176    /// Campo calculado: a expressão (`quantidade * preco`, ver [`crate::expr`]).
177    pub expression: String,
178    /// Lookup: o dataset onde procurar.
179    pub lookup_data_set: Option<ComponentId>,
180    /// Lookup: campo(s) deste dataset com a chave (`cliente_id`).
181    pub key_fields: String,
182    /// Lookup: campo(s) do outro dataset que correspondem (`id`).
183    pub lookup_key_fields: String,
184    /// Lookup: o campo trazido (`nome`).
185    pub lookup_result_field: String,
186    /// Máscara de edição (`000.000.000-00;0`, ver [`crate::mask`]).
187    pub edit_mask: String,
188    /// Dado pessoal (LGPD): os controles ligados ao campo contam como `sensitive` (as
189    /// gravações do `EventRecorder` mascaram o que é digitado neles).
190    pub sensitive: bool,
191    parsed: RefCell<Option<std::result::Result<Expr, String>>>,
192    calculate: Option<Box<CalculateFn>>,
193    get_text: Option<Box<GetTextFn>>,
194    set_text: Option<Box<SetTextFn>>,
195    validate: Option<Box<ValidateFn>>,
196    /// `on_get_text` por evento (backend remoto): textos já recebidos, por valor (JSON).
197    remote_texts: RefCell<std::collections::HashMap<String, String>>,
198    /// Valores pedidos e ainda sem texto (vão num evento só).
199    pending_texts: RefCell<Vec<Value>>,
200}
201
202impl Default for Field {
203    fn default() -> Self {
204        Self {
205            field_name: String::new(),
206            field_type: FieldType::String,
207            size: 0,
208            scale: 2,
209            rounding: Rounding::HalfUp,
210            display_label: String::new(),
211            display_width: 0.0,
212            display_format: String::new(),
213            edit_format: String::new(),
214            alignment: None,
215            required: false,
216            read_only: false,
217            visible: true,
218            min: None,
219            max: None,
220            default_value: String::new(),
221            display_values: String::new(),
222            char_case: CharCase::Normal,
223            kind: FieldKind::Data,
224            expression: String::new(),
225            lookup_data_set: None,
226            key_fields: String::new(),
227            lookup_key_fields: String::new(),
228            lookup_result_field: String::new(),
229            edit_mask: String::new(),
230            sensitive: false,
231            parsed: RefCell::new(None),
232            calculate: None,
233            get_text: None,
234            set_text: None,
235            validate: None,
236            remote_texts: RefCell::default(),
237            pending_texts: RefCell::default(),
238        }
239    }
240}
241
242impl Field {
243    pub fn new(name: impl Into<String>, field_type: FieldType) -> Self {
244        Self { field_name: name.into(), field_type, ..Default::default() }
245    }
246
247    pub fn label(mut self, label: impl Into<String>) -> Self {
248        self.display_label = label.into();
249        self
250    }
251
252    pub fn size(mut self, size: usize) -> Self {
253        self.size = size;
254        self
255    }
256
257    pub fn format(mut self, display_format: impl Into<String>) -> Self {
258        self.display_format = display_format.into();
259        self
260    }
261
262    /// Alinhamento do texto (o padrão é pelo tipo: números à direita).
263    pub fn align(mut self, alignment: TextAlign) -> Self {
264        self.alignment = Some(alignment);
265        self
266    }
267
268    /// Largura sugerida para grids.
269    pub fn width(mut self, display_width: f32) -> Self {
270        self.display_width = display_width;
271        self
272    }
273
274    pub fn required(mut self) -> Self {
275        self.required = true;
276        self
277    }
278
279    pub fn read_only(mut self) -> Self {
280        self.read_only = true;
281        self
282    }
283
284    pub fn min(mut self, min: f64) -> Self {
285        self.min = Some(min);
286        self
287    }
288
289    pub fn max(mut self, max: f64) -> Self {
290        self.max = Some(max);
291        self
292    }
293
294    pub fn default_value(mut self, text: impl Into<String>) -> Self {
295        self.default_value = text.into();
296        self
297    }
298
299    pub fn display_values(mut self, values: impl Into<String>) -> Self {
300        self.display_values = values.into();
301        self
302    }
303
304    pub fn char_case(mut self, char_case: CharCase) -> Self {
305        self.char_case = char_case;
306        self
307    }
308
309    /// Como o `OnGetText`: valor → texto. `display` é `true` para exibir e `false` para
310    /// editar.
311    pub fn on_get_text(mut self, f: impl Fn(&Value, bool) -> String + 'static) -> Self {
312        self.get_text = Some(Box::new(f));
313        self
314    }
315
316    /// Como o `OnSetText`: texto digitado → valor (ou mensagem de erro).
317    pub fn on_set_text(mut self, f: impl Fn(&str) -> std::result::Result<Value, String> + 'static) -> Self {
318        self.set_text = Some(Box::new(f));
319        self
320    }
321
322    /// Tem o `on_set_text` em Rust (a closure): ela vale no lugar do evento por nome.
323    pub(crate) fn has_set_text(&self) -> bool {
324        self.set_text.is_some()
325    }
326
327    /// Como o `OnValidate`: recusa um valor com uma mensagem.
328    pub fn on_validate(mut self, f: impl Fn(&Value) -> std::result::Result<(), String> + 'static) -> Self {
329        self.validate = Some(Box::new(f));
330        self
331    }
332
333    /// Nome para mensagens e cabeçalhos: o `display_label` ou o nome da coluna.
334    /// Campo calculado por expressão.
335    pub fn calculated(mut self, expression: impl Into<String>) -> Self {
336        self.kind = FieldKind::Calculated;
337        self.expression = expression.into();
338        self
339    }
340
341    /// Campo calculado em Rust: `get("quantidade")` lê os outros campos do registro.
342    pub fn on_calculate(mut self, f: impl Fn(&dyn Fn(&str) -> Value) -> Value + 'static) -> Self {
343        self.kind = FieldKind::Calculated;
344        self.calculate = Some(Box::new(f));
345        self
346    }
347
348    /// Campo lookup: procura `key_field` deste registro no `lookup_key` de `data_set` e
349    /// mostra o `result`.
350    pub fn lookup(mut self, data_set: ComponentId, key_field: &str, lookup_key: &str, result: &str) -> Self {
351        self.kind = FieldKind::Lookup;
352        self.lookup_data_set = Some(data_set);
353        self.key_fields = key_field.into();
354        self.lookup_key_fields = lookup_key.into();
355        self.lookup_result_field = result.into();
356        self
357    }
358
359    /// Máscara de edição (`000.000.000-00;0`).
360    pub fn mask(mut self, mask: impl Into<String>) -> Self {
361        self.edit_mask = mask.into();
362        self
363    }
364
365    /// Calcula o valor de um campo calculado (`get` lê os outros campos).
366    pub fn compute(&self, get: &dyn Fn(&str) -> Option<Value>) -> Value {
367        if let Some(f) = &self.calculate {
368            return f(&|name| get(name).unwrap_or_default());
369        }
370        if self.expression.trim().is_empty() {
371            return Value::Null;
372        }
373        let mut cache = self.parsed.borrow_mut();
374        let parsed = cache.get_or_insert_with(|| Expr::parse(&self.expression));
375        match parsed {
376            Ok(expr) => expr.eval(get).ok().and_then(|v| self.coerce(v).ok()).unwrap_or_default(),
377            Err(_) => Value::Null,
378        }
379    }
380
381    /// Erro da expressão do campo calculado, se houver (para mostrar no designer).
382    pub fn expression_error(&self) -> Option<String> {
383        if self.kind != FieldKind::Calculated || self.calculate.is_some() || self.expression.trim().is_empty() {
384            return None;
385        }
386        Expr::parse(&self.expression).err()
387    }
388
389    pub fn caption(&self) -> &str {
390        if self.display_label.is_empty() { &self.field_name } else { &self.display_label }
391    }
392
393    pub fn alignment(&self) -> TextAlign {
394        self.alignment.unwrap_or(if self.field_type.is_numeric() { TextAlign::Trailing } else { TextAlign::Leading })
395    }
396
397    pub fn is_read_only(&self) -> bool {
398        self.read_only || self.field_type == FieldType::AutoInc || self.kind != FieldKind::Data
399    }
400
401    fn bool_texts(&self) -> (String, String) {
402        let default = t("Sim;Não");
403        let values = if self.display_values.is_empty() { &default } else { &self.display_values };
404        let (t, f) = values.split_once(';').unwrap_or((values, ""));
405        (t.to_string(), f.to_string())
406    }
407
408    /// O texto que o evento `on_get_text` deu para `value`, se já chegou. Se não, guarda
409    /// o valor para o próximo pedido em lote e devolve `None`; `true` no segundo item quando
410    /// a fila estava vazia (quem chamou agenda o envio).
411    pub(crate) fn remote_text(&self, value: &Value) -> (Option<String>, bool) {
412        let key = crate::value_text(value);
413        if let Some(text) = self.remote_texts.borrow().get(&key) {
414            return (Some(text.clone()), false);
415        }
416        let mut pending = self.pending_texts.borrow_mut();
417        let first = pending.is_empty();
418        if !pending.contains(value) {
419            pending.push(value.clone());
420        }
421        (None, first)
422    }
423
424    /// Os valores que esperam texto (e esvazia a fila).
425    pub(crate) fn take_pending_texts(&self) -> Vec<Value> {
426        std::mem::take(&mut *self.pending_texts.borrow_mut())
427    }
428
429    /// Guarda textos vindos do `on_get_text` remoto.
430    pub(crate) fn store_texts(&self, texts: impl IntoIterator<Item = (Value, String)>) {
431        let mut cache = self.remote_texts.borrow_mut();
432        for (value, text) in texts {
433            cache.insert(crate::value_text(&value), text);
434        }
435    }
436
437    /// Esquece os textos recebidos (o backend mudou a regra): serão pedidos de novo.
438    pub fn clear_texts(&self) {
439        self.remote_texts.borrow_mut().clear();
440    }
441
442    /// Texto para exibir (`display = true`) ou para editar (`false`).
443    pub fn text_of(&self, value: &Value, display: bool, locale: &LocaleInfo) -> String {
444        if let Some(f) = &self.get_text {
445            return f(value, display);
446        }
447        let format = if display || self.edit_format.is_empty() { &self.display_format } else { &self.edit_format };
448        if let (Some(mask), Value::String(s)) = (Mask::parse(&self.edit_mask), value) {
449            return mask.display(s);
450        }
451        match value {
452            Value::Null => String::new(),
453            Value::Bool(b) => {
454                let (t, f) = self.bool_texts();
455                if *b { t } else { f }
456            }
457            Value::String(s) => s.clone(),
458            Value::Int(_) | Value::Float(_) | Value::Decimal(_) => {
459                let number = match (value, self.field_type) {
460                    (_, FieldType::Currency) => value.as_decimal().and_then(|d| d.round(self.scale, self.rounding)),
461                    (Value::Float(f), _) => Decimal::from_f64(*f, 10).map(trim),
462                    _ => value.as_decimal(),
463                };
464                let Some(number) = number else { return value.to_string() };
465                if display && !format.is_empty() {
466                    format_number(number, format, locale)
467                } else if display && self.field_type == FieldType::Currency {
468                    format_number(number, &format!("#,##0.{}", "0".repeat(self.scale as usize)), locale)
469                } else if !display && !self.edit_format.is_empty() {
470                    format_number(number, &self.edit_format, locale)
471                } else {
472                    plain_number(number, locale)
473                }
474            }
475            Value::Date(d) => format_date_time(Some(*d), None, self.pattern(format, &locale.short_date_format)),
476            Value::Time(t) => format_date_time(None, Some(*t), self.pattern(format, &locale.long_time_format)),
477            Value::DateTime(dt) => {
478                let (d, t) = split(*dt);
479                format_date_time(d, t, self.pattern(format, &date_time_pattern(locale)))
480            }
481            // No horário local de quem vê.
482            Value::Timestamp(ts) => {
483                let (d, t) = split(ts.to_local());
484                format_date_time(d, t, self.pattern(format, &date_time_pattern(locale)))
485            }
486            Value::Blob(b) => format!("({} bytes)", b.len()),
487        }
488    }
489
490    fn pattern<'a>(&self, format: &'a str, fallback: &'a str) -> &'a str {
491        if format.is_empty() { fallback } else { format }
492    }
493
494    /// O valor com as casas do campo, arredondado do jeito dele; estouro é erro (nunca um
495    /// valor saturado).
496    fn to_scale(&self, value: Decimal) -> std::result::Result<Decimal, String> {
497        value.round(self.scale, self.rounding).ok_or_else(|| tf("{0}: o valor {1} não cabe", &[&self.caption(), &value.to_string()]))
498    }
499
500    /// Lê o texto digitado. Texto vazio vira `Null`.
501    pub fn parse_text(&self, text: &str, locale: &LocaleInfo) -> std::result::Result<Value, String> {
502        if let Some(f) = &self.set_text {
503            return f(text);
504        }
505        let trimmed = text.trim();
506        if trimmed.is_empty() && self.field_type != FieldType::String && self.field_type != FieldType::Memo {
507            return Ok(Value::Null);
508        }
509        let caption = self.caption();
510        if let Some(mask) = Mask::parse(&self.edit_mask) {
511            let stored = mask.stored(text);
512            if stored.is_empty() {
513                return Ok(Value::Null);
514            }
515            if !mask.is_complete(text) {
516                return Err(tf("{0} incompleto: '{1}'", &[&caption, &mask.apply(text)]));
517            }
518            return Ok(Value::String(stored));
519        }
520        match self.field_type {
521            FieldType::String | FieldType::Memo => {
522                if text.is_empty() {
523                    return Ok(Value::Null);
524                }
525                Ok(Value::String(match self.char_case {
526                    CharCase::Normal => text.to_string(),
527                    CharCase::Upper => text.to_uppercase(),
528                    CharCase::Lower => text.to_lowercase(),
529                }))
530            }
531            FieldType::Integer | FieldType::AutoInc => parse_number(trimmed, locale)
532                .filter(|d| d.rescale(0) == *d)
533                .and_then(|d| d.to_i64())
534                .map(Value::Int)
535                .ok_or_else(|| tf("'{0}' não é um número inteiro válido para {1}", &[&text, &caption])),
536            FieldType::Float => parse_number(trimmed, locale)
537                .map(|d| Value::Float(d.to_f64()))
538                .ok_or_else(|| tf("'{0}' não é um número válido para {1}", &[&text, &caption])),
539            FieldType::Currency => parse_number(trimmed, locale)
540                .ok_or_else(|| tf("'{0}' não é um valor válido para {1}", &[&text, &caption]))
541                .and_then(|d| self.to_scale(d).map(Value::Decimal)),
542            FieldType::Boolean => {
543                let (t, f) = self.bool_texts();
544                let lower = trimmed.to_lowercase();
545                if lower == t.to_lowercase() || ["true", "1", "sim", "s", "yes"].contains(&lower.as_str()) {
546                    Ok(Value::Bool(true))
547                } else if lower == f.to_lowercase() || ["false", "0", "não", "nao", "n", "no"].contains(&lower.as_str()) {
548                    Ok(Value::Bool(false))
549                } else {
550                    Err(tf("'{0}' não é {1} nem {2}", &[&text, &t, &f]))
551                }
552            }
553            FieldType::Date => {
554                let pattern = self.pattern(&self.display_format, &locale.short_date_format);
555                parse_date_time(trimmed, pattern)
556                    .and_then(|(d, _)| d)
557                    .map(Value::Date)
558                    .ok_or_else(|| tf("'{0}' não é uma data válida ({1})", &[&text, &pattern]))
559            }
560            FieldType::Time => {
561                let pattern = self.pattern(&self.display_format, &locale.long_time_format);
562                parse_date_time(trimmed, pattern)
563                    .and_then(|(_, t)| t)
564                    .or_else(|| Time::parse_iso(trimmed))
565                    .map(Value::Time)
566                    .ok_or_else(|| tf("'{0}' não é uma hora válida ({1})", &[&text, &pattern]))
567            }
568            FieldType::DateTime | FieldType::Timestamp => {
569                let full = date_time_pattern(locale);
570                let pattern = self.pattern(&self.display_format, &full);
571                let typed = parse_date_time(trimmed, pattern)
572                    .and_then(|(d, t)| Some(DateTime::new(d?, t.unwrap_or_default())))
573                    .or_else(|| {
574                        let date_only = parse_date_time(trimmed, &locale.short_date_format)?.0?;
575                        Some(DateTime::new(date_only, Time::default()))
576                    })
577                    .ok_or_else(|| tf("'{0}' não é uma data/hora válida ({1})", &[&text, &pattern]))?;
578                // O instante é o do horário local que o usuário digitou.
579                Ok(if self.field_type == FieldType::Timestamp { Value::Timestamp(Timestamp::from_local(typed)) } else { Value::DateTime(typed) })
580            }
581            FieldType::Blob => Err(tf("{0} não pode ser digitado", &[&caption])),
582        }
583    }
584
585    /// Ajusta o tipo do valor ao do campo (por exemplo inteiro num campo `float`), ou
586    /// recusa.
587    pub fn coerce(&self, value: Value) -> std::result::Result<Value, String> {
588        // O nome do campo só no erro: a carga converte milhões de valores.
589        let wrong = |v: &Value| format!("{} não aceita valor do tipo {}", self.caption(), v.kind_name());
590        Ok(match (self.field_type, value) {
591            (FieldType::Integer | FieldType::AutoInc, Value::Int(i)) => Value::Int(i),
592            (FieldType::Float, Value::Float(f)) => Value::Float(f),
593            (_, Value::Null) => Value::Null,
594            (FieldType::String | FieldType::Memo, Value::String(s)) => Value::String(s),
595            (FieldType::Integer | FieldType::AutoInc, v) => Value::Int(v.as_i64().ok_or_else(|| wrong(&v))?),
596            (FieldType::Float, v) => Value::Float(v.as_f64().ok_or_else(|| wrong(&v))?),
597            (FieldType::Currency, v) => Value::Decimal(self.to_scale(v.as_decimal().ok_or_else(|| wrong(&v))?)?),
598            (FieldType::Boolean, Value::Bool(b)) => Value::Bool(b),
599            (FieldType::Date, v) => Value::Date(v.as_date().ok_or_else(|| wrong(&v))?),
600            (FieldType::Time, Value::Time(t)) => Value::Time(t),
601            (FieldType::DateTime, Value::DateTime(dt)) => Value::DateTime(dt),
602            (FieldType::DateTime, Value::Date(d)) => Value::DateTime(DateTime::new(d, Time::default())),
603            (FieldType::DateTime, Value::Timestamp(ts)) => Value::DateTime(ts.to_local()),
604            (FieldType::Timestamp, Value::Timestamp(ts)) => Value::Timestamp(ts),
605            // Uma data e hora sem fuso é o horário local de quem grava.
606            (FieldType::Timestamp, Value::DateTime(dt)) => Value::Timestamp(Timestamp::from_local(dt)),
607            (FieldType::Timestamp, Value::Date(d)) => Value::Timestamp(Timestamp::from_local(DateTime::new(d, Time::default()))),
608            (FieldType::Blob, Value::Blob(b)) => Value::Blob(b),
609            (_, v) => return Err(wrong(&v)),
610        })
611    }
612
613    /// Restrições do valor (tamanho, mínimo, máximo e `on_validate`). `required` é
614    /// conferido no `post`.
615    pub fn check(&self, value: &Value) -> std::result::Result<(), String> {
616        let caption = self.caption();
617        if let Value::String(s) = value {
618            if self.size > 0 && s.chars().count() > self.size {
619                return Err(tf("{0}: no máximo {1} caracteres", &[&caption, &self.size]));
620            }
621        }
622        if let Some(number) = value.as_f64().filter(|_| self.field_type.is_numeric()) {
623            if self.min.is_some_and(|min| number < min) {
624                return Err(tf("{0}: o mínimo é {1}", &[&caption, &self.min.unwrap_or_default()]));
625            }
626            if self.max.is_some_and(|max| number > max) {
627                return Err(tf("{0}: o máximo é {1}", &[&caption, &self.max.unwrap_or_default()]));
628            }
629        }
630        match &self.validate {
631            Some(f) => f(value),
632            None => Ok(()),
633        }
634    }
635
636    /// Valor inicial de um registro novo.
637    pub fn initial_value(&self, locale: &LocaleInfo) -> Value {
638        if self.default_value.is_empty() {
639            return Value::Null;
640        }
641        let v = match self.field_type {
642            FieldType::Date => Date::parse_iso(&self.default_value).map(Value::Date),
643            FieldType::Time => Time::parse_iso(&self.default_value).map(Value::Time),
644            FieldType::DateTime => DateTime::parse_iso(&self.default_value).map(Value::DateTime),
645            FieldType::Timestamp => Timestamp::parse_iso(&self.default_value).map(Value::Timestamp),
646            FieldType::Float | FieldType::Currency | FieldType::Integer => {
647                Decimal::parse(&self.default_value).map(Value::Decimal).and_then(|v| self.coerce(v).ok())
648            }
649            FieldType::Boolean => Some(Value::Bool(matches!(self.default_value.to_lowercase().as_str(), "true" | "1" | "sim"))),
650            _ => None,
651        };
652        v.or_else(|| self.parse_text(&self.default_value, locale).ok()).unwrap_or(Value::Null)
653    }
654}
655
656/// Tira zeros desnecessários de um decimal vindo de `f64`.
657fn trim(d: Decimal) -> Decimal {
658    let mut d = d;
659    while d.scale() > 0 && d.mantissa() % 10 == 0 {
660        d = Decimal::new(d.mantissa() / 10, d.scale() - 1);
661    }
662    d
663}
664
665const FIELD_PROPS: &[PropInfo] = &[
666    PropInfo::new("field_name", PropKind::String, "Data"),
667    PropInfo::new("type", PropKind::Enum(FieldType::NAMES), "Data").rust_type("FieldType"),
668    PropInfo::new("size", PropKind::Int, "Data"),
669    PropInfo::new("scale", PropKind::Int, "Data"),
670    PropInfo::new("rounding", PropKind::Enum(Rounding::NAMES), "Data").rust_type("Rounding"),
671    PropInfo::new("display_label", PropKind::String, "Appearance"),
672    PropInfo::new("display_width", PropKind::Float, "Appearance"),
673    PropInfo::new("display_format", PropKind::String, "Appearance"),
674    PropInfo::new("edit_format", PropKind::String, "Appearance"),
675    PropInfo::new("alignment", PropKind::Enum(<TextAlign as PropEnum>::NAMES), "Appearance").rust_type("TextAlign"),
676    PropInfo::new("required", PropKind::Bool, "Behavior"),
677    PropInfo::new("read_only", PropKind::Bool, "Behavior"),
678    PropInfo::new("visible", PropKind::Bool, "Behavior"),
679    PropInfo::new("min", PropKind::Float, "Behavior"),
680    PropInfo::new("max", PropKind::Float, "Behavior"),
681    PropInfo::new("default_value", PropKind::String, "Data"),
682    PropInfo::new("display_values", PropKind::String, "Appearance"),
683    PropInfo::new("char_case", PropKind::Enum(CharCase::NAMES), "Behavior").rust_type("CharCase"),
684    PropInfo::new("edit_mask", PropKind::String, "Behavior"),
685    PropInfo::new("sensitive", PropKind::Bool, "Behavior"),
686    PropInfo::new("kind", PropKind::Enum(FieldKind::NAMES), "Data").rust_type("FieldKind"),
687    PropInfo::new("expression", PropKind::String, "Data"),
688    PropInfo::new("lookup_data_set", PropKind::Component, "Lookup"),
689    PropInfo::new("key_fields", PropKind::String, "Lookup"),
690    PropInfo::new("lookup_key_fields", PropKind::String, "Lookup"),
691    PropInfo::new("lookup_result_field", PropKind::String, "Lookup"),
692    PropInfo::new("on_change", PropKind::Event, "Events").event_arg(aylis_core::EventArg::Value(PropKind::String)),
693    // Por nome (backend remoto): o texto de exibição vem em lote e assíncrono; a
694    // validação chega depois e trava o `post` enquanto houver erro.
695    PropInfo::new("on_get_text", PropKind::Event, "Events")
696        .event_arg(aylis_core::EventArg::Value(PropKind::Record(&crate::events::GET_TEXT_REQUEST_RECORD)))
697        .rust_type("GetTextRequest"),
698    // O texto digitado vai ao handler, que grava o valor (ou recusa): `aylis_data::set_text`.
699    PropInfo::new("on_set_text", PropKind::Event, "Events")
700        .event_arg(aylis_core::EventArg::Value(PropKind::Record(&crate::events::SET_TEXT_REQUEST_RECORD)))
701        .rust_type("SetTextRequest"),
702    PropInfo::new("on_validate", PropKind::Event, "Events"),
703];
704
705impl Component for Field {
706    fn class_name(&self) -> &'static str {
707        "Field"
708    }
709
710    fn notification(&mut self, freed: ComponentId) {
711        if self.lookup_data_set == Some(freed) {
712            self.lookup_data_set = None;
713        }
714    }
715
716    fn props(&self) -> &'static [PropInfo] {
717        FIELD_PROPS
718    }
719
720    fn get_prop(&self, name: &str) -> Option<PropValue> {
721        let opt = |v: Option<f64>| v.map_or(PropValue::Null, PropValue::Float);
722        Some(match name {
723            "field_name" => self.field_name.clone().into(),
724            "type" => PropValue::enum_value(self.field_type),
725            "size" => PropValue::Int(self.size as i64),
726            "scale" => PropValue::Int(self.scale as i64),
727            "rounding" => PropValue::enum_value(self.rounding),
728            "display_label" => self.display_label.clone().into(),
729            "display_width" => self.display_width.into(),
730            "display_format" => self.display_format.clone().into(),
731            "edit_format" => self.edit_format.clone().into(),
732            "alignment" => self.alignment.map_or(PropValue::Null, PropValue::enum_value),
733            "required" => self.required.into(),
734            "read_only" => self.read_only.into(),
735            "sensitive" => self.sensitive.into(),
736            "visible" => self.visible.into(),
737            "min" => opt(self.min),
738            "max" => opt(self.max),
739            "default_value" => self.default_value.clone().into(),
740            "display_values" => self.display_values.clone().into(),
741            "char_case" => PropValue::enum_value(self.char_case),
742            "edit_mask" => self.edit_mask.clone().into(),
743            "kind" => PropValue::enum_value(self.kind),
744            "expression" => self.expression.clone().into(),
745            "lookup_data_set" => PropValue::Component(self.lookup_data_set),
746            "key_fields" => self.key_fields.clone().into(),
747            "lookup_key_fields" => self.lookup_key_fields.clone().into(),
748            "lookup_result_field" => self.lookup_result_field.clone().into(),
749            _ => return None,
750        })
751    }
752
753    fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
754        let opt = |v: &PropValue| -> Result<Option<f64>> {
755            match v {
756                PropValue::Null => Ok(None),
757                v => v.to_f64().map(Some),
758            }
759        };
760        match name {
761            "field_name" => self.field_name = value.to_str()?.to_string(),
762            "type" => self.field_type = value.to_enum()?,
763            "size" => self.size = value.to_i64()?.max(0) as usize,
764            "scale" => self.scale = value.to_i64()?.clamp(0, 18) as u8,
765            "rounding" => self.rounding = value.to_enum()?,
766            "display_label" => self.display_label = value.to_str()?.to_string(),
767            "display_width" => self.display_width = value.to_f32()?,
768            "display_format" => self.display_format = value.to_str()?.to_string(),
769            "edit_format" => self.edit_format = value.to_str()?.to_string(),
770            "alignment" => {
771                self.alignment = match value {
772                    PropValue::Null => None,
773                    v => Some(v.to_enum()?),
774                }
775            }
776            "required" => self.required = value.to_bool()?,
777            "read_only" => self.read_only = value.to_bool()?,
778            "sensitive" => self.sensitive = value.to_bool()?,
779            "visible" => self.visible = value.to_bool()?,
780            "min" => self.min = opt(&value)?,
781            "max" => self.max = opt(&value)?,
782            "default_value" => self.default_value = value.to_str()?.to_string(),
783            "display_values" => self.display_values = value.to_str()?.to_string(),
784            "char_case" => self.char_case = value.to_enum()?,
785            "edit_mask" => self.edit_mask = value.to_str()?.to_string(),
786            "kind" => self.kind = value.to_enum()?,
787            "expression" => {
788                self.expression = value.to_str()?.to_string();
789                *self.parsed.borrow_mut() = None;
790            }
791            "lookup_data_set" => self.lookup_data_set = value.to_component()?,
792            "key_fields" => self.key_fields = value.to_str()?.to_string(),
793            "lookup_key_fields" => self.lookup_key_fields = value.to_str()?.to_string(),
794            "lookup_result_field" => self.lookup_result_field = value.to_str()?.to_string(),
795            _ => return Err(Error::UnknownProperty(name.to_string())),
796        }
797        Ok(())
798    }
799}