laravel-rust-admin 0.1.1

Admin panel framework for Laravel for Rust: auto-generated CRUD tables, forms, actions, and dashboard widgets from your models.
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
//! The [`AdminResource`] trait, and the code that serves a resource's table, form, search, and
//! export from it.

use std::collections::BTreeMap;
use std::future::Future;
use std::marker::PhantomData;
use std::str::FromStr;
use std::sync::Arc;

use futures_util::TryStreamExt;
use futures_util::future::BoxFuture;
use laravel::db::{Builder, any, col};
use laravel::http::{Request, StatusCode, Streamed};
use laravel::model::{Fill, Model};
use laravel::validation::ValidatesRequest;
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::model;
use crate::protocol::{
    ActionResponse, BadgeColor, GlobalSearchGroupDto, GlobalSearchHitDto, NavigationBadgeDto, PaginationMetaDto,
    RecordEnvelopeDto, RecordResponse, ResourceListResponse, ResourcePermissionsDto, ResourceSchemaDto, SortDirection,
};
use crate::schema::action::ActionContext;
use crate::schema::form::FormBuilder;
use crate::schema::table::TableBuilder;

/// Sidebar badge returned by [`AdminResource::navigation_badge`].
#[derive(Debug, Clone)]
pub struct NavigationBadge {
    /// The badge's text, usually a count.
    pub label: String,
    /// The badge's color.
    pub color: BadgeColor,
}

impl NavigationBadge {
    /// A neutral badge with this text.
    #[must_use]
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            color: BadgeColor::Zinc,
        }
    }

    /// Colors the badge, such as amber for something that's waiting.
    #[must_use]
    pub fn color(mut self, color: BadgeColor) -> Self {
        self.color = color;
        self
    }

    pub(crate) fn into_dto(self) -> NavigationBadgeDto {
        NavigationBadgeDto {
            label: self.label,
            color: self.color,
        }
    }
}

/// The [`CreateInput`](AdminResource::CreateInput) or [`UpdateInput`](AdminResource::UpdateInput)
/// of a resource whose records the panel doesn't create, or doesn't change.
#[derive(Debug, Clone, Copy, Default)]
pub struct ReadOnly;

/// What a resource creates or updates its records with.
///
/// Every `#[laravel::input(fills = M)]` struct implements this trait, and so does [`ReadOnly`].
/// You don't implement it yourself.
pub trait ResourceInput<M: Model>: Send + Sync + 'static {
    /// Whether the input refuses every create and update, as [`ReadOnly`] does.
    const IS_READ_ONLY: bool = false;

    /// Validates the request's input as this type, and creates a model from it.
    fn create_from_request<'a>(request: &'a Request) -> BoxFuture<'a, laravel::Result<M>>;

    /// Validates the request's input as this type, and updates the record with it.
    fn update_from_request<'a>(request: &'a Request, record: &'a mut M) -> BoxFuture<'a, laravel::Result<()>>;
}

impl<M: Model> ResourceInput<M> for ReadOnly {
    const IS_READ_ONLY: bool = true;

    fn create_from_request<'a>(_request: &'a Request) -> BoxFuture<'a, laravel::Result<M>> {
        Box::pin(async {
            Err(laravel::abort_with(
                StatusCode::METHOD_NOT_ALLOWED,
                "Creating records is disabled for this resource.",
            ))
        })
    }

    fn update_from_request<'a>(_request: &'a Request, _record: &'a mut M) -> BoxFuture<'a, laravel::Result<()>> {
        Box::pin(async {
            Err(laravel::abort_with(
                StatusCode::METHOD_NOT_ALLOWED,
                "Editing records is disabled for this resource.",
            ))
        })
    }
}

impl<M, T> ResourceInput<M> for T
where
    M: Model,
    T: DeserializeOwned + ValidatesRequest + Fill<M> + Send + Sync + 'static,
{
    const IS_READ_ONLY: bool = false;

    fn create_from_request<'a>(request: &'a Request) -> BoxFuture<'a, laravel::Result<M>> {
        Box::pin(async move {
            let input: T = request.validate().await?;
            model::create(input).await
        })
    }

    fn update_from_request<'a>(request: &'a Request, record: &'a mut M) -> BoxFuture<'a, laravel::Result<()>> {
        Box::pin(async move {
            let input: T = request.validate().await?;
            model::update(record, input).await
        })
    }
}

