laterite-admin 0.9.16

Laterite CMF admin surface: the Axum router, session middleware, and login shell
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
//! Descriptor-driven list views.
//!
//! A [`ListConfig`] describes a table and the columns to show. A generic handler
//! renders it, fetching rows with dynamic SQL built from the descriptor. This is
//! the first slice of the descriptor system: admin screens are data, rendered by
//! generic code, not hand-written per entity.
//!
//! The admin is inherently generic, so unlike the typed, compile-time-checked
//! queries in `laterite-auth`, list queries are built and checked at runtime.

use std::collections::HashMap;
use std::sync::Arc;

use askama::Template;
use axum::response::{IntoResponse, Response};
use chrono::DateTime;
use chrono_tz::Tz;
use laterite_core::query::{bind_values, bind_values_as, build, text_cast};
use laterite_core::search::SearchProfile;
use laterite_core::{AnyRowExt, Db, DbBackend, Text};
use sea_query::{Alias, Expr, Order, Query, SimpleExpr};
use serde::{Deserialize, Serialize};

use crate::field::{OverrideResolver, OverrideScope, Surface};
use crate::html::Markup;
use crate::sql::valid_ident;
use crate::{render, render_error, AdminState};

const ID_ALIAS: &str = "_lat_id";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SortDir {
    Asc,
    Desc,
}

/// One column of a list view: the source field, its display label, and its
/// column-type key (resolved through the column-type registry).
/// How a column's cells and header align.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Align {
    Left,
    Center,
    Right,
}

impl Align {
    fn class(self) -> &'static str {
        match self {
            Align::Left => "lat-col--left",
            Align::Center => "lat-col--center",
            Align::Right => "lat-col--right",
        }
    }
}

/// What a stored value reads as in a cell.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ValueLabel {
    pub value: String,
    /// Localized at render.
    pub label: Text,
}

impl ValueLabel {
    pub fn new(value: impl Into<String>, label: impl Into<Text>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
        }
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ListColumn {
    /// Comes from the key this was written under, never from the body.
    pub field: String,
    /// The column header, localized at render. Serde stays a plain string.
    pub label: Text,
    /// The column-type registry key (`text`, `date`, `boolean`, `status_pill`, ...).
    pub column_type: String,
    /// The keys that belong to the column's type, as an object: in a file they
    /// are written on the column itself. Null when there are none.
    pub options: serde_json::Value,
    /// Whether the header sorts. Off for a column whose order means nothing.
    pub sortable: bool,
    /// Hidden until the operator picks it from the column chooser.
    pub invisible: bool,
    /// A CSS width, `10%` or `120px`. `None` shares the remaining space.
    pub width: Option<String>,
    pub align: Option<Align>,
    /// A permission the operator must hold to see the column at all: it is
    /// then not queried, sorted, searched, picked or exported for them.
    pub permission: Option<String>,
    /// Whether the list's search box looks in this column. `None` follows the
    /// column type: text columns are searched, the rest are not, because a
    /// substring match on a boolean or a stored timestamp answers nonsense.
    pub searchable: Option<bool>,
    /// What a stored value reads as: `login_success` shown as "Signed in". A
    /// value with no label shows as stored.
    pub labels: Vec<ValueLabel>,
    /// The cell is the form field's control, saved on change: a column whose
    /// field is on the resource's form. Off by default.
    pub editable: bool,
}

impl ListColumn {
    pub fn new(field: &str, label: impl Into<Text>) -> Self {
        Self {
            field: field.to_string(),
            label: label.into(),
            column_type: "text".to_string(),
            sortable: true,
            invisible: false,
            width: None,
            align: None,
            permission: None,
            searchable: None,
            options: serde_json::Value::Null,
            labels: Vec::new(),
            editable: false,
        }
    }

    /// What each stored value reads as. A value not listed shows as stored.
    pub fn labels(mut self, labels: Vec<ValueLabel>) -> Self {
        self.labels = labels;
        self
    }

    /// Edits the cell in the row through the form field of the same name.
    pub fn editable(mut self) -> Self {
        self.editable = true;
        self
    }

    fn of(mut self, column_type: &str) -> Self {
        self.column_type = column_type.to_string();
        self
    }

    /// Render as a date and time in the display timezone.
    pub fn datetime(self) -> Self {
        self.of("datetime")
    }
    /// Render as a date in the display timezone.
    pub fn date(self) -> Self {
        self.of("date")
    }
    /// Render as a time in the display timezone.
    pub fn time(self) -> Self {
        self.of("time")
    }
    /// Render a boolean as Yes/No.
    pub fn yes_no(self) -> Self {
        self.of("boolean")
    }
    /// Render as a coloured status pill.
    pub fn pill(self) -> Self {
        self.of("status_pill")
    }

    /// Overrides whether the search box looks in this column.
    pub fn searchable(mut self, searchable: bool) -> Self {
        self.searchable = Some(searchable);
        self
    }

    pub fn sortable(mut self, sortable: bool) -> Self {
        self.sortable = sortable;
        self
    }

    /// Hidden by default; the column chooser still offers it.
    pub fn invisible(mut self) -> Self {
        self.invisible = true;
        self
    }

    pub fn width(mut self, width: impl Into<String>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn align(mut self, align: Align) -> Self {
        self.align = Some(align);
        self
    }

    /// Shown only to an operator holding `permission`.
    pub fn require(mut self, permission: impl Into<String>) -> Self {
        self.permission = Some(permission.into());
        self
    }

    pub(crate) fn align_class(&self) -> &'static str {
        self.align.map(Align::class).unwrap_or("")
    }

    /// Whether search looks here: the explicit choice, else text columns only.
    pub(crate) fn is_searchable(&self) -> bool {
        self.searchable.unwrap_or(self.column_type == "text")
    }
}

/// The per-cell state a column type renders from: the raw (text-cast) value, the
/// display timezone, and the locale for date month/day names.
pub struct CellCx<'a> {
    pub value: &'a str,
    pub tz: Tz,
    pub locale: chrono::Locale,
}

/// The chrono locale for month/day names, parsed from the operator's locale tag.
/// chrono locales are language + territory (`kn_IN`, `de_DE`, `ar_EG`), so a tag with
/// no territory (a bare `kn`) or one chrono does not know formats in neutral English;
/// a deployment gets localized dates by carrying a territory-bearing locale tag. No
/// language is special-cased: any locale the locale table knows resolves.
pub(crate) fn date_locale(tag: &str) -> chrono::Locale {
    chrono::Locale::try_from(tag.replace('-', "_").as_str()).unwrap_or(chrono::Locale::en_US)
}

/// A rendered cell's serialisable payload: raw value, display text, and any
/// richer data (a status pill's slug), so an override presents the same data.
#[derive(Serialize)]
pub struct CellVm {
    pub view_key: String,
    pub value: String,
    pub display: String,
    pub data: serde_json::Value,
}

/// A column type: how a list cell renders. The list counterpart of a field type,
/// sharing [`Markup`] and the override resolver ([`Surface::Column`]).
pub trait ColumnType: Send + Sync + 'static {
    fn view_key(&self) -> &'static str;
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm;
    fn render_default(&self, vm: &CellVm) -> Markup;
    /// The keys this type reads from a column's entry, beyond the ones every
    /// column has. A key outside the list is refused when the file is read.
    /// `None` accepts any key unchecked; declare yours.
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        None
    }
    /// Asset-registry keys this column's cell needs (a heavy cell widget). The
    /// page shell collects and emits them; keys must exist in the registry.
    fn assets(&self) -> Vec<&'static str> {
        Vec::new()
    }
}

/// A column type a module contributes, so a list can render a cell the framework
/// has no built-in for (a rating, a map thumbnail, a currency amount).
///
/// The key is the type's own [`ColumnType::view_key`], so a registration cannot
/// disagree with the type it registers. Use a dotted `vendor.name` to stay clear
/// of the built-ins and of other modules.
pub struct ColumnTypeReg {
    pub column_type: Arc<dyn ColumnType>,
}

impl ColumnTypeReg {
    pub fn new(column_type: Arc<dyn ColumnType>) -> Self {
        Self { column_type }
    }

    /// The key this type registers under.
    pub fn name(&self) -> &'static str {
        self.column_type.view_key()
    }
}

/// The column-type registry, keyed by [`ColumnType::view_key`].
pub type ColumnRegistry = HashMap<String, Arc<dyn ColumnType>>;

/// Renders a cell: an override if the resolver supplies one, else the default.
/// Renders one cell: the type's view-model, an override when one is registered,
/// else the type's own markup. A stored value with a label is shown as it,
/// whatever the column's type.
pub(crate) fn render_cell(
    ct: &dyn ColumnType,
    resolver: &dyn OverrideResolver,
    scope: &OverrideScope<'_>,
    cx: &CellCx<'_>,
    labels: Option<&HashMap<String, String>>,
) -> Markup {
    let mut vm = ct.view_model(cx);
    if let Some(label) = labels.and_then(|l| l.get(&vm.value)) {
        vm.display = label.clone();
    }
    match resolver.render_override(scope, &serde_json::to_value(&vm).unwrap_or_default()) {
        Some(Ok(html)) => Markup::from_override(html),
        Some(Err(_)) | None => ct.render_default(&vm),
    }
}

pub(crate) fn builtin_column_types() -> Vec<Arc<dyn ColumnType>> {
    vec![
        Arc::new(TextColumn),
        Arc::new(DateTimeColumn),
        Arc::new(DateColumn),
        Arc::new(TimeColumn),
        Arc::new(BoolColumn),
        Arc::new(StatusPillColumn),
    ]
}

/// The column registry seeded with the built-in types.
pub(crate) fn builtin_column_registry() -> ColumnRegistry {
    builtin_column_types()
        .into_iter()
        .map(|c| (c.view_key().to_string(), c))
        .collect()
}

#[derive(Template)]
#[template(path = "cells/text.html")]
struct CellTextTmpl<'a> {
    display: &'a str,
}

/// The view-model for a text-like cell: raw value plus its display text.
fn text_cell(view_key: &str, value: &str, display: String) -> CellVm {
    CellVm {
        view_key: view_key.to_string(),
        value: value.to_string(),
        display,
        data: serde_json::Value::Null,
    }
}

fn render_text(vm: &CellVm) -> Markup {
    Markup::from_template(&CellTextTmpl {
        display: &vm.display,
    })
    .unwrap_or_default()
}

/// Formats a stored UTC RFC3339 timestamp in `tz`, with month/day names in `locale`;
/// an unparseable value passes through unchanged.
pub(crate) fn format_ts(raw: &str, tz: Tz, locale: chrono::Locale, pattern: &str) -> String {
    match DateTime::parse_from_rfc3339(raw) {
        Ok(dt) => dt
            .with_timezone(&tz)
            .format_localized(pattern, locale)
            .to_string(),
        Err(_) => raw.to_string(),
    }
}

struct TextColumn;
impl ColumnType for TextColumn {
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }
    fn view_key(&self) -> &'static str {
        "text"
    }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
        text_cell("text", cx.value, cx.value.to_string())
    }
    fn render_default(&self, vm: &CellVm) -> Markup {
        render_text(vm)
    }
}

struct DateTimeColumn;
impl ColumnType for DateTimeColumn {
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }
    fn view_key(&self) -> &'static str {
        "datetime"
    }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
        text_cell(
            "datetime",
            cx.value,
            format_ts(cx.value, cx.tz, cx.locale, "%-d %b %Y, %H:%M"),
        )
    }
    fn render_default(&self, vm: &CellVm) -> Markup {
        render_text(vm)
    }
}

struct DateColumn;
impl ColumnType for DateColumn {
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }
    fn view_key(&self) -> &'static str {
        "date"
    }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
        text_cell(
            "date",
            cx.value,
            format_ts(cx.value, cx.tz, cx.locale, "%-d %b %Y"),
        )
    }
    fn render_default(&self, vm: &CellVm) -> Markup {
        render_text(vm)
    }
}

struct TimeColumn;
impl ColumnType for TimeColumn {
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }
    fn view_key(&self) -> &'static str {
        "time"
    }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
        text_cell(
            "time",
            cx.value,
            format_ts(cx.value, cx.tz, cx.locale, "%H:%M"),
        )
    }
    fn render_default(&self, vm: &CellVm) -> Markup {
        render_text(vm)
    }
}

struct BoolColumn;
impl ColumnType for BoolColumn {
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }
    fn view_key(&self) -> &'static str {
        "boolean"
    }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
        let display = match cx.value {
            "1" | "true" => "Yes",
            "0" | "false" | "" => "No",
            other => other,
        };
        text_cell("boolean", cx.value, display.to_string())
    }
    fn render_default(&self, vm: &CellVm) -> Markup {
        render_text(vm)
    }
}

#[derive(Template)]
#[template(path = "cells/status.html")]
struct CellStatusTmpl<'a> {
    label: &'a str,
    slug: &'a str,
}

/// A status shown as a coloured pill: the first Markup-bearing cell.
struct StatusPillColumn;
impl ColumnType for StatusPillColumn {
    fn option_keys(&self) -> Option<Vec<&'static str>> {
        Some(Vec::new())
    }
    fn view_key(&self) -> &'static str {
        "status_pill"
    }
    fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
        CellVm {
            view_key: "status_pill".to_string(),
            value: cx.value.to_string(),
            display: cx.value.to_string(),
            data: serde_json::json!({ "slug": status_slug(cx.value) }),
        }
    }
    fn render_default(&self, vm: &CellVm) -> Markup {
        let slug = vm.data.get("slug").and_then(|v| v.as_str()).unwrap_or("");
        Markup::from_template(&CellStatusTmpl {
            label: &vm.display,
            slug,
        })
        .unwrap_or_default()
    }
}

/// A CSS-safe modifier from a status value (lowercased, non-alphanumerics to `-`).
fn status_slug(value: &str) -> String {
    value
        .trim()
        .to_lowercase()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect()
}

impl Default for ListColumn {
    /// A text column. The name comes from the key it is written under, and the
    /// label from the name when a file gives none.
    fn default() -> Self {
        Self::new("", Text::new(""))
    }
}

impl Default for ListFilter {
    /// A text filter, named and labelled like a column.
    fn default() -> Self {
        Self::of("", Text::new(""), "text")
    }
}

impl<'de> Deserialize<'de> for ListColumn {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct Entry;
        impl<'de> serde::de::Visitor<'de> for Entry {
            type Value = ListColumn;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a column: its own keys and its type's")
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                map: A,
            ) -> Result<ListColumn, A::Error> {
                let mut column = ListColumn::default();
                let theirs = crate::keyed::split_entry(map, |key, map| {
                    match key {
                        "label" => column.label = map.next_value()?,
                        "type" => column.column_type = map.next_value()?,
                        "sortable" => column.sortable = map.next_value()?,
                        "invisible" => column.invisible = map.next_value()?,
                        "width" => column.width = map.next_value()?,
                        "align" => column.align = map.next_value()?,
                        "permission" => column.permission = map.next_value()?,
                        "searchable" => column.searchable = map.next_value()?,
                        "labels" => column.labels = map.next_value()?,
                        "editable" => column.editable = map.next_value()?,
                        _ => return Ok(false),
                    }
                    Ok(true)
                })?;
                column.options = theirs;
                Ok(column)
            }

            /// A key written bare (`title:`) is a column with every default.
            fn visit_unit<E: serde::de::Error>(self) -> Result<ListColumn, E> {
                Ok(ListColumn::default())
            }
        }
        de.deserialize_map(Entry)
    }
}

