tinkr 0.0.43

Tinkr is a web framework for quickly building full-stack web applications with Leptos.
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
#[cfg(feature = "ssr")]
use crate::StorageAuthed;

use crate::{
    AppError, Datetime, RecordId,
    components::{
        Align, Button, Image, Page, SectionStyled, Tooltip,
        button::{BtnColor, BtnVariant, ButtonIcon},
        heading::Heading,
    },
};

#[cfg(feature = "ssr")]
use crate::{date_utils::time, db_init, session::get_user, session::get_user_option};

use leptos::prelude::*;
use partial_struct::Partial;
use serde::{Deserialize, Serialize};

use crate::{
    order::{
        list::{OrderSideBarWrapper, UserOrderListNarrow},
        order_model::create_order_from_cart,
        view::UserOrderView,
    },
    product::product::ProductDetail,
};

type UserId = RecordId;
type ProductId = RecordId;

pub const SHIPPING_COST: f64 = 160.0;

#[derive(Debug, Clone, Serialize, Deserialize, Partial)]
#[partial(
    "CreateCartItem",
    derive(Debug, Serialize, Deserialize, Clone),
    omit(id, user, date_added)
)]
#[partial("CartItemNoId", derive(Debug, Serialize, Deserialize, Clone), omit(id))]
pub struct CartItem {
    pub id: RecordId,
    pub name: String,
    pub user: UserId,
    /// legacy field: use product as the "paint colour"
    pub product: ProductId,
    pub variant: String,
    pub price: f64,
    pub date_added: Option<Datetime>,
}

impl CartItem {
    #[tracing::instrument(name = "CartItem::from_string")]
    #[cfg(feature = "ssr")]
    pub async fn from_string(id: String) -> Result<Option<CartItem>, AppError> {
        use std::str::FromStr;
        let db = db_init().await?;
        let record = RecordId::from_str(&id)?;
        tracing::debug!(%record, "Fetching cart item from database");
        let item: Option<CartItem> = db.select(record).await?;
        tracing::debug!(?item, "Fetched cart item from database");
        Ok(item)
    }

    // pub fn delete_item_from_string(id: String) -> Result<(), AppError> {
    //     let db = db_init()?;
    //     let _: Option<CartItem> = db.delete(("cart_item", id)).await?;

    //     Ok(())
    // }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CartItemWithProduct {
    pub id: RecordId,
    pub name: String,
    pub variant: String,
    pub price: f64,
    pub product: ProductDetail,
}

#[cfg(feature = "ssr")]
impl StorageAuthed<CreateCartItem, CartItem> for CartItem {
    const TABLE_NAME: &str = "cart_item";
}

#[server]
pub async fn add_cart_item(item: CreateCartItem) -> Result<CartItem, ServerFnError> {
    let user = get_user().await?;
    let db = db_init().await?;

    let content = CartItemNoId {
        user: user.id.clone(),
        name: item.name,
        product: item.product,
        variant: item.variant,
        price: item.price,
        date_added: Some(time::now()),
    };

    let mut result = db
        .query("CREATE cart_item CONTENT $content;")
        .bind(("content", content))
        .await?;

    let created_item: Option<CartItem> = result.take(0)?;

    let created_item = match created_item {
        Some(token) => token,
        None => return Err(ServerFnError::new("Failed to add item to cart")),
    };

    Ok(created_item)
}

#[server]
pub async fn get_cart_items() -> Result<Vec<CartItemWithProduct>, ServerFnError> {
    let user = get_user().await?;
    let db = db_init().await?;

    let items: Vec<CartItemWithProduct> = db
        .query("SELECT *, product.* FROM cart_item WHERE user = $user")
        .bind(("user", user.id))
        .await?
        .take(0)?;

    Ok(items)
}

#[server]
pub async fn delete_cart_item(id: String) -> Result<bool, ServerFnError> {
    let cartitem = CartItem::from_string(id.clone()).await?;

    let cartitem = match cartitem {
        Some(item) => item,
        None => return Err(ServerFnError::new("Cart item not found")),
    };

    let result = cartitem.delete_self().await?;

    // let _: Option<CartItem> = db.delete(("cart_item", id)).await?;

    Ok(result)
}

#[server]
pub async fn clear_cart() -> Result<bool, ServerFnError> {
    let user = get_user().await?;

    let db = db_init().await?;

    db.query("DELETE cart_item WHERE user = $user;")
        .bind(("user", user.id))
        .await?;

    Ok(true)
}

#[server]
pub async fn get_cart_count() -> Result<usize, AppError> {
    let user = get_user_option().await?;

    let user = match user {
        Some(u) => u,
        None => return Ok(0),
    };

    let db = db_init().await?;

    let count: Vec<CartItem> = db
        .query("SELECT * FROM cart_item WHERE user = $user")
        .bind(("user", user.id))
        .await?
        .take(0)?;

    Ok(count.len())
}