/// A model in the admin panel: its place in the sidebar, its table, its form, and who may do what
/// with its records.
///
/// `#[derive(AdminResource)]` on a `#[model]` struct builds all of this from the struct's fields.
/// Implement the trait by hand, usually on a unit struct, when a resource needs more: tabs,
/// actions, a relationship in its table, or authorization.
///
/// ```ignore
/// pub struct PostResource;
///
/// impl AdminResource for PostResource {
///     type Model = Post;
///     type CreateInput = StorePost;
///     type UpdateInput = StorePost;
///
///     fn slug() -> &'static str { "posts" }
///     fn label() -> &'static str { "Post" }
///     fn plural_label() -> &'static str { "Posts" }
///
///     fn table(table: TableBuilder<Post>) -> TableBuilder<Post> {
///         table
///             .column(Column::text("title").searchable().sortable())
///             .column(Column::badge("status"))
///     }
///
///     fn form(form: FormBuilder) -> FormBuilder {
///         form.field(Field::text("title").required())
///     }
///
///     async fn authorize_delete(request: &Request, post: &Post) -> laravel::Result<bool> {
///         request.can(PostPolicy::delete, post).await
///     }
/// }
/// ```
///
/// # Authorization
///
/// Every `authorize_*` method allows everything until you override it. Each one receives the
/// request, so it can check a [policy](laravel::auth::policy) with `request.can(..)`. The panel
/// checks them on the server for every request, and also uses their answers to hide what the user
/// may not do. To limit which records a user sees at all, narrow [`query`](Self::query).
pub trait AdminResource: Send + Sync + 'static {
    /// The `#[model]` managed by this resource.
    type Model: Model + Serialize;

    /// What the "new record" form submits: any `#[laravel::input(fills = Self::Model)]` struct,
    /// or [`ReadOnly`] for a resource whose records the panel doesn't create. The struct's
    /// validation rules run before a record is created, and only its fields can be written.
    type CreateInput: ResourceInput<Self::Model>;

    /// What the edit form submits: any `#[laravel::input(fills = Self::Model)]` struct, or
    /// [`ReadOnly`] for a resource whose records the panel doesn't change.
    type UpdateInput: ResourceInput<Self::Model>;

    /// The resource's name in URLs, such as `posts` for `/admin/resources/posts`.
    fn slug() -> &'static str;

    /// What one record is called, such as `Post`.
    fn label() -> &'static str;

    /// What several records are called, such as `Posts`.
    fn plural_label() -> &'static str;

    /// The name of the icon shown beside the resource in the sidebar, such as `users`,
    /// `document-text`, or `shopping-bag`.
    fn icon() -> &'static str {
        "table-cells"
    }

    /// The sidebar group to list the resource under, such as `Some("Content")`.
    fn navigation_group() -> Option<&'static str> {
        None
    }

    /// Where the resource comes in the sidebar. Lower numbers come first.
    fn navigation_sort() -> i32 {
        0
    }

    /// The column that names a record, such as `title`. The panel uses it in search results,
    /// breadcrumbs, and confirmations. Without one, the panel uses the table's first column.
    fn record_title_column() -> Option<&'static str> {
        None
    }

    /// Whether the panel offers to create records. It doesn't when
    /// [`CreateInput`](Self::CreateInput) is [`ReadOnly`].
    fn can_create() -> bool {
        !Self::CreateInput::IS_READ_ONLY
    }

    /// Whether the panel offers to edit records. It doesn't when
    /// [`UpdateInput`](Self::UpdateInput) is [`ReadOnly`].
    fn can_edit() -> bool {
        !Self::UpdateInput::IS_READ_ONLY
    }

    /// Whether the panel offers to delete records.
    fn can_delete() -> bool {
        true
    }

    /// The page sizes the table offers.
    fn per_page_options() -> &'static [u64] {
        &[10, 25, 50, 100]
    }

    /// How many records a page of the table holds until the user picks another size.
    fn default_per_page() -> u64 {
        15
    }

    /// Adjusts the query behind everything the resource does: its table, its search, its export,
    /// and each lookup of a single record.
    ///
    /// Load the relationships the table shows here, and limit the records to the ones this
    /// request's user may see. A record the query leaves out doesn't exist as far as the panel
    /// is concerned: its URL responds with a `404`.
    ///
    /// ```ignore
    /// async fn query(request: &Request, query: Builder<Order>) -> laravel::Result<Builder<Order>> {
    ///     let user = request.user::<User>().await?.or_abort(401)?;
    ///     Ok(query.with(Order::customer).filter(Order::team_id.eq(user.team_id)))
    /// }
    /// ```
    fn query(
        _request: &Request,
        query: Builder<Self::Model>,
    ) -> impl Future<Output = laravel::Result<Builder<Self::Model>>> + Send {
        async move { Ok(query) }
    }

    /// The resource's table: its columns, filters, tabs, default order, and actions.
    fn table(table: TableBuilder<Self::Model>) -> TableBuilder<Self::Model>;

    /// The form for creating and editing a record: its sections and fields.
    fn form(form: FormBuilder) -> FormBuilder {
        form
    }

    /// Whether the user may see the resource at all. When they may not, the resource isn't in
    /// the sidebar and every request for it responds with a `403`.
    fn authorize_view_any(_request: &Request) -> impl Future<Output = laravel::Result<bool>> + Send {
        async { Ok(true) }
    }

    /// Whether the user may open a record.
    fn authorize_view(_request: &Request, _record: &Self::Model) -> impl Future<Output = laravel::Result<bool>> + Send {
        async { Ok(true) }
    }

    /// Whether the user may create a record.
    fn authorize_create(_request: &Request) -> impl Future<Output = laravel::Result<bool>> + Send {
        async { Ok(true) }
    }

    /// Whether the user may change a record.
    fn authorize_update(
        _request: &Request,
        _record: &Self::Model,
    ) -> impl Future<Output = laravel::Result<bool>> + Send {
        async { Ok(true) }
    }

    /// Whether the user may delete a record, alone or as one of several selected records.
    fn authorize_delete(
        _request: &Request,
        _record: &Self::Model,
    ) -> impl Future<Output = laravel::Result<bool>> + Send {
        async { Ok(true) }
    }

    /// Whether the user may run a custom row or bulk action.
    ///
    /// `action` is the action's name. `record` is the record a row action runs on, and `None`
    /// for a bulk action. The built-in delete goes through
    /// [`authorize_delete`](Self::authorize_delete) instead.
    fn authorize_action(
        _request: &Request,
        _action: &str,
        _record: Option<&Self::Model>,
    ) -> impl Future<Output = laravel::Result<bool>> + Send {
        async { Ok(true) }
    }

    /// A badge beside the resource in the sidebar, such as how many orders are waiting. The
    /// panel asks again after every change the user makes.
    fn navigation_badge(_request: &Request) -> impl Future<Output = laravel::Result<Option<NavigationBadge>>> + Send {
        async { Ok(None) }
    }
}