impl Serialize for ListColumn {
    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = ser.serialize_map(None)?;
        map.serialize_entry("label", &self.label)?;
        map.serialize_entry("type", &self.column_type)?;
        map.serialize_entry("sortable", &self.sortable)?;
        map.serialize_entry("editable", &self.editable)?;
        map.serialize_entry("invisible", &self.invisible)?;
        map.serialize_entry("width", &self.width)?;
        map.serialize_entry("align", &self.align)?;
        map.serialize_entry("permission", &self.permission)?;
        map.serialize_entry("searchable", &self.searchable)?;
        if !self.labels.is_empty() {
            map.serialize_entry("labels", &self.labels)?;
        }
        crate::keyed::serialize_theirs(&mut map, &self.options)?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for ListFilter {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct Entry;
        impl<'de> serde::de::Visitor<'de> for Entry {
            type Value = ListFilter;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a filter: its own keys and its type's")
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                map: A,
            ) -> Result<ListFilter, A::Error> {
                let mut filter = ListFilter::default();
                let theirs = crate::keyed::split_entry(map, |key, map| {
                    match key {
                        "label" => filter.label = map.next_value()?,
                        "type" => filter.filter_type = map.next_value()?,
                        "default_value" => filter.default_value = map.next_value()?,
                        "permission" => filter.permission = map.next_value()?,
                        _ => return Ok(false),
                    }
                    Ok(true)
                })?;
                filter.options = theirs;
                Ok(filter)
            }

            /// A key written bare is a text filter with every default.
            fn visit_unit<E: serde::de::Error>(self) -> Result<ListFilter, E> {
                Ok(ListFilter::default())
            }
        }
        de.deserialize_map(Entry)
    }
}

impl Serialize for ListFilter {
    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = ser.serialize_map(None)?;
        map.serialize_entry("label", &self.label)?;
        map.serialize_entry("type", &self.filter_type)?;
        map.serialize_entry("default_value", &self.default_value)?;
        map.serialize_entry("permission", &self.permission)?;
        crate::keyed::serialize_theirs(&mut map, &self.options)?;
        map.end()
    }
}

impl crate::keyed::Keyed for ListColumn {
    fn key(&self) -> &str {
        &self.field
    }
    fn set_key(&mut self, key: String) {
        self.field = key;
    }
}

impl crate::keyed::Keyed for ListFilter {
    fn key(&self) -> &str {
        &self.field
    }
    fn set_key(&mut self, key: String) {
        self.field = key;
    }
}

/// One value a `select` filter offers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterOption {
    pub value: String,
    /// The option's label, localized at render.
    pub label: Text,
}

impl FilterOption {
    pub fn new(value: &str, label: impl Into<Text>) -> Self {
        Self {
            value: value.to_string(),
            label: label.into(),
        }
    }
}

/// One filter offered above a list: a column, its label, and what it offers.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ListFilter {
    /// Comes from the key this was written under, never from the body.
    pub field: String,
    /// The control's label, localized at render.
    pub label: Text,
    /// What the filter offers: `boolean`, `select`, `text`, `number` or `date`.
    pub filter_type: String,
    /// The keys that belong to the filter's type, as an object: in a file they
    /// are written on the filter itself. A `select` carries its choices here.
    pub options: serde_json::Value,
    /// Applied when the request names no value for this filter at all, so a
    /// screen can open already narrowed. Clearing it is still "no filter".
    pub default_value: Option<String>,
    /// A permission the operator must hold to see this filter, and to have its
    /// default applied.
    pub permission: Option<String>,
}

impl ListFilter {
    /// A filter of any declared type, with no options.
    pub fn of(field: &str, label: impl Into<Text>, filter_type: &str) -> Self {
        Self {
            field: field.to_string(),
            label: label.into(),
            filter_type: filter_type.to_string(),
            options: serde_json::Value::Null,
            default_value: None,
            permission: None,
        }
    }

    /// A yes/no filter over a boolean column.
    pub fn boolean(field: &str, label: impl Into<Text>) -> Self {
        Self::of(field, label, "boolean")
    }

    /// A filter offering a fixed set of values. Only a declared one reaches the
    /// query.
    pub fn select(field: &str, label: impl Into<Text>, options: Vec<FilterOption>) -> Self {
        let mut filter = Self::of(field, label, "select");
        filter.options = serde_json::json!({ "options": options });
        filter
    }

    /// A substring match, folded the way the search box folds.
    pub fn text(field: &str, label: impl Into<Text>) -> Self {
        Self::of(field, label, "text")
    }

    /// An exact match on a whole number.
    pub fn number(field: &str, label: impl Into<Text>) -> Self {
        Self::of(field, label, "number")
    }

    /// Rows on one calendar day, whether the column stores a date or a
    /// timestamp.
    pub fn date(field: &str, label: impl Into<Text>) -> Self {
        Self::of(field, label, "date")
    }

    /// The choices a `select` offers, or none for any other type.
    pub(crate) fn choices(&self) -> Vec<FilterOption> {
        self.options
            .get("options")
            .and_then(|v| serde_json::from_value(v.clone()).ok())
            .unwrap_or_default()
    }

    /// The value to apply when the request names none.
    pub fn default_value(mut self, value: impl Into<String>) -> Self {
        self.default_value = Some(value.into());
        self
    }

    /// Shown only to an operator holding `permission`.
    pub fn require(mut self, permission: impl Into<String>) -> Self {
        self.permission = Some(permission.into());
        self
    }

    pub(crate) fn param(&self) -> String {
        format!("f_{}", self.field)
    }
}

/// A button a list offers in its toolbar, beside the built-in New.
///
/// Where a list's Import button goes, and who sees it.
#[derive(Clone, Debug)]
pub(crate) struct ImportLink {
    pub href: String,
    pub permission: String,
}

/// A resource declares its own; the framework contributes New and the export
/// menu the same way, so the toolbar is one list of buttons rather than a
/// hardcoded bar with special cases.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolbarButton {
    /// The button's text, localized at render.
    pub label: Text,
    /// Where it goes: a path under the admin root (starting with a slash), or an
    /// absolute URL.
    pub href: String,
    /// An icon name from the shared set. Absent renders the label alone.
    pub icon: Option<String>,
    /// Hidden from an operator who lacks this permission. Absent shows it to
    /// anyone who can reach the screen.
    pub permission: Option<String>,
    /// Rendered as the prominent action rather than a secondary one.
    pub primary: bool,
}

impl ToolbarButton {
    pub fn new(label: impl Into<Text>, href: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            href: href.into(),
            icon: None,
            permission: None,
            primary: false,
        }
    }

    pub fn icon(mut self, icon: &str) -> Self {
        self.icon = Some(icon.to_string());
        self
    }

    /// Hides the button from an operator without this permission.
    pub fn require(mut self, permission: impl Into<String>) -> Self {
        self.permission = Some(permission.into());
        self
    }

    pub fn primary(mut self) -> Self {
        self.primary = true;
        self
    }
}

/// One rendered toolbar button.
pub struct ToolbarView {
    pub label: String,
    pub href: String,
    /// Inline SVG for the icon, empty when the button has none.
    pub icon: String,
    pub primary: bool,
}

/// The toolbar an operator sees: the framework's New (when the resource creates)
/// followed by the resource's own buttons, minus anything they lack permission
/// for.
fn toolbar_views(
    config: &ListConfig,
    admin_path: &str,
    user: &laterite_auth::AuthenticatedUser,
    shell: &crate::Shell,
) -> Vec<ToolbarView> {
    let mut out = Vec::new();
    if config.creatable {
        if let Some(base) = &config.edit_base {
            out.push(ToolbarView {
                label: shell.tt(&laterite_core::t!("New")),
                // `edit_base` is already under the admin mount (see
                // `prefix_resource`), like the row links that use it.
                href: format!("{base}/new"),
                icon: String::new(),
                primary: true,
            });
        }
    }
    for button in &config.toolbar {
        if let Some(needed) = &button.permission {
            if !user.permissions.allows(needed) {
                continue;
            }
        }
        let href = if button.href.starts_with('/') {
            format!("{admin_path}{}", button.href)
        } else {
            button.href.clone()
        };
        out.push(ToolbarView {
            label: shell.tt(&button.label),
            href,
            icon: crate::icons::svg(&shell.icon_set, &shell.sprite_url, button.icon.as_deref()),
            primary: button.primary,
        });
    }
    out
}

/// The preference key holding one operator's chosen columns for a list. Keyed by
/// the list's own path, so two resources over the same table stay separate.
pub(crate) fn columns_preference_key(base_path: &str) -> String {
    format!("list.columns.{base_path}")
}

/// One operator's stored column choice for a list, or `None` if they have none.
///
/// A failed read is a warning, not an error: a preference is a convenience, so
/// the screen shows every column rather than failing.
pub(crate) async fn stored_columns(
    state: &AdminState,
    path: &str,
    user: &laterite_auth::AuthenticatedUser,
) -> Option<String> {
    match laterite_auth::store::user_preference(
        &state.db,
        user.user.id,
        &columns_preference_key(path),
    )
    .await
    {
        Ok(stored) => stored,
        Err(e) => {
            tracing::warn!(error = %e, "reading the column preference failed");
            None
        }
    }
}

/// The preference key holding one operator's page size for a list.
pub(crate) fn per_page_preference_key(base_path: &str) -> String {
    format!("list.per_page:{base_path}")
}

/// This operator's page size for the list: their stored choice when the
/// descriptor still offers it, the descriptor's own otherwise. A failed read
/// is a warning, the way the column preference is.
pub(crate) async fn stored_per_page(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    user: &laterite_auth::AuthenticatedUser,
) -> i64 {
    let stored = match laterite_auth::store::user_preference(
        &state.db,
        user.user.id,
        &per_page_preference_key(path),
    )
    .await
    {
        Ok(stored) => stored,
        Err(e) => {
            tracing::warn!(error = %e, "reading the page-size preference failed");
            None
        }
    };
    offered_per_page(config, stored.as_deref().and_then(|s| s.parse().ok()))
}

/// A size the descriptor offers, else its own.
pub(crate) fn offered_per_page(config: &ListConfig, size: Option<i64>) -> i64 {
    size.filter(|n| config.per_page_options.contains(n))
        .unwrap_or(config.per_page)
}

/// The columns this operator may see at all: every one without a permission,
/// plus those whose permission they hold.
pub(crate) fn allowed_columns<'a>(
    config: &'a ListConfig,
    user: &laterite_auth::AuthenticatedUser,
) -> Vec<&'a ListColumn> {
    config
        .columns
        .iter()
        .filter(|c| {
            c.permission
                .as_deref()
                .is_none_or(|p| user.permissions.allows(p))
        })
        .collect()
}

/// The filters this operator may use: every one without a permission, plus
/// those whose permission they hold.
pub(crate) fn allowed_filters<'a>(
    config: &'a ListConfig,
    user: &laterite_auth::AuthenticatedUser,
) -> Vec<&'a ListFilter> {
    config
        .filters
        .iter()
        .filter(|f| {
            f.permission
                .as_deref()
                .is_none_or(|p| user.permissions.allows(p))
        })
        .collect()
}

/// The descriptor with only the columns this operator sees. One place, so the
/// query, the headers, sorting, searching and the export all work from it.
pub(crate) fn narrowed(
    config: &ListConfig,
    stored: Option<&str>,
    user: &laterite_auth::AuthenticatedUser,
) -> ListConfig {
    ListConfig {
        columns: visible_columns(config, stored, user)
            .into_iter()
            .cloned()
            .collect(),
        filters: allowed_filters(config, user).into_iter().cloned().collect(),
        ..config.clone()
    }
}

/// The columns to show: the operator's stored choice, narrowed to what the
/// descriptor still declares and they may see; without a choice, every column
/// they may see that is not `invisible`.
///
/// A stored choice that no longer names any such column falls back to that
/// default, so a descriptor that drops or renames a column leaves an operator
/// with a working list rather than an empty one.
pub(crate) fn visible_columns<'a>(
    config: &'a ListConfig,
    stored: Option<&str>,
    user: &laterite_auth::AuthenticatedUser,
) -> Vec<&'a ListColumn> {
    let allowed = allowed_columns(config, user);
    let by_default = || allowed.iter().copied().filter(|c| !c.invisible).collect();
    let Some(stored) = stored else {
        return by_default();
    };
    let chosen: Vec<&str> = stored
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();
    let kept: Vec<&ListColumn> = allowed
        .iter()
        .copied()
        .filter(|c| chosen.iter().any(|n| *n == c.field))
        .collect();
    if kept.is_empty() {
        return by_default();
    }
    kept
}

/// Checks a list against the column-type registry at router build, so a
/// descriptor naming a type nobody registered aborts boot naming the column,
/// the way a form does for a field type. Without this the cell rendered empty.
pub(crate) fn check(
    config: &ListConfig,
    column_types: &ColumnRegistry,
    permission_codes: &std::collections::HashSet<String>,
) -> Result<(), String> {
    if let Some(tree) = &config.tree {
        if !valid_ident(&tree.parent_key) {
            return Err(format!(
                "tree names an invalid parent column `{}`",
                tree.parent_key
            ));
        }
    }
    if let Some(reorder) = &config.reorder {
        if !valid_ident(&reorder.column) {
            return Err(format!(
                "reorder names an invalid column `{}`",
                reorder.column
            ));
        }
    }
    for col in &config.columns {
        if column_types.get(&col.column_type).is_none() {
            return Err(format!(
                "column `{}` uses unregistered type `{}`",
                col.field, col.column_type
            ));
        }
        // An unregistered permission can never be granted, so the column would
        // be hidden from everyone but a superuser: a wiring bug, not a choice.
        if let Some(p) = &col.permission {
            if !permission_codes.contains(p) {
                return Err(format!(
                    "column `{}` requires unregistered permission `{p}`",
                    col.field
                ));
            }
        }
    }
    for filter in &config.filters {
        if let Some(p) = &filter.permission {
            if !permission_codes.contains(p) {
                return Err(format!(
                    "filter `{}` requires unregistered permission `{p}`",
                    filter.field
                ));
            }
        }
    }
    Ok(())
}

/// The list's search box. On by default, over the columns marked searchable.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct SearchConfig {
    /// `false` removes the box.
    pub enabled: bool,
    /// The placeholder, localized at render. `None` shows "Search".
    pub prompt: Option<Text>,
    /// Ask on Enter only, instead of as the operator types.
    pub on_enter: bool,
}

impl Default for SearchConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            prompt: None,
            on_enter: false,
        }
    }
}

impl SearchConfig {
    /// No search box at all.
    pub fn off() -> Self {
        Self {
            enabled: false,
            ..Self::default()
        }
    }

    pub fn prompt(mut self, text: impl Into<Text>) -> Self {
        self.prompt = Some(text.into());
        self
    }

    pub fn on_enter(mut self) -> Self {
        self.on_enter = true;
        self
    }
}

/// The order rows keep of their own, held in an integer column (not null,
/// default `0`). Keys are spaced by a thousand so a move rewrites one row; a
/// move into a closed gap renumbers the list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct ReorderConfig {
    /// The integer column holding each row's position. Default `sort_order`.
    pub column: String,
}

impl Default for ReorderConfig {
    fn default() -> Self {
        Self {
            column: "sort_order".to_string(),
        }
    }
}

/// `reorder: true` takes the default column; `reorder: { column: position }`
/// names one; `false` or absent is off.
fn deserialize_reorder<'de, D>(deserializer: D) -> Result<Option<ReorderConfig>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Key {
        Flag(bool),
        Config(ReorderConfig),
    }
    Ok(match Option::<Key>::deserialize(deserializer)? {
        Some(Key::Flag(true)) => Some(ReorderConfig::default()),
        Some(Key::Flag(false)) | None => None,
        Some(Key::Config(config)) => Some(config),
    })
}

/// The spacing between keys after a renumber, and the step past either end.
const REORDER_STEP: i64 = 1000;