#[derive(Clone, Copy)]
pub struct CartCountTrigger(pub RwSignal<usize>);

#[component]
pub fn CartButton() -> impl IntoView {
    let trigger = expect_context::<CartCountTrigger>();
    let cart_count = Resource::new(
        move || trigger.0.get(),
        |_| async { get_cart_count().await.unwrap_or(0) },
    );

    // Add window focus event listener to refetch cart count
    #[cfg(not(feature = "ssr"))]
    Effect::new(move |_| {
        use leptos::wasm_bindgen::{JsCast, closure::Closure};
        use leptos::web_sys;

        let handle_focus = move || {
            trigger.0.update(|v| *v += 1);
        };

        let window = web_sys::window().expect("no global window exists");
        let closure = Closure::wrap(Box::new(handle_focus) as Box<dyn Fn()>);

        window
            .add_event_listener_with_callback("focus", closure.as_ref().unchecked_ref())
            .expect("failed to add focus listener");

        closure.forget();
    });

    view! {
        <Tooltip label="View Cart" align=Align::Bottom>
            <div id="cart-icon-target">

                <Transition>
                    {move || {
                        cart_count
                            .get()
                            .map(|count| {
                                if count > 0 {
                                    view! {
                                        <Button
                                            href="/cart"
                                            icon=ButtonIcon::Icon(phosphor_leptos::SHOPPING_CART)
                                            variant=BtnVariant::Default
                                            color=BtnColor::Neutral
                                        >
                                            {count.to_string()}
                                        </Button>
                                    }
                                        .into_any()
                                } else {
                                    view! {
                                        <Button
                                            href="/cart"
                                            icon=ButtonIcon::Icon(phosphor_leptos::SHOPPING_CART)
                                            variant=BtnVariant::Square
                                            color=BtnColor::Neutral
                                        />
                                    }
                                        .into_any()
                                }
                            })
                    }}
                </Transition>
            </div>
        </Tooltip>
    }
}

#[component]
pub fn ProductMini(
    background: String,
    brand_name: String,
    model_name: String,
    product_name: String,
    product_code: String,
    product_variant: String,
) -> impl IntoView {
    view! {
        <div class="flex items-center gap-3">
            <div
                class="box-content h-14 w-16 rounded border dark:border-neutral-700"
                style:background=background
            />
            <div class="flex-1">
                <h4 class="text-xs font-bold dark:text-neutral-100">
                    {brand_name} " " {model_name}
                </h4>
                <p class="font-semibold capitalize dark:text-neutral-200">{product_name}</p>
                <p class="text-xs text-neutral-500 dark:text-neutral-400">
                    "Code: " {product_code}
                </p>
                <p class="text-xs text-neutral-600 dark:text-neutral-300">{product_variant}</p>
            </div>
        </div>
    }
}

fn format_price(price: f64) -> String {
    let formatted = format!("{:.2}", price);
    formatted
        .split('.')
        .next()
        .unwrap_or(&formatted)
        .chars()
        .rev()
        .collect::<Vec<_>>()
        .chunks(3)
        .map(|c| c.iter().collect::<String>())
        .collect::<Vec<_>>()
        .join(" ")
        .chars()
        .rev()
        .collect::<String>()
        + "."
        + formatted.split('.').nth(1).unwrap_or("00")
}