/// What a request asks of a resource's table, read from the query string of
/// `GET {base}/api/resources/{slug}` and of the CSV export.
#[derive(Debug, Clone, Default)]
pub(crate) struct ListQuery {
    /// The page to return, starting at 1.
    pub(crate) page: u64,
    /// How many records a page holds, or `None` for the resource's default.
    pub(crate) per_page: Option<u64>,
    /// Text to look for in the resource's searchable columns.
    pub(crate) search: Option<String>,
    /// The column to sort by. It only applies when the table marks that column sortable.
    pub(crate) sort: Option<String>,
    pub(crate) dir: Option<SortDirection>,
    /// The key of the table tab to apply.
    pub(crate) tab: Option<String>,
    /// The value of each filter in use, by the filter's name.
    pub(crate) filters: BTreeMap<String, String>,
}

impl ListQuery {
    /// Reads the parameters from a URL's query string, ignoring anything it doesn't understand.
    pub(crate) fn from_query_str(raw: Option<&str>) -> Self {
        let mut query = Self {
            page: 1,
            ..Self::default()
        };
        let Some(raw) = raw else {
            return query;
        };
        for (key, value) in url::form_urlencoded::parse(raw.as_bytes()) {
            let value = value.into_owned();
            match key.as_ref() {
                "page" => {
                    if let Ok(parsed) = value.parse::<u64>() {
                        query.page = parsed.max(1);
                    }
                }
                "per_page" => {
                    if let Ok(parsed) = value.parse::<u64>() {
                        query.per_page = Some(parsed.clamp(1, 250));
                    }
                }
                "search" | "q" => {
                    let trimmed = value.trim().to_owned();
                    if !trimmed.is_empty() {
                        query.search = Some(trimmed);
                    }
                }
                "sort" => {
                    if !value.is_empty() {
                        query.sort = Some(value);
                    }
                }
                "dir" => {
                    query.dir = match value.to_ascii_lowercase().as_str() {
                        "desc" => Some(SortDirection::Desc),
                        "asc" => Some(SortDirection::Asc),
                        _ => None,
                    };
                }
                "tab" => {
                    if !value.is_empty() {
                        query.tab = Some(value);
                    }
                }
                other => {
                    if let Some(name) = other.strip_prefix("filter[").and_then(|s| s.strip_suffix(']'))
                        && !value.is_empty()
                    {
                        query.filters.insert(name.to_owned(), value);
                    }
                }
            }
        }
        query
    }
}