/// Rows that form a tree through a parent column (adjacency): the list opens
/// on the rows with no parent, each row with children expands in place, and
/// a row can be moved under another parent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct TreeConfig {
    /// The column holding a row's parent id, null at the top level. Default
    /// `parent_id`.
    pub parent_key: String,
    /// A registered picker source over this entity. When set, every row
    /// offers "Move to", which picks the new parent from it; empty means the
    /// top level.
    pub source: Option<String>,
}

impl TreeConfig {
    /// A tree on `parent_key`.
    pub fn new(parent_key: impl Into<String>) -> Self {
        Self {
            parent_key: parent_key.into(),
            source: None,
        }
    }

    /// Offers "Move to" on every row, picking the new parent from `source`.
    pub fn move_to(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }
}

impl Default for TreeConfig {
    fn default() -> Self {
        Self::new("parent_id")
    }
}

/// `tree: true` takes the default parent column; `tree: { parent_key, source }`
/// names them; `false` or absent is off.
fn deserialize_tree<'de, D>(deserializer: D) -> Result<Option<TreeConfig>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Key {
        Flag(bool),
        Config(TreeConfig),
    }
    Ok(match Option::<Key>::deserialize(deserializer)? {
        Some(Key::Flag(true)) => Some(TreeConfig::default()),
        Some(Key::Flag(false)) | None => None,
        Some(Key::Config(config)) => Some(config),
    })
}

/// Children shown under one parent in a single request.
const TREE_CHILDREN_LIMIT: i64 = 1000;

/// The form an editable cell writes through.
#[derive(Clone)]
pub(crate) struct Editor(pub Arc<crate::form::PreparedForm>);

impl std::fmt::Debug for Editor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Editor")
    }
}

/// A list view descriptor: which table, which columns, default ordering, page
/// size, and (optionally) where per-row edit links point.
///
/// Built with [`ListConfig::new`] plus its builder methods. Non-exhaustive, so a
/// struct literal outside this crate cannot freeze the field set at 1.0; that
/// rules out `..Default::default()` too, which is why the builders exist.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct ListConfig {
    pub entity: String,
    /// The screen title, localized at render. Serde stays a plain string.
    pub title: Text,
    #[serde(
        deserialize_with = "crate::keyed::deserialize",
        serialize_with = "crate::keyed::serialize"
    )]
    pub columns: Vec<ListColumn>,
    pub order_by: String,
    pub order_dir: SortDir,
    pub per_page: i64,
    pub id_field: String,
    /// When set, rows link to `{edit_base}/{id}/edit`.
    pub edit_base: Option<String>,
    /// Whether to offer a "New" link to `{edit_base}/new`. A resource that only
    /// edits existing records (no create screen) sets this false.
    pub creatable: bool,
    /// Filters offered above the table. Empty hides the bar.
    #[serde(
        deserialize_with = "crate::keyed::deserialize",
        serialize_with = "crate::keyed::serialize"
    )]
    pub filters: Vec<ListFilter>,
    /// Whether rows can be selected and deleted from this list. Off by default:
    /// a list that shows a log, or records another screen owns, has no business
    /// offering it.
    pub deletable: bool,
    /// Whether this resource offers an export. Off by default: exporting is a
    /// capability a resource opts into, not something every list should carry.
    pub exportable: bool,
    /// The import pages mounted under this resource, when it declared
    /// `import`; shown beside the export menu to an operator holding the
    /// permission. Set by the router from the resource, never by a descriptor.
    #[serde(skip)]
    pub(crate) import: Option<ImportLink>,
    /// A fixed condition every query carries. Set per request by a relation
    /// section, never by a descriptor.
    #[serde(skip)]
    pub(crate) scope: Option<Scope>,
    /// Rows kept in an order of their own, held in an integer column. Off by
    /// default; `reorder: true` in a file orders by `sort_order`.
    #[serde(deserialize_with = "deserialize_reorder")]
    pub reorder: Option<ReorderConfig>,
    /// Rows shown as a tree on their own parent column. Off by default;
    /// `tree: true` in a file reads `parent_id`.
    #[serde(deserialize_with = "deserialize_tree")]
    pub tree: Option<TreeConfig>,
    /// The resource's form, prepared, behind the editable cells. Set by the
    /// router, never by a descriptor.
    #[serde(skip)]
    pub(crate) editor: Option<Editor>,
    /// Extra buttons in the toolbar, beside New and the export menu.
    pub toolbar: Vec<ToolbarButton>,
    pub search: SearchConfig,
    /// Page sizes the operator may choose from in the list setup, remembered
    /// with their column choice. Empty offers no choice.
    pub per_page_options: Vec<i64>,
    /// Shown when the list has no records at all. `None` shows "No records yet."
    pub no_records_message: Option<Text>,
    /// What clicking a row does. Default `open`: the row opens its record when
    /// the list has an `edit_base`.
    pub row_click: RowClick,
    /// Whether the sort, search, filters and page an operator last used come
    /// back when they return to the list. Default `true`.
    pub remember: bool,
}

/// What clicking a list row does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RowClick {
    /// Opens the record, when the list links rows to a form.
    #[default]
    Open,
    /// Nothing: only the Edit link opens it.
    None,
}

impl ListConfig {
    /// A list over `entity` titled `title`, showing `columns`.
    ///
    /// Everything else takes the defaults below and is opted into through a
    /// builder method, so a field added later costs existing descriptors nothing.
    pub fn new(
        entity: impl Into<String>,
        title: impl Into<Text>,
        columns: Vec<ListColumn>,
    ) -> Self {
        Self {
            entity: entity.into(),
            title: title.into(),
            columns,
            ..Self::default()
        }
    }

    /// Orders by `column` in `dir` rather than newest id first.
    pub fn order(mut self, column: impl Into<String>, dir: SortDir) -> Self {
        self.order_by = column.into();
        self.order_dir = dir;
        self
    }

    pub fn per_page(mut self, rows: i64) -> Self {
        self.per_page = rows;
        self
    }

    /// The primary-key column, when it is not `id`.
    pub fn id_field(mut self, column: impl Into<String>) -> Self {
        self.id_field = column.into();
        self
    }

    /// Links rows to `{base}/{id}/edit`.
    pub fn edit_base(mut self, base: impl Into<String>) -> Self {
        self.edit_base = Some(base.into());
        self
    }

    /// Offers a New link to `{edit_base}/new`. Opt in, matching the read-only
    /// default: a list over a log, or over records another screen owns, should
    /// not invite an operator to create one.
    pub fn creatable(mut self) -> Self {
        self.creatable = true;
        self
    }

    /// Offers CSV and JSON exports of the current query. Opt in: a resource
    /// whose rows should not leave the panel simply never calls this, and the
    /// route is not registered for it.
    pub fn exportable(mut self) -> Self {
        self.exportable = true;
        self
    }

    pub fn filters(mut self, filters: Vec<ListFilter>) -> Self {
        self.filters = filters;
        self
    }

    /// Lets rows be selected and deleted. Off by default: a list showing a log,
    /// or records another screen owns, has no business offering it.
    pub fn deletable(mut self) -> Self {
        self.deletable = true;
        self
    }

    /// Shows the rows as a tree on their parent column: the list opens on the
    /// top level, and a row with children expands in place.
    pub fn tree(mut self, tree: TreeConfig) -> Self {
        self.tree = Some(tree);
        self
    }

    /// Keeps the rows in an order of their own, held in `column`: the list
    /// opens in that order with a grip and Move up / Move down on every row.
    pub fn reorder(mut self, column: impl Into<String>) -> Self {
        self.reorder = Some(ReorderConfig {
            column: column.into(),
        });
        self
    }

    pub fn toolbar(mut self, buttons: Vec<ToolbarButton>) -> Self {
        self.toolbar = buttons;
        self
    }

    pub fn search(mut self, search: SearchConfig) -> Self {
        self.search = search;
        self
    }

    pub fn per_page_options(mut self, sizes: Vec<i64>) -> Self {
        self.per_page_options = sizes;
        self
    }

    pub fn no_records_message(mut self, text: impl Into<Text>) -> Self {
        self.no_records_message = Some(text.into());
        self
    }

    /// What clicking a row does. Default: it opens the record.
    pub fn row_click(mut self, action: RowClick) -> Self {
        self.row_click = action;
        self
    }

    /// Whether the query an operator last used comes back when they return.
    /// Default `true`.
    pub fn remember(mut self, remember: bool) -> Self {
        self.remember = remember;
        self
    }
}

impl Default for ListConfig {
    /// A minimal list: no columns, newest-id first, 25 to a page, read-only.
    ///
    /// Descriptors use this as the tail of a struct literal
    /// (`..Default::default()`) and set only what they mean. A field added here
    /// later is then additive for every descriptor rather than breaking it, which
    /// three consecutive additions made the case for.
    fn default() -> Self {
        Self {
            entity: String::new(),
            title: Text::new(""),
            columns: Vec::new(),
            order_by: "id".to_string(),
            order_dir: SortDir::Desc,
            per_page: 25,
            id_field: "id".to_string(),
            edit_base: None,
            creatable: false,
            filters: Vec::new(),
            deletable: false,
            exportable: false,
            import: None,
            scope: None,
            reorder: None,
            tree: None,
            editor: None,
            toolbar: Vec::new(),
            search: SearchConfig::default(),
            per_page_options: Vec::new(),
            no_records_message: None,
            row_click: RowClick::Open,
            remember: true,
        }
    }
}

/// Query-string parameters for a list view.
#[derive(Deserialize, Default)]
pub struct ListParams {
    page: Option<i64>,
    sort: Option<String>,
    dir: Option<String>,
    q: Option<String>,
    /// A tree's parent to show the children of; absent is the top level.
    parent: Option<String>,
    /// How deep those children sit, for their indent.
    depth: Option<i64>,
}

/// The ordering a request resolves to: the submitted `sort` when it names a
/// column the descriptor declares, the descriptor's own order otherwise. Only a
/// declared column reaches the query, so a crafted `sort` cannot order by an
/// arbitrary column. An unrecognised `dir` falls back the same way.
pub(crate) fn resolve_sort(
    config: &ListConfig,
    sort: Option<&str>,
    dir: Option<&str>,
) -> (String, SortDir) {
    let (natural, natural_dir) = natural_order(config);
    let by = match sort.filter(|s| config.columns.iter().any(|c| c.field == *s && c.sortable)) {
        Some(field) => field.to_string(),
        None => natural.to_string(),
    };
    let dir = match dir {
        Some("asc") => SortDir::Asc,
        Some("desc") => SortDir::Desc,
        // No explicit direction: the configured one for the configured column, so
        // a list ordered newest-first stays that way until a header is clicked.
        _ if by == natural => natural_dir,
        _ => SortDir::Asc,
    };
    (by, dir)
}

/// The order a list opens in: its own column ascending when rows keep an
/// order, else the descriptor's `order_by`.
fn natural_order(config: &ListConfig) -> (&str, SortDir) {
    match &config.reorder {
        Some(reorder) => (&reorder.column, SortDir::Asc),
        None => (&config.order_by, config.order_dir),
    }
}

/// One rendered row: its id (for edit links) and its display cells.
pub struct RowView {
    pub id: String,
    pub cells: Vec<String>,
    /// How many rows name this one as parent, when the query asked.
    pub children: i64,
}

/// One rendered cell and the class its column's alignment gives it.
pub struct CellView {
    pub html: String,
    pub class: String,
}

/// A row as the template receives it: each cell already rendered.
pub struct RenderedRow {
    pub id: String,
    pub cells: Vec<CellView>,
    /// The tree position: how deep the row sits, and where its children load
    /// from when it has any.
    pub depth: i64,
    pub indent: String,
    pub toggle: Option<String>,
}

/// Display-ready rows plus the total row count for the pager.
pub struct ListPage {
    pub rows: Vec<RowView>,
    pub total: i64,
}

/// What one list request asks for: the page window, the resolved ordering, and
/// the search term (empty for no search).
pub(crate) struct ListQuery<'a> {
    pub offset: i64,
    pub order_by: &'a str,
    pub order_dir: SortDir,
    pub q: &'a str,
    pub filters: &'a [ActiveFilter<'a>],
    /// Rows per round trip. `None` uses the descriptor's page size; the export
    /// reads larger pages because it is building a file, not a screen.
    pub per_page: Option<i64>,
    /// A tree's parent column: each row then carries how many rows name it.
    pub children_of: Option<&'a str>,
}

/// A filter the request actually selected: the declared filter and its accepted
/// value. Built only from declared filters and, for a select, declared options,
/// so a crafted parameter cannot reach the query.
pub(crate) struct ActiveFilter<'a> {
    filter: &'a ListFilter,
    /// The raw value as submitted, for re-rendering the control and the links.
    raw: String,
    /// How the accepted value matches. Owned and `Send`, because a built
    /// `sea_query` expression is neither and this is held across the query.
    matcher: FilterMatch,
}

/// How an accepted filter value matches its column.
pub(crate) enum FilterMatch {
    /// Exactly this value.
    Equals(sea_query::Value),
    /// A folded substring, the way the search box matches.
    Contains(String),
    /// Anything starting with this, for a day against a stored timestamp.
    StartsWith(String),
}

/// How one filter matches for a submitted value, or `None` when the value is
/// not one this type accepts.
///
/// Every type validates before returning, so a crafted parameter reaches the
/// query only in a shape the filter declared.
fn filter_match(filter: &ListFilter, raw: &str) -> Option<FilterMatch> {
    match filter.filter_type.as_str() {
        // Only the two spellings the control emits; anything else is dropped
        // rather than guessed at.
        "boolean" => match raw {
            "1" => Some(FilterMatch::Equals(true.into())),
            "0" => Some(FilterMatch::Equals(false.into())),
            _ => None,
        },
        "select" => filter
            .choices()
            .iter()
            .any(|o| o.value == raw)
            .then(|| FilterMatch::Equals(raw.into())),
        "text" => Some(FilterMatch::Contains(raw.to_string())),
        "number" => raw
            .parse::<i64>()
            .ok()
            .map(|n| FilterMatch::Equals(n.into())),
        // A day, matched as a prefix so a date column and a stored timestamp
        // both answer. The shape is checked here, so the pattern that reaches
        // the query has nothing in it to escape.
        "date" => is_iso_date(raw).then(|| FilterMatch::StartsWith(raw.to_string())),
        _ => None,
    }
}

/// `YYYY-MM-DD`, and nothing else.
fn is_iso_date(raw: &str) -> bool {
    raw.len() == 10
        && raw.as_bytes().iter().enumerate().all(|(i, b)| {
            if i == 4 || i == 7 {
                *b == b'-'
            } else {
                b.is_ascii_digit()
            }
        })
}

/// Reads the declared filters out of the request's query parameters, dropping
/// anything undeclared, unrecognised, or blank.
pub(crate) fn resolve_filters<'a>(
    config: &'a ListConfig,
    params: &HashMap<String, String>,
) -> Vec<ActiveFilter<'a>> {
    let mut out = Vec::new();
    for filter in &config.filters {
        let submitted = params.get(&filter.param()).map(|v| v.trim());
        let raw = match submitted {
            // Named, so the operator decided: a blank value clears the filter.
            Some(value) => value,
            // Not named at all, so nothing has been decided yet.
            None => filter.default_value.as_deref().unwrap_or_default(),
        };
        if raw.is_empty() {
            continue;
        }
        let Some(matcher) = filter_match(filter, raw) else {
            continue;
        };
        out.push(ActiveFilter {
            filter,
            raw: raw.to_string(),
            matcher,
        });
    }
    out
}

