tablo-core 0.2.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
//! Record forms, end to end.

use std::collections::{HashMap, HashSet};

use http::StatusCode;
use tablo_core::{
    Ability, DeclarationErrorKind, Field, FieldErrorKind, FieldErrors, NoForm, Panel, RecordForm,
    Repeater, Resource, ResourceDef, Schema, Table, Tenancy, Tenant, TextColumn, lens,
    write_create,
};
use toasty::Db;
use topcoat::context::{Cx, CxTestBuilder};
use uuid::Uuid;

use crate::common::{
    body_string, field_error, get, input_value, memory_db, mount, panel, panel_router, post_fields,
    refusal,
};

#[derive(Debug, Clone, toasty::Model)]
struct Item {
    #[key]
    #[auto]
    id: Uuid,
    title: String,
    notes: String,
    priority: i64,
    done: bool,
}

/// Every column, with the blank answers the optional controls need.
#[derive(tablo_core::RecordForm)]
#[form(model = Item)]
struct ItemForm {
    title: String,
    notes: String,
    #[form(blank = 3)]
    priority: i64,
    #[form(blank = false)]
    done: bool,
}

fn item_schema() -> Schema {
    Schema::new((
        Field::text(Item::fields().title()),
        Field::text(Item::fields().notes()).optional(),
        Field::text(Item::fields().priority()).optional(),
        Field::choice(Item::fields().done())
            .options(vec!["true".to_string(), "false".to_string()])
            .optional(),
    ))
}

fn item_table() -> Table<Item> {
    Table::new(TextColumn::new(lens!(Item.title)))
}

struct ItemResource;

impl Resource for ItemResource {
    type Model = Item;
    type Form = ItemForm;

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            .slug("items")
            .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                matches!(
                    ability,
                    Ability::ViewAny | Ability::View(_) | Ability::Create | Ability::Update(_)
                )
            })
            .table(item_table())
            .form(item_schema())
            .view(Schema::new(Field::text(Item::fields().title())))
    }

    fn validate_record(_cx: &Cx, form: &ItemForm) -> FieldErrors {
        let mut errors = FieldErrors::new();
        if form.priority > 10 {
            errors.add("priority", "Priority is at most 10");
        }
        errors
    }
}

async fn item_db() -> Db {
    memory_db(toasty::models!(Item)).await
}

async fn seed_item(db: &Db) -> Item {
    let mut db = db.clone();
    toasty::create!(Item {
        title: "Stored".to_string(),
        notes: "keep me".to_string(),
        priority: 7,
        done: true,
    })
    .exec(&mut db)
    .await
    .expect("seed item")
}

async fn reload(db: &Db, id: Uuid) -> Item {
    let mut db = db.clone();
    Item::get_by_id(&mut db, &id)
        .await
        .expect("the item exists")
}

fn cx_for(db: &Db) -> Cx {
    CxTestBuilder::new().app_context(db.clone()).build()
}

fn map(pairs: &[(&str, &str)]) -> HashMap<String, String> {
    pairs
        .iter()
        .map(|(key, value)| (key.to_string(), value.to_string()))
        .collect()
}

/// The upstream fact `into_update`'s `Option` rests on.
#[tokio::test]
#[should_panic(expected = "RecvError")]
async fn toasty_refuses_an_update_with_no_assignment() {
    let db = item_db().await;
    let mut record = seed_item(&db).await;
    let mut db = db.clone();
    let _ = record.update().exec(&mut db).await;
}

/// The derived update reloads the record it wrote.
#[tokio::test]
async fn the_derived_update_reloads_the_record_it_wrote() {
    let db = item_db().await;
    let mut record = seed_item(&db).await;
    let form = ItemForm {
        title: "Written".to_string(),
        notes: String::new(),
        priority: 1,
        done: false,
    };
    let named = HashSet::from([ItemFormField::Title]);
    let update = form
        .into_update(&mut record, &named)
        .expect("a named field builds an update");
    let mut handle = db.clone();
    update.exec(&mut handle).await.expect("the update runs");
    assert_eq!(record.title, "Written", "the record holds the written row");
    let stored = reload(&db, record.id).await;
    assert_eq!(stored.title, "Written");
    assert_eq!(stored.notes, "keep me", "unnamed fields are not assigned");
    assert_eq!(stored.priority, 7);
}

#[tokio::test]
async fn into_update_is_none_when_no_field_is_named() {
    let db = item_db().await;
    let mut record = seed_item(&db).await;
    let form = ItemForm {
        title: "x".to_string(),
        notes: String::new(),
        priority: 1,
        done: false,
    };
    assert!(form.into_update(&mut record, &HashSet::new()).is_none());
}