/// Type-erased resource controller stored in [`crate::PanelState`].
pub(crate) trait ErasedResource: Send + Sync {
    fn slug(&self) -> &'static str;
    fn plural_label(&self) -> &'static str;
    fn icon(&self) -> &'static str;
    fn navigation_sort(&self) -> i32;

    fn schema<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<ResourceSchemaDto>>;

    fn total_count<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<u64>>;

    fn list<'a>(
        &'a self,
        request: &'a Request,
        params: ListQuery,
    ) -> BoxFuture<'a, laravel::Result<ResourceListResponse>>;

    fn export_csv<'a>(&'a self, request: &'a Request, params: ListQuery) -> BoxFuture<'a, laravel::Result<Streamed>>;

    fn show<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>>;

    fn create<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<RecordResponse>>;

    fn update<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>>;

    fn delete<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<ActionResponse>>;

    fn run_row_action<'a>(
        &'a self,
        request: &'a Arc<Request>,
        id: String,
        action_name: String,
        data: BTreeMap<String, serde_json::Value>,
    ) -> BoxFuture<'a, laravel::Result<ActionResponse>>;

    fn run_bulk_action<'a>(
        &'a self,
        request: &'a Arc<Request>,
        action_name: String,
        ids: Vec<String>,
        data: BTreeMap<String, serde_json::Value>,
    ) -> BoxFuture<'a, laravel::Result<ActionResponse>>;

    fn global_search<'a>(
        &'a self,
        request: &'a Request,
        query: String,
        limit: u64,
    ) -> BoxFuture<'a, laravel::Result<Option<GlobalSearchGroupDto>>>;
}

pub(crate) struct ResourceAdapter<R: AdminResource> {
    table: TableBuilder<R::Model>,
    form: FormBuilder,
    _marker: PhantomData<fn() -> R>,
}