/// The filters ANDed together, or `None` when none are active.
fn filter_condition(active: &[ActiveFilter<'_>]) -> Option<sea_query::Condition> {
    if active.is_empty() {
        return None;
    }
    let caps = laterite_core::capabilities::CapabilitySet::default();
    let mut all = sea_query::Condition::all();
    for f in active {
        let col = Expr::col(Alias::new(&f.filter.field));
        all = match &f.matcher {
            FilterMatch::Equals(value) => all.add(col.eq(value.clone())),
            // A term that folds away to nothing narrows nothing.
            FilterMatch::Contains(term) => {
                match SearchProfile::new().condition(&caps, &f.filter.field, term) {
                    Some(cond) => all.add(cond),
                    None => all,
                }
            }
            FilterMatch::StartsWith(prefix) => all.add(col.like(format!("{prefix}%"))),
        };
    }
    Some(all)
}

/// The condition matching `q` across the searchable columns, or `None` when
/// there is nothing to match: a blank term, a term that folds away, or a list
/// whose columns are all unsearchable.
fn search_condition(config: &ListConfig, q: &str) -> Option<sea_query::Condition> {
    // Capability-gated matchers are deferred and `Db` carries no
    // capability set yet, so the portable default applies. Descriptor-named
    // profiles are PR4; until then a list folds case, like the picker.
    let caps = laterite_core::capabilities::CapabilitySet::default();
    let profile = SearchProfile::new();
    let mut any = sea_query::Condition::any();
    let mut matched = false;
    for column in config.columns.iter().filter(|c| c.is_searchable()) {
        if let Some(cond) = profile.condition(&caps, &column.field, q) {
            any = any.add(cond);
            matched = true;
        }
    }
    matched.then_some(any)
}

/// What narrows a list to one parent record's rows: a relation section sets
/// it per request.
#[derive(Clone, Debug)]
pub(crate) enum Scope {
    /// Rows whose `column` equals `value`, or is null when there is none: a
    /// has-many's foreign key, a tree's parent column.
    Column {
        column: String,
        value: Option<String>,
    },
    /// Rows a pivot table joins to the parent: those whose id appears as
    /// `related_key` on a pivot row whose `parent_key` equals `value`. Each row
    /// is then identified by its pivot row's `id_field`, so the section's
    /// links and removals name the membership, never the record.
    Pivot {
        table: String,
        parent_key: String,
        related_key: String,
        id_field: String,
        value: String,
    },
}

impl Scope {
    fn idents_valid(&self) -> bool {
        match self {
            Scope::Column { column, .. } => valid_ident(column),
            Scope::Pivot {
                table,
                parent_key,
                related_key,
                id_field,
                ..
            } => {
                valid_ident(table)
                    && valid_ident(parent_key)
                    && valid_ident(related_key)
                    && valid_ident(id_field)
            }
        }
    }

    /// The condition every query and count carries.
    fn condition(&self, backend: DbBackend, entity_id: &str) -> SimpleExpr {
        let cast = Alias::new(text_cast(backend));
        match self {
            Scope::Column {
                column,
                value: Some(value),
            } => Expr::col(Alias::new(column))
                .cast_as(cast)
                .eq(value.clone()),
            Scope::Column {
                column,
                value: None,
            } => Expr::col(Alias::new(column)).is_null(),
            Scope::Pivot {
                table,
                parent_key,
                related_key,
                value,
                ..
            } => Expr::col(Alias::new(entity_id)).in_subquery(
                Query::select()
                    .column(Alias::new(related_key))
                    .from(Alias::new(table))
                    .and_where(
                        Expr::col(Alias::new(parent_key))
                            .cast_as(cast)
                            .eq(value.clone()),
                    )
                    .to_owned(),
            ),
        }
    }

    /// The expression identifying each row, when the scope changes it: the
    /// pivot row's id, found by a scalar subquery on the entity's own id.
    fn row_id(&self, backend: DbBackend, entity: &str, entity_id: &str) -> Option<SimpleExpr> {
        match self {
            Scope::Column { .. } => None,
            Scope::Pivot {
                table,
                parent_key,
                related_key,
                id_field,
                value,
            } => {
                let pivot = Alias::new("lat_pivot");
                Some(SimpleExpr::SubQuery(
                    None,
                    Box::new(
                        Query::select()
                            .column((pivot.clone(), Alias::new(id_field)))
                            .from_as(Alias::new(table), pivot.clone())
                            .and_where(
                                Expr::col((pivot.clone(), Alias::new(related_key)))
                                    .equals((Alias::new(entity), Alias::new(entity_id))),
                            )
                            .and_where(
                                Expr::col((pivot, Alias::new(parent_key)))
                                    .cast_as(Alias::new(text_cast(backend)))
                                    .eq(value.clone()),
                            )
                            .to_owned()
                            .into_sub_query_statement(),
                    ),
                ))
            }
        }
    }
}

/// Runs the list query for a config, returning display-ready rows and the total.
/// Built with `sea-query` and dynamic identifiers (`Alias`), and every selected
/// column is cast to text so a value of any type reads back uniformly as a
/// string for display, without a Postgres-specific `row_to_json`.
pub(crate) async fn query(
    db: &Db,
    config: &ListConfig,
    req: &ListQuery<'_>,
) -> anyhow::Result<ListPage> {
    if !valid_ident(&config.entity)
        || !valid_ident(&config.order_by)
        || !valid_ident(req.order_by)
        || !valid_ident(&config.id_field)
        || !config.columns.iter().all(|c| valid_ident(&c.field))
        || !config.filters.iter().all(|f| valid_ident(&f.field))
        || !config.scope.iter().all(Scope::idents_valid)
    {
        anyhow::bail!("invalid identifier in list config for '{}'", config.entity);
    }

    let dir = match req.order_dir {
        SortDir::Asc => Order::Asc,
        SortDir::Desc => Order::Desc,
    };
    // Scope each sea-query builder so it drops before the await that follows: its
    // identifiers are reference-counted (not `Send`), and a live builder across
    // the await would make this future non-`Send`.
    let (sql, values) = {
        let mut select = Query::select();
        for column in &config.columns {
            select.expr_as(
                Expr::col(Alias::new(&column.field)).cast_as(Alias::new(text_cast(db.backend))),
                Alias::new(&column.field),
            );
        }
        let row_id = config
            .scope
            .as_ref()
            .and_then(|scope| scope.row_id(db.backend, &config.entity, &config.id_field))
            .unwrap_or_else(|| Expr::col(Alias::new(&config.id_field)).into());
        select
            .expr_as(
                row_id.cast_as(Alias::new(text_cast(db.backend))),
                Alias::new(ID_ALIAS),
            )
            .from(Alias::new(&config.entity))
            .order_by(Alias::new(req.order_by), dir);
        if let Some(parent_key) = req.children_of {
            let child = Alias::new("lat_child");
            select.expr_as(
                SimpleExpr::SubQuery(
                    None,
                    Box::new(
                        Query::select()
                            .expr(Expr::col((child.clone(), Alias::new(&config.id_field))).count())
                            .from_as(Alias::new(&config.entity), child.clone())
                            .and_where(
                                Expr::col((child, Alias::new(parent_key))).equals((
                                    Alias::new(&config.entity),
                                    Alias::new(&config.id_field),
                                )),
                            )
                            .to_owned()
                            .into_sub_query_statement(),
                    ),
                )
                .cast_as(Alias::new(text_cast(db.backend))),
                Alias::new("lat_children"),
            );
        }
        // Ties fall back to the id, so paging and reordering see one order.
        if req.order_by != config.id_field {
            select.order_by(Alias::new(&config.id_field), Order::Asc);
        }
        select
            .limit(req.per_page.unwrap_or(config.per_page).max(0) as u64)
            .offset(req.offset.max(0) as u64);
        if let Some(cond) = search_condition(config, req.q) {
            select.cond_where(cond);
        }
        if let Some(cond) = filter_condition(req.filters) {
            select.cond_where(cond);
        }
        if let Some(scope) = &config.scope {
            select.and_where(scope.condition(db.backend, &config.id_field));
        }
        build(db.backend, select)
    };
    let raw = bind_values(sqlx::query(&sql), values)
        .fetch_all(&db.pool)
        .await?;

    let (csql, cvalues) = {
        let mut count = Query::select();
        count
            .expr(Expr::col(Alias::new(&config.id_field)).count())
            .from(Alias::new(&config.entity));
        // The same conditions, so the pager counts what the list returns.
        if let Some(cond) = search_condition(config, req.q) {
            count.cond_where(cond);
        }
        if let Some(cond) = filter_condition(req.filters) {
            count.cond_where(cond);
        }
        if let Some(scope) = &config.scope {
            count.and_where(scope.condition(db.backend, &config.id_field));
        }
        build(db.backend, count)
    };
    let total: i64 = bind_values_as(sqlx::query_as::<_, (i64,)>(&csql), cvalues)
        .fetch_one(&db.pool)
        .await?
        .0;

    let rows = raw
        .iter()
        .map(|row| RowView {
            id: get_text(row, ID_ALIAS),
            cells: config
                .columns
                .iter()
                .map(|c| get_text(row, &c.field))
                .collect(),
            children: match req.children_of {
                Some(_) => get_text(row, "lat_children").trim().parse().unwrap_or(0),
                None => 0,
            },
        })
        .collect();
    Ok(ListPage { rows, total })
}

/// Reads a text-cast column as a display string, treating null or a decode
/// error as empty.
fn get_text(row: &sqlx::any::AnyRow, column: &str) -> String {
    // `get_text_opt` falls back to a byte read for MySQL, where a cast-to-char of
    // a `text` column still comes back typed as BLOB.
    row.get_text_opt(column).ok().flatten().unwrap_or_default()
}

/// Renders a list view for the given config, remembering nothing.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    params: ListParams,
    raw: &HashMap<String, String>,
    user: &laterite_auth::AuthenticatedUser,
    shell: crate::Shell,
    headers: &axum::http::HeaderMap,
) -> Response {
    handle_remembering(
        state, config, path, params, raw, user, shell, headers, None, None,
    )
    .await
}

/// The query as a request narrows the list, with the parts a return should
/// bring back: the sort when it is not the descriptor's own, the search, the
/// filters. The page is left out, since the rows behind it move.
fn query_to_remember(
    config: &ListConfig,
    params: &ListParams,
    active: &[ActiveFilter<'_>],
) -> Option<String> {
    let mut parts = Vec::new();
    let (by, dir) = resolve_sort(config, params.sort.as_deref(), params.dir.as_deref());
    let (natural, natural_dir) = natural_order(config);
    if by != natural || dir != natural_dir {
        let dir = match dir {
            SortDir::Asc => "asc",
            SortDir::Desc => "desc",
        };
        parts.push(format!("sort={}&dir={dir}", urlencode(&by)));
    }
    if let Some(q) = params.q.as_deref().map(str::trim).filter(|q| !q.is_empty()) {
        parts.push(format!("q={}", urlencode(q)));
    }
    for f in active {
        parts.push(format!("{}={}", f.filter.param(), urlencode(&f.raw)));
    }
    (!parts.is_empty()).then(|| parts.join("&"))
}

/// [`handle`], remembering the query in the session when the list asks to.
///
/// A request with no query at all is sent to the query the operator last used;
/// a request with one records it, and one that narrows nothing forgets it. Only
/// a plain page load is redirected: a swap always names what it wants.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_remembering(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    params: ListParams,
    raw: &HashMap<String, String>,
    user: &laterite_auth::AuthenticatedUser,
    shell: crate::Shell,
    headers: &axum::http::HeaderMap,
    query_string: Option<&str>,
    session: Option<&crate::session::SessionHandle>,
) -> Response {
    if let Some(session) = session.filter(|_| config.remember) {
        match query_string.filter(|q| !q.is_empty()) {
            None if !crate::form::is_htmx(headers) => {
                if let Some(remembered) = session.remembered_list(path) {
                    return axum::response::Redirect::to(&format!("{path}?{remembered}"))
                        .into_response();
                }
            }
            None => {}
            Some(_) => {
                let active = resolve_filters(config, raw);
                let keep = query_to_remember(config, &params, &active);
                session.remember_list(path, keep.as_deref());
            }
        }
    }
    show(state, config, path, params, raw, user, shell, headers).await
}

/// Renders the list for the request as it stands.
#[allow(clippy::too_many_arguments)]
async fn show(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    params: ListParams,
    raw: &HashMap<String, String>,
    user: &laterite_auth::AuthenticatedUser,
    shell: crate::Shell,
    headers: &axum::http::HeaderMap,
) -> Response {
    let children = params.parent.is_some();
    match build_page(state, config, path, params, raw, user, shell).await {
        // An htmx request gets the list region alone, which replaces itself in
        // place; anything else gets the whole page, so sorting and paging still
        // work as ordinary links with scripting off. A tree row expanding asks
        // for its children and gets the rows alone.
        Some(page_view) => {
            if crate::form::is_htmx(headers) && children && page_view.tree.is_some() {
                render(rows_of(page_view, "lat-list", None))
            } else if crate::form::is_htmx(headers) {
                render(fragment_of(page_view, "lat-list", None))
            } else {
                render(page_view)
            }
        }
        None => render_error(),
    }
}