#[tokio::test]
async fn blank_keys_take_each_fields_blank_answer() {
    let db = item_db().await;
    let cx = cx_for(&db);
    let form = ItemForm::parse(
        &cx,
        &map(&[("title", " "), ("notes", ""), ("priority", "")]),
    )
    .expect("every field answers blank");
    assert_eq!(form.title, "", "a `String` answers the empty string");
    assert_eq!(form.priority, 3, "a declared blank answers itself");
    assert!(!form.done, "an absent key reads as blank");
}

#[tokio::test]
async fn a_blank_with_no_answer_and_a_bad_value_are_refused_by_key() {
    #[derive(tablo_core::RecordForm)]
    #[form(model = Item)]
    struct StrictForm {
        priority: i64,
        done: bool,
    }

    let db = item_db().await;
    let cx = cx_for(&db);
    let Err(errors) = StrictForm::parse(&cx, &map(&[("priority", ""), ("done", "maybe")])) else {
        panic!("both fields fail");
    };
    assert_eq!(
        errors.len(),
        2,
        "every failing key reports once: {errors:?}"
    );
    assert_eq!(errors[0].key, "priority");
    assert_eq!(errors[0].kind, FieldErrorKind::Required);
    assert_eq!(errors[1].key, "done");
    assert_eq!(errors[1].kind, FieldErrorKind::Invalid);
    assert_eq!(errors[1].message, "`maybe` is not a valid yes/no value");
}

#[tokio::test]
async fn hydrate_is_the_parse_s_inverse() {
    let db = item_db().await;
    let cx = cx_for(&db);
    let record = seed_item(&db).await;
    let values = ItemForm::hydrate(&cx, &record);
    assert_eq!(values["title"], "Stored");
    assert_eq!(values["notes"], "keep me");
    assert_eq!(values["priority"], "7");
    assert_eq!(values["done"], "true");
    let form = ItemForm::parse(&cx, &values).expect("a hydrated record parses");
    assert_eq!(form.priority, 7);
    assert!(form.done);
}

#[tokio::test]
async fn a_create_writes_the_parsed_form() {
    let db = item_db().await;
    let router = panel_router::<ItemResource>(db.clone());
    let response = post_fields(&router, "/admin/items/create", &[("title", "New")]).await;
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
    let mut handle = db.clone();
    let items = Item::all().exec(&mut handle).await.unwrap();
    assert_eq!(items.len(), 1);
    assert_eq!(items[0].title, "New");
    assert_eq!(items[0].notes, "");
    assert_eq!(
        items[0].priority, 3,
        "an absent optional key takes its blank answer"
    );
    assert!(!items[0].done);
}

/// An edit that posts one key changes one field.
#[tokio::test]
async fn an_edit_writes_only_the_fields_it_names() {
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<ItemResource>(db.clone());
    let response = post_fields(
        &router,
        &format!("/admin/items/{}/edit", item.id),
        &[("priority", "9")],
    )
    .await;
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
    let stored = reload(&db, item.id).await;
    assert_eq!(stored.priority, 9);
    assert_eq!(
        stored.title, "Stored",
        "an omitted required key keeps its value"
    );
    assert_eq!(stored.notes, "keep me");
    assert!(stored.done);
}

#[tokio::test]
async fn an_emptied_control_stores_its_blank_answer() {
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<ItemResource>(db.clone());
    let response = post_fields(
        &router,
        &format!("/admin/items/{}/edit", item.id),
        &[("notes", ""), ("priority", ""), ("done", "")],
    )
    .await;
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
    let stored = reload(&db, item.id).await;
    assert_eq!(stored.notes, "", "an emptied `String` clears");
    assert_eq!(stored.priority, 3);
    assert!(!stored.done);
    assert_eq!(stored.title, "Stored");
}

/// A submission naming no form field runs no statement.
#[tokio::test]
async fn an_edit_naming_no_field_writes_nothing_and_redirects() {
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<ItemResource>(db.clone());
    let response = post_fields(&router, &format!("/admin/items/{}/edit", item.id), &[]).await;
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
    let stored = reload(&db, item.id).await;
    assert_eq!(stored.title, "Stored");
    assert_eq!(stored.priority, 7);
}

/// Schema and record errors render in one round.
#[tokio::test]
async fn schema_and_record_errors_render_in_one_round() {
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<ItemResource>(db.clone());
    let response = post_fields(
        &router,
        &format!("/admin/items/{}/edit", item.id),
        &[("title", ""), ("priority", "11")],
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK, "the form re-renders");
    let html = body_string(response).await;
    assert_eq!(
        field_error(&html, "title").as_deref(),
        Some("Title is required"),
        "{html}"
    );
    assert_eq!(
        field_error(&html, "priority").as_deref(),
        Some("Priority is at most 10"),
        "{html}"
    );
    let stored = reload(&db, item.id).await;
    assert_eq!(stored.priority, 7, "a refused submission writes nothing");
}

