lariv-rs 0.1.0

Compile-time plugin web application framework built on Axum, SeaORM, Maud, and HTMX
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
//! Shared accounting app sidebar — base links plus addon plugin patches at install time.
//!
//! The hub plugin registers this capability via `cap_attach` + `cap_hook(BaseHook)` in
//! [`define_plugin_install!`](crate::plugin_install::define_plugin_install). Finance addon
//! plugins add links with `cap_hook(AccountingSidebarTag, AccountingSidebarCap, Hook)`.

use std::marker::PhantomData;
use std::sync::OnceLock;

use crate::{
    app::App,
    capability::{CapHookExt, Capability, HasCapTag},
    components::{
        SidebarMenu, SidebarNavLink, active_nav_key, normalize_nav_path, sidebar_menu,
        sidebar_nav_items_pane,
    },
    http::RouteUrl,
    tag::Tagged,
    traits::add::{AddCapability, CapTagAbsent},
};
use frunk::{HCons, HNil, hlist::HList};
use maud::Markup;

use crate::plugins::finance_accounts::accounting_preferences_patch::{
    AccountingPreferencesRegistry, store_accounting_preferences_addons,
};

static LINKS: OnceLock<Vec<AccountingSidebarLink>> = OnceLock::new();

/// Capability tag for the accounting sidebar registry.
pub struct AccountingSidebarTag;

/// One navigation entry in the accounting app sidebar.
#[derive(Clone, Debug)]
pub struct AccountingSidebarLink {
    pub section: &'static str,
    pub label: &'static str,
    pub url: String,
    pub order: u16,
    pub icon: Option<&'static str>,
    /// Extra path prefixes that mark this link active. Empty ⇒ use [`Self::url`] only.
    pub match_prefixes: &'static [&'static str],
}

/// Build a sidebar link from a typed route tag (compile-time path checking).
pub fn link<R: RouteUrl + Default>(
    section: &'static str,
    label: &'static str,
    order: u16,
    icon: Option<&'static str>,
) -> AccountingSidebarLink {
    AccountingSidebarLink {
        section,
        label,
        url: R::default().url(),
        order,
        icon,
        match_prefixes: &[],
    }
}

/// Like [`link`], but with extra path prefixes for active-state matching.
pub fn link_with_prefixes<R: RouteUrl + Default>(
    section: &'static str,
    label: &'static str,
    order: u16,
    icon: Option<&'static str>,
    match_prefixes: &'static [&'static str],
) -> AccountingSidebarLink {
    AccountingSidebarLink {
        section,
        label,
        url: R::default().url(),
        order,
        icon,
        match_prefixes,
    }
}

/// Strip query string and trailing slash (except root) for sidebar matching.
pub fn normalize_current_path(path_and_query: &str) -> String {
    normalize_nav_path(path_and_query)
}

fn nav_links_from(links: &[AccountingSidebarLink]) -> Vec<SidebarNavLink<'_>> {
    links
        .iter()
        .map(|link| SidebarNavLink {
            key: link.section,
            title: link.label,
            url: link.url.as_str(),
            icon_name: link.icon,
            match_prefixes: link.match_prefixes,
        })
        .collect()
}

/// Longest matching prefix wins; returns the active section key.
pub fn active_section_for_path<'a>(
    links: &'a [AccountingSidebarLink],
    current_path: &str,
) -> Option<&'a str> {
    let nav = nav_links_from(links);
    active_nav_key(&nav, current_path)
}

/// Plugin hook for patching accounting sidebar links and preferences (mirrors Go menu/page patches).
pub trait AccountingSidebarRegistrar: Sized {
    fn register_accounting_sidebar(
        self,
        cap: AccountingSidebarRegistry,
    ) -> AccountingSidebarRegistry;

    fn register_accounting_preferences(
        self,
        cap: AccountingPreferencesRegistry,
    ) -> AccountingPreferencesRegistry {
        let _ = self;
        cap
    }
}

/// Sidebar link registry folded from base + addon hooks.
#[derive(Clone, Debug, Default)]
pub struct AccountingSidebarRegistry {
    links: Vec<AccountingSidebarLink>,
}

impl AccountingSidebarRegistry {
    pub fn new() -> Self {
        Self { links: Vec::new() }
    }

    pub fn push(mut self, link: AccountingSidebarLink) -> Self {
        if !self.links.iter().any(|l| l.section == link.section) {
            self.links.push(link);
        }
        self
    }

    fn sorted_links(self) -> Vec<AccountingSidebarLink> {
        let mut links = self.links;
        links.sort_by_key(|l| (l.order, l.label));
        links
    }