/// The list page as a template, or `None` when the query failed.
async fn build_page(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    params: ListParams,
    raw: &HashMap<String, String>,
    user: &laterite_auth::AuthenticatedUser,
    shell: crate::Shell,
) -> Option<ListTemplate> {
    // The operator's chosen columns narrow the descriptor once, here, so
    // everything downstream (the query, the headers, sorting, searching) works
    // from one list: what is shown is what is queried.
    let stored = stored_columns(state, path, user).await;
    let declared = config;
    let narrowed = narrowed(config, stored.as_deref(), user);
    let config = &narrowed;

    let page = params.page.unwrap_or(1).max(1);
    let per_page = stored_per_page(state, config, path, user).await;
    let (order_by, order_dir) = resolve_sort(config, params.sort.as_deref(), params.dir.as_deref());
    let q = params.q.unwrap_or_default();
    let active = resolve_filters(config, raw);
    // The list's own order, whole: what the grip and the tree both need. A
    // sorted, searched or filtered view is a flat result.
    let (natural, natural_dir) = natural_order(config);
    let own_order =
        order_by == natural && order_dir == natural_dir && q.trim().is_empty() && active.is_empty();
    let reorder = config
        .reorder
        .as_ref()
        .filter(|_| own_order)
        .map(|_| ReorderView {
            path: format!("{path}/reorder"),
            page,
            parent: params.parent.clone().unwrap_or_default(),
        });
    // In structure the query is scoped to one parent's children: the top
    // level by default, or the parent asked for.
    let structure = config.tree.as_ref().filter(|_| own_order);
    let scoped;
    let config = match structure {
        Some(tree) => {
            let mut c = config.clone();
            c.scope = Some(Scope::Column {
                column: tree.parent_key.clone(),
                value: params.parent.clone(),
            });
            scoped = c;
            &scoped
        }
        None => config,
    };
    let under_parent = structure.is_some() && params.parent.is_some();
    let depth = if under_parent {
        params.depth.unwrap_or(1).max(1)
    } else {
        0
    };
    // A parent's children show together, since they expand in place.
    let per_page = if under_parent {
        TREE_CHILDREN_LIMIT
    } else {
        per_page
    };
    let offset = (page - 1) * per_page;
    let tree = structure.map(|t| TreeView {
        move_path: t.source.as_ref().map(|_| path.to_string()),
    });
    let crumbs = match (structure, &params.parent) {
        (Some(t), Some(parent)) => crumbs(&state.db, config, t, parent, path).await,
        _ => Vec::new(),
    };
    let req = ListQuery {
        offset,
        order_by: &order_by,
        order_dir,
        q: q.trim(),
        filters: &active,
        per_page: Some(per_page),
        children_of: structure.map(|t| t.parent_key.as_str()),
    };
    // Everything a sort or pager link must preserve, as raw `&k=v` pairs. Askama
    // escapes it into the href, so the ampersands are correct in the markup.
    let mut carry = String::new();
    if !q.trim().is_empty() {
        carry.push_str(&format!("&q={}", urlencode(q.trim())));
    }
    for f in &active {
        carry.push_str(&format!("&{}={}", f.filter.param(), urlencode(&f.raw)));
    }
    let result = query(&state.db, config, &req).await.ok()?;
    {
        {
            let total_pages = ((result.total + per_page - 1) / per_page).max(1);
            let date_loc = date_locale(shell.locale());
            // Each column's labels, localized once for the page.
            let labels: Vec<Option<HashMap<String, String>>> = config
                .columns
                .iter()
                .map(|c| {
                    (!c.labels.is_empty()).then(|| {
                        c.labels
                            .iter()
                            .map(|l| (l.value.clone(), shell.tt(&l.label)))
                            .collect()
                    })
                })
                .collect();
            let rows: Vec<RenderedRow> = result
                .rows
                .into_iter()
                .map(|row| RenderedRow {
                    depth,
                    indent: format!("{}px", 16 + depth * 18),
                    toggle: (structure.is_some() && row.children > 0)
                        .then(|| format!("{path}?parent={}&depth={}", row.id, depth + 1)),
                    id: row.id.clone(),
                    cells: row
                        .cells
                        .iter()
                        .zip(config.columns.iter().zip(&labels))
                        .map(|(raw, (col, labels))| {
                            let cx = CellCx {
                                value: raw,
                                tz: shell.tz,
                                locale: date_loc,
                            };
                            let scope = OverrideScope {
                                surface: Surface::Column,
                                view_key: &col.column_type,
                                resource: Some(&config.entity),
                                field: Some(&col.field),
                            };
                            let html = match (&config.editor, col.editable) {
                                (Some(editor), true) => cell_markup(
                                    state, &editor.0, path, &row.id, &col.field, raw, &shell, None,
                                ),
                                _ => match state.column_types.get(&col.column_type) {
                                    Some(ct) => render_cell(
                                        ct.as_ref(),
                                        state.overrides.as_ref(),
                                        &scope,
                                        &cx,
                                        labels.as_ref(),
                                    )
                                    .into_string(),
                                    // Unreachable: `check` refused the type at boot.
                                    None => String::new(),
                                },
                            };
                            CellView {
                                html,
                                class: col.align_class().to_string(),
                            }
                        })
                        .collect(),
                })
                .collect();
            let editable_assets: Vec<&'static str> = match &config.editor {
                Some(editor) => config
                    .columns
                    .iter()
                    .filter(|c| c.editable)
                    .flat_map(|c| editor.0.field_assets(&c.field))
                    .collect(),
                None => Vec::new(),
            };
            let keys: Vec<&str> = config
                .columns
                .iter()
                .filter_map(|c| state.column_types.get(&c.column_type).map(|ct| ct.assets()))
                .flatten()
                .chain(editable_assets)
                .collect();
            let mut shell = shell;
            shell.assets = crate::page_assets(&keys, &shell.base, &state.assets, &state.asset_urls);
            let shown = rows.len() as i64;
            // Localize the title and column headers before the shell is moved in.
            let title = shell.tt(&config.title);
            let active_dir = match order_dir {
                SortDir::Asc => "asc",
                SortDir::Desc => "desc",
            };
            let columns: Vec<ColumnHead> = config
                .columns
                .iter()
                .map(|c| {
                    let active = c.field == order_by;
                    ColumnHead {
                        label: shell.tt(&c.label),
                        field: c.field.clone(),
                        // Clicking the sorted column flips it; any other column
                        // starts ascending.
                        next_dir: if active && active_dir == "asc" {
                            "desc".to_string()
                        } else {
                            "asc".to_string()
                        },
                        active: if active {
                            active_dir.to_string()
                        } else {
                            String::new()
                        },
                        sortable: c.sortable,
                        width: c.width.clone(),
                        align_class: c.align_class().to_string(),
                    }
                })
                .collect();
            let shell_for_toolbar = shell.clone();
            let filter_views = filter_views(config, &active, &shell);
            let pickers: Vec<ColumnChoice> = allowed_columns(declared, user)
                .into_iter()
                .map(|c| ColumnChoice {
                    field: c.field.clone(),
                    label: shell.tt(&c.label),
                    shown: config.columns.iter().any(|v| v.field == c.field),
                })
                .collect();
            // Built before the literal moves `order_by` into `sort`.
            let export_query = format!("&sort={order_by}&dir={active_dir}{carry}");
            let toolbar = toolbar_views(declared, &state.admin_path, user, &shell_for_toolbar);
            // Localized before the literal moves `shell` in.
            let search_prompt = config.search.prompt.as_ref().map(|p| shell.tt(p));
            let no_records_message = config.no_records_message.as_ref().map(|m| shell.tt(m));
            let page_view = ListTemplate {
                shell,
                title,
                columns,
                rows,
                shown,
                page,
                total: result.total,
                total_pages,
                edit_base: config.edit_base.clone(),
                row_link: config.row_click == RowClick::Open,
                sort: order_by,
                dir: active_dir.to_string(),
                q: q.trim().to_string(),
                searchable: config.search.enabled
                    && config.columns.iter().any(|c| c.is_searchable()),
                search_prompt,
                search_on_enter: config.search.on_enter,
                no_records_message,
                per_page,
                per_page_options: config.per_page_options.clone(),
                pickers,
                toolbar,
                export_query,
                path: path.to_string(),
                filters: filter_views,
                deletable: config.deletable,
                exportable: config.exportable,
                import_href: config
                    .import
                    .as_ref()
                    .filter(|link| user.permissions.allows(&link.permission))
                    .map(|link| link.href.clone()),
                filtered: !active.is_empty() || !q.trim().is_empty(),
                carry: carry.clone(),
                region: "lat-list".to_string(),
                delete_path: None,
                reorder,
                tree,
                crumbs,
            };
            Some(page_view)
        }
    }
}

/// A per-row action posted with the row's id, for a list with no action bar of
/// its own: a section's Delete, or a membership's Remove.
#[derive(Clone, Debug)]
pub(crate) struct RowAction {
    pub path: String,
    pub label: String,
    pub confirm: String,
    /// The glyph on the button; the label is its name for assistive tech.
    pub icon: &'static str,
}

/// What the grip and Move buttons post to, and the page to come back to.
#[derive(Clone, Debug)]
pub(crate) struct ReorderView {
    pub path: String,
    pub page: i64,
    /// The tree parent the rows sit under, empty at the top level, so a move
    /// stays among siblings.
    pub parent: String,
}

/// The tree's row furniture.
#[derive(Clone, Debug)]
pub(crate) struct TreeView {
    /// The list path, when rows offer "Move to"; the link is `{path}/{id}/move`.
    pub move_path: Option<String>,
}

/// One step of the way down to a parent.
pub(crate) struct Crumb {
    pub label: String,
    pub href: String,
}

/// The way down to `parent`: the top level, then each ancestor by its first
/// column, nearest last.
async fn crumbs(
    db: &Db,
    config: &ListConfig,
    tree: &TreeConfig,
    parent: &str,
    path: &str,
) -> Vec<Crumb> {
    let mut trail = Vec::new();
    let mut current = Some(parent.to_string());
    // A cycle in the data would otherwise walk forever.
    for _ in 0..64 {
        let Some(id) = current.take() else { break };
        match parent_row(db, config, tree, &id).await {
            Ok(Some((label, above))) => {
                trail.push(Crumb {
                    label,
                    href: format!("{path}?parent={id}"),
                });
                current = above;
            }
            _ => break,
        }
    }
    trail.push(Crumb {
        label: String::new(),
        href: path.to_string(),
    });
    trail.reverse();
    trail
}

/// A row's label (its first column) and its parent, or `None` when there is
/// no such row.
async fn parent_row(
    db: &Db,
    config: &ListConfig,
    tree: &TreeConfig,
    id: &str,
) -> anyhow::Result<Option<(String, Option<String>)>> {
    let label_col = config
        .columns
        .first()
        .map(|c| c.field.as_str())
        .unwrap_or(&config.id_field);
    let (sql, values) = {
        let cast = Alias::new(text_cast(db.backend));
        build(
            db.backend,
            Query::select()
                .expr_as(
                    Expr::col(Alias::new(label_col)).cast_as(cast.clone()),
                    Alias::new("lat_label"),
                )
                .expr_as(
                    Expr::col(Alias::new(&tree.parent_key)).cast_as(cast.clone()),
                    Alias::new("lat_parent"),
                )
                .from(Alias::new(&config.entity))
                .and_where(
                    Expr::col(Alias::new(&config.id_field))
                        .cast_as(cast)
                        .eq(id.to_string()),
                )
                .to_owned(),
        )
    };
    let row = bind_values(sqlx::query(&sql), values)
        .fetch_optional(&db.pool)
        .await?;
    Ok(row.map(|row| {
        let above = row.get_text("lat_parent").ok().filter(|p| !p.is_empty());
        (get_text(&row, "lat_label"), above)
    }))
}

/// One row's id and its position key, in the list's own order.
async fn ordered_keys(
    db: &Db,
    config: &ListConfig,
    column: &str,
) -> anyhow::Result<Vec<(String, i64)>> {
    let (sql, values) = {
        let cast = Alias::new(text_cast(db.backend));
        let mut select = Query::select();
        select
            .expr_as(
                Expr::col(Alias::new(&config.id_field)).cast_as(cast.clone()),
                Alias::new(ID_ALIAS),
            )
            .expr_as(
                Expr::col(Alias::new(column)).cast_as(cast),
                Alias::new("lat_key"),
            )
            .from(Alias::new(&config.entity))
            .order_by(Alias::new(column), Order::Asc)
            .order_by(Alias::new(&config.id_field), Order::Asc);
        if let Some(scope) = &config.scope {
            select.and_where(scope.condition(db.backend, &config.id_field));
        }
        build(db.backend, select)
    };
    let rows = bind_values(sqlx::query(&sql), values)
        .fetch_all(&db.pool)
        .await?;
    Ok(rows
        .iter()
        .map(|row| {
            let key = get_text(row, "lat_key").trim().parse().unwrap_or(0);
            (get_text(row, ID_ALIAS), key)
        })
        .collect())
}

/// Writes new position keys, all in one transaction.
async fn write_keys(
    db: &Db,
    config: &ListConfig,
    column: &str,
    changes: &[(String, i64)],
) -> anyhow::Result<()> {
    let mut tx = db.pool.begin().await?;
    for (id, key) in changes {
        let (sql, values) = build(
            db.backend,
            Query::update()
                .table(Alias::new(&config.entity))
                .value(Alias::new(column), *key)
                .and_where(
                    Expr::col(Alias::new(&config.id_field))
                        .cast_as(Alias::new(text_cast(db.backend)))
                        .eq(id.clone()),
                )
                .to_owned(),
        );
        bind_values(sqlx::query(&sql), values)
            .execute(&mut *tx)
            .await?;
    }
    tx.commit().await?;
    Ok(())
}

/// Where a row goes: one step either way, or beside a named row.
enum Move {
    Up,
    Down,
    Before(String),
    After(String),
}

/// The keys to write so that `id` lands at `target` in `order`: the moved
/// row's alone when a gap holds it, every row's when the list renumbers.
fn placement(order: &[(String, i64)], id: &str, target: usize) -> Vec<(String, i64)> {
    let mut ids: Vec<&str> = order.iter().map(|(i, _)| i.as_str()).collect();
    let from = match ids.iter().position(|i| *i == id) {
        Some(from) => from,
        None => return Vec::new(),
    };
    ids.remove(from);
    let target = target.min(ids.len());
    ids.insert(target, id);
    let key_of = |i: &str| {
        order
            .iter()
            .find(|(o, _)| o == i)
            .map(|(_, k)| *k)
            .unwrap_or(0)
    };
    let prev = target.checked_sub(1).map(|i| key_of(ids[i]));
    let next = ids.get(target + 1).map(|i| key_of(i));
    let key = match (prev, next) {
        (Some(a), Some(b)) if b - a >= 2 => Some(a + (b - a) / 2),
        (Some(a), None) => Some(a + REORDER_STEP),
        (None, Some(b)) => Some(b - REORDER_STEP),
        (None, None) => Some(key_of(id)),
        _ => None,
    };
    match key {
        Some(key) => vec![(id.to_string(), key)],
        None => ids
            .iter()
            .enumerate()
            .map(|(i, row)| (row.to_string(), (i as i64 + 1) * REORDER_STEP))
            .filter(|(row, key)| key_of(row) != *key)
            .collect(),
    }
}

/// Handles a posted move: `id` with `move=up|down`, `before=<id>` or
/// `after=<id>`, and the `page` to show again. An htmx request gets the list
/// region back; a plain one returns to that page of the list.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn reorder_handler(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    region: &str,
    row_action: Option<RowAction>,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    shell: crate::Shell,
    headers: &axum::http::HeaderMap,
    pairs: &[(String, String)],
) -> Response {
    let Some(reorder) = &config.reorder else {
        return crate::not_found();
    };
    let field = |name: &str| {
        pairs
            .iter()
            .find(|(k, _)| k == name)
            .map(|(_, v)| v.trim().to_string())
            .filter(|v| !v.is_empty())
    };
    let page = field("page")
        .and_then(|p| p.parse().ok())
        .unwrap_or(1)
        .max(1);
    // Under a tree the move stays among one parent's children.
    let parent = field("parent");
    let scoped;
    let config = match &config.tree {
        Some(tree) => {
            let mut c = config.clone();
            c.scope = Some(Scope::Column {
                column: tree.parent_key.clone(),
                value: parent.clone(),
            });
            scoped = c;
            &scoped
        }
        None => config,
    };
    let fatal = 'apply: {
        let (Some(id), Some(mv)) = (
            field("id"),
            match (field("move").as_deref(), field("before"), field("after")) {
                (Some("up"), _, _) => Some(Move::Up),
                (Some("down"), _, _) => Some(Move::Down),
                (_, Some(before), _) => Some(Move::Before(before)),
                (_, _, Some(after)) => Some(Move::After(after)),
                _ => None,
            },
        ) else {
            break 'apply false;
        };
        let order = match ordered_keys(&state.db, config, &reorder.column).await {
            Ok(order) => order,
            Err(e) => {
                tracing::error!(entity = %config.entity, error = %e, "reorder read failed");
                break 'apply true;
            }
        };
        let position = |needle: &str| order.iter().position(|(i, _)| i == needle);
        let Some(from) = position(&id) else {
            session.push_flash(
                crate::session::FlashLevel::Error,
                laterite_core::t!("That record is no longer in the list."),
            );
            break 'apply false;
        };
        let target = match mv {
            Move::Up => from.saturating_sub(1),
            Move::Down => from + 1,
            Move::Before(other) => match position(&other) {
                Some(p) if p > from => p - 1,
                Some(p) => p,
                None => from,
            },
            Move::After(other) => match position(&other) {
                Some(p) if p > from => p,
                Some(p) => p + 1,
                None => from,
            },
        };
        let changes = placement(&order, &id, target);
        if changes.is_empty() {
            break 'apply false;
        }
        if let Err(e) = write_keys(&state.db, config, &reorder.column, &changes).await {
            tracing::error!(entity = %config.entity, error = %e, "reorder write failed");
            break 'apply true;
        }
        crate::audit::record(
            state,
            user,
            &format!("{}.reorder", config.entity),
            Some(&config.entity),
            Some(&id),
            None,
            Some(&format!("position {}", target.min(order.len() - 1) + 1)),
        )
        .await;
        false
    };
    if fatal {
        return render_error();
    }
    if crate::form::is_htmx(headers) {
        let params = ListParams {
            page: Some(page),
            parent: parent.clone(),
            depth: field("depth").and_then(|d| d.parse().ok()),
            ..Default::default()
        };
        let Some(view) =
            build_page(state, config, path, params, &HashMap::new(), user, shell).await
        else {
            return render_error();
        };
        return if parent.is_some() && view.tree.is_some() {
            render(rows_of(view, region, row_action))
        } else {
            render(fragment_of(view, region, row_action))
        };
    }
    let back = match parent {
        Some(parent) => format!("{path}?parent={parent}&page={page}"),
        None => format!("{path}?page={page}"),
    };
    axum::response::Redirect::to(&back).into_response()
}