impl<R> ResourceAdapter<R>
where
    R: AdminResource,
    <R::Model as Model>::Key: FromStr,
{
    /// Builds the resource's table and form once, and hides its model type from the panel.
    pub(crate) fn erased() -> Arc<dyn ErasedResource> {
        let table = R::table(TableBuilder::default());
        let form = R::form(FormBuilder::default());

        // A dotted column reads a loaded relationship from the serialized record. The database
        // has no such column, so sorting or searching by it would fail on the first request.
        // Fail when the panel is built instead.
        for column in &table.columns {
            assert!(
                !column.name.contains('.') || !(column.sortable || column.searchable),
                "the `{}` column of the `{}` resource reads a relationship, so it can't be \
                 `.sortable()` or `.searchable()`",
                column.name,
                R::slug(),
            );
        }

        Arc::new(Self {
            table,
            form,
            _marker: PhantomData,
        })
    }

    /// The resource's own query, which every read and write of its records starts from.
    async fn base_query(&self, request: &Request) -> laravel::Result<Builder<R::Model>> {
        R::query(request, model::query()).await
    }

    fn parse_key(raw: &str) -> laravel::Result<<R::Model as Model>::Key> {
        raw.parse::<<R::Model as Model>::Key>()
            .map_err(|_| laravel::abort_with(StatusCode::NOT_FOUND, "Record not found."))
    }

    fn extract_title(&self, data: &serde_json::Value) -> Option<String> {
        let title_col = R::record_title_column().or_else(|| {
            self.table
                .columns
                .iter()
                .find(|c| c.name != R::Model::META.key.name())
                .map(|c| c.name.as_str())
        })?;
        lookup(data, title_col).and_then(json_value_to_string)
    }

    async fn envelope(&self, request: &Request, model: &R::Model) -> laravel::Result<RecordEnvelopeDto> {
        let key = R::Model::META.key.get(model).to_string();
        let data = serde_json::to_value(model)?;
        let title = self.extract_title(&data);
        let can_view = R::authorize_view(request, model).await?;
        let can_edit = R::can_edit() && R::authorize_update(request, model).await?;
        let can_delete = R::can_delete() && R::authorize_delete(request, model).await?;

        // The actions to offer for this record: the ones that apply to it, and that this user
        // may run on it. Running an action checks both again.
        let mut actions = Vec::new();
        for action in &self.table.row_actions {
            if action.is_available(model) && R::authorize_action(request, &action.name, Some(model)).await? {
                actions.push(action.name.clone());
            }
        }

        Ok(RecordEnvelopeDto {
            key,
            title,
            data,
            can_view,
            can_edit,
            can_delete,
            actions,
        })
    }

    fn apply_search_and_filters(&self, mut query: Builder<R::Model>, params: &ListQuery) -> Builder<R::Model> {
        if let Some(search) = params.search.as_deref() {
            let searchable = self.table.search_columns();
            if !searchable.is_empty() {
                query = query.filter(any(searchable.into_iter().map(|c| col(c).contains(search))));
            }
        }

        for filter in &self.table.filters {
            if let Some(value) = params.filters.get(&filter.name) {
                query = (filter.apply)(query, value);
            }
        }

        query
    }

    fn apply_tab(&self, query: Builder<R::Model>, tab_key: Option<&str>) -> Builder<R::Model> {
        if let Some(key) = tab_key
            && let Some(tab) = self.table.tabs.iter().find(|t| t.key == key)
        {
            return (tab.apply)(query);
        }
        query
    }

    fn apply_sort(&self, query: Builder<R::Model>, params: &ListQuery) -> Builder<R::Model> {
        // Strict column whitelist so untrusted sort params can never inject SQL.
        let requested = params.sort.as_deref().and_then(|name| {
            self.table
                .columns
                .iter()
                .find(|c| c.sortable && c.name == name)
                .map(|c| (c.name.as_str(), params.dir.unwrap_or(SortDirection::Asc)))
        });

        let sort = requested.or_else(|| {
            self.table
                .default_sort
                .as_ref()
                .map(|s| (s.column.as_str(), s.direction))
        });

        match sort {
            Some((column, direction)) => {
                let ordered = match direction {
                    SortDirection::Asc => query.order_by(col(column).asc()),
                    SortDirection::Desc => query.order_by(col(column).desc()),
                };
                // Rows that tie on the sorted column need a fixed order too, or they could move
                // between pages from one request to the next.
                if column == R::Model::META.key.name() {
                    ordered
                } else {
                    ordered.order_by(R::Model::META.key.desc())
                }
            }
            None => query.order_by(R::Model::META.key.desc()),
        }
    }
}