#[component]
pub fn CartView() -> impl IntoView {
    let cart_items = Resource::new(|| (), |_| async { get_cart_items().await });
    let delete_action = Action::new(|id: &String| {
        let id = id.clone();
        async move { delete_cart_item(id).await }
    });
    let cart_trigger = expect_context::<CartCountTrigger>();

    let total = move || {
        cart_items
            .get()
            .and_then(|items| items.ok())
            .map(|items| items.iter().map(|i| i.price).sum::<f64>())
            .unwrap_or(0.0)
    };

    let total_with_shipping = move || total() + SHIPPING_COST;

    // let item_count = move || {
    //     cart_items
    //         .get()
    //         .and_then(|items| items.ok())
    //         .map(|items| items.len())
    //         .unwrap_or(0)
    // };

    Effect::new(move |_| {
        if delete_action.value().get().is_some() {
            cart_items.refetch();
            cart_trigger.0.update(|v| *v += 1);
        }
    });

    view! {
        <Page>

            <Transition>
                {move || {
                    cart_items
                        .get()
                        .map(|result| {
                            match result {
                                Ok(items) if items.is_empty() => {
                                    view! {
                                        <Heading>"My Cart"</Heading>
                                        <div class="font-mono text-neutral-500 py-8 text-center">
                                            "Cart is empty"
                                        </div>
                                    }
                                        .into_any()
                                }
                                Ok(items) => {
                                    view! {
                                        <div>
                                            <div class="flex justify-between items-center mb-4">
                                                <div>
                                                    <Heading>"My Cart"</Heading>
                                                </div>
                                                <Button
                                                    variant=BtnVariant::Default
                                                    color=BtnColor::Neutral
                                                    icon=ButtonIcon::Icon(phosphor_leptos::TRASH)
                                                    on_click=Callback::new(move |_| {
                                                        leptos::task::spawn_local(async move {
                                                            if let Ok(_) = clear_cart().await {
                                                                cart_items.refetch();
                                                                cart_trigger.0.update(|v| *v += 1);
                                                            }
                                                        });
                                                    })
                                                >
                                                    "Clear"
                                                </Button>
                                            </div>
                                            <table class="w-full text-left">
                                                <thead>
                                                    <tr>
                                                        <th class="pb-4 font-medium text-neutral-500 dark:text-neutral-400">
                                                            "Product"
                                                        </th>
                                                        <th class="pb-4 pr-3 text-right font-medium text-neutral-500 dark:text-neutral-400">
                                                            "Price"
                                                        </th>
                                                        <th></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {items
                                                        .into_iter()
                                                        .map(|item| {
                                                            let item_id = item.id.to_string();
                                                            let item_id_clone = item_id.clone();

                                                            view! {
                                                                <tr class="border-b border-neutral-100 dark:border-neutral-700 hover:bg-neutral-50 dark:hover:bg-neutral-700">
                                                                    <td class="py-4 text-neutral-900 dark:text-neutral-100 pl-5">
                                                                        <ProductMini
                                                                            background=item.product.colour
                                                                            brand_name=item.product.brand_name
                                                                            model_name=item.product.model_name
                                                                            product_name=item.product.product_name
                                                                            product_code=item.product.code
                                                                            product_variant=item.name
                                                                        />
                                                                    </td>
                                                                    <td class="py-4 pr-3 text-right text-neutral-900 dark:text-neutral-100">
                                                                        "R " {format!("{:.2}", item.price)}
                                                                    </td>
                                                                    <td class="py-4 text-left">
                                                                        <div class="flex justify-end flex-row pr-5">
                                                                            <Button
                                                                                variant=BtnVariant::Square
                                                                                color=BtnColor::Neutral
                                                                                icon=ButtonIcon::Icon(phosphor_leptos::X)
                                                                                class="bg-transparent"
                                                                                on_click=Callback::new(move |_| {
                                                                                    delete_action.dispatch(item_id_clone.clone());
                                                                                })
                                                                            />
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            }
                                                        })
                                                        .collect_view()}
                                                </tbody>
                                            </table>

                                            <div class="mt-8 flex justify-end text-neutral-500 dark:text-neutral-300 gap-5">
                                                <div>"Shipping"</div>
                                                <div>"R " {format!("{:.2}", SHIPPING_COST)}</div>
                                            </div>

                                            <div class="mt-4 flex justify-end text-2xl font-bold text-black dark:text-white gap-5">
                                                <div>"Total"</div>
                                                <div>
                                                    "R " {move || format_price(total_with_shipping())}
                                                </div>
                                            </div>

                                        </div>
                                    }
                                        .into_any()
                                }
                                Err(_) => {
                                    view! {
                                        <div class="text-center py-8 text-red-500">
                                            "Failed to load cart. Please try again."
                                        </div>
                                    }
                                        .into_any()
                                }
                            }
                        })
                }}
            </Transition>

            <Heading>"Delivery Address"</Heading>
            <crate::auth::account_details::AccountForm />

            <div class="flex justify-end">
                <Button
                    variant=BtnVariant::CallToAction
                    color=BtnColor::Success
                    icon=ButtonIcon::Icon(phosphor_leptos::ARROW_RIGHT)
                    class="bg-green-500 hover:bg-green-600 text-white"
                    on_click=Callback::new(move |_| {
                        leptos::task::spawn_local(async move {
                            let rest = create_order_from_cart().await;
                            if let Ok(order_id) = rest {
                                let order_path = format!("/order/{}", order_id.key());
                                let navigate = leptos_router::hooks::use_navigate();
                                navigate(&order_path, Default::default());
                            }
                        });
                    })
                >

                    "Create Order"
                </Button>
            </div>

        </Page>
    }
}

#[component]
pub fn CartPage() -> impl IntoView {
    move || {
        view! {
            <OrderSideBarWrapper>
                <CartView />
            </OrderSideBarWrapper>
        }
    }
}