/// The "Move to" page: the row's parent, chosen from the tree's picker.
pub(crate) async fn move_form(
    state: &AdminState,
    config: &ListConfig,
    form: &crate::form::PreparedForm,
    path: &str,
    id: &str,
    shell: crate::Shell,
) -> Response {
    let Some(tree) = &config.tree else {
        return crate::not_found();
    };
    let current = match parent_row(&state.db, config, tree, id).await {
        Ok(Some((_, parent))) => parent.unwrap_or_default(),
        Ok(None) => return crate::not_found(),
        Err(_) => return render_error(),
    };
    let mut values = HashMap::new();
    values.insert(tree.parent_key.clone(), current);
    let action = format!("{path}/{id}/move");
    crate::form::page(state, form, &action, &values, &shell)
}

/// Moves a row under the chosen parent (none for the top level), refusing a
/// parent that is the row itself or sits beneath it.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn move_record(
    state: &AdminState,
    config: &ListConfig,
    form: &crate::form::PreparedForm,
    path: &str,
    id: &str,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    shell: crate::Shell,
    headers: &axum::http::HeaderMap,
    data: HashMap<String, String>,
) -> Response {
    let Some(tree) = &config.tree else {
        return crate::not_found();
    };
    match parent_row(&state.db, config, tree, id).await {
        Ok(Some(_)) => {}
        Ok(None) => return crate::not_found(),
        Err(_) => return render_error(),
    }
    let action = format!("{path}/{id}/move");
    let chosen = data
        .get(&tree.parent_key)
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty());
    let mut bag = laterite_core::validation::ErrorBag::default();
    if let Some(parent) = &chosen {
        // Walk up from the chosen parent: reaching the row itself would close
        // a loop, and a parent that is not there is no parent.
        let mut current = Some(parent.clone());
        let mut steps = 0;
        while let Some(at) = current.take() {
            if at == id {
                bag.add(
                    &tree.parent_key,
                    laterite_core::t!("A record cannot be moved under itself."),
                );
                break;
            }
            match parent_row(&state.db, config, tree, &at).await {
                Ok(Some((_, above))) => current = above,
                Ok(None) => {
                    bag.add(
                        &tree.parent_key,
                        laterite_core::t!("There is no such record."),
                    );
                    break;
                }
                Err(_) => return render_error(),
            }
            steps += 1;
            if steps > 64 {
                break;
            }
        }
    }
    let htmx = crate::form::is_htmx(headers);
    if !bag.is_empty() {
        return crate::form::refused(htmx, state, form, &action, None, &data, &bag, &shell);
    }
    let actor = laterite_core::Actor::from(user);
    let outcome = async {
        let mut tx = state
            .db
            .pool
            .begin()
            .await
            .map_err(|e| MoveFailure::Failed(e.to_string()))?;
        let mut cx = laterite_core::SaveCx::new(state.db.backend, &mut tx, actor);
        let request = crate::persist::MoveTo {
            entity: &config.entity,
            id_field: &config.id_field,
            id,
            parent_key: &tree.parent_key,
            parent: chosen.as_deref(),
        };
        form.persister()
            .move_to(&mut cx, &request)
            .await
            .map_err(|e| match e {
                crate::persist::SaveError::Invalid(bag) => MoveFailure::Refused(bag),
                crate::persist::SaveError::Failed(m) => MoveFailure::Failed(m),
            })?;
        tx.commit()
            .await
            .map_err(|e| MoveFailure::Failed(e.to_string()))
    }
    .await;
    match outcome {
        Ok(()) => {
            crate::audit::record(
                state,
                user,
                &format!("{}.move", config.entity),
                Some(&config.entity),
                Some(id),
                None,
                Some(&match &chosen {
                    Some(parent) => format!("under {parent}"),
                    None => "top level".to_string(),
                }),
            )
            .await;
            session.push_flash(
                crate::session::FlashLevel::Success,
                laterite_core::t!("Moved."),
            );
            let back = match chosen {
                Some(parent) => format!("{path}?parent={parent}"),
                None => path.to_string(),
            };
            crate::form::saved_response(htmx, &back)
        }
        Err(MoveFailure::Refused(bag)) => {
            crate::form::refused(htmx, state, form, &action, None, &data, &bag, &shell)
        }
        Err(MoveFailure::Failed(m)) => {
            tracing::error!(entity = %config.entity, id, error = %m, "move failed");
            crate::form::refused(
                htmx,
                state,
                form,
                &action,
                Some(laterite_core::t!("Could not move. Try again.")),
                &data,
                &bag,
                &shell,
            )
        }
    }
}

enum MoveFailure {
    Refused(laterite_core::validation::ErrorBag),
    Failed(String),
}

/// An editable cell: the field's control in a form of its own that saves on
/// change, with a Save button for a page without scripting. A refused value
/// comes back with its message beneath the control.
#[allow(clippy::too_many_arguments)]
fn cell_markup(
    state: &AdminState,
    form: &crate::form::PreparedForm,
    path: &str,
    id: &str,
    field: &str,
    value: &str,
    shell: &crate::Shell,
    error: Option<&str>,
) -> String {
    let dom_id = format!("cell-{id}-{field}");
    let control = form
        .control(state, field, &dom_id, value, shell)
        .unwrap_or_default();
    let action = format!("{path}/{id}/cell");
    let mut html = format!(
        r#"<form class="lat-cell{}" method="post" action="{action}" hx-post="{action}" hx-trigger="change, submit" hx-target="this" hx-swap="outerHTML" data-lat-widget="cell" data-lat-enter-scope><input type="hidden" name="_csrf" value="{}"><input type="hidden" name="field" value="{}">{control}<button class="lat-btn lat-btn--ghost lat-btn--sm lat-cell__save" type="submit">{}</button>"#,
        if error.is_some() { " is-invalid" } else { "" },
        crate::form::escape_attr(&shell.csrf_token),
        crate::form::escape_attr(field),
        shell.tt(&laterite_core::t!("Save")),
    );
    if let Some(message) = error {
        html.push_str(&format!(
            r#"<span class="lat-cell__error">{}</span>"#,
            crate::form::escape_attr(message)
        ));
    }
    html.push_str("</form>");
    html
}

/// Saves one cell: the row as it stands with the submitted field over it, written
/// through the form's rules, persister and listeners. An htmx request gets the
/// cell back, holding the stored value or the refusal; a plain one returns to
/// the list with a flash.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn cell_handler(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    id: &str,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    shell: crate::Shell,
    headers: &axum::http::HeaderMap,
    mut data: HashMap<String, String>,
) -> Response {
    let Some(editor) = &config.editor else {
        return crate::not_found();
    };
    let form = &editor.0;
    let Some(field) = data.remove("field") else {
        return crate::not_found();
    };
    data.remove("_csrf");
    if !config
        .columns
        .iter()
        .any(|c| c.editable && c.field == field)
        || !form.has_field(&field)
    {
        return crate::not_found();
    }
    let htmx = crate::form::is_htmx(headers);
    let back = path.to_string();
    let current = match crate::form::load_values(&state.db, form, id).await {
        Ok(Some(values)) => values,
        Ok(None) => return crate::not_found(),
        Err(_) => return render_error(),
    };
    // The row as stored, with the submission over it. The edited field is
    // taken from the submission alone, so a control that posts nothing when
    // cleared (a switch) clears it rather than keeping the stored value.
    let submitted = data.get(&field).cloned().unwrap_or_default();
    let mut merged = current.clone();
    merged.remove(&field);
    for (key, value) in data {
        merged.insert(key, value);
    }
    let merged = crate::form::gathered(form, merged);
    let actor = laterite_core::Actor::from(user);
    match crate::form::write(&state.db, form, &merged, Some(id), &actor).await {
        Ok(_) => {
            if htmx {
                let stored = crate::form::load_values(&state.db, form, id)
                    .await
                    .ok()
                    .flatten()
                    .and_then(|values| values.get(&field).cloned())
                    .unwrap_or(submitted);
                let html = cell_markup(state, form, path, id, &field, &stored, &shell, None);
                return axum::response::Html(html).into_response();
            }
            session.push_flash(
                crate::session::FlashLevel::Success,
                laterite_core::t!("Saved."),
            );
            crate::form::saved_response(false, &back)
        }
        Err(crate::persist::SaveError::Invalid(bag)) => {
            let message = bag
                .messages(&field)
                .first()
                .map(|m| shell.tt(m))
                .or_else(|| {
                    bag.iter()
                        .next()
                        .and_then(|(_, m)| m.first())
                        .map(|m| shell.tt(m))
                })
                .unwrap_or_else(|| shell.tt(&laterite_core::t!("Could not save.")));
            if htmx {
                let html = cell_markup(
                    state,
                    form,
                    path,
                    id,
                    &field,
                    &submitted,
                    &shell,
                    Some(&message),
                );
                return (
                    axum::http::StatusCode::UNPROCESSABLE_ENTITY,
                    axum::response::Html(html),
                )
                    .into_response();
            }
            session.push_flash(crate::session::FlashLevel::Error, Text::dynamic(message));
            crate::form::saved_response(false, &back)
        }
        Err(crate::persist::SaveError::Failed(m)) => {
            tracing::error!(entity = %config.entity, id, field, error = %m, "cell save failed");
            render_error()
        }
    }
}

/// The list region alone, cut out of a built page.
fn fragment_of(page: ListTemplate, region: &str, delete_path: Option<RowAction>) -> ListFragment {
    ListFragment {
        shell: page.shell,
        columns: page.columns,
        rows: page.rows,
        shown: page.shown,
        page: page.page,
        total: page.total,
        total_pages: page.total_pages,
        edit_base: page.edit_base,
        row_link: page.row_link,
        sort: page.sort,
        dir: page.dir,
        carry: page.carry,
        filtered: page.filtered,
        deletable: page.deletable,
        no_records_message: page.no_records_message,
        path: page.path,
        region: region.to_string(),
        delete_path,
        reorder: page.reorder,
        tree: page.tree,
    }
}

/// The rows alone, cut out of a built page.
fn rows_of(page: ListTemplate, region: &str, delete_path: Option<RowAction>) -> RowsFragment {
    RowsFragment {
        shell: page.shell,
        rows: page.rows,
        page: page.page,
        total_pages: page.total_pages,
        edit_base: page.edit_base,
        row_link: page.row_link,
        deletable: page.deletable,
        region: region.to_string(),
        delete_path,
        reorder: page.reorder,
        tree: page.tree,
    }
}

/// A list rendered as a region for another page to hold: a relation section on
/// a form. The query, sorting, paging and search work from `path`, and a
/// per-row delete posts to `delete_path` when there is one.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn fragment(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    params: ListParams,
    raw: &HashMap<String, String>,
    user: &laterite_auth::AuthenticatedUser,
    shell: crate::Shell,
    region: &str,
    delete_path: Option<RowAction>,
) -> Result<crate::html::Markup, ()> {
    let page = build_page(state, config, path, params, raw, user, shell)
        .await
        .ok_or(())?;
    crate::html::Markup::from_template(&fragment_of(page, region, delete_path)).map_err(|_| ())
}

/// Stores which columns this operator wants on this list.
///
/// Choosing every column clears the preference rather than storing them all, so
/// the operator keeps following the descriptor as it gains or loses columns.
/// Choosing none is refused: a list with no columns shows nothing and offers no
/// way back, so the request is treated as "no preference".
pub(crate) async fn set_columns(
    state: &AdminState,
    config: &ListConfig,
    path: &str,
    user: &laterite_auth::AuthenticatedUser,
    session: &crate::session::SessionHandle,
    headers: &axum::http::HeaderMap,
    pairs: &[(String, String)],
) -> Response {
    let allowed = allowed_columns(config, user);
    let chosen: Vec<&str> = pairs
        .iter()
        .filter(|(k, _)| k == "column")
        .map(|(_, v)| v.trim())
        .filter(|v| allowed.iter().any(|c| c.field == *v))
        .collect();
    // "Every column" means the default set: what shows with no preference. An
    // `invisible` column chosen on purpose must not clear the choice that
    // revealed it.
    let mut by_default: Vec<&str> = allowed
        .iter()
        .filter(|c| !c.invisible)
        .map(|c| c.field.as_str())
        .collect();
    let mut as_chosen = chosen.clone();
    by_default.sort_unstable();
    as_chosen.sort_unstable();
    as_chosen.dedup();

    // The page size travels on the same form. Only an offered size is kept, and
    // the descriptor's own clears the preference, like choosing every column.
    let size_key = per_page_preference_key(path);
    let size = pairs
        .iter()
        .find(|(k, _)| k == "per_page")
        .and_then(|(_, v)| v.trim().parse::<i64>().ok())
        .filter(|n| config.per_page_options.contains(n));
    let size_result = match size {
        Some(n) if n != config.per_page => {
            laterite_auth::store::set_user_preference(
                &state.db,
                user.user.id,
                &size_key,
                &n.to_string(),
            )
            .await
        }
        _ => laterite_auth::store::clear_user_preference(&state.db, user.user.id, &size_key).await,
    };

    let key = columns_preference_key(path);
    let result = if chosen.is_empty() || as_chosen == by_default {
        laterite_auth::store::clear_user_preference(&state.db, user.user.id, &key).await
    } else {
        laterite_auth::store::set_user_preference(&state.db, user.user.id, &key, &chosen.join(","))
            .await
    };
    match result.and(size_result) {
        Ok(()) => session.push_flash(
            crate::session::FlashLevel::Success,
            laterite_core::t!("List setup saved."),
        ),
        Err(e) => {
            tracing::error!(error = %e, "storing the list setup failed");
            session.push_flash(
                crate::session::FlashLevel::Error,
                laterite_core::t!("Could not save your list setup."),
            );
        }
    }
    let back = format!("{}{}", state.admin_path, path);
    crate::form::saved_response(crate::form::is_htmx(headers), &back)
}

/// One row of the column picker.
pub struct ColumnChoice {
    pub field: String,
    pub label: String,
    pub shown: bool,
}

/// One column header: its label, the field a click sorts by, the direction that
/// click asks for, and the direction it is sorted in now (empty when it is not).
pub struct ColumnHead {
    pub label: String,
    pub field: String,
    pub next_dir: String,
    pub active: String,
    pub sortable: bool,
    pub width: Option<String>,
    pub align_class: String,
}