/// A repeater label-keyed rule renders in the group.
#[tokio::test]
async fn a_repeater_label_keyed_rule_renders_in_the_group() {
    struct Tagged;

    impl Resource for Tagged {
        type Model = Item;
        type Form = ItemForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("items")
                .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                    matches!(
                        ability,
                        Ability::ViewAny | Ability::View(_) | Ability::Update(_)
                    )
                })
                .table(item_table())
                // Every control `ItemForm` binds.
                .form(Schema::new((
                    Field::text(Item::fields().title()),
                    Repeater::new("Tags").schema((
                        Field::text(Item::fields().notes()).optional(),
                        Field::text(Item::fields().priority()).optional(),
                        Field::choice(Item::fields().done())
                            .options(vec!["true".to_string(), "false".to_string()])
                            .optional(),
                    )),
                )))
        }

        fn validate_record(_cx: &Cx, _form: &ItemForm) -> FieldErrors {
            let mut errors = FieldErrors::new();
            errors.add("Tags", "At least one tag");
            errors
        }
    }

    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<Tagged>(db.clone());
    let response = post_fields(&router, &format!("/admin/items/{}/edit", item.id), &[]).await;
    assert_eq!(response.status(), StatusCode::OK, "the form re-renders");
    let html = body_string(response).await;
    assert_eq!(
        field_error(&html, "tags").as_deref(),
        Some("At least one tag"),
        "{html}"
    );
    assert_eq!(reload(&db, item.id).await.priority, 7, "nothing is written");
}

/// The detail page of a form resource reads the form's projection.
#[tokio::test]
async fn the_detail_page_reads_the_forms_projection() {
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<ItemResource>(db.clone());
    let response = get(&router, &format!("/admin/items/{}", item.id)).await;
    assert_eq!(response.status(), StatusCode::OK);
    let html = body_string(response).await;
    assert!(html.contains("Stored"), "{html}");
}

#[derive(Debug, Clone, toasty::Model)]
struct Owned {
    #[key]
    #[auto]
    id: Uuid,
    #[index]
    tenant_id: Uuid,
    title: String,
}

#[derive(tablo_core::RecordForm)]
#[form(model = Owned)]
struct OwnedForm {
    title: String,
}

struct OwnedResource;

impl Resource for OwnedResource {
    type Model = Owned;
    type Form = OwnedForm;

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            .slug("owned")
            .policy(|_cx: &Cx, ability: Ability<'_, Owned>| {
                matches!(ability, Ability::ViewAny | Ability::Create)
            })
            .tenancy(Tenancy::column(Owned::fields().tenant_id()))
            .table(Table::new(TextColumn::new(lens!(Owned.title))))
            .form(Schema::new(Field::text(Owned::fields().title())))
    }
}

#[tokio::test]
async fn the_derived_create_stamps_the_request_tenant() {
    let db = memory_db(toasty::models!(Owned)).await;
    let tenant = Uuid::new_v4();
    let cx = CxTestBuilder::new()
        .app_context(db.clone())
        .request_context(Tenant(tenant))
        .build();
    let mut handle = db.clone();
    let created = write_create::<OwnedResource>(
        &cx,
        OwnedForm {
            title: "Mine".to_string(),
        },
        &mut handle,
    )
    .await
    .expect("the create runs");
    assert_eq!(created.tenant_id, tenant, "the request tenant is stamped");
}

/// What a panel over `R` refuses to mount with.
fn refused<R: Resource>(db: Db) -> Vec<DeclarationErrorKind> {
    refusal(mount(db, panel().resource::<R>()))
        .into_iter()
        .map(|error| error.kind)
        .collect()
}

/// A resource over [`Item`] whose form is `F` and whose schema is `schema`.
macro_rules! item_resource {
    ($name:ident, $form:ty, $schema:expr) => {
        struct $name;

        impl Resource for $name {
            type Model = Item;
            type Form = $form;

            fn declare() -> ResourceDef<Self> {
                ResourceDef::new()
                    .slug("items")
                    .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                        matches!(ability, Ability::ViewAny)
                    })
                    .table(item_table())
                    .form($schema)
            }
        }
    };
}

#[derive(tablo_core::RecordForm)]
#[form(model = Item)]
struct TitleForm {
    title: String,
}

#[derive(tablo_core::RecordForm)]
#[form(model = Item)]
struct PriorityForm {
    priority: i64,
}

#[tokio::test]
async fn build_refuses_a_control_no_field_binds() {
    item_resource!(
        Unbound,
        TitleForm,
        Schema::new((
            Field::text(Item::fields().title()),
            Field::text(Item::fields().notes()),
        ))
    );
    let errors = refused::<Unbound>(item_db().await);
    assert!(
        errors.contains(&DeclarationErrorKind::UnboundControl {
            control: "notes".to_string()
        }),
        "{errors:?}"
    );
}