    /// Sorted sidebar links (for tests and inspection).
    pub fn links(&self) -> &[AccountingSidebarLink] {
        &self.links
    }
}

/// Builder-phase accounting sidebar capability.
#[derive(Clone, Default)]
pub struct AccountingSidebarCap<Hooks> {
    pub hooks: Hooks,
    pub items: AccountingSidebarRegistry,
    pub preferences: AccountingPreferencesRegistry,
    _tag: PhantomData<fn() -> AccountingSidebarTag>,
}

impl<Hooks> AccountingSidebarCap<Hooks> {
    pub fn new() -> Self
    where
        Hooks: Default,
    {
        Self {
            hooks: Hooks::default(),
            items: AccountingSidebarRegistry::new(),
            preferences: AccountingPreferencesRegistry::new(),
            _tag: PhantomData,
        }
    }

    pub fn add_hook<HTag, H>(self, hook: H) -> AccountingSidebarCap<HCons<Tagged<HTag, H>, Hooks>> {
        AccountingSidebarCap {
            hooks: HCons {
                head: Tagged::new(hook),
                tail: self.hooks,
            },
            items: self.items,
            preferences: self.preferences,
            _tag: PhantomData,
        }
    }

    /// Eagerly fold registrar hooks into items (testing / pre-mount inspection).
    pub fn resolve_hooks(self) -> AccountingSidebarCap<HNil>
    where
        Hooks: FoldSidebarRegistrarHooks,
    {
        let (items, preferences) = self.hooks.fold(self.items, self.preferences);
        AccountingSidebarCap {
            hooks: HNil,
            items,
            preferences,
            _tag: PhantomData,
        }
    }
}

impl<Hooks> HasCapTag for AccountingSidebarCap<Hooks> {
    type Tag = AccountingSidebarTag;
}

impl<Hooks, Plugin, Hook> CapHookExt<Plugin, Hook> for AccountingSidebarCap<Hooks> {
    type Hooked = AccountingSidebarCap<HCons<Tagged<Plugin, Hook>, Hooks>>;

    fn prepend_cap_hook(self, hook: Hook) -> Self::Hooked {
        self.add_hook::<Plugin, Hook>(hook)
    }
}

/// Fold registrar hooks over the sidebar and preferences registries (tail first = install order).
pub trait FoldSidebarRegistrarHooks {
    fn fold(
        self,
        sidebar: AccountingSidebarRegistry,
        preferences: AccountingPreferencesRegistry,
    ) -> (AccountingSidebarRegistry, AccountingPreferencesRegistry);
}

impl FoldSidebarRegistrarHooks for HNil {
    fn fold(
        self,
        sidebar: AccountingSidebarRegistry,
        preferences: AccountingPreferencesRegistry,
    ) -> (AccountingSidebarRegistry, AccountingPreferencesRegistry) {
        (sidebar, preferences)
    }
}

impl<Plugin, H, Tail> FoldSidebarRegistrarHooks for HCons<Tagged<Plugin, H>, Tail>
where
    Tail: FoldSidebarRegistrarHooks,
    H: AccountingSidebarRegistrar + Copy,
{
    fn fold(
        self,
        sidebar: AccountingSidebarRegistry,
        preferences: AccountingPreferencesRegistry,
    ) -> (AccountingSidebarRegistry, AccountingPreferencesRegistry) {
        let (sidebar, preferences) = self.tail.fold(sidebar, preferences);
        let hook = self.head.value;
        (
            hook.register_accounting_sidebar(sidebar),
            hook.register_accounting_preferences(preferences),
        )
    }
}

impl<Hooks> Capability for AccountingSidebarCap<Hooks>
where
    Hooks: FoldSidebarRegistrarHooks,
{
    type Value = AccountingSidebarRegistry;
    type Output = Tagged<AccountingSidebarTag, AccountingSidebarRegistry>;
    type Hooks = Hooks;
    type Items = AccountingSidebarRegistry;

    fn mount(self) -> Self::Output {
        let (registry, preferences) = self.hooks.fold(self.items, self.preferences);
        let sorted = registry.clone().sorted_links();
        if LINKS.set(sorted).is_err() {
            tracing::error!("accounting sidebar LINKS already initialized");
        }
        store_accounting_preferences_addons(&preferences);
        Tagged::new(registry)
    }
}

/// Attach an empty accounting sidebar capability to the app builder.
///
/// Prefer `cap_attach` in the accounts plugin install steps; this helper remains for
/// manual wiring or tests outside the install macro.
pub fn with_accounting_sidebar<L, Proof>(app: App<L>) -> App<HCons<AccountingSidebarCap<HNil>, L>>
where
    L: HList + CapTagAbsent<AccountingSidebarTag, Proof>,
{
    app.add_capability(AccountingSidebarCap::new())
}