#[derive(Template)]
#[template(path = "list.html")]
struct ListTemplate {
    shell: crate::Shell,
    title: String,
    columns: Vec<ColumnHead>,
    rows: Vec<RenderedRow>,
    /// The count on this page (`rows.len()`), precomputed as `i64` for the footer.
    shown: i64,
    page: i64,
    total: i64,
    total_pages: i64,
    edit_base: Option<String>,
    /// A row opens its record; the Edit link is there regardless.
    row_link: bool,
    /// The active ordering, carried on the pager links so paging keeps the sort.
    sort: String,
    dir: String,
    /// The active search term, shown in the box and carried on every link.
    q: String,
    /// Whether the box appears: search is on and some column is searchable.
    searchable: bool,
    /// The placeholder when the descriptor set one, localized.
    search_prompt: Option<String>,
    search_on_enter: bool,
    /// The empty-state message when the descriptor set one, localized.
    no_records_message: Option<String>,
    /// This operator's page size, and the sizes the list setup offers; empty
    /// renders no chooser.
    per_page: i64,
    per_page_options: Vec<i64>,
    /// Whether rows carry a checkbox and the Delete button is offered.
    deletable: bool,
    /// Whether this resource offers an export, which puts the menu beside the
    /// title. Off leaves the title row bare.
    exportable: bool,
    /// The import pages, when the resource declared them and this operator may
    /// use them.
    import_href: Option<String>,
    /// Every declared column, with the shown ones ticked, for the picker.
    pickers: Vec<ColumnChoice>,
    /// The toolbar buttons this operator may see.
    toolbar: Vec<ToolbarView>,
    /// The search, filters and sort, as `&k=v` pairs, so an export link carries
    /// the same view the screen is showing.
    export_query: String,
    /// This list's own path, for the search form to post back to.
    path: String,
    /// The filter controls, with the active value marked.
    filters: Vec<FilterView>,
    /// Whether anything is narrowing the list, so a Clear link is offered.
    filtered: bool,
    /// The query-string pairs a sort or pager link must carry.
    carry: String,
    /// The list region's element id; a page's own list is `lat-list`.
    region: String,
    /// A per-row action, for a list with no action bar; a page's list has the bar.
    delete_path: Option<RowAction>,
    /// The grip and Move buttons, when the list is in its own order.
    reorder: Option<ReorderView>,
    /// The tree, when the list shows one: the toggles and the Move to link.
    tree: Option<TreeView>,
    /// The way down to the parent whose children a page shows.
    crumbs: Vec<Crumb>,
}

/// One rendered filter control.
pub struct FilterView {
    pub param: String,
    pub label: String,
    /// The input kind when there are no options: `text`, `number` or `date`.
    pub input_type: String,
    pub options: Vec<FilterOptionView>,
    /// The selected value, empty when the filter is off.
    pub value: String,
}

pub struct FilterOptionView {
    pub value: String,
    pub label: String,
}