#[tokio::test]
async fn build_refuses_a_field_no_control_declares() {
    item_resource!(
        Unclaimed,
        ItemForm,
        Schema::new(Field::text(Item::fields().title()))
    );
    let errors = refused::<Unclaimed>(item_db().await);
    assert!(
        errors.contains(&DeclarationErrorKind::MissingControl {
            field: "notes".to_string(),
            key: "notes".to_string(),
        }),
        "{errors:?}"
    );
}

#[tokio::test]
async fn build_refuses_an_optional_control_with_no_blank_answer() {
    item_resource!(
        Unanswered,
        PriorityForm,
        Schema::new(Field::text(Item::fields().priority()).optional())
    );
    let errors = refused::<Unanswered>(item_db().await);
    assert!(
        errors.contains(&DeclarationErrorKind::NoBlankAnswer {
            control: "priority".to_string(),
            field: "priority".to_string(),
            in_repeater: false,
        }),
        "{errors:?}"
    );
}

#[tokio::test]
async fn build_refuses_a_repeater_control_with_no_blank_answer() {
    item_resource!(
        Repeated,
        PriorityForm,
        Schema::new(Repeater::new("Priorities").schema(Field::text(Item::fields().priority())))
    );
    let errors = refused::<Repeated>(item_db().await);
    assert!(
        errors.contains(&DeclarationErrorKind::NoBlankAnswer {
            control: "priority".to_string(),
            field: "priority".to_string(),
            in_repeater: true,
        }),
        "{errors:?}"
    );
}

#[tokio::test]
async fn build_refuses_a_shared_leaf_with_no_blank_answer() {
    /// A shared column.
    #[derive(Debug, Clone, PartialEq, toasty::Embed, tablo_core::EmbeddedForm)]
    enum Life {
        #[column(variant = 1)]
        Draft { note: String },
        #[column(variant = 2)]
        Live {
            #[shared(stamp)]
            published_at: i64,
        },
    }

    #[derive(Debug, Clone, toasty::Model)]
    struct Dated {
        #[key]
        #[auto]
        id: Uuid,
        title: String,
        life: Life,
    }

    #[derive(tablo_core::RecordForm)]
    #[form(model = Dated)]
    struct DatedForm {
        #[form(embed)]
        life: Life,
    }

    struct DatedResource;

    impl Resource for DatedResource {
        type Model = Dated;
        type Form = DatedForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("dated")
                .table(Table::new(TextColumn::new(lens!(Dated.title))))
                .form(Schema::new(Life::form(Dated::fields().life())))
        }
    }

    let errors = refused::<DatedResource>(memory_db(toasty::models!(Dated)).await);
    assert!(
        errors.iter().any(
            |error| matches!(error, DeclarationErrorKind::NoBlankAnswer {
                control,
                in_repeater: false,
                ..
            } if control == "life_stamp")
        ),
        "{errors:?}"
    );
}

#[tokio::test]
async fn build_refuses_a_repeater_held_variant_payload_without_an_answer() {
    /// A variant payload leaf with no blank answer.
    #[derive(Debug, Clone, PartialEq, toasty::Embed, tablo_core::EmbeddedForm)]
    enum Body {
        #[column(variant = 1)]
        Text { note: String },
        #[column(variant = 2)]
        Video { seconds: i64 },
    }

    #[derive(Debug, Clone, toasty::Model)]
    struct Clip {
        #[key]
        #[auto]
        id: Uuid,
        title: String,
        body: Body,
    }

    #[derive(tablo_core::RecordForm)]
    #[form(model = Clip)]
    struct ClipForm {
        #[form(embed)]
        body: Body,
    }

    struct ClipResource;

    impl Resource for ClipResource {
        type Model = Clip;
        type Form = ClipForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("clips")
                .table(Table::new(TextColumn::new(lens!(Clip.title))))
                .form(Schema::new(
                    Repeater::new("Clips").schema(Body::form(Clip::fields().body())),
                ))
        }
    }

    // An all-empty `Repeater` group skips requiredness.
    let errors = refused::<ClipResource>(memory_db(toasty::models!(Clip)).await);
    assert!(
        errors.iter().any(
            |error| matches!(error, DeclarationErrorKind::NoBlankAnswer {
                field,
                in_repeater: true,
                ..
            } if field == "body")
        ),
        "{errors:?}"
    );
}

#[tokio::test]
async fn build_refuses_a_gated_form_claiming_the_tenant_column() {
    #[derive(tablo_core::RecordForm)]
    #[form(model = Owned)]
    struct ClaimingForm {
        tenant_id: Uuid,
        title: String,
    }

    struct Claiming;

    impl Resource for Claiming {
        type Model = Owned;
        type Form = ClaimingForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .tenancy(Tenancy::column(Owned::fields().tenant_id()))
                .table(Table::new(TextColumn::new(lens!(Owned.title))))
                .form(Schema::new((
                    Field::text(Owned::fields().tenant_id()),
                    Field::text(Owned::fields().title()),
                )))
        }
    }

    let errors = refused::<Claiming>(memory_db(toasty::models!(Owned)).await);
    assert!(
        errors.contains(&DeclarationErrorKind::FormClaimsTenantColumn {
            field: "tenant_id".to_string(),
            column: "tenant_id".to_string(),
        }),
        "{errors:?}"
    );
}