impl<R> ErasedResource for ResourceAdapter<R>
where
    R: AdminResource,
    <R::Model as Model>::Key: FromStr,
{
    fn slug(&self) -> &'static str {
        R::slug()
    }

    fn plural_label(&self) -> &'static str {
        R::plural_label()
    }

    fn icon(&self) -> &'static str {
        R::icon()
    }

    fn navigation_sort(&self) -> i32 {
        R::navigation_sort()
    }

    fn schema<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<ResourceSchemaDto>> {
        Box::pin(async move {
            let view_any = R::authorize_view_any(request).await?;
            let create = R::can_create() && R::authorize_create(request).await?;
            let edit = R::can_edit();
            let delete = R::can_delete();
            let badge = R::navigation_badge(request).await?.map(NavigationBadge::into_dto);

            // A bulk action the user may not run isn't offered at all.
            let mut bulk_actions = Vec::new();
            for action in &self.table.bulk_actions {
                if R::authorize_action(request, &action.name, None).await? {
                    bulk_actions.push(action.to_dto());
                }
            }

            Ok(ResourceSchemaDto {
                slug: R::slug().to_owned(),
                label: R::label().to_owned(),
                plural_label: R::plural_label().to_owned(),
                icon: R::icon().to_owned(),
                navigation_group: R::navigation_group().map(str::to_owned),
                navigation_sort: R::navigation_sort(),
                navigation_badge: badge,
                key_column: R::Model::META.key.name().to_owned(),
                title_column: R::record_title_column().map(str::to_owned),
                permissions: ResourcePermissionsDto {
                    view_any,
                    create,
                    edit,
                    delete,
                },
                per_page_options: R::per_page_options().to_vec(),
                default_per_page: R::default_per_page(),
                searchable: !self.table.search_columns().is_empty(),
                exportable: self.table.exportable,
                default_sort: self.table.default_sort.clone(),
                columns: self.table.columns.iter().map(|c| c.to_dto()).collect(),
                filters: self.table.filters.iter().map(|f| f.to_dto()).collect(),
                tabs: self.table.tabs.iter().map(|t| t.to_dto()).collect(),
                row_actions: self.table.row_actions.iter().map(|a| a.to_dto()).collect(),
                bulk_actions,
                form_sections: self.form.to_dto(),
            })
        })
    }

    fn total_count<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<u64>> {
        Box::pin(async move { self.base_query(request).await?.count().await })
    }

    fn list<'a>(
        &'a self,
        request: &'a Request,
        params: ListQuery,
    ) -> BoxFuture<'a, laravel::Result<ResourceListResponse>> {
        Box::pin(async move {
            if !R::authorize_view_any(request).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to view this resource.",
                ));
            }

            let per_page = params.per_page.unwrap_or_else(R::default_per_page).clamp(1, 250);
            let pre_tab = self.apply_search_and_filters(self.base_query(request).await?, &params);

            // Compute live counts for each declared tab.
            let mut tab_counts = BTreeMap::new();
            for tab in &self.table.tabs {
                let count = (tab.apply)(pre_tab.clone()).count().await?;
                tab_counts.insert(tab.key.clone(), count);
            }

            let filtered = self.apply_tab(pre_tab, params.tab.as_deref());
            let total = filtered.count().await?;
            let last_page = if total == 0 { 1 } else { total.div_ceil(per_page) };
            let current_page = params.page.clamp(1, last_page);
            let offset = (current_page - 1).saturating_mul(per_page);

            let rows = self
                .apply_sort(filtered, &params)
                .limit(per_page)
                .offset(offset)
                .get()
                .await?;

            let mut data = Vec::with_capacity(rows.len());
            for row in &rows {
                data.push(self.envelope(request, row).await?);
            }

            let (from, to) = if data.is_empty() {
                (None, None)
            } else {
                (Some(offset + 1), Some(offset + data.len() as u64))
            };

            Ok(ResourceListResponse {
                data,
                meta: PaginationMetaDto {
                    current_page,
                    last_page,
                    per_page,
                    total,
                    from,
                    to,
                },
                tab_counts,
            })
        })
    }

    fn export_csv<'a>(&'a self, request: &'a Request, params: ListQuery) -> BoxFuture<'a, laravel::Result<Streamed>> {
        Box::pin(async move {
            if !self.table.exportable {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "CSV export is disabled for this resource.",
                ));
            }
            if !R::authorize_view_any(request).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to export this resource.",
                ));
            }

            let pre_tab = self.apply_search_and_filters(self.base_query(request).await?, &params);
            let filtered = self.apply_tab(pre_tab, params.tab.as_deref());
            let query = self.apply_sort(filtered, &params);

            let columns: Vec<(String, String)> = self
                .table
                .columns
                .iter()
                .map(|c| (c.name.clone(), c.label.clone()))
                .collect();

            // Rows are read and sent a page at a time, so an export of any size never has to fit
            // in memory, and nothing is silently cut off.
            let streamed = Streamed::channel(move |sender| async move {
                let mut header = columns
                    .iter()
                    .map(|(_, label)| csv_escape(label))
                    .collect::<Vec<_>>()
                    .join(",");
                header.push('\n');
                sender.send(header).await?;

                let mut pages = query.chunk(EXPORT_CHUNK_SIZE);
                while let Some(rows) = pages.try_next().await? {
                    let mut out = String::new();
                    for row in &rows {
                        let value = serde_json::to_value(row)?;
                        let line: Vec<String> = columns
                            .iter()
                            .map(|(name, _)| {
                                let cell = lookup(&value, name).and_then(json_value_to_string).unwrap_or_default();
                                csv_escape(&csv_neutralize(cell))
                            })
                            .collect();
                        out.push_str(&line.join(","));
                        out.push('\n');
                    }
                    sender.send(out).await?;
                }

                Ok(())
            })
            .content_type("text/csv; charset=utf-8")
            .with_header(
                "content-disposition",
                format!("attachment; filename=\"{}.csv\"", R::slug()),
            );

            Ok(streamed)
        })
    }

    fn show<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>> {
        Box::pin(async move {
            let key = Self::parse_key(&id)?;
            let model = self.base_query(request).await?.find_or_fail(key).await?;
            if !R::authorize_view(request, &model).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to view this record.",
                ));
            }
            let record = self.envelope(request, &model).await?;
            Ok(RecordResponse { record, message: None })
        })
    }

    fn create<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<RecordResponse>> {
        Box::pin(async move {
            if !R::can_create() {
                return Err(laravel::abort_with(
                    StatusCode::METHOD_NOT_ALLOWED,
                    "Creating records is disabled for this resource.",
                ));
            }
            if !R::authorize_create(request).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to create this resource.",
                ));
            }

            let created = R::CreateInput::create_from_request(request).await?;
            let record = self.envelope(request, &created).await?;
            Ok(RecordResponse {
                record,
                message: Some(format!("{} created.", R::label())),
            })
        })
    }

    fn update<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>> {
        Box::pin(async move {
            if !R::can_edit() {
                return Err(laravel::abort_with(
                    StatusCode::METHOD_NOT_ALLOWED,
                    "Editing records is disabled for this resource.",
                ));
            }
            let key = Self::parse_key(&id)?;
            let mut model = self.base_query(request).await?.find_or_fail(key).await?;
            if !R::authorize_update(request, &model).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to edit this record.",
                ));
            }

            R::UpdateInput::update_from_request(request, &mut model).await?;
            let record = self.envelope(request, &model).await?;
            Ok(RecordResponse {
                record,
                message: Some(format!("{} updated.", R::label())),
            })
        })
    }

    fn delete<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<ActionResponse>> {
        Box::pin(async move {
            if !R::can_delete() {
                return Err(laravel::abort_with(
                    StatusCode::METHOD_NOT_ALLOWED,
                    "Deleting records is disabled for this resource.",
                ));
            }
            let key = Self::parse_key(&id)?;
            let model = self.base_query(request).await?.find_or_fail(key).await?;
            if !R::authorize_delete(request, &model).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to delete this record.",
                ));
            }

            model::delete(model).await?;
            Ok(ActionResponse {
                message: format!("{} deleted.", R::label()),
                affected: 1,
                redirect_to: None,
                refresh: true,
            })
        })
    }

    fn run_row_action<'a>(
        &'a self,
        request: &'a Arc<Request>,
        id: String,
        action_name: String,
        data: BTreeMap<String, serde_json::Value>,
    ) -> BoxFuture<'a, laravel::Result<ActionResponse>> {
        Box::pin(async move {
            let Some(action) = self.table.row_actions.iter().find(|a| a.name == action_name) else {
                return Err(laravel::abort_with(StatusCode::NOT_FOUND, "Action not found."));
            };

            let key = Self::parse_key(&id)?;
            let model = self.base_query(request).await?.find_or_fail(key).await?;
            if !R::authorize_view(request, &model).await?
                || !R::authorize_action(request, &action_name, Some(&model)).await?
            {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to run this action.",
                ));
            }

            if !action.is_available(&model) {
                return Err(laravel::abort_with(
                    StatusCode::UNPROCESSABLE_ENTITY,
                    format!(
                        "“{}” isn't available for this {}.",
                        action.label,
                        R::label().to_lowercase()
                    ),
                ));
            }

            let context = ActionContext::new(request, data);
            let outcome = (action.handler)(context, model).await?;
            Ok(outcome.into_response())
        })
    }

    fn run_bulk_action<'a>(
        &'a self,
        request: &'a Arc<Request>,
        action_name: String,
        ids: Vec<String>,
        data: BTreeMap<String, serde_json::Value>,
    ) -> BoxFuture<'a, laravel::Result<ActionResponse>> {
        Box::pin(async move {
            if ids.is_empty() {
                return Err(laravel::abort_with(StatusCode::BAD_REQUEST, "No records selected."));
            }

            let mut keys = Vec::with_capacity(ids.len());
            for id in &ids {
                keys.push(Self::parse_key(id)?);
            }

            let models = self
                .base_query(request)
                .await?
                .filter(R::Model::META.key.is_in(keys))
                .get()
                .await?;

            // Built-in bulk delete action.
            if action_name == "delete" {
                if !R::can_delete() {
                    return Err(laravel::abort_with(
                        StatusCode::METHOD_NOT_ALLOWED,
                        "Deleting records is disabled for this resource.",
                    ));
                }
                for model in &models {
                    if !R::authorize_delete(request, model).await? {
                        return Err(laravel::abort_with(
                            StatusCode::FORBIDDEN,
                            "You are not authorized to delete one or more selected records.",
                        ));
                    }
                }
                let count = models.len() as u64;
                for model in models {
                    model::delete(model).await?;
                }
                return Ok(ActionResponse {
                    message: format!(
                        "Deleted {count} {}.",
                        if count == 1 { R::label() } else { R::plural_label() }
                    ),
                    affected: count,
                    redirect_to: None,
                    refresh: true,
                });
            }

            let Some(action) = self.table.bulk_actions.iter().find(|a| a.name == action_name) else {
                return Err(laravel::abort_with(StatusCode::NOT_FOUND, "Bulk action not found."));
            };

            if !R::authorize_view_any(request).await? || !R::authorize_action(request, &action_name, None).await? {
                return Err(laravel::abort_with(
                    StatusCode::FORBIDDEN,
                    "You are not authorized to run this action.",
                ));
            }

            let context = ActionContext::new(request, data);
            let outcome = (action.handler)(context, models).await?;
            Ok(outcome.into_response())
        })
    }

    fn global_search<'a>(
        &'a self,
        request: &'a Request,
        query_text: String,
        limit: u64,
    ) -> BoxFuture<'a, laravel::Result<Option<GlobalSearchGroupDto>>> {
        Box::pin(async move {
            let searchable = self.table.search_columns();
            if searchable.is_empty() || !R::authorize_view_any(request).await? {
                return Ok(None);
            }

            let rows = self
                .base_query(request)
                .await?
                .filter(any(searchable.iter().map(|c| col(*c).contains(query_text.as_str()))))
                .order_by(R::Model::META.key.desc())
                .limit(limit)
                .get()
                .await?;

            if rows.is_empty() {
                return Ok(None);
            }

            let subtitle_col = searchable.get(1).copied();
            let mut hits = Vec::with_capacity(rows.len());
            for row in &rows {
                let key = R::Model::META.key.get(row).to_string();
                let value = serde_json::to_value(row)?;
                let title = self
                    .extract_title(&value)
                    .unwrap_or_else(|| format!("{} #{key}", R::label()));
                let subtitle = subtitle_col
                    .and_then(|c| lookup(&value, c))
                    .and_then(json_value_to_string)
                    .filter(|s| s != &title);
                hits.push(GlobalSearchHitDto { key, title, subtitle });
            }

            Ok(Some(GlobalSearchGroupDto {
                resource_slug: R::slug().to_owned(),
                resource_label: R::plural_label().to_owned(),
                icon: R::icon().to_owned(),
                hits,
            }))
        })
    }
}

/// Reads a column's value from a serialized record. A column's name is a field of the record,
/// or a dotted path into a loaded relationship, such as `customer.name`.
fn lookup<'a>(record: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> {
    path.split('.').try_fold(record, |value, key| value.get(key))
}

fn json_value_to_string(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::Null => None,
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Bool(b) => Some(b.to_string()),
        serde_json::Value::Number(n) => Some(n.to_string()),
        other => Some(other.to_string()),
    }
}

/// How many rows an export reads from the database at a time.
const EXPORT_CHUNK_SIZE: u64 = 500;

/// Keeps a spreadsheet from running a cell as a formula. A cell that starts with `=`, `+`, `-`,
/// `@`, a tab, or a carriage return gets a leading apostrophe, unless it's a plain number such as
/// `-12.5`.
fn csv_neutralize(cell: String) -> String {
    let risky = cell.starts_with(['=', '+', '-', '@', '\t', '\r']);
    if risky && cell.parse::<f64>().is_err() {
        format!("'{cell}")
    } else {
        cell
    }
}

fn csv_escape(input: &str) -> String {
    if input.contains([',', '"', '\n', '\r']) {
        format!("\"{}\"", input.replace('"', "\"\""))
    } else {
        input.to_owned()
    }
}