1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
use leptos::prelude::*;
use crate::surrealtypes::Datetime;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Clone, Debug)]
struct DashboardOrderListItem {
pub x: Datetime,
pub y: String,
}
#[derive(Deserialize, Serialize, Clone, Debug)]
struct DailyData {
pub date: String,
pub total: f64,
pub count: usize,
pub avg_7day: f64,
}
#[server]
async fn fetch_daily_orders() -> Result<Vec<DailyData>, ServerFnError> {
let user = crate::session::get_user().await?;
if user.is_admin != Some(true) {
return Err(ServerFnError::ServerError("Unauthorized".into()));
}
let db = crate::db::db_init().await?;
let mut orders_req = db
.query("SELECT created_at as x, total as y FROM order WHERE paid = true ORDER BY created_at ASC;")
.await?;
let orders = orders_req.take::<Vec<DashboardOrderListItem>>(0)?;
// Group orders by day
let mut daily_map: std::collections::HashMap<String, (f64, usize)> =
std::collections::HashMap::new();
for order in orders {
let date = order.x.format("%Y-%m-%d");
let total: f64 = order.y.parse().unwrap_or(0.0);
let entry = daily_map.entry(date).or_insert((0.0, 0));
entry.0 += total;
entry.1 += 1;
}
// Convert to sorted vec
let mut daily_data: Vec<(String, f64, usize)> = daily_map
.into_iter()
.map(|(date, (total, count))| (date, total, count))
.collect();
daily_data.sort_by(|a, b| a.0.cmp(&b.0)); // Sort chronologically
// Calculate 7-day running average
let mut result: Vec<DailyData> = Vec::new();
for i in 0..daily_data.len() {
let start_idx = if i >= 6 { i - 6 } else { 0 };
let window = &daily_data[start_idx..=i];
let sum: f64 = window.iter().map(|(_, total, _)| total).sum();
// let days_in_window = window.len() as f64;
// let avg_7day = sum / days_in_window;
result.push(DailyData {
date: daily_data[i].0.clone(),
total: daily_data[i].1,
count: daily_data[i].2,
avg_7day: sum,
});
}
let last_days = 180;
let len = result.len();
if len > last_days {
result = result.into_iter().skip(len - last_days).collect();
}
Ok(result)
}
#[component]
pub fn OrderChartWeeklyRunning() -> impl IntoView {
let daily_resource = Resource::new(|| (), |_| async move { fetch_daily_orders().await });
view! {
<div class="w-full">
<Suspense fallback=move || {
view! {
<div class="flex items-center justify-center h-64">
<p class="text-neutral-500 dark:text-neutral-400">"Loading chart..."</p>
</div>
}
}>
{move || {
daily_resource
.get()
.map(|data_result| {
match data_result {
Ok(daily_data) => {
if daily_data.is_empty() {
view! {
<div class="flex items-center justify-center h-64">
<p class="text-neutral-500 dark:text-neutral-400">
"No order data available"
</p>
</div>
}
.into_any()
} else {
let max_value = daily_data
.iter()
.map(|d| d.avg_7day)
.fold(0.0f64, f64::max);
view! {
<div class="space-y-4">
<div class="bg-white dark:bg-neutral-900 p-6 rounded-lg shadow">
<h3 class="text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-4">
"7-Day Running Average Revenue"
</h3>
{
let chart_width = 800.0;
let chart_height = 400.0;
let padding = 60.0;
let plot_width = chart_width - 2.0 * padding;
let plot_height = chart_height - 2.0 * padding;
let data_len = daily_data.len();
let step_x = if data_len > 1 {
plot_width / (data_len as f64 - 1.0)
} else {
plot_width
};
let y_scale = if max_value > 0.0 {
plot_height / max_value
} else {
1.0
};
let points: Vec<_> = daily_data
.iter()
.enumerate()
.map(|(i, d)| {
let x = padding + (i as f64 * step_x);
let y = chart_height - padding - (d.avg_7day * y_scale);
(x, y, d.avg_7day, d.date.clone(), d.count)
})
.collect();
let path_data = points
.iter()
.enumerate()
.map(|(i, (x, y, _, _, _))| {
if i == 0 {
format!("M {} {}", x, y)
} else {
format!("L {} {}", x, y)
}
})
.collect::<Vec<_>>()
.join(" ");
let y_ticks = 5;
let y_tick_step = max_value / y_ticks as f64;
view! {
<svg
viewBox=format!("0 0 {} {}", chart_width, chart_height)
class="w-full h-auto"
>
<defs>
<linearGradient
id="lineGradient"
x1="0%"
y1="0%"
x2="0%"
y2="100%"
>
<stop
offset="0%"
style="stop-color:rgb(59, 130, 246);stop-opacity:0.3"
/>
<stop
offset="100%"
style="stop-color:rgb(59, 130, 246);stop-opacity:0"
/>
</linearGradient>
</defs>
<g>
{(0..=y_ticks)
.map(|i| {
let y_pos = chart_height - padding
- (i as f64 * y_tick_step * y_scale);
let value = i as f64 * y_tick_step;
view! {
<g>
<line
x1=padding
y1=y_pos
x2=chart_width - padding
y2=y_pos
stroke="currentColor"
class="text-neutral-200 dark:text-neutral-700"
stroke-width="1"
/>
<text
x=padding - 10.0
y=y_pos + 5.0
text-anchor="end"
class="text-xs fill-neutral-500 dark:fill-neutral-400"
>
{"R "}
{value.round().to_string()}
</text>
</g>
}
})
.collect::<Vec<_>>()}
</g>
<g>
{points
.iter()
.enumerate()
.map(|(i, (x, _, _, date, _))| {
let show_label = if data_len <= 30 {
i % 7 == 0
} else {
i % 14 == 0
};
let date_label = if let Some(parts) = date
.split('-')
.collect::<Vec<_>>()
.get(1..3)
{
format!("{}-{}", parts[0], parts[1])
} else {
date.clone()
};
let x = *x;
view! {
<g>
<line
x1=x
y1=chart_height - padding
x2=x
y2=chart_height - padding + 5.0
stroke="currentColor"
class="text-neutral-400 dark:text-neutral-600"
stroke-width="1"
/>
{show_label
.then(|| {
view! {
<text
x=x
y=chart_height - padding + 20.0
text-anchor="middle"
class="text-xs fill-neutral-600 dark:fill-neutral-400"
>
{date_label}
</text>
}
})}
</g>
}
})
.collect::<Vec<_>>()}
</g>
<path
d=format!(
"{} L {} {} L {} {} Z",
path_data,
chart_width - padding,
chart_height - padding,
padding,
chart_height - padding,
)
fill="url(#lineGradient)"
/>
<path
d=path_data
fill="none"
stroke="rgb(59, 130, 246)"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
/>
<g>
{points
.into_iter()
.map(|(x, y, avg_7day, date, _count)| {
view! {
<g>
<circle
cx=x
cy=y
r="4"
class="fill-blue-500 stroke-white dark:stroke-neutral-900"
stroke-width="2"
/>
<title>
{format!("{}: R {} (7-day avg)", date, avg_7day.round())}
</title>
</g>
}
})
.collect::<Vec<_>>()}
</g>
</svg>
}
}
</div>
</div>
}
.into_any()
}
}
Err(err) => {
view! {
<div class="flex items-center justify-center h-64">
<p class="text-red-500 dark:text-red-400">
"Error loading chart: " {err.to_string()}
</p>
</div>
}
.into_any()
}
}
})
}}
</Suspense>
</div>
}
}
#[derive(Deserialize, Serialize, Clone, Debug)]
struct MonthlyData {
pub month: String,
pub total: f64,
pub count: usize,
}
#[server]
async fn fetch_monthly_orders() -> Result<Vec<MonthlyData>, ServerFnError> {
let user = crate::session::get_user().await?;
if user.is_admin != Some(true) {
return Err(ServerFnError::ServerError("Unauthorized".into()));
}
let db = crate::db::db_init().await?;
let mut orders_req = db
.query("SELECT created_at as x, total as y FROM order WHERE paid = true ORDER BY created_at ASC;")
.await?;
let orders = orders_req.take::<Vec<DashboardOrderListItem>>(0)?;
// Group orders by month
let mut monthly_map: std::collections::HashMap<String, (f64, usize)> =
std::collections::HashMap::new();
for order in orders {
let month = order.x.format("%Y-%m");
let total: f64 = order.y.parse().unwrap_or(0.0);
let entry = monthly_map.entry(month).or_insert((0.0, 0));
entry.0 += total;
entry.1 += 1;
}
// Convert to sorted vec
let mut monthly_data: Vec<MonthlyData> = monthly_map
.into_iter()
.map(|(month, (total, count))| MonthlyData {
month,
total,
count,
})
.collect();
monthly_data.sort_by(|a, b| a.month.cmp(&b.month)); // Sort chronologically
// Keep last 12 months
let len = monthly_data.len();
if len > 12 {
monthly_data = monthly_data.into_iter().skip(len - 12).collect();
}
Ok(monthly_data)
}
#[component]
pub fn OrderChartMonthly() -> impl IntoView {
let monthly_resource = Resource::new(|| (), |_| async move { fetch_monthly_orders().await });
view! {
<div class="w-full">
<Suspense fallback=move || {
view! {
<div class="flex items-center justify-center h-64">
<p class="text-neutral-500 dark:text-neutral-400">"Loading chart..."</p>
</div>
}
}>
{move || {
monthly_resource
.get()
.map(|data_result| {
match data_result {
Ok(monthly_data) => {
if monthly_data.is_empty() {
view! {
<div class="flex items-center justify-center h-64">
<p class="text-neutral-500 dark:text-neutral-400">
"No order data available"
</p>
</div>
}
.into_any()
} else {
let max_value = monthly_data
.iter()
.map(|d| d.total)
.fold(0.0f64, f64::max);
view! {
<div class="space-y-4">
<div class="bg-white dark:bg-neutral-900 p-6 rounded-lg shadow">
<h3 class="text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-4">
"Monthly Revenue"
</h3>
{
let chart_width = 800.0;
let chart_height = 400.0;
let padding = 60.0;
let plot_width = chart_width - 2.0 * padding;
let plot_height = chart_height - 2.0 * padding;
let data_len = monthly_data.len();
let bar_width = if data_len > 0 {
(plot_width / data_len as f64) * 0.7
} else {
20.0
};
let y_scale = if max_value > 0.0 {
plot_height / max_value
} else {
1.0
};
let bars: Vec<_> = monthly_data
.iter()
.enumerate()
.map(|(i, d)| {
let x = padding
+ (i as f64 * (plot_width / data_len as f64))
+ (plot_width / data_len as f64 - bar_width) / 2.0;
let bar_height = d.total * y_scale;
let y = chart_height - padding - bar_height;
(x, y, bar_height, d.total, d.month.clone(), d.count)
})
.collect();
let y_ticks = 5;
let y_tick_step = max_value / y_ticks as f64;
view! {
<svg
viewBox=format!("0 0 {} {}", chart_width, chart_height)
class="w-full h-auto"
>
<g>
{(0..=y_ticks)
.map(|i| {
let y_pos = chart_height - padding
- (i as f64 * y_tick_step * y_scale);
let value = i as f64 * y_tick_step;
view! {
<g>
<line
x1=padding
y1=y_pos
x2=chart_width - padding
y2=y_pos
stroke="currentColor"
class="text-neutral-200 dark:text-neutral-700"
stroke-width="1"
/>
<text
x=padding - 10.0
y=y_pos + 5.0
text-anchor="end"
class="text-xs fill-neutral-500 dark:fill-neutral-400"
>
{"R "}
{value.round().to_string()}
</text>
</g>
}
})
.collect::<Vec<_>>()}
</g>
<line
x1=padding
y1=chart_height - padding
x2=chart_width - padding
y2=chart_height - padding
stroke="currentColor"
class="text-neutral-400 dark:text-neutral-600"
stroke-width="2"
/>
<g>
{bars
.iter()
.enumerate()
.map(|(i, (x, _y, _h, _total, month, _count))| {
let x_center = x + bar_width / 2.0;
let month_label = if let Some(parts) = month
.split('-')
.collect::<Vec<_>>()
.get(0..2)
{
let year = parts[0];
let month_num = parts[1];
let month_name = match month_num {
"01" => "Jan",
"02" => "Feb",
"03" => "Mar",
"04" => "Apr",
"05" => "May",
"06" => "Jun",
"07" => "Jul",
"08" => "Aug",
"09" => "Sep",
"10" => "Oct",
"11" => "Nov",
"12" => "Dec",
_ => month_num,
};
(month_name.to_string(), year.to_string())
} else {
("".to_string(), "".to_string())
};
view! {
<g>
<line
x1=x_center
y1=chart_height - padding
x2=x_center
y2=chart_height - padding + 5.0
stroke="currentColor"
class="text-neutral-400 dark:text-neutral-600"
stroke-width="1"
/>
<text
x=x_center
y=chart_height - padding + 20.0
text-anchor="middle"
class="text-xs fill-neutral-600 dark:fill-neutral-400"
>
{month_label.0}
</text>
<text
x=x_center
y=chart_height - padding + 20.0 + 12.0
text-anchor="middle"
class="text-xs fill-neutral-600 dark:fill-neutral-400"
>
{month_label.1}
</text>
</g>
}
})
.collect::<Vec<_>>()}
</g>
<g>
{bars
.into_iter()
.map(|(x, y, h, total, month, count)| {
view! {
<g>
<rect
x=x
y=y
width=bar_width
height=h
class="fill-blue-500 hover:fill-blue-600 transition-colors"
/>
<title>
{format!(
"{}: R {} ({} orders)",
month,
total.round(),
count,
)}
</title>
</g>
}
})
.collect::<Vec<_>>()}
</g>
</svg>
}
}
</div>
</div>
}
.into_any()
}
}
Err(err) => {
view! {
<div class="flex items-center justify-center h-64">
<p class="text-red-500 dark:text-red-400">
"Error loading chart: " {err.to_string()}
</p>
</div>
}
.into_any()
}
}
})
}}
</Suspense>
</div>
}
}