/// A `NoForm` resource over [`Item`].
macro_rules! list_only_resource {
    ($name:ident, $create:expr, $schema:expr) => {
        struct $name;

        impl Resource for $name {
            type Model = Item;
            type Form = NoForm<Self::Model>;

            fn declare() -> ResourceDef<Self> {
                ResourceDef::new()
                    .slug("items")
                    .policy(|_cx: &Cx, ability: Ability<'_, Item>| match ability {
                        Ability::Create => $create,
                        _ => false,
                    })
                    .table(item_table())
                    .form($schema)
            }
        }
    };
}

#[tokio::test]
async fn build_refuses_a_list_only_resource_that_allows_create() {
    list_only_resource!(Creating, true, Schema::empty());
    assert_eq!(
        refused::<Creating>(item_db().await),
        [DeclarationErrorKind::CreateWithoutForm]
    );
}

#[tokio::test]
async fn build_refuses_a_list_only_resource_that_declares_a_schema() {
    list_only_resource!(Schematic, false, item_schema());
    assert_eq!(
        refused::<Schematic>(item_db().await),
        [DeclarationErrorKind::FormWithoutRecordForm]
    );
}

#[tokio::test]
async fn build_refuses_an_empty_form_override() {
    item_resource!(Emptied, TitleForm, Schema::empty());
    assert_eq!(
        refused::<Emptied>(item_db().await),
        [DeclarationErrorKind::EmptyFormOverride]
    );
}

#[tokio::test]
async fn a_list_only_resource_serves_no_form_route() {
    list_only_resource!(Listed, false, Schema::empty());
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<Listed>(db.clone());
    let edit = format!("/admin/items/{}/edit", item.id);
    // `create` falls to the GET-only detail route.
    for (response, status) in [
        (
            get(&router, "/admin/items/create").await,
            StatusCode::NOT_FOUND,
        ),
        (
            get(&router, "/admin/items/options?field=title").await,
            StatusCode::NOT_FOUND,
        ),
        (get(&router, &edit).await, StatusCode::NOT_FOUND),
        (
            post_fields(&router, "/admin/items/create", &[("title", "New")]).await,
            StatusCode::METHOD_NOT_ALLOWED,
        ),
        (
            post_fields(&router, &edit, &[("title", "New")]).await,
            StatusCode::NOT_FOUND,
        ),
    ] {
        assert_eq!(response.status(), status);
    }
    assert_eq!(reload(&db, item.id).await.title, "Stored");
}

/// A `NoForm` resource renders its detail page from `view_values` alone.
#[tokio::test]
async fn a_list_only_detail_page_reads_view_values() {
    struct Viewed;

    impl Resource for Viewed {
        type Model = Item;
        type Form = NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("items")
                .policy(|_cx: &Cx, ability: Ability<'_, Item>| matches!(ability, Ability::View(_)))
                .table(item_table())
                .view(Schema::new(Field::text(Item::fields().title())))
        }

        fn view_values(_cx: &Cx, record: &Item) -> HashMap<String, String> {
            HashMap::from([("title".to_string(), format!("{} (view)", record.title))])
        }
    }

    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<Viewed>(db);
    let response = get(&router, &format!("/admin/items/{}", item.id)).await;
    assert_eq!(response.status(), StatusCode::OK);
    let html = body_string(response).await;
    assert!(html.contains("Stored (view)"), "{html}");
}

#[tokio::test]
async fn a_form_resource_serves_create_and_edit() {
    let db = item_db().await;
    let item = seed_item(&db).await;
    let router: topcoat::router::Router = mount(
        db,
        Panel::new("admin")
            .auth(tablo_core::Auth::disabled())
            .resource::<ItemResource>(),
    )
    .expect("panel builds");
    let create = get(&router, "/admin/items/create").await;
    assert_eq!(create.status(), StatusCode::OK);
    let html = body_string(create).await;
    for name in ["title", "notes", "priority", "done"] {
        assert!(
            html.contains(&format!("name=\"{name}\"")),
            "`{name}` posts: {html}"
        );
    }
    assert_eq!(
        get(&router, &format!("/admin/items/{}/edit", item.id))
            .await
            .status(),
        StatusCode::OK
    );
}

/// A resource over [`Item`] that allows create through `F`.
macro_rules! title_only_resource {
    ($name:ident, $columns:expr) => {
        struct $name;

        impl Resource for $name {
            type Model = Item;
            type Form = TitleForm;

            fn declare() -> ResourceDef<Self> {
                ResourceDef::new()
                    .slug("items")
                    .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                        matches!(ability, Ability::Create)
                    })
                    .table(item_table())
                    .form(Schema::new(Field::text(Item::fields().title())))
                    .create_columns($columns)
            }
        }
    };
}