/// Builds the filter controls, marking whichever value the request selected.
fn filter_views(
    config: &ListConfig,
    active: &[ActiveFilter<'_>],
    shell: &crate::Shell,
) -> Vec<FilterView> {
    config
        .filters
        .iter()
        .map(|f| {
            let value = active
                .iter()
                .find(|a| a.filter.field == f.field)
                .map(|a| a.raw.clone())
                .unwrap_or_default();
            // A list of choices renders as a select; anything else as an
            // input of the matching kind.
            let options: Vec<FilterOptionView> = match f.filter_type.as_str() {
                "boolean" => vec![
                    FilterOptionView {
                        value: "1".to_string(),
                        label: shell.tt(&laterite_core::t!("Yes")),
                    },
                    FilterOptionView {
                        value: "0".to_string(),
                        label: shell.tt(&laterite_core::t!("No")),
                    },
                ],
                "select" => f
                    .choices()
                    .iter()
                    .map(|o| FilterOptionView {
                        value: o.value.clone(),
                        label: shell.tt(&o.label),
                    })
                    .collect(),
                _ => Vec::new(),
            };
            let input_type = match f.filter_type.as_str() {
                "number" => "number",
                "date" => "date",
                _ => "text",
            };
            FilterView {
                param: f.param(),
                label: shell.tt(&f.label),
                input_type: input_type.to_string(),
                options,
                value,
            }
        })
        .collect()
}

/// Percent-encodes a query-string value.
fn urlencode(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.as_bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(*byte as char)
            }
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

/// The list region alone, for an htmx sort or page that swaps it in place.
#[derive(Template)]
#[template(path = "_list_table.html")]
struct ListFragment {
    shell: crate::Shell,
    columns: Vec<ColumnHead>,
    rows: Vec<RenderedRow>,
    shown: i64,
    page: i64,
    total: i64,
    total_pages: i64,
    edit_base: Option<String>,
    /// A row opens its record; the Edit link is there regardless.
    row_link: bool,
    sort: String,
    dir: String,
    carry: String,
    /// Rendered onto the region as `data-filtered`, so the bar's Clear link can
    /// react without the bar itself having to swap. Also picks the empty state:
    /// a filtered list with no rows has not run out of records, it has no match.
    filtered: bool,
    deletable: bool,
    no_records_message: Option<String>,
    /// The list's own path, so sort and pager links stay right when the
    /// fragment sits inside another page.
    path: String,
    /// The region's element id: `lat-list` for a page's list, one of its own
    /// for a section inside a form.
    region: String,
    /// A per-row action, posted with the row's id, for a list with no action
    /// bar of its own.
    delete_path: Option<RowAction>,
    /// The grip and Move buttons, when the list is in its own order.
    reorder: Option<ReorderView>,
    tree: Option<TreeView>,
}

/// A parent's children alone, for a tree row that expands in place.
#[derive(Template)]
#[template(path = "_list_rows.html")]
struct RowsFragment {
    shell: crate::Shell,
    rows: Vec<RenderedRow>,
    page: i64,
    total_pages: i64,
    edit_base: Option<String>,
    row_link: bool,
    deletable: bool,
    region: String,
    delete_path: Option<RowAction>,
    reorder: Option<ReorderView>,
    tree: Option<TreeView>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config() -> ListConfig {
        ListConfig {
            entity: "backend_users".to_string(),
            title: "Users".into(),
            columns: vec![
                ListColumn::new("username", "Username"),
                ListColumn::new("is_superuser", "Superuser").yes_no(),
            ],
            order_by: "created_at".to_string(),
            order_dir: SortDir::Desc,
            per_page: 25,
            id_field: "id".to_string(),
            edit_base: None,
            creatable: false,
            filters: vec![ListFilter::boolean("is_superuser", "Superuser")],
            deletable: true,
            ..Default::default()
        }
    }

    #[test]
    fn column_types_format_their_cell_display() {
        let ist: Tz = "Asia/Kolkata".parse().unwrap();
        let display = |ct: &dyn ColumnType, value: &str, tz: Tz| {
            ct.view_model(&CellCx {
                value,
                tz,
                locale: chrono::Locale::en_US,
            })
            .display
        };
        // 10:00 UTC is 15:30 in Asia/Kolkata (UTC+5:30)
        assert_eq!(
            display(&DateTimeColumn, "2026-08-13T10:00:00+00:00", ist),
            "13 Aug 2026, 15:30"
        );
        assert_eq!(
            display(&DateColumn, "2026-08-13T10:00:00+00:00", Tz::UTC),
            "13 Aug 2026"
        );
        assert_eq!(
            display(&TimeColumn, "2026-08-13T10:00:00+00:00", ist),
            "15:30"
        );
        assert_eq!(display(&BoolColumn, "true", Tz::UTC), "Yes");
        assert_eq!(display(&BoolColumn, "false", Tz::UTC), "No");
        assert_eq!(display(&TextColumn, "root", Tz::UTC), "root");
        // An unparseable timestamp falls through unchanged.
        assert_eq!(display(&DateTimeColumn, "n/a", Tz::UTC), "n/a");
    }

    #[test]
    fn sort_falls_back_to_the_configured_order() {
        let c = config();
        assert_eq!(
            resolve_sort(&c, None, None),
            ("created_at".to_string(), SortDir::Desc)
        );
    }

    #[test]
    fn a_declared_column_can_be_sorted_either_way() {
        let c = config();
        assert_eq!(
            resolve_sort(&c, Some("username"), Some("asc")),
            ("username".to_string(), SortDir::Asc)
        );
        assert_eq!(
            resolve_sort(&c, Some("username"), Some("desc")),
            ("username".to_string(), SortDir::Desc)
        );
    }

    /// The whitelist: a column the descriptor does not declare never reaches the
    /// query, however it is spelled.
    #[test]
    fn an_undeclared_sort_column_is_ignored() {
        let c = config();
        for crafted in [
            "password_hash",
            "id) --",
            "username; drop table backend_users",
            "",
        ] {
            assert_eq!(
                resolve_sort(&c, Some(crafted), Some("asc")).0,
                "created_at",
                "{crafted} must not reach the query"
            );
        }
    }

    #[test]
    fn an_unknown_direction_falls_back() {
        let c = config();
        // On a column other than the configured one, ascending.
        assert_eq!(
            resolve_sort(&c, Some("username"), Some("sideways")).1,
            SortDir::Asc
        );
        // On the configured column, its configured direction.
        assert_eq!(resolve_sort(&c, Some("created_at"), None).1, SortDir::Desc);
    }

    /// A module's own column type renders its cells, which is the point of the
    /// registry being open rather than a fixed set.
    #[test]
    fn a_contributed_column_type_renders_its_cell() {
        struct Rating;
        impl ColumnType for Rating {
            fn view_key(&self) -> &'static str {
                "acme.rating"
            }
            fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
                let stars = cx.value.parse::<usize>().unwrap_or(0);
                text_cell("acme.rating", cx.value, "*".repeat(stars))
            }
            fn render_default(&self, vm: &CellVm) -> Markup {
                render_text(vm)
            }
        }

        let reg = ColumnTypeReg::new(Arc::new(Rating));
        assert_eq!(reg.name(), "acme.rating", "the type names itself");

        let mut registry = builtin_column_registry();
        registry.insert(reg.name().to_string(), reg.column_type);
        let rendered = render_cell(
            registry.get("acme.rating").unwrap().as_ref(),
            &crate::field::NoOverrides,
            &OverrideScope {
                surface: Surface::Column,
                view_key: "acme.rating",
                resource: Some("products"),
                field: Some("stars"),
            },
            &CellCx {
                value: "3",
                tz: Tz::UTC,
                locale: chrono::Locale::en_US,
            },
            None,
        );
        assert!(rendered.into_string().contains("***"));
    }

    /// A contributed type cannot quietly replace a built-in: the key is the
    /// type's own `view_key`, and the router refuses a duplicate at boot.
    #[test]
    fn a_contributed_key_is_the_types_own_and_collides_visibly() {
        struct Impostor;
        impl ColumnType for Impostor {
            fn view_key(&self) -> &'static str {
                "text"
            }
            fn view_model(&self, cx: &CellCx<'_>) -> CellVm {
                text_cell("text", cx.value, String::new())
            }
            fn render_default(&self, vm: &CellVm) -> Markup {
                render_text(vm)
            }
        }
        let reg = ColumnTypeReg::new(Arc::new(Impostor));
        assert_eq!(reg.name(), "text");
        // The router inserts into this map and panics when one is already there.
        assert!(builtin_column_registry().contains_key(reg.name()));
    }

    #[test]
    fn status_pill_renders_a_slugged_markup_span() {
        let vm = StatusPillColumn.view_model(&CellCx {
            value: "In Progress",
            tz: Tz::UTC,
            locale: chrono::Locale::en_US,
        });
        let html = StatusPillColumn.render_default(&vm).into_string();
        assert!(html.contains(r#"class="lat-status lat-status--in-progress""#));
        assert!(html.contains(">In Progress<"));
    }

    /// A fresh test database with the auth tables migrated in, on whichever
    /// backend the run targets. Hold the returned guard for the test's lifetime.
    async fn test_db() -> (Db, laterite_core::testing::TestGuard) {
        laterite_core::testing::connect_test(&[laterite_auth::migrations()]).await
    }

    #[tokio::test]
    async fn query_returns_display_rows() {
        let (db, _guard) = test_db().await;
        let hash = laterite_auth::password::hash_password("pw").unwrap();
        laterite_auth::store::create_user(
            &db,
            "root",
            "root@example.test",
            "Ada",
            None,
            &hash,
            true,
        )
        .await
        .unwrap();

        let c = config();
        let result = query(&db, &c, &plain(&c)).await.unwrap();
        assert_eq!(result.total, 1);
        assert_eq!(result.rows.len(), 1);
        assert_eq!(result.rows[0].cells[0], "root");
        // Booleans store as 0/1 integers everywhere, so a cast-to-text superuser
        // flag reads back as "1"; the display layer maps it to "Yes".
        assert_eq!(result.rows[0].cells[1], "1");
        assert!(!result.rows[0].id.is_empty());
    }

    async fn get(params: ListParams, headers: axum::http::HeaderMap) -> String {
        get_with(params, HashMap::new(), headers).await
    }

    async fn get_with(
        params: ListParams,
        raw: HashMap<String, String>,
        headers: axum::http::HeaderMap,
    ) -> String {
        let (db, _guard) = test_db().await;
        let state = AdminState::new(
            laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
            db,
        );
        let resp = handle(
            &state,
            &config(),
            "/admin/users",
            params,
            &raw,
            &crate::audit::test_actor(),
            crate::Shell::test(),
            &headers,
        )
        .await;
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    #[test]
    fn a_typed_filter_accepts_only_its_own_shape() {
        let mut c = config();
        c.filters = vec![
            ListFilter::number("views", "Views"),
            ListFilter::date("created_at", "Created"),
            ListFilter::text("username", "Username"),
        ];
        let accepted = |param: &str, value: &str| {
            !resolve_filters(&c, &filter_params(&[(param, value)])).is_empty()
        };
        assert!(accepted("f_views", "42"));
        assert!(
            !accepted("f_views", "4.2"),
            "a number filter takes whole numbers"
        );
        assert!(!accepted("f_views", "; drop table"), "and nothing else");

        assert!(accepted("f_created_at", "2026-09-21"));
        assert!(
            !accepted("f_created_at", "2026-9-21"),
            "a date is ISO or nothing"
        );
        assert!(
            !accepted("f_created_at", "2026-09-21%"),
            "so a pattern cannot slip in"
        );

        assert!(accepted("f_username", "ada"));
    }

    #[test]
    fn a_filter_default_applies_only_until_the_operator_decides() {
        let mut c = config();
        c.filters = vec![ListFilter::boolean("is_superuser", "Superuser").default_value("1")];
        // Nothing named: the default narrows the list.
        assert_eq!(resolve_filters(&c, &filter_params(&[])).len(), 1);
        // Named blank: the operator cleared it, so no filter.
        assert!(resolve_filters(&c, &filter_params(&[("f_is_superuser", "")])).is_empty());
        // Named otherwise: their value, not the default.
        let active = resolve_filters(&c, &filter_params(&[("f_is_superuser", "0")]));
        assert_eq!(active.len(), 1);
    }

    #[test]
    fn a_gated_filter_is_narrowed_away_with_its_default() {
        let mut c = config();
        c.filters = vec![ListFilter::boolean("is_superuser", "Superuser")
            .default_value("1")
            .require("acme.secret")];
        let plain = laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(false, [], [], []),
            ..crate::audit::test_actor()
        };
        assert!(allowed_filters(&c, &plain).is_empty());
        // And the narrowed descriptor carries none, so the default cannot apply.
        let narrowed = narrowed(&c, None, &plain);
        assert!(resolve_filters(&narrowed, &filter_params(&[])).is_empty());
        assert_eq!(allowed_filters(&c, &root()).len(), 1);
    }

    #[test]
    fn a_stored_page_size_counts_only_while_it_is_offered() {
        let mut cfg = config();
        assert_eq!(offered_per_page(&cfg, Some(50)), 25, "nothing offered");
        cfg.per_page_options = vec![25, 50, 100];
        assert_eq!(offered_per_page(&cfg, Some(50)), 50);
        assert_eq!(offered_per_page(&cfg, Some(999)), 25, "no longer offered");
        assert_eq!(offered_per_page(&cfg, None), 25);
    }

    fn params(sort: Option<&str>) -> ListParams {
        ListParams {
            page: None,
            sort: sort.map(|s| s.to_string()),
            dir: Some("asc".to_string()),
            q: None,
            parent: None,
            depth: None,
        }
    }

    /// The default window and ordering, with no search and no filter.
    fn plain(config: &ListConfig) -> ListQuery<'_> {
        ListQuery {
            offset: 0,
            order_by: &config.order_by,
            order_dir: config.order_dir,
            q: "",
            filters: &[],
            per_page: None,
            children_of: None,
        }
    }

    fn searched<'a>(config: &'a ListConfig, q: &'a str) -> ListQuery<'a> {
        ListQuery {
            offset: 0,
            order_by: &config.order_by,
            order_dir: config.order_dir,
            q,
            filters: &[],
            per_page: None,
            children_of: None,
        }
    }

    /// Both `&amp;` and `&#38;` are an ampersand; the escaper picks one, and a
    /// test should assert on the link, not on which spelling it chose.
    fn amps(html: &str) -> String {
        html.replace("&#38;", "&").replace("&amp;", "&")
    }

    /// The request's filter parameters, as the query string would carry them.
    fn filter_params(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[tokio::test]
    async fn search_filters_rows_and_the_total() {
        let (db, _guard) = test_db().await;
        for name in ["ada", "brendan", "clara"] {
            let hash = laterite_auth::password::hash_password("x").unwrap();
            laterite_auth::store::create_user(
                &db,
                name,
                &format!("{name}@example.test"),
                name,
                None,
                &hash,
                false,
            )
            .await
            .unwrap();
        }
        let c = config();

        let hit = query(&db, &c, &searched(&c, "bren")).await.unwrap();
        assert_eq!(hit.rows.len(), 1);
        assert_eq!(hit.rows[0].cells[0], "brendan");
        // The pager counts the filtered set, not the table.
        assert_eq!(hit.total, 1);

        // Case folds, as the picker's default profile does.
        assert_eq!(
            query(&db, &c, &searched(&c, "BREN")).await.unwrap().total,
            1
        );

        // A blank term is no filter, not a filter matching nothing.
        assert_eq!(query(&db, &c, &searched(&c, "")).await.unwrap().total, 3);
        assert_eq!(query(&db, &c, &searched(&c, "   ")).await.unwrap().total, 3);

        // A LIKE wildcard is literal, so it does not match every row.
        assert_eq!(query(&db, &c, &searched(&c, "%")).await.unwrap().total, 0);
    }

    /// Only text columns are searched by default: a substring match against a
    /// boolean would make every row containing `1` a hit.
    #[tokio::test]
    async fn search_skips_a_non_text_column() {
        let (db, _guard) = test_db().await;
        let hash = laterite_auth::password::hash_password("x").unwrap();
        laterite_auth::store::create_user(&db, "ada", "a@example.test", "Ada", None, &hash, true)
            .await
            .unwrap();
        let c = config();
        assert!(c.columns[0].is_searchable(), "username is text");
        assert!(!c.columns[1].is_searchable(), "is_superuser is a boolean");
        // The stored superuser flag is `1`, but searching it finds nothing.
        assert_eq!(query(&db, &c, &searched(&c, "1")).await.unwrap().total, 0);
    }

    #[test]
    fn a_column_can_override_its_searchability() {
        assert!(ListColumn::new("code", "Code").is_searchable());
        assert!(!ListColumn::new("code", "Code")
            .searchable(false)
            .is_searchable());
        assert!(ListColumn::new("at", "At")
            .datetime()
            .searchable(true)
            .is_searchable());
    }

    async fn seed_users(db: &Db) {
        for (name, su) in [("ada", true), ("brendan", false), ("clara", false)] {
            let hash = laterite_auth::password::hash_password("x").unwrap();
            laterite_auth::store::create_user(
                db,
                name,
                &format!("{name}@example.test"),
                name,
                None,
                &hash,
                su,
            )
            .await
            .unwrap();
        }
    }

    async fn total_with(db: &Db, c: &ListConfig, params: &HashMap<String, String>) -> i64 {
        let active = resolve_filters(c, params);
        let req = ListQuery {
            offset: 0,
            order_by: &c.order_by,
            order_dir: c.order_dir,
            q: "",
            filters: &active,
            per_page: None,
            children_of: None,
        };
        query(db, c, &req).await.unwrap().total
    }

    #[tokio::test]
    async fn a_filter_narrows_the_rows_and_the_total() {
        let (db, _guard) = test_db().await;
        seed_users(&db).await;
        let c = config();

        assert_eq!(total_with(&db, &c, &filter_params(&[])).await, 3);
        assert_eq!(
            total_with(&db, &c, &filter_params(&[("f_is_superuser", "1")])).await,
            1
        );
        assert_eq!(
            total_with(&db, &c, &filter_params(&[("f_is_superuser", "0")])).await,
            2
        );
    }

    /// The whitelist: only a declared filter, and for a select only a declared
    /// option, reaches the query. Anything else is dropped, not guessed at.
    #[test]
    fn an_undeclared_filter_or_value_is_ignored() {
        let c = config();
        // A column that exists but is not a declared filter.
        assert!(resolve_filters(&c, &filter_params(&[("f_username", "ada")])).is_empty());
        // A declared boolean filter with a value its control never emits.
        for bad in ["yes", "true", "1 or 1=1", "", "  "] {
            assert!(
                resolve_filters(&c, &filter_params(&[("f_is_superuser", bad)])).is_empty(),
                "{bad} must not reach the query"
            );
        }

        let with_select = ListConfig {
            filters: vec![ListFilter::select(
                "status",
                "Status",
                vec![FilterOption::new("live", "Live")],
            )],
            ..config()
        };
        assert_eq!(
            resolve_filters(&with_select, &filter_params(&[("f_status", "live")])).len(),
            1
        );
        assert!(
            resolve_filters(&with_select, &filter_params(&[("f_status", "draft")])).is_empty(),
            "an option the descriptor never offered is dropped"
        );
    }

    #[tokio::test]
    async fn a_filter_survives_a_sort_link_and_shows_as_selected() {
        let mut p = params(Some("username"));
        p.q = None;
        let html = get_with(
            p,
            filter_params(&[("f_is_superuser", "1")]),
            axum::http::HeaderMap::new(),
        )
        .await;
        let links = amps(&html);
        assert!(
            links.contains("?sort=is_superuser&dir=asc&f_is_superuser=1"),
            "a sort link carries the filter"
        );
        // The sorted column's own link flips direction and keeps it too.
        assert!(links.contains("?sort=username&dir=desc&f_is_superuser=1"));
        assert!(
            html.contains(r#"<option value="1" selected>"#),
            "the control shows the active value"
        );
        assert!(html.contains("Clear"), "and a way back to the full list");
        assert!(
            html.contains(r#"data-filtered="true""#),
            "the region says the list is narrowed, which is what reveals Clear"
        );
    }

    /// A filtered list with no rows has not run out of records; it has no match.
    /// Saying "No records yet" there reads as an empty table and hides the filter.
    #[tokio::test]
    async fn the_empty_state_distinguishes_no_records_from_no_match() {
        let (db, _guard) = test_db().await;
        let state = AdminState::new(
            laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
            db,
        );
        let render = |raw: HashMap<String, String>, q: Option<&str>| {
            let q = q.map(String::from);
            let state = state.clone();
            async move {
                let p = ListParams {
                    page: None,
                    sort: None,
                    dir: None,
                    q,
                    parent: None,
                    depth: None,
                };
                let resp = handle(
                    &state,
                    &config(),
                    "/admin/users",
                    p,
                    &raw,
                    &crate::audit::test_actor(),
                    crate::Shell::test(),
                    &axum::http::HeaderMap::new(),
                )
                .await;
                let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
                    .await
                    .unwrap();
                String::from_utf8(bytes.to_vec()).unwrap()
            }
        };

        // Nothing stored and nothing asked for: the table is genuinely empty.
        let bare = render(HashMap::new(), None).await;
        assert!(bare.contains("No records yet."));

        // Filtered to nothing: the records may exist, the filter excluded them.
        let filtered = render(filter_params(&[("f_is_superuser", "1")]), None).await;
        assert!(filtered.contains("No records match."));
        assert!(!filtered.contains("No records yet."));

        // A search that matches nothing reads the same way.
        let searched = render(HashMap::new(), Some("zzz")).await;
        assert!(searched.contains("No records match."));
    }

    /// A superuser, who sees every column, for the narrowing tests.
    fn root() -> laterite_auth::AuthenticatedUser {
        laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(true, [], [], []),
            ..crate::audit::test_actor()
        }
    }

    #[test]
    fn an_invisible_column_is_left_out_of_the_default_but_may_be_chosen() {
        let mut c = config();
        c.columns[1].invisible = true;
        assert_eq!(visible_columns(&c, None, &root()).len(), 1);
        assert_eq!(visible_columns(&c, Some("is_superuser"), &root()).len(), 1);
        assert_eq!(
            visible_columns(&c, Some("is_superuser"), &root())[0].field,
            "is_superuser"
        );
    }

    #[test]
    fn a_gated_column_is_narrowed_away_for_an_operator_without_the_grant() {
        let mut c = config();
        c.columns[1].permission = Some("acme.secret".into());
        let plain = laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(false, [], [], []),
            ..crate::audit::test_actor()
        };
        assert_eq!(visible_columns(&c, None, &plain).len(), 1);
        // Choosing it by name does not reveal it either.
        assert_eq!(visible_columns(&c, Some("is_superuser"), &plain).len(), 1);
        assert_eq!(visible_columns(&c, None, &root()).len(), 2);
    }

    #[test]
    fn an_unsortable_column_is_not_sorted_by() {
        let mut c = config();
        c.columns[0].sortable = false;
        let (by, _) = resolve_sort(&c, Some("username"), Some("asc"));
        assert_eq!(by, c.order_by, "falls back to the descriptor's order");
    }

    #[test]
    fn a_stored_choice_narrows_the_columns_in_descriptor_order() {
        let c = config();
        // Stored out of order; the descriptor's order still wins, because the
        // choice is about which columns, not where they sit.
        let kept = visible_columns(&c, Some("is_superuser,username"), &root());
        assert_eq!(
            kept.iter().map(|c| c.field.as_str()).collect::<Vec<_>>(),
            ["username", "is_superuser"]
        );
    }

    #[test]
    fn no_stored_choice_shows_every_column() {
        let c = config();
        assert_eq!(visible_columns(&c, None, &root()).len(), c.columns.len());
    }

    /// A descriptor that drops or renames a column must not leave an operator
    /// staring at an empty table because of a choice they made months ago.
    #[test]
    fn a_stale_choice_falls_back_to_every_column() {
        let c = config();
        assert_eq!(
            visible_columns(&c, Some("gone,removed"), &root()).len(),
            c.columns.len()
        );
        assert_eq!(
            visible_columns(&c, Some(""), &root()).len(),
            c.columns.len()
        );
        assert_eq!(
            visible_columns(&c, Some("  , "), &root()).len(),
            c.columns.len()
        );
        // A partly stale choice keeps what still exists.
        assert_eq!(visible_columns(&c, Some("gone,username"), &root()).len(), 1);
    }

    /// A button the operator cannot use is not shown, rather than shown and
    /// answering 403 when they reach it.
    #[test]
    fn the_toolbar_hides_what_the_operator_may_not_do() {
        let shell = crate::Shell::test();
        let cfg = ListConfig {
            creatable: false,
            toolbar: vec![
                ToolbarButton::new("Open", "/reports"),
                ToolbarButton::new("Audit", "/audit").require("backend.view_audit"),
            ],
            ..config()
        };

        // A superuser sees everything, gated or not.
        let root = laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(true, [], [], []),
            ..crate::audit::test_actor()
        };
        let views = toolbar_views(&cfg, "/admin", &root, &shell);
        assert_eq!(
            views.iter().map(|v| v.label.as_str()).collect::<Vec<_>>(),
            ["Open", "Audit"]
        );

        // Someone holding the named permission sees it too.
        let granted = laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(
                false,
                ["backend.view_audit".to_string()],
                [],
                [],
            ),
            ..crate::audit::test_actor()
        };
        assert_eq!(toolbar_views(&cfg, "/admin", &granted, &shell).len(), 2);

        // Someone holding nothing sees only the ungated button.
        let plain = laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(false, [], [], []),
            ..crate::audit::test_actor()
        };
        let views = toolbar_views(&cfg, "/admin", &plain, &shell);
        assert_eq!(
            views.iter().map(|v| v.label.as_str()).collect::<Vec<_>>(),
            ["Open"]
        );
    }

    /// A relative href is resolved against the configured admin mount, so a moved
    /// panel moves its buttons with it.
    #[test]
    fn a_toolbar_href_follows_the_admin_mount() {
        let shell = crate::Shell::test();
        let cfg = ListConfig {
            creatable: true,
            // Already under the mount, as `prefix_resource` leaves it at boot.
            edit_base: Some("/backoffice/roles".to_string()),
            toolbar: vec![
                ToolbarButton::new("Reports", "/reports"),
                ToolbarButton::new("Docs", "https://example.test/docs"),
            ],
            ..config()
        };
        let root = laterite_auth::AuthenticatedUser {
            permissions: laterite_auth::PermissionSet::with_overrides(true, [], [], []),
            ..crate::audit::test_actor()
        };
        let views = toolbar_views(&cfg, "/backoffice", &root, &shell);
        assert_eq!(views[0].href, "/backoffice/roles/new", "New comes first");
        assert_eq!(views[1].href, "/backoffice/reports");
        // An absolute URL is left alone.
        assert_eq!(views[2].href, "https://example.test/docs");
    }

    #[tokio::test]
    async fn an_htmx_sort_returns_the_list_region_alone() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert("hx-request", "true".parse().unwrap());
        let html = get(params(Some("username")), headers).await;
        assert!(html.contains(r#"id="lat-list""#), "the region comes back");
        assert!(html.contains("aria-sort=\"ascending\""), "sorted ascending");
        // A fragment, not a page: swapping a document into the region would nest
        // the admin inside itself.
        assert!(!html.contains("<body"), "no page chrome");
        // The bar cannot re-render per swap, so the region carries the state.
        assert!(html.contains(r#"data-filtered="false""#));
    }

    /// A sort or a page must not silently drop the search, or the second click
    /// would widen the result back to the whole table.
    #[tokio::test]
    async fn the_search_term_survives_a_sort_link() {
        let mut p = params(Some("username"));
        p.q = Some("bren".to_string());
        let html = get(p, axum::http::HeaderMap::new()).await;
        assert!(
            amps(&html).contains("?sort=username&dir=desc&q=bren"),
            "sort and pager links carry the term"
        );
        assert!(
            html.contains(r#"value="bren""#),
            "and the box still shows it"
        );
    }

    #[tokio::test]
    async fn a_plain_sort_returns_the_whole_page() {
        let html = get(params(Some("username")), axum::http::HeaderMap::new()).await;
        assert!(html.contains("<body"), "lists still work without htmx");
        assert!(html.contains(r#"id="lat-list""#));
        // The links work without scripting, so they carry a real href, built
        // on the list's own path so they hold inside another page too.
        assert!(
            html.contains(r#"?sort=username"#) && html.contains(r#"href="/admin/"#),
            "{html}"
        );
    }

    #[tokio::test]
    async fn query_rejects_bad_identifiers() {
        let (db, _guard) = test_db().await;
        let mut bad = config();
        bad.entity = "backend_users; drop table backend_users".to_string();
        assert!(query(&db, &bad, &plain(&bad)).await.is_err());
    }
}