1use std::collections::HashMap;
4use std::future::Future;
5use std::marker::PhantomData;
6use std::str::FromStr;
7use std::sync::Arc;
8
9use futures_util::future::BoxFuture;
10use laravel::config::app::Environment;
11use laravel::config::{Config, Env};
12use laravel::container::{Container, Registrar};
13use laravel::foundation::ServiceProvider;
14use laravel::http::{IntoMiddleware, MiddlewareGroup, Request};
15use laravel::model::Model;
16use serde::Serialize;
17
18use crate::config::{AccentColor, AdminConfig};
19use crate::http::{AuthorizePanel, LOCKED_MESSAGE, LockedPanel, register_routes};
20use crate::protocol::{AdminUserDto, BadgeColor, DashboardWidgetDto, ShellBootstrap};
21use crate::resource::{AdminResource, ErasedResource, ResourceAdapter};
22use crate::widget::{DashboardWidget, ErasedWidget, FnWidget, RequestWidget, StatWidget};
23
24#[derive(Debug, Clone)]
26pub struct AdminUser {
27 pub name: String,
29 pub email: Option<String>,
31 pub avatar_url: Option<String>,
33 pub role: Option<String>,
35}
36
37impl AdminUser {
38 #[must_use]
40 pub fn new(name: impl Into<String>) -> Self {
41 Self {
42 name: name.into(),
43 email: None,
44 avatar_url: None,
45 role: None,
46 }
47 }
48
49 #[must_use]
51 pub fn email(mut self, email: impl Into<String>) -> Self {
52 self.email = Some(email.into());
53 self
54 }
55
56 #[must_use]
58 pub fn avatar_url(mut self, url: impl Into<String>) -> Self {
59 self.avatar_url = Some(url.into());
60 self
61 }
62
63 #[must_use]
65 pub fn role(mut self, role: impl Into<String>) -> Self {
66 self.role = Some(role.into());
67 self
68 }
69
70 pub(crate) fn into_dto(self) -> AdminUserDto {
71 AdminUserDto {
72 name: self.name,
73 email: self.email,
74 avatar_url: self.avatar_url,
75 role: self.role,
76 }
77 }
78}
79
80pub trait RequestFn<'a, T>: Send + Sync + 'static {
97 type Future: Future<Output = laravel::Result<T>> + Send + 'a;
99
100 fn call(&self, request: &'a Request) -> Self::Future;
102}
103
104impl<'a, T, F, Fut> RequestFn<'a, T> for F
105where
106 F: Fn(&'a Request) -> Fut + Send + Sync + 'static,
107 Fut: Future<Output = laravel::Result<T>> + Send + 'a,
108{
109 type Future = Fut;
110
111 fn call(&self, request: &'a Request) -> Fut {
112 self(request)
113 }
114}
115
116pub(crate) type RequestHook<T> = Arc<dyn for<'a> Fn(&'a Request) -> BoxFuture<'a, laravel::Result<T>> + Send + Sync>;
118
119fn hook<T: 'static>(function: impl for<'a> RequestFn<'a, T>) -> RequestHook<T> {
120 Arc::new(move |request| Box::pin(function.call(request)))
121}
122
123pub(crate) type PanelGate = RequestHook<bool>;
124
125pub(crate) type UserResolver = RequestHook<Option<AdminUser>>;
126
127#[derive(Clone)]
129pub struct PanelState {
130 pub(crate) base_path: String,
131 pub(crate) brand: String,
132 pub(crate) subtitle: Option<String>,
133 pub(crate) accent: AccentColor,
134 pub(crate) logout_url: Option<String>,
135 pub(crate) vite_dev_url: Option<String>,
136 pub(crate) resources: Arc<Vec<Arc<dyn ErasedResource>>>,
137 pub(crate) resource_index: Arc<HashMap<String, usize>>,
138 pub(crate) widgets: Arc<Vec<Arc<dyn ErasedWidget>>>,
139 pub(crate) user_resolver: Option<UserResolver>,
140}
141
142impl std::fmt::Debug for PanelState {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 f.debug_struct("PanelState")
145 .field("base_path", &self.base_path)
146 .field("brand", &self.brand)
147 .field("resources", &self.resources.len())
148 .field("widgets", &self.widgets.len())
149 .finish_non_exhaustive()
150 }
151}
152
153impl PanelState {
154 pub(crate) fn find_resource(&self, slug: &str) -> Option<&Arc<dyn ErasedResource>> {
155 let index = *self.resource_index.get(slug)?;
156 self.resources.get(index)
157 }
158
159 pub(crate) fn bootstrap(&self) -> ShellBootstrap {
160 ShellBootstrap {
161 base_path: self.base_path.clone(),
162 api_base: format!("{}/api", self.base_path),
163 brand: self.brand.clone(),
164 subtitle: self.subtitle.clone(),
165 accent: self.accent,
166 logout_url: self.logout_url.clone(),
167 }
168 }
169
170 pub(crate) async fn resolve_user(&self, request: &Request) -> laravel::Result<Option<AdminUserDto>> {
171 let Some(resolver) = &self.user_resolver else {
172 return Ok(None);
173 };
174 Ok(resolver(request).await?.map(AdminUser::into_dto))
175 }
176
177 pub(crate) async fn resolve_dashboard_widgets(
178 &self,
179 request: &Request,
180 ) -> laravel::Result<Vec<DashboardWidgetDto>> {
181 if !self.widgets.is_empty() {
182 let mut resolved = Vec::with_capacity(self.widgets.len());
183 for widget in self.widgets.iter() {
184 resolved.push(widget.resolve(request).await?);
185 }
186 return Ok(resolved);
187 }
188
189 let mut resolved = Vec::with_capacity(self.resources.len());
191 for resource in self.resources.iter() {
192 let count = resource.total_count(request).await?;
193 let slug = resource.slug();
194 resolved.push(
195 StatWidget::new(
196 format!("resource_count_{slug}"),
197 resource.plural_label(),
198 format_number(count),
199 )
200 .description(format!("Total {} in database", resource.plural_label().to_lowercase()))
201 .icon(resource.icon())
202 .color(BadgeColor::Zinc)
203 .href(format!("{}/resources/{slug}", self.base_path))
204 .build(),
205 );
206 }
207 Ok(resolved)
208 }
209}
210
211pub struct AdminPanel {
227 path: Option<String>,
228 brand: Option<String>,
229 subtitle: Option<String>,
230 accent: AccentColor,
231 logout_url: Option<String>,
232 vite_dev_url: Option<String>,
233 middleware: MiddlewareGroup,
234 has_middleware: bool,
236 resources: Vec<Arc<dyn ErasedResource>>,
237 widgets: Vec<Arc<dyn ErasedWidget>>,
238 gate: Option<PanelGate>,
239 user_resolver: Option<UserResolver>,
240}
241
242impl std::fmt::Debug for AdminPanel {
243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244 f.debug_struct("AdminPanel")
245 .field("path", &self.path)
246 .field("brand", &self.brand)
247 .field("accent", &self.accent)
248 .field("resources", &self.resources.len())
249 .field("widgets", &self.widgets.len())
250 .finish_non_exhaustive()
251 }
252}
253
254impl Default for AdminPanel {
255 fn default() -> Self {
256 Self::new()
257 }
258}
259
260impl AdminPanel {
261 #[must_use]
263 pub fn new() -> Self {
264 Self {
265 path: None,
266 brand: None,
267 subtitle: None,
268 accent: AccentColor::Zinc,
269 logout_url: None,
270 vite_dev_url: None,
271 middleware: MiddlewareGroup::new(),
272 has_middleware: false,
273 resources: Vec::new(),
274 widgets: Vec::new(),
275 gate: None,
276 user_resolver: None,
277 }
278 }
279
280 #[must_use]
282 pub fn path(mut self, path: impl Into<String>) -> Self {
283 self.path = Some(normalize_path(&path.into()));
284 self
285 }
286
287 #[must_use]
289 pub fn brand(mut self, brand: impl Into<String>) -> Self {
290 self.brand = Some(brand.into());
291 self
292 }
293
294 #[must_use]
296 pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
297 self.subtitle = Some(subtitle.into());
298 self
299 }
300
301 #[must_use]
303 pub fn accent(mut self, accent: AccentColor) -> Self {
304 self.accent = accent;
305 self
306 }
307
308 #[must_use]
310 pub fn logout_url(mut self, url: impl Into<String>) -> Self {
311 self.logout_url = Some(url.into());
312 self
313 }
314
315 #[must_use]
317 pub fn vite_dev_url(mut self, url: impl Into<String>) -> Self {
318 self.vite_dev_url = Some(url.into().trim_end_matches('/').to_owned());
319 self
320 }
321
322 #[must_use]
328 pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
329 self.middleware.append(middleware);
330 self.has_middleware = true;
331 self
332 }
333
334 #[must_use]
350 pub fn authorize(mut self, gate: impl for<'a> RequestFn<'a, bool>) -> Self {
351 self.gate = Some(hook(gate));
352 self
353 }
354
355 #[must_use]
367 pub fn user_resolver(mut self, resolver: impl for<'a> RequestFn<'a, Option<AdminUser>>) -> Self {
368 self.user_resolver = Some(hook(resolver));
369 self
370 }
371
372 #[must_use]
374 pub fn resource<R>(mut self) -> Self
375 where
376 R: AdminResource,
377 <R::Model as Model>::Key: FromStr,
378 R::Model: Serialize,
379 {
380 assert!(
382 self.resources.iter().all(|resource| resource.slug() != R::slug()),
383 "two admin resources share the slug `{}`; give one of them a different `slug()`",
384 R::slug(),
385 );
386 self.resources.push(ResourceAdapter::<R>::erased());
387 self
388 }
389
390 #[must_use]
394 pub fn widget(mut self, widget: impl DashboardWidget) -> Self {
395 self.widgets.push(Arc::new(widget));
396 self
397 }
398
399 #[must_use]
412 pub fn widget_fn<F, Fut, W>(self, widget: F) -> Self
413 where
414 F: Fn() -> Fut + Send + Sync + 'static,
415 Fut: Future<Output = laravel::Result<W>> + Send + 'static,
416 W: Into<DashboardWidgetDto> + 'static,
417 {
418 self.widget(FnWidget(widget))
419 }
420
421 #[must_use]
425 pub fn widget_for_request<F, W>(self, widget: F) -> Self
426 where
427 F: for<'a> RequestFn<'a, W>,
428 W: Into<DashboardWidgetDto> + 'static,
429 {
430 self.widget(RequestWidget(widget, PhantomData))
431 }
432}
433
434impl ServiceProvider for AdminPanel {
435 fn config(&self, config: &mut Config, env: &Env) {
436 config.discover(env!("CARGO_CRATE_NAME"), env);
437 }
438
439 fn register(&self, app: &mut Registrar) {
440 let cfg = app.config().section::<AdminConfig>();
441 let base_path = normalize_path(self.path.as_deref().unwrap_or(&cfg.path));
442 let brand = self.brand.clone().unwrap_or_else(|| cfg.brand.clone());
443 let vite_dev_url = self
444 .vite_dev_url
445 .clone()
446 .or_else(|| cfg.vite_dev_url.clone())
447 .map(|url| url.trim_end_matches('/').to_owned());
448
449 let mut resources = self.resources.clone();
450 resources.sort_by_key(|r| r.navigation_sort());
451
452 let mut resource_index = HashMap::with_capacity(resources.len());
453 for (idx, resource) in resources.iter().enumerate() {
454 resource_index.insert(resource.slug().to_owned(), idx);
455 }
456
457 let state = PanelState {
458 base_path: base_path.clone(),
459 brand,
460 subtitle: self.subtitle.clone(),
461 accent: self.accent,
462 logout_url: self.logout_url.clone(),
463 vite_dev_url,
464 resources: Arc::new(resources),
465 resource_index: Arc::new(resource_index),
466 widgets: Arc::new(self.widgets.clone()),
467 user_resolver: self.user_resolver.clone(),
468 };
469
470 app.instance(state.clone());
471 app.routing().assets("laravel-rust-admin", laravel::embed!("dist"));
472
473 let mut middleware = self.middleware.clone();
474 if let Some(gate) = self.gate.clone() {
475 middleware.append(AuthorizePanel::new(gate));
476 }
477 if self.is_locked(&app.config().app.env) {
478 middleware.append(LockedPanel);
479 }
480
481 app.routing().web(move |router| {
482 register_routes(router, &base_path, middleware);
483 });
484 }
485
486 async fn boot(&self, app: &Container) -> laravel::Result<()> {
487 let environment = &app.config().app.env;
488 if self.is_locked(environment) {
489 tracing::warn!(
490 environment = environment.as_str(),
491 "laravel-rust-admin: {LOCKED_MESSAGE}"
492 );
493 }
494
495 Ok(())
496 }
497}
498
499impl AdminPanel {
500 fn is_locked(&self, environment: &Environment) -> bool {
503 let unprotected = self.gate.is_none() && !self.has_middleware;
504 unprotected && !matches!(environment, Environment::Local | Environment::Testing)
505 }
506}
507
508fn normalize_path(raw: &str) -> String {
509 let trimmed = raw.trim().trim_matches('/');
510 if trimmed.is_empty() {
511 "/admin".to_owned()
512 } else {
513 format!("/{trimmed}")
514 }
515}
516
517fn format_number(n: u64) -> String {
518 let digits = n.to_string();
519 let mut out = String::with_capacity(digits.len() + digits.len() / 3);
520 for (idx, ch) in digits.chars().rev().enumerate() {
521 if idx > 0 && idx % 3 == 0 {
522 out.push(',');
523 }
524 out.push(ch);
525 }
526 out.chars().rev().collect()
527}