#[tokio::test]
async fn build_refuses_a_create_that_leaves_a_required_column_unset() {
    title_only_resource!(Partial, []);
    let errors = refused::<Partial>(item_db().await);
    assert!(
        errors.contains(&DeclarationErrorKind::UnwrittenColumn {
            column: "notes".to_string()
        }),
        "{errors:?}"
    );
}

#[tokio::test]
async fn create_columns_names_what_an_override_sets() {
    title_only_resource!(Covered, ["notes", "priority", "done"]);
    mount(item_db().await, panel().resource::<Covered>())
        .expect("the override's own columns are declared");

    title_only_resource!(Misnamed, ["notes", "priority", "done", "nope"]);
    assert_eq!(
        refused::<Misnamed>(item_db().await),
        [DeclarationErrorKind::UnknownCreateColumn { column: "nope" }]
    );
}

/// A value the control lets through but the field's type refuses renders inline.
#[tokio::test]
async fn a_value_the_form_type_refuses_renders_inline() {
    struct Loose;

    impl Resource for Loose {
        type Model = Item;
        type Form = PriorityForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("items")
                .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                    matches!(ability, Ability::View(_) | Ability::Update(_))
                })
                .table(item_table())
                .form(
                    // A static-options select checks membership, not the column's type.
                    Schema::new(
                        Field::choice(Item::fields().priority())
                            .options(vec!["1".to_string(), "lots".to_string()]),
                    ),
                )
        }
    }

    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<Loose>(db.clone());
    let response = post_fields(
        &router,
        &format!("/admin/items/{}/edit", item.id),
        &[("priority", "lots")],
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK, "the form re-renders");
    let html = body_string(response).await;
    assert_eq!(
        field_error(&html, "priority").as_deref(),
        Some("`lots` is not a valid whole number"),
        "{html}"
    );
    assert_eq!(reload(&db, item.id).await.priority, 7);
}

/// An unkeyable record rule fails closed.
#[tokio::test]
async fn an_unkeyable_record_rule_fails_closed() {
    /// [`PriorityForm`] with no keys: nothing can render its errors.
    struct Keyless(PriorityForm);

    impl RecordForm for Keyless {
        type Model = Item;
        type Field = PriorityFormField;

        fn fields() -> Vec<tablo_core::FormField<PriorityFormField>> {
            Vec::new()
        }

        fn hydrate(cx: &Cx, record: &Item) -> HashMap<String, String> {
            PriorityForm::hydrate(cx, record)
        }

        fn parse(
            _cx: &Cx,
            _values: &HashMap<String, String>,
        ) -> Result<Self, Vec<tablo_core::FieldError>> {
            Ok(Keyless(PriorityForm { priority: 1 }))
        }

        fn into_create(self) -> <Item as toasty::schema::Model>::Create {
            self.0.into_create()
        }

        fn into_update<'a>(
            self,
            record: &'a mut Item,
            named: &HashSet<PriorityFormField>,
        ) -> Option<<Item as toasty::schema::Model>::Update<'a>> {
            self.0.into_update(record, named)
        }

        fn exec_update<'a>(
            update: <Item as toasty::schema::Model>::Update<'a>,
            ex: &'a mut dyn toasty::Executor,
        ) -> impl std::future::Future<Output = toasty::Result<()>> + Send + 'a {
            PriorityForm::exec_update(update, ex)
        }
    }

    struct Refusing;

    impl Resource for Refusing {
        type Model = Item;
        type Form = Keyless;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("items")
                .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                    matches!(ability, Ability::View(_) | Ability::Update(_))
                })
                .table(item_table())
                .form(Schema::empty())
        }

        fn validate_record(_cx: &Cx, _form: &Keyless) -> FieldErrors {
            let mut errors = FieldErrors::new();
            errors.add("priority", "never");
            errors
        }
    }

    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<Refusing>(db.clone());
    let response = post_fields(&router, &format!("/admin/items/{}/edit", item.id), &[]).await;
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(reload(&db, item.id).await.priority, 7, "nothing is written");
}

