Skip to main content

laravel_rust_admin/
resource.rs

1//! The [`AdminResource`] trait, and the code that serves a resource's table, form, search, and
2//! export from it.
3
4use std::collections::BTreeMap;
5use std::future::Future;
6use std::marker::PhantomData;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use futures_util::TryStreamExt;
11use futures_util::future::BoxFuture;
12use laravel::db::{Builder, any, col};
13use laravel::http::{Request, StatusCode, Streamed};
14use laravel::model::{Fill, Model};
15use laravel::validation::ValidatesRequest;
16use serde::Serialize;
17use serde::de::DeserializeOwned;
18
19use crate::model;
20use crate::protocol::{
21    ActionResponse, BadgeColor, GlobalSearchGroupDto, GlobalSearchHitDto, NavigationBadgeDto, PaginationMetaDto,
22    RecordEnvelopeDto, RecordResponse, ResourceListResponse, ResourcePermissionsDto, ResourceSchemaDto, SortDirection,
23};
24use crate::schema::action::ActionContext;
25use crate::schema::form::FormBuilder;
26use crate::schema::table::TableBuilder;
27
28/// Sidebar badge returned by [`AdminResource::navigation_badge`].
29#[derive(Debug, Clone)]
30pub struct NavigationBadge {
31    /// The badge's text, usually a count.
32    pub label: String,
33    /// The badge's color.
34    pub color: BadgeColor,
35}
36
37impl NavigationBadge {
38    /// A neutral badge with this text.
39    #[must_use]
40    pub fn new(label: impl Into<String>) -> Self {
41        Self {
42            label: label.into(),
43            color: BadgeColor::Zinc,
44        }
45    }
46
47    /// Colors the badge, such as amber for something that's waiting.
48    #[must_use]
49    pub fn color(mut self, color: BadgeColor) -> Self {
50        self.color = color;
51        self
52    }
53
54    pub(crate) fn into_dto(self) -> NavigationBadgeDto {
55        NavigationBadgeDto {
56            label: self.label,
57            color: self.color,
58        }
59    }
60}
61
62/// The [`CreateInput`](AdminResource::CreateInput) or [`UpdateInput`](AdminResource::UpdateInput)
63/// of a resource whose records the panel doesn't create, or doesn't change.
64#[derive(Debug, Clone, Copy, Default)]
65pub struct ReadOnly;
66
67/// What a resource creates or updates its records with.
68///
69/// Every `#[laravel::input(fills = M)]` struct implements this trait, and so does [`ReadOnly`].
70/// You don't implement it yourself.
71pub trait ResourceInput<M: Model>: Send + Sync + 'static {
72    /// Whether the input refuses every create and update, as [`ReadOnly`] does.
73    const IS_READ_ONLY: bool = false;
74
75    /// Validates the request's input as this type, and creates a model from it.
76    fn create_from_request<'a>(request: &'a Request) -> BoxFuture<'a, laravel::Result<M>>;
77
78    /// Validates the request's input as this type, and updates the record with it.
79    fn update_from_request<'a>(request: &'a Request, record: &'a mut M) -> BoxFuture<'a, laravel::Result<()>>;
80}
81
82impl<M: Model> ResourceInput<M> for ReadOnly {
83    const IS_READ_ONLY: bool = true;
84
85    fn create_from_request<'a>(_request: &'a Request) -> BoxFuture<'a, laravel::Result<M>> {
86        Box::pin(async {
87            Err(laravel::abort_with(
88                StatusCode::METHOD_NOT_ALLOWED,
89                "Creating records is disabled for this resource.",
90            ))
91        })
92    }
93
94    fn update_from_request<'a>(_request: &'a Request, _record: &'a mut M) -> BoxFuture<'a, laravel::Result<()>> {
95        Box::pin(async {
96            Err(laravel::abort_with(
97                StatusCode::METHOD_NOT_ALLOWED,
98                "Editing records is disabled for this resource.",
99            ))
100        })
101    }
102}
103
104impl<M, T> ResourceInput<M> for T
105where
106    M: Model,
107    T: DeserializeOwned + ValidatesRequest + Fill<M> + Send + Sync + 'static,
108{
109    const IS_READ_ONLY: bool = false;
110
111    fn create_from_request<'a>(request: &'a Request) -> BoxFuture<'a, laravel::Result<M>> {
112        Box::pin(async move {
113            let input: T = request.validate().await?;
114            model::create(input).await
115        })
116    }
117
118    fn update_from_request<'a>(request: &'a Request, record: &'a mut M) -> BoxFuture<'a, laravel::Result<()>> {
119        Box::pin(async move {
120            let input: T = request.validate().await?;
121            model::update(record, input).await
122        })
123    }
124}
125
126/// A model in the admin panel: its place in the sidebar, its table, its form, and who may do what
127/// with its records.
128///
129/// `#[derive(AdminResource)]` on a `#[model]` struct builds all of this from the struct's fields.
130/// Implement the trait by hand, usually on a unit struct, when a resource needs more: tabs,
131/// actions, a relationship in its table, or authorization.
132///
133/// ```ignore
134/// pub struct PostResource;
135///
136/// impl AdminResource for PostResource {
137///     type Model = Post;
138///     type CreateInput = StorePost;
139///     type UpdateInput = StorePost;
140///
141///     fn slug() -> &'static str { "posts" }
142///     fn label() -> &'static str { "Post" }
143///     fn plural_label() -> &'static str { "Posts" }
144///
145///     fn table(table: TableBuilder<Post>) -> TableBuilder<Post> {
146///         table
147///             .column(Column::text("title").searchable().sortable())
148///             .column(Column::badge("status"))
149///     }
150///
151///     fn form(form: FormBuilder) -> FormBuilder {
152///         form.field(Field::text("title").required())
153///     }
154///
155///     async fn authorize_delete(request: &Request, post: &Post) -> laravel::Result<bool> {
156///         request.can(PostPolicy::delete, post).await
157///     }
158/// }
159/// ```
160///
161/// # Authorization
162///
163/// Every `authorize_*` method allows everything until you override it. Each one receives the
164/// request, so it can check a [policy](laravel::auth::policy) with `request.can(..)`. The panel
165/// checks them on the server for every request, and also uses their answers to hide what the user
166/// may not do. To limit which records a user sees at all, narrow [`query`](Self::query).
167pub trait AdminResource: Send + Sync + 'static {
168    /// The `#[model]` managed by this resource.
169    type Model: Model + Serialize;
170
171    /// What the "new record" form submits: any `#[laravel::input(fills = Self::Model)]` struct,
172    /// or [`ReadOnly`] for a resource whose records the panel doesn't create. The struct's
173    /// validation rules run before a record is created, and only its fields can be written.
174    type CreateInput: ResourceInput<Self::Model>;
175
176    /// What the edit form submits: any `#[laravel::input(fills = Self::Model)]` struct, or
177    /// [`ReadOnly`] for a resource whose records the panel doesn't change.
178    type UpdateInput: ResourceInput<Self::Model>;
179
180    /// The resource's name in URLs, such as `posts` for `/admin/resources/posts`.
181    fn slug() -> &'static str;
182
183    /// What one record is called, such as `Post`.
184    fn label() -> &'static str;
185
186    /// What several records are called, such as `Posts`.
187    fn plural_label() -> &'static str;
188
189    /// The name of the icon shown beside the resource in the sidebar, such as `users`,
190    /// `document-text`, or `shopping-bag`.
191    fn icon() -> &'static str {
192        "table-cells"
193    }
194
195    /// The sidebar group to list the resource under, such as `Some("Content")`.
196    fn navigation_group() -> Option<&'static str> {
197        None
198    }
199
200    /// Where the resource comes in the sidebar. Lower numbers come first.
201    fn navigation_sort() -> i32 {
202        0
203    }
204
205    /// The column that names a record, such as `title`. The panel uses it in search results,
206    /// breadcrumbs, and confirmations. Without one, the panel uses the table's first column.
207    fn record_title_column() -> Option<&'static str> {
208        None
209    }
210
211    /// Whether the panel offers to create records. It doesn't when
212    /// [`CreateInput`](Self::CreateInput) is [`ReadOnly`].
213    fn can_create() -> bool {
214        !Self::CreateInput::IS_READ_ONLY
215    }
216
217    /// Whether the panel offers to edit records. It doesn't when
218    /// [`UpdateInput`](Self::UpdateInput) is [`ReadOnly`].
219    fn can_edit() -> bool {
220        !Self::UpdateInput::IS_READ_ONLY
221    }
222
223    /// Whether the panel offers to delete records.
224    fn can_delete() -> bool {
225        true
226    }
227
228    /// The page sizes the table offers.
229    fn per_page_options() -> &'static [u64] {
230        &[10, 25, 50, 100]
231    }
232
233    /// How many records a page of the table holds until the user picks another size.
234    fn default_per_page() -> u64 {
235        15
236    }
237
238    /// Adjusts the query behind everything the resource does: its table, its search, its export,
239    /// and each lookup of a single record.
240    ///
241    /// Load the relationships the table shows here, and limit the records to the ones this
242    /// request's user may see. A record the query leaves out doesn't exist as far as the panel
243    /// is concerned: its URL responds with a `404`.
244    ///
245    /// ```ignore
246    /// async fn query(request: &Request, query: Builder<Order>) -> laravel::Result<Builder<Order>> {
247    ///     let user = request.user::<User>().await?.or_abort(401)?;
248    ///     Ok(query.with(Order::customer).filter(Order::team_id.eq(user.team_id)))
249    /// }
250    /// ```
251    fn query(
252        _request: &Request,
253        query: Builder<Self::Model>,
254    ) -> impl Future<Output = laravel::Result<Builder<Self::Model>>> + Send {
255        async move { Ok(query) }
256    }
257
258    /// The resource's table: its columns, filters, tabs, default order, and actions.
259    fn table(table: TableBuilder<Self::Model>) -> TableBuilder<Self::Model>;
260
261    /// The form for creating and editing a record: its sections and fields.
262    fn form(form: FormBuilder) -> FormBuilder {
263        form
264    }
265
266    /// Whether the user may see the resource at all. When they may not, the resource isn't in
267    /// the sidebar and every request for it responds with a `403`.
268    fn authorize_view_any(_request: &Request) -> impl Future<Output = laravel::Result<bool>> + Send {
269        async { Ok(true) }
270    }
271
272    /// Whether the user may open a record.
273    fn authorize_view(_request: &Request, _record: &Self::Model) -> impl Future<Output = laravel::Result<bool>> + Send {
274        async { Ok(true) }
275    }
276
277    /// Whether the user may create a record.
278    fn authorize_create(_request: &Request) -> impl Future<Output = laravel::Result<bool>> + Send {
279        async { Ok(true) }
280    }
281
282    /// Whether the user may change a record.
283    fn authorize_update(
284        _request: &Request,
285        _record: &Self::Model,
286    ) -> impl Future<Output = laravel::Result<bool>> + Send {
287        async { Ok(true) }
288    }
289
290    /// Whether the user may delete a record, alone or as one of several selected records.
291    fn authorize_delete(
292        _request: &Request,
293        _record: &Self::Model,
294    ) -> impl Future<Output = laravel::Result<bool>> + Send {
295        async { Ok(true) }
296    }
297
298    /// Whether the user may run a custom row or bulk action.
299    ///
300    /// `action` is the action's name. `record` is the record a row action runs on, and `None`
301    /// for a bulk action. The built-in delete goes through
302    /// [`authorize_delete`](Self::authorize_delete) instead.
303    fn authorize_action(
304        _request: &Request,
305        _action: &str,
306        _record: Option<&Self::Model>,
307    ) -> impl Future<Output = laravel::Result<bool>> + Send {
308        async { Ok(true) }
309    }
310
311    /// A badge beside the resource in the sidebar, such as how many orders are waiting. The
312    /// panel asks again after every change the user makes.
313    fn navigation_badge(_request: &Request) -> impl Future<Output = laravel::Result<Option<NavigationBadge>>> + Send {
314        async { Ok(None) }
315    }
316}
317
318/// What a request asks of a resource's table, read from the query string of
319/// `GET {base}/api/resources/{slug}` and of the CSV export.
320#[derive(Debug, Clone, Default)]
321pub(crate) struct ListQuery {
322    /// The page to return, starting at 1.
323    pub(crate) page: u64,
324    /// How many records a page holds, or `None` for the resource's default.
325    pub(crate) per_page: Option<u64>,
326    /// Text to look for in the resource's searchable columns.
327    pub(crate) search: Option<String>,
328    /// The column to sort by. It only applies when the table marks that column sortable.
329    pub(crate) sort: Option<String>,
330    pub(crate) dir: Option<SortDirection>,
331    /// The key of the table tab to apply.
332    pub(crate) tab: Option<String>,
333    /// The value of each filter in use, by the filter's name.
334    pub(crate) filters: BTreeMap<String, String>,
335}
336
337impl ListQuery {
338    /// Reads the parameters from a URL's query string, ignoring anything it doesn't understand.
339    pub(crate) fn from_query_str(raw: Option<&str>) -> Self {
340        let mut query = Self {
341            page: 1,
342            ..Self::default()
343        };
344        let Some(raw) = raw else {
345            return query;
346        };
347        for (key, value) in url::form_urlencoded::parse(raw.as_bytes()) {
348            let value = value.into_owned();
349            match key.as_ref() {
350                "page" => {
351                    if let Ok(parsed) = value.parse::<u64>() {
352                        query.page = parsed.max(1);
353                    }
354                }
355                "per_page" => {
356                    if let Ok(parsed) = value.parse::<u64>() {
357                        query.per_page = Some(parsed.clamp(1, 250));
358                    }
359                }
360                "search" | "q" => {
361                    let trimmed = value.trim().to_owned();
362                    if !trimmed.is_empty() {
363                        query.search = Some(trimmed);
364                    }
365                }
366                "sort" => {
367                    if !value.is_empty() {
368                        query.sort = Some(value);
369                    }
370                }
371                "dir" => {
372                    query.dir = match value.to_ascii_lowercase().as_str() {
373                        "desc" => Some(SortDirection::Desc),
374                        "asc" => Some(SortDirection::Asc),
375                        _ => None,
376                    };
377                }
378                "tab" => {
379                    if !value.is_empty() {
380                        query.tab = Some(value);
381                    }
382                }
383                other => {
384                    if let Some(name) = other.strip_prefix("filter[").and_then(|s| s.strip_suffix(']'))
385                        && !value.is_empty()
386                    {
387                        query.filters.insert(name.to_owned(), value);
388                    }
389                }
390            }
391        }
392        query
393    }
394}
395
396/// Type-erased resource controller stored in [`crate::PanelState`].
397pub(crate) trait ErasedResource: Send + Sync {
398    fn slug(&self) -> &'static str;
399    fn plural_label(&self) -> &'static str;
400    fn icon(&self) -> &'static str;
401    fn navigation_sort(&self) -> i32;
402
403    fn schema<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<ResourceSchemaDto>>;
404
405    fn total_count<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<u64>>;
406
407    fn list<'a>(
408        &'a self,
409        request: &'a Request,
410        params: ListQuery,
411    ) -> BoxFuture<'a, laravel::Result<ResourceListResponse>>;
412
413    fn export_csv<'a>(&'a self, request: &'a Request, params: ListQuery) -> BoxFuture<'a, laravel::Result<Streamed>>;
414
415    fn show<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>>;
416
417    fn create<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<RecordResponse>>;
418
419    fn update<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>>;
420
421    fn delete<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<ActionResponse>>;
422
423    fn run_row_action<'a>(
424        &'a self,
425        request: &'a Arc<Request>,
426        id: String,
427        action_name: String,
428        data: BTreeMap<String, serde_json::Value>,
429    ) -> BoxFuture<'a, laravel::Result<ActionResponse>>;
430
431    fn run_bulk_action<'a>(
432        &'a self,
433        request: &'a Arc<Request>,
434        action_name: String,
435        ids: Vec<String>,
436        data: BTreeMap<String, serde_json::Value>,
437    ) -> BoxFuture<'a, laravel::Result<ActionResponse>>;
438
439    fn global_search<'a>(
440        &'a self,
441        request: &'a Request,
442        query: String,
443        limit: u64,
444    ) -> BoxFuture<'a, laravel::Result<Option<GlobalSearchGroupDto>>>;
445}
446
447pub(crate) struct ResourceAdapter<R: AdminResource> {
448    table: TableBuilder<R::Model>,
449    form: FormBuilder,
450    _marker: PhantomData<fn() -> R>,
451}
452
453impl<R> ResourceAdapter<R>
454where
455    R: AdminResource,
456    <R::Model as Model>::Key: FromStr,
457{
458    /// Builds the resource's table and form once, and hides its model type from the panel.
459    pub(crate) fn erased() -> Arc<dyn ErasedResource> {
460        let table = R::table(TableBuilder::default());
461        let form = R::form(FormBuilder::default());
462
463        // A dotted column reads a loaded relationship from the serialized record. The database
464        // has no such column, so sorting or searching by it would fail on the first request.
465        // Fail when the panel is built instead.
466        for column in &table.columns {
467            assert!(
468                !column.name.contains('.') || !(column.sortable || column.searchable),
469                "the `{}` column of the `{}` resource reads a relationship, so it can't be \
470                 `.sortable()` or `.searchable()`",
471                column.name,
472                R::slug(),
473            );
474        }
475
476        Arc::new(Self {
477            table,
478            form,
479            _marker: PhantomData,
480        })
481    }
482
483    /// The resource's own query, which every read and write of its records starts from.
484    async fn base_query(&self, request: &Request) -> laravel::Result<Builder<R::Model>> {
485        R::query(request, model::query()).await
486    }
487
488    fn parse_key(raw: &str) -> laravel::Result<<R::Model as Model>::Key> {
489        raw.parse::<<R::Model as Model>::Key>()
490            .map_err(|_| laravel::abort_with(StatusCode::NOT_FOUND, "Record not found."))
491    }
492
493    fn extract_title(&self, data: &serde_json::Value) -> Option<String> {
494        let title_col = R::record_title_column().or_else(|| {
495            self.table
496                .columns
497                .iter()
498                .find(|c| c.name != R::Model::META.key.name())
499                .map(|c| c.name.as_str())
500        })?;
501        lookup(data, title_col).and_then(json_value_to_string)
502    }
503
504    async fn envelope(&self, request: &Request, model: &R::Model) -> laravel::Result<RecordEnvelopeDto> {
505        let key = R::Model::META.key.get(model).to_string();
506        let data = serde_json::to_value(model)?;
507        let title = self.extract_title(&data);
508        let can_view = R::authorize_view(request, model).await?;
509        let can_edit = R::can_edit() && R::authorize_update(request, model).await?;
510        let can_delete = R::can_delete() && R::authorize_delete(request, model).await?;
511
512        // The actions to offer for this record: the ones that apply to it, and that this user
513        // may run on it. Running an action checks both again.
514        let mut actions = Vec::new();
515        for action in &self.table.row_actions {
516            if action.is_available(model) && R::authorize_action(request, &action.name, Some(model)).await? {
517                actions.push(action.name.clone());
518            }
519        }
520
521        Ok(RecordEnvelopeDto {
522            key,
523            title,
524            data,
525            can_view,
526            can_edit,
527            can_delete,
528            actions,
529        })
530    }
531
532    fn apply_search_and_filters(&self, mut query: Builder<R::Model>, params: &ListQuery) -> Builder<R::Model> {
533        if let Some(search) = params.search.as_deref() {
534            let searchable = self.table.search_columns();
535            if !searchable.is_empty() {
536                query = query.filter(any(searchable.into_iter().map(|c| col(c).contains(search))));
537            }
538        }
539
540        for filter in &self.table.filters {
541            if let Some(value) = params.filters.get(&filter.name) {
542                query = (filter.apply)(query, value);
543            }
544        }
545
546        query
547    }
548
549    fn apply_tab(&self, query: Builder<R::Model>, tab_key: Option<&str>) -> Builder<R::Model> {
550        if let Some(key) = tab_key
551            && let Some(tab) = self.table.tabs.iter().find(|t| t.key == key)
552        {
553            return (tab.apply)(query);
554        }
555        query
556    }
557
558    fn apply_sort(&self, query: Builder<R::Model>, params: &ListQuery) -> Builder<R::Model> {
559        // Strict column whitelist so untrusted sort params can never inject SQL.
560        let requested = params.sort.as_deref().and_then(|name| {
561            self.table
562                .columns
563                .iter()
564                .find(|c| c.sortable && c.name == name)
565                .map(|c| (c.name.as_str(), params.dir.unwrap_or(SortDirection::Asc)))
566        });
567
568        let sort = requested.or_else(|| {
569            self.table
570                .default_sort
571                .as_ref()
572                .map(|s| (s.column.as_str(), s.direction))
573        });
574
575        match sort {
576            Some((column, direction)) => {
577                let ordered = match direction {
578                    SortDirection::Asc => query.order_by(col(column).asc()),
579                    SortDirection::Desc => query.order_by(col(column).desc()),
580                };
581                // Rows that tie on the sorted column need a fixed order too, or they could move
582                // between pages from one request to the next.
583                if column == R::Model::META.key.name() {
584                    ordered
585                } else {
586                    ordered.order_by(R::Model::META.key.desc())
587                }
588            }
589            None => query.order_by(R::Model::META.key.desc()),
590        }
591    }
592}
593
594impl<R> ErasedResource for ResourceAdapter<R>
595where
596    R: AdminResource,
597    <R::Model as Model>::Key: FromStr,
598{
599    fn slug(&self) -> &'static str {
600        R::slug()
601    }
602
603    fn plural_label(&self) -> &'static str {
604        R::plural_label()
605    }
606
607    fn icon(&self) -> &'static str {
608        R::icon()
609    }
610
611    fn navigation_sort(&self) -> i32 {
612        R::navigation_sort()
613    }
614
615    fn schema<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<ResourceSchemaDto>> {
616        Box::pin(async move {
617            let view_any = R::authorize_view_any(request).await?;
618            let create = R::can_create() && R::authorize_create(request).await?;
619            let edit = R::can_edit();
620            let delete = R::can_delete();
621            let badge = R::navigation_badge(request).await?.map(NavigationBadge::into_dto);
622
623            // A bulk action the user may not run isn't offered at all.
624            let mut bulk_actions = Vec::new();
625            for action in &self.table.bulk_actions {
626                if R::authorize_action(request, &action.name, None).await? {
627                    bulk_actions.push(action.to_dto());
628                }
629            }
630
631            Ok(ResourceSchemaDto {
632                slug: R::slug().to_owned(),
633                label: R::label().to_owned(),
634                plural_label: R::plural_label().to_owned(),
635                icon: R::icon().to_owned(),
636                navigation_group: R::navigation_group().map(str::to_owned),
637                navigation_sort: R::navigation_sort(),
638                navigation_badge: badge,
639                key_column: R::Model::META.key.name().to_owned(),
640                title_column: R::record_title_column().map(str::to_owned),
641                permissions: ResourcePermissionsDto {
642                    view_any,
643                    create,
644                    edit,
645                    delete,
646                },
647                per_page_options: R::per_page_options().to_vec(),
648                default_per_page: R::default_per_page(),
649                searchable: !self.table.search_columns().is_empty(),
650                exportable: self.table.exportable,
651                default_sort: self.table.default_sort.clone(),
652                columns: self.table.columns.iter().map(|c| c.to_dto()).collect(),
653                filters: self.table.filters.iter().map(|f| f.to_dto()).collect(),
654                tabs: self.table.tabs.iter().map(|t| t.to_dto()).collect(),
655                row_actions: self.table.row_actions.iter().map(|a| a.to_dto()).collect(),
656                bulk_actions,
657                form_sections: self.form.to_dto(),
658            })
659        })
660    }
661
662    fn total_count<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<u64>> {
663        Box::pin(async move { self.base_query(request).await?.count().await })
664    }
665
666    fn list<'a>(
667        &'a self,
668        request: &'a Request,
669        params: ListQuery,
670    ) -> BoxFuture<'a, laravel::Result<ResourceListResponse>> {
671        Box::pin(async move {
672            if !R::authorize_view_any(request).await? {
673                return Err(laravel::abort_with(
674                    StatusCode::FORBIDDEN,
675                    "You are not authorized to view this resource.",
676                ));
677            }
678
679            let per_page = params.per_page.unwrap_or_else(R::default_per_page).clamp(1, 250);
680            let pre_tab = self.apply_search_and_filters(self.base_query(request).await?, &params);
681
682            // Compute live counts for each declared tab.
683            let mut tab_counts = BTreeMap::new();
684            for tab in &self.table.tabs {
685                let count = (tab.apply)(pre_tab.clone()).count().await?;
686                tab_counts.insert(tab.key.clone(), count);
687            }
688
689            let filtered = self.apply_tab(pre_tab, params.tab.as_deref());
690            let total = filtered.count().await?;
691            let last_page = if total == 0 { 1 } else { total.div_ceil(per_page) };
692            let current_page = params.page.clamp(1, last_page);
693            let offset = (current_page - 1).saturating_mul(per_page);
694
695            let rows = self
696                .apply_sort(filtered, &params)
697                .limit(per_page)
698                .offset(offset)
699                .get()
700                .await?;
701
702            let mut data = Vec::with_capacity(rows.len());
703            for row in &rows {
704                data.push(self.envelope(request, row).await?);
705            }
706
707            let (from, to) = if data.is_empty() {
708                (None, None)
709            } else {
710                (Some(offset + 1), Some(offset + data.len() as u64))
711            };
712
713            Ok(ResourceListResponse {
714                data,
715                meta: PaginationMetaDto {
716                    current_page,
717                    last_page,
718                    per_page,
719                    total,
720                    from,
721                    to,
722                },
723                tab_counts,
724            })
725        })
726    }
727
728    fn export_csv<'a>(&'a self, request: &'a Request, params: ListQuery) -> BoxFuture<'a, laravel::Result<Streamed>> {
729        Box::pin(async move {
730            if !self.table.exportable {
731                return Err(laravel::abort_with(
732                    StatusCode::FORBIDDEN,
733                    "CSV export is disabled for this resource.",
734                ));
735            }
736            if !R::authorize_view_any(request).await? {
737                return Err(laravel::abort_with(
738                    StatusCode::FORBIDDEN,
739                    "You are not authorized to export this resource.",
740                ));
741            }
742
743            let pre_tab = self.apply_search_and_filters(self.base_query(request).await?, &params);
744            let filtered = self.apply_tab(pre_tab, params.tab.as_deref());
745            let query = self.apply_sort(filtered, &params);
746
747            let columns: Vec<(String, String)> = self
748                .table
749                .columns
750                .iter()
751                .map(|c| (c.name.clone(), c.label.clone()))
752                .collect();
753
754            // Rows are read and sent a page at a time, so an export of any size never has to fit
755            // in memory, and nothing is silently cut off.
756            let streamed = Streamed::channel(move |sender| async move {
757                let mut header = columns
758                    .iter()
759                    .map(|(_, label)| csv_escape(label))
760                    .collect::<Vec<_>>()
761                    .join(",");
762                header.push('\n');
763                sender.send(header).await?;
764
765                let mut pages = query.chunk(EXPORT_CHUNK_SIZE);
766                while let Some(rows) = pages.try_next().await? {
767                    let mut out = String::new();
768                    for row in &rows {
769                        let value = serde_json::to_value(row)?;
770                        let line: Vec<String> = columns
771                            .iter()
772                            .map(|(name, _)| {
773                                let cell = lookup(&value, name).and_then(json_value_to_string).unwrap_or_default();
774                                csv_escape(&csv_neutralize(cell))
775                            })
776                            .collect();
777                        out.push_str(&line.join(","));
778                        out.push('\n');
779                    }
780                    sender.send(out).await?;
781                }
782
783                Ok(())
784            })
785            .content_type("text/csv; charset=utf-8")
786            .with_header(
787                "content-disposition",
788                format!("attachment; filename=\"{}.csv\"", R::slug()),
789            );
790
791            Ok(streamed)
792        })
793    }
794
795    fn show<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>> {
796        Box::pin(async move {
797            let key = Self::parse_key(&id)?;
798            let model = self.base_query(request).await?.find_or_fail(key).await?;
799            if !R::authorize_view(request, &model).await? {
800                return Err(laravel::abort_with(
801                    StatusCode::FORBIDDEN,
802                    "You are not authorized to view this record.",
803                ));
804            }
805            let record = self.envelope(request, &model).await?;
806            Ok(RecordResponse { record, message: None })
807        })
808    }
809
810    fn create<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<RecordResponse>> {
811        Box::pin(async move {
812            if !R::can_create() {
813                return Err(laravel::abort_with(
814                    StatusCode::METHOD_NOT_ALLOWED,
815                    "Creating records is disabled for this resource.",
816                ));
817            }
818            if !R::authorize_create(request).await? {
819                return Err(laravel::abort_with(
820                    StatusCode::FORBIDDEN,
821                    "You are not authorized to create this resource.",
822                ));
823            }
824
825            let created = R::CreateInput::create_from_request(request).await?;
826            let record = self.envelope(request, &created).await?;
827            Ok(RecordResponse {
828                record,
829                message: Some(format!("{} created.", R::label())),
830            })
831        })
832    }
833
834    fn update<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<RecordResponse>> {
835        Box::pin(async move {
836            if !R::can_edit() {
837                return Err(laravel::abort_with(
838                    StatusCode::METHOD_NOT_ALLOWED,
839                    "Editing records is disabled for this resource.",
840                ));
841            }
842            let key = Self::parse_key(&id)?;
843            let mut model = self.base_query(request).await?.find_or_fail(key).await?;
844            if !R::authorize_update(request, &model).await? {
845                return Err(laravel::abort_with(
846                    StatusCode::FORBIDDEN,
847                    "You are not authorized to edit this record.",
848                ));
849            }
850
851            R::UpdateInput::update_from_request(request, &mut model).await?;
852            let record = self.envelope(request, &model).await?;
853            Ok(RecordResponse {
854                record,
855                message: Some(format!("{} updated.", R::label())),
856            })
857        })
858    }
859
860    fn delete<'a>(&'a self, request: &'a Request, id: String) -> BoxFuture<'a, laravel::Result<ActionResponse>> {
861        Box::pin(async move {
862            if !R::can_delete() {
863                return Err(laravel::abort_with(
864                    StatusCode::METHOD_NOT_ALLOWED,
865                    "Deleting records is disabled for this resource.",
866                ));
867            }
868            let key = Self::parse_key(&id)?;
869            let model = self.base_query(request).await?.find_or_fail(key).await?;
870            if !R::authorize_delete(request, &model).await? {
871                return Err(laravel::abort_with(
872                    StatusCode::FORBIDDEN,
873                    "You are not authorized to delete this record.",
874                ));
875            }
876
877            model::delete(model).await?;
878            Ok(ActionResponse {
879                message: format!("{} deleted.", R::label()),
880                affected: 1,
881                redirect_to: None,
882                refresh: true,
883            })
884        })
885    }
886
887    fn run_row_action<'a>(
888        &'a self,
889        request: &'a Arc<Request>,
890        id: String,
891        action_name: String,
892        data: BTreeMap<String, serde_json::Value>,
893    ) -> BoxFuture<'a, laravel::Result<ActionResponse>> {
894        Box::pin(async move {
895            let Some(action) = self.table.row_actions.iter().find(|a| a.name == action_name) else {
896                return Err(laravel::abort_with(StatusCode::NOT_FOUND, "Action not found."));
897            };
898
899            let key = Self::parse_key(&id)?;
900            let model = self.base_query(request).await?.find_or_fail(key).await?;
901            if !R::authorize_view(request, &model).await?
902                || !R::authorize_action(request, &action_name, Some(&model)).await?
903            {
904                return Err(laravel::abort_with(
905                    StatusCode::FORBIDDEN,
906                    "You are not authorized to run this action.",
907                ));
908            }
909
910            if !action.is_available(&model) {
911                return Err(laravel::abort_with(
912                    StatusCode::UNPROCESSABLE_ENTITY,
913                    format!(
914                        "“{}” isn't available for this {}.",
915                        action.label,
916                        R::label().to_lowercase()
917                    ),
918                ));
919            }
920
921            let context = ActionContext::new(request, data);
922            let outcome = (action.handler)(context, model).await?;
923            Ok(outcome.into_response())
924        })
925    }
926
927    fn run_bulk_action<'a>(
928        &'a self,
929        request: &'a Arc<Request>,
930        action_name: String,
931        ids: Vec<String>,
932        data: BTreeMap<String, serde_json::Value>,
933    ) -> BoxFuture<'a, laravel::Result<ActionResponse>> {
934        Box::pin(async move {
935            if ids.is_empty() {
936                return Err(laravel::abort_with(StatusCode::BAD_REQUEST, "No records selected."));
937            }
938
939            let mut keys = Vec::with_capacity(ids.len());
940            for id in &ids {
941                keys.push(Self::parse_key(id)?);
942            }
943
944            let models = self
945                .base_query(request)
946                .await?
947                .filter(R::Model::META.key.is_in(keys))
948                .get()
949                .await?;
950
951            // Built-in bulk delete action.
952            if action_name == "delete" {
953                if !R::can_delete() {
954                    return Err(laravel::abort_with(
955                        StatusCode::METHOD_NOT_ALLOWED,
956                        "Deleting records is disabled for this resource.",
957                    ));
958                }
959                for model in &models {
960                    if !R::authorize_delete(request, model).await? {
961                        return Err(laravel::abort_with(
962                            StatusCode::FORBIDDEN,
963                            "You are not authorized to delete one or more selected records.",
964                        ));
965                    }
966                }
967                let count = models.len() as u64;
968                for model in models {
969                    model::delete(model).await?;
970                }
971                return Ok(ActionResponse {
972                    message: format!(
973                        "Deleted {count} {}.",
974                        if count == 1 { R::label() } else { R::plural_label() }
975                    ),
976                    affected: count,
977                    redirect_to: None,
978                    refresh: true,
979                });
980            }
981
982            let Some(action) = self.table.bulk_actions.iter().find(|a| a.name == action_name) else {
983                return Err(laravel::abort_with(StatusCode::NOT_FOUND, "Bulk action not found."));
984            };
985
986            if !R::authorize_view_any(request).await? || !R::authorize_action(request, &action_name, None).await? {
987                return Err(laravel::abort_with(
988                    StatusCode::FORBIDDEN,
989                    "You are not authorized to run this action.",
990                ));
991            }
992
993            let context = ActionContext::new(request, data);
994            let outcome = (action.handler)(context, models).await?;
995            Ok(outcome.into_response())
996        })
997    }
998
999    fn global_search<'a>(
1000        &'a self,
1001        request: &'a Request,
1002        query_text: String,
1003        limit: u64,
1004    ) -> BoxFuture<'a, laravel::Result<Option<GlobalSearchGroupDto>>> {
1005        Box::pin(async move {
1006            let searchable = self.table.search_columns();
1007            if searchable.is_empty() || !R::authorize_view_any(request).await? {
1008                return Ok(None);
1009            }
1010
1011            let rows = self
1012                .base_query(request)
1013                .await?
1014                .filter(any(searchable.iter().map(|c| col(*c).contains(query_text.as_str()))))
1015                .order_by(R::Model::META.key.desc())
1016                .limit(limit)
1017                .get()
1018                .await?;
1019
1020            if rows.is_empty() {
1021                return Ok(None);
1022            }
1023
1024            let subtitle_col = searchable.get(1).copied();
1025            let mut hits = Vec::with_capacity(rows.len());
1026            for row in &rows {
1027                let key = R::Model::META.key.get(row).to_string();
1028                let value = serde_json::to_value(row)?;
1029                let title = self
1030                    .extract_title(&value)
1031                    .unwrap_or_else(|| format!("{} #{key}", R::label()));
1032                let subtitle = subtitle_col
1033                    .and_then(|c| lookup(&value, c))
1034                    .and_then(json_value_to_string)
1035                    .filter(|s| s != &title);
1036                hits.push(GlobalSearchHitDto { key, title, subtitle });
1037            }
1038
1039            Ok(Some(GlobalSearchGroupDto {
1040                resource_slug: R::slug().to_owned(),
1041                resource_label: R::plural_label().to_owned(),
1042                icon: R::icon().to_owned(),
1043                hits,
1044            }))
1045        })
1046    }
1047}
1048
1049/// Reads a column's value from a serialized record. A column's name is a field of the record,
1050/// or a dotted path into a loaded relationship, such as `customer.name`.
1051fn lookup<'a>(record: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> {
1052    path.split('.').try_fold(record, |value, key| value.get(key))
1053}
1054
1055fn json_value_to_string(value: &serde_json::Value) -> Option<String> {
1056    match value {
1057        serde_json::Value::Null => None,
1058        serde_json::Value::String(s) => Some(s.clone()),
1059        serde_json::Value::Bool(b) => Some(b.to_string()),
1060        serde_json::Value::Number(n) => Some(n.to_string()),
1061        other => Some(other.to_string()),
1062    }
1063}
1064
1065/// How many rows an export reads from the database at a time.
1066const EXPORT_CHUNK_SIZE: u64 = 500;
1067
1068/// Keeps a spreadsheet from running a cell as a formula. A cell that starts with `=`, `+`, `-`,
1069/// `@`, a tab, or a carriage return gets a leading apostrophe, unless it's a plain number such as
1070/// `-12.5`.
1071fn csv_neutralize(cell: String) -> String {
1072    let risky = cell.starts_with(['=', '+', '-', '@', '\t', '\r']);
1073    if risky && cell.parse::<f64>().is_err() {
1074        format!("'{cell}")
1075    } else {
1076        cell
1077    }
1078}
1079
1080fn csv_escape(input: &str) -> String {
1081    if input.contains([',', '"', '\n', '\r']) {
1082        format!("\"{}\"", input.replace('"', "\"\""))
1083    } else {
1084        input.to_owned()
1085    }
1086}