/// Render the patched accounting sidebar, highlighting the link that matches `current_path`.
pub fn accounting_sidebar(current_path: &str) -> Markup {
    let links = LINKS
        .get()
        .expect("accounting sidebar not initialized — mount the app after finance plugins install");
    let nav = nav_links_from(links);
    sidebar_menu(SidebarMenu {
        title: "Accounting",
        children: sidebar_nav_items_pane(&nav, current_path),
    })
}

/// Base accounting sidebar links registered by the finance accounts hub.
#[derive(Clone, Copy, Default)]
pub struct BaseHook;

impl AccountingSidebarRegistrar for BaseHook {
    fn register_accounting_sidebar(
        self,
        cap: AccountingSidebarRegistry,
    ) -> AccountingSidebarRegistry {
        use crate::plugins::finance_accounts::routes::{
            AccountingPreferencesRouteTag, CurrencyListRouteTag, FinanceDefaultRouteTag,
            JournalListRouteTag,
        };

        cap.push(link_with_prefixes::<FinanceDefaultRouteTag>(
            "accounts",
            "Accounts",
            10,
            Some("building-library"),
            &["/finance", "/finance/accounts"],
        ))
        .push(link::<CurrencyListRouteTag>(
            "currencies",
            "Currencies",
            20,
            Some("currency-dollar"),
        ))
        .push(link_with_prefixes::<JournalListRouteTag>(
            "journals",
            "Journals",
            30,
            Some("book-open"),
            &["/finance/journals", "/finance/journal-entries"],
        ))
        .push(link::<AccountingPreferencesRouteTag>(
            "preferences",
            "Accounting preferences",
            40,
            Some("adjustments-horizontal"),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugins::finance_accounts::routes::FinanceDefaultRouteTag;

    struct TestAddonTag;

    #[derive(Copy, Clone)]
    struct TestAddonHook;

    impl AccountingSidebarRegistrar for TestAddonHook {
        fn register_accounting_sidebar(
            self,
            cap: AccountingSidebarRegistry,
        ) -> AccountingSidebarRegistry {
            cap.push(link::<FinanceDefaultRouteTag>(
                "test-addon",
                "Test addon",
                15,
                None,
            ))
        }
    }

    fn sample_links() -> Vec<AccountingSidebarLink> {
        vec![
            AccountingSidebarLink {
                section: "accounts",
                label: "Accounts",
                url: "/finance/".into(),
                order: 10,
                icon: None,
                match_prefixes: &["/finance", "/finance/accounts"],
            },
            AccountingSidebarLink {
                section: "customers",
                label: "Customers",
                url: "/customers/".into(),
                order: 50,
                icon: None,
                match_prefixes: &[],
            },
            AccountingSidebarLink {
                section: "journals",
                label: "Journals",
                url: "/finance/journals/".into(),
                order: 30,
                icon: None,
                match_prefixes: &["/finance/journals", "/finance/journal-entries"],
            },
            AccountingSidebarLink {
                section: "preferences",
                label: "Preferences",
                url: "/finance/preferences/".into(),
                order: 40,
                icon: None,
                match_prefixes: &[],
            },
        ]
    }

    #[test]
    fn resolve_hooks_folds_base_and_addon_links() {
        let cap = AccountingSidebarCap::<HNil>::new()
            .add_hook::<crate::plugins::finance_accounts::FinanceAccountsTag, _>(BaseHook)
            .add_hook::<TestAddonTag, _>(TestAddonHook)
            .resolve_hooks();

        assert_eq!(cap.items.links().len(), 5);
        let sections: Vec<_> = cap.items.links().iter().map(|l| l.section).collect();
        assert!(sections.contains(&"accounts"));
        assert!(sections.contains(&"test-addon"));
        assert!(sections.contains(&"preferences"));
    }

    #[test]
    fn active_section_longest_prefix() {
        let links = sample_links();
        assert_eq!(
            active_section_for_path(&links, "/finance"),
            Some("accounts")
        );
        assert_eq!(
            active_section_for_path(&links, "/finance/accounts/create"),
            Some("accounts")
        );
        assert_eq!(
            active_section_for_path(&links, "/finance/journals?page=2"),
            Some("journals")
        );
        assert_eq!(
            active_section_for_path(&links, "/finance/journal-entries/9"),
            Some("journals")
        );
        assert_eq!(
            active_section_for_path(&links, "/customers/c/1"),
            Some("customers")
        );
        assert_eq!(
            active_section_for_path(&links, "/finance/preferences"),
            Some("preferences")
        );
    }
}