/// An unkeyable parse failure fails closed.
#[tokio::test]
async fn an_unkeyable_parse_failure_fails_closed() {
    /// [`PriorityForm`] with no keys, refusing on a key nothing renders.
    struct Unkeyable(PriorityForm);

    impl RecordForm for Unkeyable {
        type Model = Item;
        type Field = PriorityFormField;

        fn fields() -> Vec<tablo_core::FormField<PriorityFormField>> {
            Vec::new()
        }

        fn hydrate(cx: &Cx, record: &Item) -> HashMap<String, String> {
            PriorityForm::hydrate(cx, record)
        }

        fn parse(
            _cx: &Cx,
            _values: &HashMap<String, String>,
        ) -> Result<Self, Vec<tablo_core::FieldError>> {
            Err(vec![tablo_core::FieldError::invalid(
                "never",
                "never renders",
            )])
        }

        fn into_create(self) -> <Item as toasty::schema::Model>::Create {
            self.0.into_create()
        }

        fn into_update<'a>(
            self,
            record: &'a mut Item,
            named: &HashSet<PriorityFormField>,
        ) -> Option<<Item as toasty::schema::Model>::Update<'a>> {
            self.0.into_update(record, named)
        }

        fn exec_update<'a>(
            update: <Item as toasty::schema::Model>::Update<'a>,
            ex: &'a mut dyn toasty::Executor,
        ) -> impl std::future::Future<Output = toasty::Result<()>> + Send + 'a {
            PriorityForm::exec_update(update, ex)
        }
    }

    struct Parseless;

    impl Resource for Parseless {
        type Model = Item;
        type Form = Unkeyable;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("items")
                .policy(|_cx: &Cx, ability: Ability<'_, Item>| {
                    matches!(ability, Ability::View(_) | Ability::Update(_))
                })
                .table(item_table())
                .form(Schema::empty())
        }
    }

    let db = item_db().await;
    let item = seed_item(&db).await;
    let router = panel_router::<Parseless>(db.clone());
    let response = post_fields(&router, &format!("/admin/items/{}/edit", item.id), &[]).await;
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(reload(&db, item.id).await.priority, 7, "nothing is written");
}

/// A list-only resource never links to create.
#[tokio::test]
async fn a_list_only_resource_never_links_to_create() {
    struct TenantCreates;

    impl Resource for TenantCreates {
        type Model = Item;
        type Form = tablo_core::NoForm<Self::Model>;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("items")
                .policy(|cx: &Cx, ability: Ability<'_, Item>| match ability {
                    Ability::ViewAny => true,
                    Ability::Create => tablo_core::tenant_id(cx).is_some(),
                    _ => false,
                })
                .table(item_table())
        }
    }

    let router = mount(item_db().await, panel().resource::<TenantCreates>())
        .expect("create is denied without a request");
    let request = http::Request::builder()
        .uri("/admin/items")
        .extension(Tenant(Uuid::new_v4()))
        .body(topcoat::router::Body::empty())
        .unwrap();
    let response = router.handle(request).await;
    assert_eq!(response.status(), StatusCode::OK);
    let html = body_string(response).await;
    assert!(!html.contains("/admin/items/create"), "{html}");
}

/// The derived default form renders and writes.
#[tokio::test]
async fn the_derived_default_form_renders_and_writes() {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, tablo_core::Options)]
    enum WidgetRole {
        Admin,
        Member,
    }

    assert_eq!(WidgetRole::Admin.value(), "admin");

    #[derive(Debug, Clone, toasty::Model)]
    struct Widget {
        #[key]
        #[auto]
        id: Uuid,
        name: String,
        role: String,
        active: bool,
    }

    #[derive(tablo_core::RecordForm)]
    #[form(model = Widget)]
    struct WidgetForm {
        name: String,
        #[form(options = WidgetRole, blank = WidgetRole::Member.value())]
        role: String,
        active: bool,
    }

    struct WidgetResource;

    impl Resource for WidgetResource {
        type Model = Widget;
        type Form = WidgetForm;

        fn declare() -> ResourceDef<Self> {
            ResourceDef::new()
                .slug("widgets")
                .policy(|_cx: &Cx, ability: Ability<'_, Widget>| {
                    matches!(
                        ability,
                        Ability::ViewAny | Ability::View(_) | Ability::Create | Ability::Update(_)
                    )
                })
                .table(Table::new(TextColumn::new(lens!(Widget.name))))
        }
    }

    let db = memory_db(toasty::models!(Widget)).await;
    let router = panel_router::<WidgetResource>(db.clone());
    let create = get(&router, "/admin/widgets/create").await;
    assert_eq!(create.status(), StatusCode::OK);
    let html = body_string(create).await;
    for name in ["name", "role", "active"] {
        assert!(
            html.contains(&format!("name=\"{name}\"")),
            "`{name}` posts: {html}"
        );
    }
    assert!(
        html.find("name=\"name\"").unwrap() < html.find("name=\"role\"").unwrap()
            && html.find("name=\"role\"").unwrap() < html.find("name=\"active\"").unwrap(),
        "the default schema keeps declaration order: {html}"
    );
    assert!(
        html.contains("value=\"admin\"") && html.contains("value=\"member\""),
        "the choice carries the Options list: {html}"
    );

    let response = post_fields(
        &router,
        "/admin/widgets/create",
        &[("name", "New"), ("role", "admin")],
    )
    .await;
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
    let mut handle = db.clone();
    let rows = Widget::all().exec(&mut handle).await.unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].name, "New");
    assert_eq!(rows[0].role, "admin");
    assert!(!rows[0].active, "an absent toggle reads as false");

    let edit = get(&router, &format!("/admin/widgets/{}/edit", rows[0].id)).await;
    assert_eq!(edit.status(), StatusCode::OK);
    let html = body_string(edit).await;
    assert_eq!(
        input_value(&html, "name").as_deref(),
        Some("New"),
        "the edit form hydrates the stored value: {html}"
    );
    let response = post_fields(
        &router,
        &format!("/admin/widgets/{}/edit", rows[0].id),
        &[("active", "true")],
    )
    .await;
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
    let mut handle = db.clone();
    let stored = Widget::get_by_id(&mut handle, &rows[0].id)
        .await
        .expect("the widget exists");
    assert!(stored.active);
    assert_eq!(stored.name, "New", "an unposted key keeps its value");
    assert_eq!(stored.role, "admin", "an unposted key keeps its value");
}

