datacraft-core 0.1.3

Headless domain model, command bus and application state for DataCraft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! The placed-control handlers (split from `forms.rs` for the size gate,
//! item H56): add, move, set the content and delete one control of a
//! form — validation first, then the mutation, then the event.

use crate::core::{Core, failed};
use crate::event::Event;
use crate::failure::FailureCode;

use super::{binding_error, bound_field, validate_binding};

impl Core {
    pub(crate) fn add_control(
        &mut self,
        form: &str,
        mut control: crate::form::ControlDef,
    ) -> Vec<Event> {
        let Some(db) = self.state.database.as_mut() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        let Some(def) = db
            .forms
            .iter_mut()
            .find(|f| f.name.to_lowercase() == form.to_lowercase())
        else {
            return failed(FailureCode::NotFound, format!("form {form:?} not found"));
        };
        if control.name.trim().is_empty() {
            return failed(FailureCode::InvalidInput, "control names must not be empty");
        }
        if def
            .controls
            .iter()
            .any(|c| c.name.to_lowercase() == control.name.to_lowercase())
        {
            return failed(
                FailureCode::Duplicate,
                format!("duplicate control name {:?}", control.name),
            );
        }
        if let Some(bound) = bound_field(&control) {
            let detail = validate_binding(def, &db.tables, &bound);
            if let Some(detail) = detail {
                return failed(FailureCode::InvalidInput, detail);
            }
        }
        control.rect = crate::canvas::snap_rect(control.rect, def.grid);
        if control.rect.x + control.rect.width > def.size.width
            || control.rect.y + control.rect.height > def.size.height
        {
            return failed(
                FailureCode::InvalidInput,
                format!(
                    "control {:?} exceeds the canvas bounds ({} x {})",
                    control.name, def.size.width, def.size.height
                ),
            );
        }
        let name = control.name.clone();
        def.controls.push(control);
        vec![Event::ControlAdded {
            form: def.name.clone(),
            control: name,
        }]
    }

    pub(crate) fn set_control_rect(
        &mut self,
        form: &str,
        control: &str,
        rect: crate::canvas::Rect,
    ) -> Vec<Event> {
        let Some(db) = self.state.database.as_mut() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        let Some(def) = db
            .forms
            .iter_mut()
            .find(|f| f.name.to_lowercase() == form.to_lowercase())
        else {
            return failed(FailureCode::NotFound, format!("form {form:?} not found"));
        };
        let Some(target) = def
            .controls
            .iter_mut()
            .find(|c| c.name.to_lowercase() == control.to_lowercase())
        else {
            return failed(
                FailureCode::NotFound,
                format!("control {control:?} not found"),
            );
        };
        let snapped = crate::canvas::snap_rect(rect, def.grid);
        if snapped.x + snapped.width > def.size.width
            || snapped.y + snapped.height > def.size.height
        {
            return failed(
                FailureCode::InvalidInput,
                format!(
                    "control {control:?} exceeds the canvas bounds ({} x {})",
                    def.size.width, def.size.height
                ),
            );
        }
        target.rect = snapped;
        vec![Event::ControlRectSet {
            form: def.name.clone(),
            control: target.name.clone(),
        }]
    }

    /// Sets the one content property a placed control carries (step 63.1,
    /// item H56): the label text, button caption, bound source field or
    /// embedded form. Validation runs before the mutation — unknown
    /// fields and unknown subforms answer precisely.
    pub(crate) fn set_control_content(
        &mut self,
        form: &str,
        control: &str,
        value: &str,
    ) -> Vec<Event> {
        let Some(db) = self.state.database.as_mut() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        let Some(pos) = db
            .forms
            .iter()
            .position(|f| f.name.to_lowercase() == form.to_lowercase())
        else {
            return failed(FailureCode::NotFound, format!("form {form:?} not found"));
        };
        let Some(control_pos) = db.forms[pos]
            .controls
            .iter()
            .position(|c| c.name.to_lowercase() == control.to_lowercase())
        else {
            return failed(
                FailureCode::NotFound,
                format!("control {control:?} not found"),
            );
        };
        let source = db.forms[pos].source.clone();
        let kind_is_binding = matches!(
            db.forms[pos].controls[control_pos].kind,
            crate::form::ControlKind::TextBox { .. }
                | crate::form::ControlKind::CheckBox { .. }
                | crate::form::ControlKind::ComboBox { .. }
        );
        let kind_is_subform = matches!(
            db.forms[pos].controls[control_pos].kind,
            crate::form::ControlKind::SubForm { .. }
        );
        if kind_is_binding
            && !value.trim().is_empty()
            && let Some(detail) = binding_error(&source, &db.tables, value)
        {
            return failed(FailureCode::InvalidInput, detail);
        }
        if kind_is_subform {
            let trimmed = value.trim();
            if trimmed.is_empty()
                || !db
                    .forms
                    .iter()
                    .any(|f| f.name.eq_ignore_ascii_case(trimmed))
            {
                return failed(
                    FailureCode::InvalidInput,
                    format!("subform {value:?} not found"),
                );
            }
        }
        let form_name = db.forms[pos].name.clone();
        let control_name = db.forms[pos].controls[control_pos].name.clone();
        let target = &mut db.forms[pos].controls[control_pos];
        match &mut target.kind {
            crate::form::ControlKind::Label { text } => *text = value.to_owned(),
            crate::form::ControlKind::Button { caption, .. } => *caption = value.to_owned(),
            crate::form::ControlKind::TextBox { bound_field }
            | crate::form::ControlKind::CheckBox { bound_field }
            | crate::form::ControlKind::ComboBox { bound_field, .. } => {
                *bound_field = if value.trim().is_empty() {
                    None
                } else {
                    Some(value.to_owned())
                };
            }
            crate::form::ControlKind::SubForm { form: embedded } => {
                *embedded = value.trim().to_owned();
            }
        }
        vec![Event::ControlContentSet {
            form: form_name,
            control: control_name,
        }]
    }

    /// Sets the kind-specific design data of a placed control (phase 64,
    /// ADR-8). Both variants resolve their targets against the open
    /// database before the mutation; empty data clears the property.
    pub(crate) fn set_control_data(&mut self, data: &crate::form::SetControlData) -> Vec<Event> {
        let Some(db) = self.state.database.as_ref() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        let Some(form_def) = db
            .forms
            .iter()
            .find(|f| f.name.eq_ignore_ascii_case(&data.form))
        else {
            return failed(
                FailureCode::NotFound,
                format!("form {:?} not found", data.form),
            );
        };
        let Some(control) = form_def
            .controls
            .iter()
            .find(|c| c.name.eq_ignore_ascii_case(&data.control))
        else {
            return failed(
                FailureCode::NotFound,
                format!("control {:?} not found", data.control),
            );
        };
        let form_name = form_def.name.clone();
        let control_name = control.name.clone();
        let canonical = match (&data.data, &control.kind) {
            (
                crate::form::ControlData::ComboSource {
                    row_source,
                    display_field,
                },
                crate::form::ControlKind::ComboBox { .. },
            ) => {
                let source = row_source.trim();
                let field = display_field.trim();
                let (row_source, display_field) = if source.is_empty() {
                    (String::new(), String::new())
                } else if let Some(table) = db
                    .tables
                    .iter()
                    .find(|table| table.name.eq_ignore_ascii_case(source))
                {
                    if field.is_empty() {
                        return failed(
                            FailureCode::InvalidInput,
                            format!("row source {:?} needs a display field", table.name),
                        );
                    }
                    let Some(column) = table
                        .fields
                        .iter()
                        .find(|column| column.name.eq_ignore_ascii_case(field))
                    else {
                        return failed(
                            FailureCode::InvalidInput,
                            format!(
                                "display field {display_field:?} is not a field of {:?}",
                                table.name
                            ),
                        );
                    };
                    (table.name.clone(), column.name.clone())
                } else {
                    if field.is_empty() {
                        return failed(
                            FailureCode::InvalidInput,
                            format!("row source {source:?} needs a display field"),
                        );
                    }
                    let canonical = db
                        .queries
                        .iter()
                        .find(|query| query.name.eq_ignore_ascii_case(source))
                        .map(|query| query.name.clone())
                        .or_else(|| {
                            db.native_queries
                                .iter()
                                .find(|query| query.name.eq_ignore_ascii_case(source))
                                .map(|query| query.name.clone())
                        });
                    let Some(canonical) = canonical else {
                        return failed(
                            FailureCode::NotFound,
                            format!("row source {row_source:?} not found"),
                        );
                    };
                    match self.run_query(&canonical) {
                        Ok(result) => {
                            let Some(column) = result
                                .columns
                                .iter()
                                .find(|column| column.eq_ignore_ascii_case(field))
                            else {
                                return failed(
                                    FailureCode::InvalidInput,
                                    format!(
                                        "display field {display_field:?} is not a column of {canonical:?}"
                                    ),
                                );
                            };
                            (canonical, column.clone())
                        }
                        Err(reason) => return failed(FailureCode::InvalidInput, reason),
                    }
                };
                crate::form::ControlData::ComboSource {
                    row_source,
                    display_field,
                }
            }
            (
                crate::form::ControlData::Button { action },
                crate::form::ControlKind::Button { .. },
            ) => {
                let action = match action {
                    None => None,
                    Some(crate::form::ButtonAction::OpenForm { form }) => {
                        let Some(target) = db
                            .forms
                            .iter()
                            .find(|candidate| candidate.name.eq_ignore_ascii_case(form))
                        else {
                            return failed(
                                FailureCode::NotFound,
                                format!("form {form:?} not found"),
                            );
                        };
                        Some(crate::form::ButtonAction::OpenForm {
                            form: target.name.clone(),
                        })
                    }
                    Some(crate::form::ButtonAction::OpenReport { report }) => {
                        let Some(target) = db
                            .reports
                            .iter()
                            .find(|candidate| candidate.name.eq_ignore_ascii_case(report))
                        else {
                            return failed(
                                FailureCode::NotFound,
                                format!("report {report:?} not found"),
                            );
                        };
                        Some(crate::form::ButtonAction::OpenReport {
                            report: target.name.clone(),
                        })
                    }
                    Some(crate::form::ButtonAction::RunQuery { query }) => {
                        let canonical = db
                            .queries
                            .iter()
                            .find(|candidate| candidate.name.eq_ignore_ascii_case(query))
                            .map(|candidate| candidate.name.clone())
                            .or_else(|| {
                                db.native_queries
                                    .iter()
                                    .find(|candidate| candidate.name.eq_ignore_ascii_case(query))
                                    .map(|candidate| candidate.name.clone())
                            });
                        let Some(canonical) = canonical else {
                            return failed(
                                FailureCode::NotFound,
                                format!("query {query:?} not found"),
                            );
                        };
                        Some(crate::form::ButtonAction::RunQuery { query: canonical })
                    }
                    Some(crate::form::ButtonAction::ApplyFilter { criteria }) => {
                        let criteria = criteria.trim();
                        if criteria.is_empty() {
                            return failed(
                                FailureCode::InvalidInput,
                                "a button filter needs criteria".to_owned(),
                            );
                        }
                        if let Err(error) = crate::expr::parse(criteria) {
                            return failed(
                                FailureCode::InvalidInput,
                                format!("filter criteria {criteria:?}: {error}"),
                            );
                        }
                        Some(crate::form::ButtonAction::ApplyFilter {
                            criteria: criteria.to_owned(),
                        })
                    }
                };
                crate::form::ControlData::Button { action }
            }
            (crate::form::ControlData::ComboSource { .. }, _) => {
                return failed(
                    FailureCode::InvalidInput,
                    format!("control {control_name:?} is not a combo box"),
                );
            }
            (crate::form::ControlData::Button { .. }, _) => {
                return failed(
                    FailureCode::InvalidInput,
                    format!("control {control_name:?} is not a command button"),
                );
            }
        };
        let Some(db) = self.state.database.as_mut() else {
            return failed(FailureCode::NoDatabase, "the database was closed");
        };
        let Some(control) = db
            .forms
            .iter_mut()
            .find(|form| form.name == form_name)
            .and_then(|form| {
                form.controls
                    .iter_mut()
                    .find(|control| control.name == control_name)
            })
        else {
            return failed(
                FailureCode::NotFound,
                format!("control {control_name:?} not found"),
            );
        };
        match (&canonical, &mut control.kind) {
            (
                crate::form::ControlData::ComboSource {
                    row_source,
                    display_field,
                },
                crate::form::ControlKind::ComboBox {
                    row_source: slot_source,
                    display_field: slot_field,
                    ..
                },
            ) => {
                *slot_source = row_source.clone();
                *slot_field = display_field.clone();
            }
            (
                crate::form::ControlData::Button { action },
                crate::form::ControlKind::Button { action: slot, .. },
            ) => {
                *slot = action.clone();
            }
            _ => {
                return failed(
                    FailureCode::InvalidInput,
                    format!("control {control_name:?} does not carry this data"),
                );
            }
        }
        vec![Event::ControlDataSet {
            form: form_name,
            control: control_name,
        }]
    }

    pub(crate) fn delete_control(&mut self, form: &str, control: &str) -> Vec<Event> {
        let Some(db) = self.state.database.as_mut() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        let Some(def) = db
            .forms
            .iter_mut()
            .find(|f| f.name.to_lowercase() == form.to_lowercase())
        else {
            return failed(FailureCode::NotFound, format!("form {form:?} not found"));
        };
        let Some(pos) = def
            .controls
            .iter()
            .position(|c| c.name.to_lowercase() == control.to_lowercase())
        else {
            return failed(
                FailureCode::NotFound,
                format!("control {control:?} not found"),
            );
        };
        let canonical = def.controls.remove(pos).name;
        vec![Event::ControlDropped {
            form: def.name.clone(),
            control: canonical,
        }]
    }
}