#[derive(Debug, Clone, toasty::Model)]
struct Ticket {
    #[key]
    #[auto]
    id: Uuid,
    subject: String,
    status: String,
    urgent: bool,
    estimate: i64,
}

#[derive(tablo_core::Options)]
enum TicketStatus {
    Open,
    #[option(label = "Waiting on customer")]
    Waiting,
}

#[derive(tablo_core::RecordForm)]
#[form(model = Ticket)]
struct TicketForm {
    subject: String,
    #[form(options = TicketStatus)]
    status: String,
    urgent: bool,
    estimate: i64,
}

/// A resource naming only its model, its form and its policy.
struct TicketResource;

impl Resource for TicketResource {
    type Model = Ticket;
    type Form = TicketForm;

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new().policy(tablo_core::ReadOnly)
    }
}

/// The same resource with its detail page turned off.
struct UnviewedTicketResource;

impl Resource for UnviewedTicketResource {
    type Model = Ticket;
    type Form = TicketForm;

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            .policy(tablo_core::ReadOnly)
            .view(Schema::empty())
    }
}

async fn ticket_db() -> (Db, Ticket) {
    let mut db = memory_db(toasty::models!(Ticket)).await;
    let ticket = toasty::create!(Ticket {
        subject: "Printer jam".to_string(),
        status: TicketStatus::Waiting.value().to_string(),
        urgent: true,
        estimate: 3,
    })
    .exec(&mut db)
    .await
    .expect("seed ticket");
    toasty::create!(Ticket {
        subject: "New laptop".to_string(),
        status: TicketStatus::Open.value().to_string(),
        urgent: false,
        estimate: 8,
    })
    .exec(&mut db)
    .await
    .expect("seed ticket");
    (db, ticket)
}

/// The record form derives the table: a sortable column per text field, searchable over a
/// `String`, an options field by its label, and a toggle as yes or no.
#[tokio::test]
async fn the_record_form_derives_the_table() {
    let (db, _) = ticket_db().await;
    let router = panel_router::<TicketResource>(db);

    let html = body_string(get(&router, "/admin/tickets?sort=estimate&dir=desc").await).await;
    for header in ["Subject", "Status", "Urgent", "Estimate"] {
        assert!(html.contains(header), "a {header} column: {html}");
    }
    assert!(
        html.contains("Waiting on customer") && !html.contains(">waiting<"),
        "an options field shows its label: {html}"
    );
    assert!(html.contains("Yes") && html.contains("No"), "{html}");
    assert!(
        html.find("New laptop").unwrap() < html.find("Printer jam").unwrap(),
        "sorted by the estimate, descending: {html}"
    );

    let searched = body_string(get(&router, "/admin/tickets?q=printer").await).await;
    assert!(
        searched.contains("Printer jam") && !searched.contains("New laptop"),
        "searched by the subject: {searched}"
    );
}

/// The detail page defaults to the form, read-only; an empty view turns it off.
#[tokio::test]
async fn the_view_defaults_to_the_form() {
    let (db, ticket) = ticket_db().await;
    let viewed = panel_router::<TicketResource>(db.clone());
    let detail = get(&viewed, &format!("/admin/tickets/{}", ticket.id)).await;
    assert_eq!(detail.status(), StatusCode::OK);
    let detail = body_string(detail).await;
    assert!(
        detail.contains("Printer jam"),
        "the form's fields, read-only: {detail}"
    );
    assert_eq!(
        input_value(&detail, "subject"),
        None,
        "the detail page renders no control for the field: {detail}"
    );

    let unviewed = panel_router::<UnviewedTicketResource>(db);
    let detail = get(&unviewed, &format!("/admin/unviewed-tickets/{}", ticket.id)).await;
    assert_eq!(detail.status(), StatusCode::NOT_FOUND);
}