Procházet zdrojové kódy

Add overview dashboard with store tree and daily AI note

feature/dashboard
fahmisaad před 2 dny
rodič
revize
d860f0a6d1
46 změnil soubory, kde provedl 3517 přidání a 150 odebrání
  1. 3
    0
      .env
  2. 18
    2
      PROGRESS.md
  3. 5
    3
      app/Ai/Drivers/FakeDriver.php
  4. 438
    0
      app/Dashboard/OverviewStats.php
  5. 308
    0
      app/Dashboard/StorePulse.php
  6. 75
    0
      app/Http/Controllers/DashboardController.php
  7. 0
    15
      app/Http/Controllers/StoreController.php
  8. 27
    0
      app/Http/Middleware/HandleInertiaRequests.php
  9. 49
    0
      app/Models/DashboardPulse.php
  10. 16
    0
      config/ai.php
  11. 39
    0
      database/migrations/2026_11_22_000001_create_dashboard_pulses_table.php
  12. 2
    0
      phpunit.xml
  13. 94
    0
      resources/css/app.css
  14. 1
    1
      resources/js/components/app-header.tsx
  15. 12
    19
      resources/js/components/app-sidebar.tsx
  16. 9
    2
      resources/js/components/nav-main.tsx
  17. 74
    0
      resources/js/components/nav-plan.tsx
  18. 252
    0
      resources/js/components/nav-stores.tsx
  19. 90
    0
      resources/js/components/overview/format.ts
  20. 261
    0
      resources/js/components/overview/kpi-cards.tsx
  21. 199
    0
      resources/js/components/overview/pulse-card.tsx
  22. 260
    0
      resources/js/components/overview/sales-chart.tsx
  23. 544
    0
      resources/js/components/overview/sections.tsx
  24. 41
    0
      resources/js/components/overview/use-count-up.ts
  25. 1
    1
      resources/js/pages/billing/index.tsx
  26. 324
    92
      resources/js/pages/dashboard.tsx
  27. 5
    0
      resources/js/pages/legal/privacy.tsx
  28. 1
    1
      resources/js/pages/stores/collections/form.tsx
  29. 1
    1
      resources/js/pages/stores/create.tsx
  30. 1
    1
      resources/js/pages/stores/discounts/automatic-form.tsx
  31. 1
    1
      resources/js/pages/stores/discounts/form.tsx
  32. 1
    1
      resources/js/pages/stores/discounts/index.tsx
  33. 1
    1
      resources/js/pages/stores/orders/index.tsx
  34. 1
    1
      resources/js/pages/stores/orders/show.tsx
  35. 1
    1
      resources/js/pages/stores/products/create.tsx
  36. 1
    1
      resources/js/pages/stores/products/edit.tsx
  37. 1
    1
      resources/js/pages/stores/products/index.tsx
  38. 1
    1
      resources/js/pages/stores/settings.tsx
  39. 1
    1
      resources/js/pages/stores/show.tsx
  40. 2
    0
      resources/js/types/global.d.ts
  41. 1
    0
      resources/js/types/index.ts
  42. 89
    0
      resources/js/types/overview.ts
  43. 15
    0
      resources/js/types/store.ts
  44. 3
    1
      routes/web.php
  45. 2
    2
      tests/Feature/Billing/BillingTest.php
  46. 246
    0
      tests/Feature/Dashboard/OverviewTest.php

+ 3
- 0
.env Zobrazit soubor

@@ -81,6 +81,9 @@ AI_GENERATE_PROVIDER=
81 81
 AI_GENERATE_MODEL=
82 82
 AI_EDIT_PROVIDER=
83 83
 AI_EDIT_MODEL=
84
+AI_PULSE_PROVIDER=
85
+AI_PULSE_MODEL=
86
+AI_PULSE_DAILY_REWRITES=
84 87
 AI_FAKE_DELAY=
85 88
 ANTHROPIC_API_KEY=
86 89
 DEEPSEEK_API_KEY=

+ 18
- 2
PROGRESS.md Zobrazit soubor

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-22
7
-**Current step:** Step 10 (before launch): home page done, privacy policy and terms done (on `feature/homepage`, not committed yet); Step 9 part 8 on hold
8
-**Next action:** Commit the privacy and terms pages. Have a lawyer read both pages before launch, and fill the `LEGAL_` lines in `.env.local` once the business is registered. Then choose: backup AI provider, hosting, Stripe Connect (who receives the money), Step 7 part 2, or part 8. `main` and the redesign branches stay apart for comparison
7
+**Current step:** Step 10 (before launch): new Overview dashboard with store tree and daily AI note done on `feature/dashboard` (not committed yet); home page, privacy and terms done; Step 9 part 8 on hold
8
+**Next action:** Commit the dashboard on `feature/dashboard`. Then: have a lawyer read the privacy and terms pages, fill the `LEGAL_` lines, and choose: backup AI provider, hosting, Stripe Connect (who receives the money), Step 7 part 2, or part 8. `main` and the redesign branches stay apart for comparison
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -285,6 +285,19 @@ Changing from Claude to another AI model (or back) must be a settings change, no
285 285
 - Who runs the service, the SSM number, contact email and address come from `LEGAL_OPERATOR`, `LEGAL_REGISTRATION`, `LEGAL_EMAIL` (falls back to `MAIL_FROM_ADDRESS`) and `LEGAL_ADDRESS`. The "last changed" date is in `config/legal.php`; change it whenever the wording changes.
286 286
 - Promises made in the terms: 30 days' notice before a price change or closing the service, 14 days before important changes to the terms, no refunds for unused days, replies to data requests within 21 days. The terms do not yet say how merchants are paid; update them once Stripe Connect is decided.
287 287
 
288
+### Overview dashboard and Store pulse (added 2026-11-22)
289
+
290
+- The dashboard page is now an Overview (`DashboardController`, `app/Dashboard/OverviewStats.php`, `resources/js/pages/dashboard.tsx`, `resources/js/components/overview/`), in the home page colours with its own dark version (`.overview` tokens in `app.css`). Chosen from three trend designs: an AI note on top of colourful number boxes.
291
+- Order, top to bottom: Store pulse (AI note), four numbers (sales, paid orders, average order, to ship now), sales chart beside "Needs attention", sales by store beside top products, recent orders. Filters: Today, 7 days, 30 days, This month, and a store picker.
292
+- Only paid orders count as sales, on the Malaysian day they were paid. Sales are what shoppers paid, shipping included. Each range is compared with the same length of time just before it; "This month" with the same days of last month.
293
+- "Needs attention": orders to ship per store, products with 5 or fewer left (active, not bundles), unpublished design changes, stores designed but not published (several make one line), trial ending in 7 days or plan ended.
294
+- Before the first sale the page shows "Get your first sale" (create, design, products, publish) and zero boxes instead of empty charts. No AI note then.
295
+- The stores list moved to the sidebar as a tree: Overview, "Your stores" (Create store first, then each store with Design, Products, Orders with a to-ship badge, Discounts, Settings; green dot live, yellow draft), Account (Billing), and a plan box. Shared on every page as `sidebar` (`HandleInertiaRequests`). The starter kit's Repository and Documentation links are gone. Breadcrumbs say "Overview".
296
+- Store pulse (`app/Dashboard/StorePulse.php`, table `dashboard_pulses`): AI task `pulse` (DeepSeek by default, `AI_PULSE_PROVIDER`/`AI_PULSE_MODEL`, 400 tokens). Written once per Malaysian day per view (all stores, or one store) and saved, so refreshing costs nothing; it loads just after the page (deferred). Only numbers, store names and product names go to the AI, never shoppers' details (the privacy page says so).
297
+- "Write again" asks for a fresh note, 3 times a day in all (`AI_PULSE_DAILY_REWRITES`), shown under the button ("2 of 3 left today"). It does not count toward the plan's AI changes. A failed AI answer does not use a turn.
298
+- If the AI cannot answer, the note is written from the numbers instead. The buttons under the note (ship, restock, publish) are worked out by us from the numbers, not by the AI.
299
+- First real note: 442 tokens in, 63 out.
300
+
288 301
 ### Category guides for the AI (agreed 2026-11-17)
289 302
 
290 303
 - The category the merchant picks on the Create store page (Fashion, Beauty, Food, Home, Electronics, Health, Kids, Digital, Other) chooses a short design guide that is sent to the AI with the brand description.
@@ -452,6 +465,7 @@ Notes:
452 465
 
453 466
 - [x] Our own home page at `/` (done 2026-11-22, branch `feature/homepage`, made from the part 7 branch)
454 467
 
468
+- [x] Overview dashboard with stats, store tree in the sidebar and daily AI note (done 2026-11-22, branch `feature/dashboard`)
455 469
 - [ ] Choose hosting and deploy
456 470
 - [x] Privacy policy and terms of service, naming the AI providers (done 2026-11-22, `/privacy` and `/terms`; a lawyer should read them before launch)
457 471
 - [ ] Backup AI provider in case one is down
@@ -555,6 +569,7 @@ Then, from the project folder:
555 569
 | Video and Bento boxes                  | `app/StorePlan/SectionEditor.php`, `VideoSectionController`, `BentoSectionController`, `components/stores/video-box.tsx`, `bento-box.tsx`                                              |
556 570
 | Home page                              | `resources/js/pages/home.tsx`, `app/Http/Controllers/HomeController.php`                                                                                                               |
557 571
 | Privacy and terms                      | `resources/js/pages/legal/`, `app/Http/Controllers/LegalController.php`, `config/legal.php`                                                                                            |
572
+| Overview dashboard and Store pulse     | `app/Dashboard/`, `DashboardController`, `resources/js/pages/dashboard.tsx`, `resources/js/components/overview/`, `nav-stores.tsx`, `nav-plan.tsx`                                     |
558 573
 | Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                                                                      |
559 574
 | Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                                                                     |
560 575
 | Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                                                            |
@@ -623,3 +638,4 @@ Add one line per work session: date, what was done, what is next.
623 638
 | 2026-11-22 | Part 7 committed on `redesign/part-7-collections-bento-video`. Part 8 (real reviews) put on hold by the merchant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Choose next step                                                |
624 639
 | 2026-11-22 | Built our own home page on branch `feature/homepage`: content outline like afilink.app with our own look, real plan prices, store-name box that fills the Create store form. 288 tests pass; checked on desktop and phone. Then made the hero picture move like afilink's (pinned scroll on wide screens, plays once on phones, floating tags), fixed tags covering text, added hover lift on the hero pieces and pricing cards, made the store and bubble float, and added six more animations (fade-up, typing bubble, playing chat, changing styles, steps line, shop-types strip). | Commit; choose next step                                        |
625 640
 | 2026-11-22 | Home page committed. Added the privacy policy (`/privacy`) and terms of service (`/terms`) for Malaysian law, naming the AI companies from the AI settings, linked from the home footer and sign-up. 293 tests pass; checked on desktop and phone.                                                                                                                                                                                                                                                                                                                                     | Commit; lawyer check; choose next                               |
641
+| 2026-11-22 | Redesigned the dashboard on branch `feature/dashboard` (picked from three trend designs: AI note on top of colourful boxes). Stats with filters, needs attention, sales chart, store tree in the sidebar, daily Store pulse from DeepSeek saved per day with 3 "Write again" a day, first-sale steps for new merchants. 303 tests pass; checked on desktop, phone and dark mode.                                                                                                                                                                                                       | Commit; choose next step                                        |

+ 5
- 3
app/Ai/Drivers/FakeDriver.php Zobrazit soubor

@@ -26,9 +26,11 @@ final class FakeDriver implements AiDriver
26 26
     {
27 27
         Sleep::for((int) ($this->config['delay'] ?? 0))->seconds();
28 28
 
29
-        $answer = $request->task === 'edit'
30
-            ? ['reply' => 'Fake AI: I made the main colour darker.', 'theme' => ['colors' => ['primary' => '#3B2A20']]]
31
-            : SamplePlan::forName($this->storeName($request->prompt));
29
+        $answer = match ($request->task) {
30
+            'edit' => ['reply' => 'Fake AI: I made the main colour darker.', 'theme' => ['colors' => ['primary' => '#3B2A20']]],
31
+            'pulse' => ['summary' => 'Fake AI: sales are steady this month. Ship your waiting orders first, then check your stock.'],
32
+            default => SamplePlan::forName($this->storeName($request->prompt)),
33
+        };
32 34
 
33 35
         return new AiResponse(
34 36
             text: (string) json_encode($answer),

+ 438
- 0
app/Dashboard/OverviewStats.php Zobrazit soubor

@@ -0,0 +1,438 @@
1
+<?php
2
+
3
+namespace App\Dashboard;
4
+
5
+use App\Enums\OrderStatus;
6
+use App\Enums\ProductStatus;
7
+use App\Models\Order;
8
+use App\Models\OrderItem;
9
+use App\Models\Product;
10
+use App\Models\Store;
11
+use App\Models\User;
12
+use Carbon\CarbonImmutable;
13
+use Illuminate\Support\Collection;
14
+
15
+/**
16
+ * The numbers on the dashboard's Overview page, for one merchant.
17
+ *
18
+ * - Only paid orders count as sales. The day an order counts for is the Malaysian day it was paid.
19
+ * - Sales are what shoppers paid in total, shipping included. Money leaves this class in ringgit.
20
+ * - Every range is compared with the same length of time just before it. "This month" is compared
21
+ *   with the same days of last month, so the comparison is fair on the 5th as on the 28th.
22
+ */
23
+class OverviewStats
24
+{
25
+    public const string TIMEZONE = 'Asia/Kuala_Lumpur';
26
+
27
+    /** @var list<string> */
28
+    public const array RANGES = ['today', '7d', '30d', 'month'];
29
+
30
+    /** A product with this many or fewer left shows in "Needs attention". */
31
+    public const int LOW_STOCK = 5;
32
+
33
+    /**
34
+     * @return array<string, mixed>
35
+     */
36
+    public function for(User $user, string $range, ?Store $store, ?CarbonImmutable $now = null): array
37
+    {
38
+        $now = ($now ?? CarbonImmutable::now())->setTimezone(self::TIMEZONE);
39
+        $range = in_array($range, self::RANGES, true) ? $range : '30d';
40
+
41
+        /** @var Collection<int, Store> $stores */
42
+        $stores = $user->stores()->orderBy('created_at')->get();
43
+        $storeIds = $store !== null ? [$store->id] : $stores->pluck('id')->all();
44
+
45
+        [$start, $previousStart, $buckets] = $this->period($range, $now);
46
+        $previousEnd = $this->shift($range, $now);
47
+
48
+        $orders = Order::query()
49
+            ->whereIn('store_id', $stores->pluck('id'))
50
+            ->where('status', OrderStatus::Paid)
51
+            ->where('paid_at', '>=', $previousStart->utc())
52
+            ->where('paid_at', '<=', $now->utc())
53
+            ->get(['id', 'store_id', 'total', 'paid_at']);
54
+
55
+        $current = $orders->filter(fn (Order $order) => $order->paid_at >= $start);
56
+        $previous = $orders->filter(fn (Order $order) => $order->paid_at < $start && $order->paid_at <= $previousEnd);
57
+        $mine = fn (Collection $list) => $list->whereIn('store_id', $storeIds);
58
+
59
+        $sales = $mine($current)->sum('total') / 100;
60
+        $previousSales = $mine($previous)->sum('total') / 100;
61
+        $count = $mine($current)->count();
62
+        $previousCount = $mine($previous)->count();
63
+
64
+        return [
65
+            'range' => $range,
66
+            'label' => $this->label($range, $now),
67
+            'compare_label' => match ($range) {
68
+                'today' => 'vs yesterday at this time',
69
+                '7d' => 'vs the 7 days before',
70
+                '30d' => 'vs the 30 days before',
71
+                'month' => 'vs the same days last month',
72
+            },
73
+            'sales' => round($sales, 2),
74
+            'previous_sales' => round($previousSales, 2),
75
+            'sales_change' => $this->change($sales, $previousSales),
76
+            'orders' => $count,
77
+            'previous_orders' => $previousCount,
78
+            'average' => $count > 0 ? round($sales / $count, 2) : 0,
79
+            'previous_average' => $previousCount > 0 ? round($previousSales / $previousCount, 2) : 0,
80
+            'series' => $this->series($range, $buckets, $start, $previousStart, $mine($current), $mine($previous)),
81
+            'to_ship' => $this->toShip($storeIds, $now),
82
+            'attention' => $this->attention($user, $stores, $storeIds, $now),
83
+            'by_store' => $stores->map(function (Store $each) use ($current, $store) {
84
+                $storeSales = $current->where('store_id', $each->id)->sum('total') / 100;
85
+                $allSales = $current->sum('total') / 100;
86
+
87
+                return [
88
+                    'name' => $each->name,
89
+                    'slug' => $each->slug,
90
+                    'is_published' => $each->isPublished(),
91
+                    'sales' => round($storeSales, 2),
92
+                    'share' => $allSales > 0 ? (int) round($storeSales / $allSales * 100) : 0,
93
+                    'selected' => $store?->id === $each->id,
94
+                ];
95
+            })->values()->all(),
96
+            'top_products' => $this->topProducts($storeIds, $start, $now, $stores),
97
+            'recent_orders' => $this->recentOrders($storeIds, $stores),
98
+        ];
99
+    }
100
+
101
+    /**
102
+     * Whether any of the merchant's stores has ever had a paid order. Until then the dashboard shows
103
+     * the "Get your first sale" steps instead of empty charts.
104
+     */
105
+    public function hasSales(User $user): bool
106
+    {
107
+        return Order::query()
108
+            ->whereIn('store_id', $user->stores()->select('id'))
109
+            ->where('status', OrderStatus::Paid)
110
+            ->exists();
111
+    }
112
+
113
+    /**
114
+     * The four steps to a first sale, and which are done.
115
+     *
116
+     * @return array{store: array{name: string, slug: string}|null, steps: array<string, bool>}
117
+     */
118
+    public function gettingStarted(User $user): array
119
+    {
120
+        $stores = $user->stores()->orderBy('created_at')->get();
121
+        $first = $stores->first();
122
+
123
+        return [
124
+            'store' => $first !== null ? ['name' => $first->name, 'slug' => $first->slug] : null,
125
+            'steps' => [
126
+                'create' => $stores->isNotEmpty(),
127
+                'design' => $stores->contains(fn (Store $store) => $store->plan !== null),
128
+                'products' => Product::query()->whereIn('store_id', $stores->pluck('id'))->where('status', ProductStatus::Active)->exists(),
129
+                'publish' => $stores->contains(fn (Store $store) => $store->isPublished()),
130
+            ],
131
+        ];
132
+    }
133
+
134
+    /**
135
+     * Where the range starts, where the period before it starts, and how many points the chart has.
136
+     *
137
+     * @return array{0: CarbonImmutable, 1: CarbonImmutable, 2: int}
138
+     */
139
+    private function period(string $range, CarbonImmutable $now): array
140
+    {
141
+        $today = $now->startOfDay();
142
+
143
+        return match ($range) {
144
+            'today' => [$today, $today->subDay(), $now->hour + 1],
145
+            '7d' => [$today->subDays(6), $today->subDays(13), 7],
146
+            '30d' => [$today->subDays(29), $today->subDays(59), 30],
147
+            'month' => [$now->startOfMonth(), $now->startOfMonth()->subMonthNoOverflow(), $now->day],
148
+        };
149
+    }
150
+
151
+    /**
152
+     * The same moment in the period before. Orders after it are left out, so a half-finished
153
+     * day is compared with the same half of the day before.
154
+     */
155
+    private function shift(string $range, CarbonImmutable $moment): CarbonImmutable
156
+    {
157
+        return match ($range) {
158
+            'today' => $moment->subDay(),
159
+            '7d' => $moment->subDays(7),
160
+            '30d' => $moment->subDays(30),
161
+            'month' => $moment->subMonthNoOverflow(),
162
+        };
163
+    }
164
+
165
+    private function label(string $range, CarbonImmutable $now): string
166
+    {
167
+        return match ($range) {
168
+            'today' => 'Today, by hour',
169
+            '7d' => 'Last 7 days',
170
+            '30d' => 'Last 30 days',
171
+            'month' => $now->day === 1 ? $now->format('j F') : '1 to '.$now->format('j F'),
172
+        };
173
+    }
174
+
175
+    /**
176
+     * The change in percent, or null when there is nothing to compare with.
177
+     */
178
+    private function change(float $now, float $before): ?int
179
+    {
180
+        return $before > 0 ? (int) round(($now - $before) / $before * 100) : null;
181
+    }
182
+
183
+    /**
184
+     * One point per hour (today) or per day, for this period and the one before.
185
+     *
186
+     * @param  Collection<int, Order>  $current
187
+     * @param  Collection<int, Order>  $previous
188
+     * @return list<array{label: string, sales: float, previous: float, orders: int}>
189
+     */
190
+    private function series(string $range, int $buckets, CarbonImmutable $start, CarbonImmutable $previousStart, Collection $current, Collection $previous): array
191
+    {
192
+        $index = function (Order $order, CarbonImmutable $from) use ($range): int {
193
+            $paid = CarbonImmutable::parse($order->paid_at)->setTimezone(self::TIMEZONE);
194
+
195
+            return $range === 'today'
196
+                ? $paid->hour
197
+                : (int) $from->diffInDays($paid->startOfDay());
198
+        };
199
+
200
+        $points = [];
201
+
202
+        for ($i = 0; $i < $buckets; $i++) {
203
+            $moment = $range === 'today' ? $start->addHours($i) : $start->addDays($i);
204
+            $points[$i] = [
205
+                'label' => $range === 'today' ? strtolower($moment->format('ga')) : $moment->format('j M'),
206
+                'sales' => 0.0,
207
+                'previous' => 0.0,
208
+                'orders' => 0,
209
+            ];
210
+        }
211
+
212
+        foreach ($current as $order) {
213
+            $i = $index($order, $start);
214
+
215
+            if (isset($points[$i])) {
216
+                $points[$i]['sales'] += $order->total / 100;
217
+                $points[$i]['orders']++;
218
+            }
219
+        }
220
+
221
+        foreach ($previous as $order) {
222
+            $i = $index($order, $previousStart);
223
+
224
+            if (isset($points[$i])) {
225
+                $points[$i]['previous'] += $order->total / 100;
226
+            }
227
+        }
228
+
229
+        return array_map(fn (array $point) => [
230
+            ...$point,
231
+            'sales' => round($point['sales'], 2),
232
+            'previous' => round($point['previous'], 2),
233
+        ], array_values($points));
234
+    }
235
+
236
+    /**
237
+     * Paid orders not shipped yet, and how many days the oldest has waited.
238
+     *
239
+     * @param  list<int>  $storeIds
240
+     * @return array{count: int, oldest_days: int|null}
241
+     */
242
+    private function toShip(array $storeIds, CarbonImmutable $now): array
243
+    {
244
+        $waiting = Order::query()
245
+            ->whereIn('store_id', $storeIds)
246
+            ->where('status', OrderStatus::Paid)
247
+            ->whereNull('shipped_at');
248
+
249
+        $oldest = (clone $waiting)->min('paid_at');
250
+
251
+        return [
252
+            'count' => $waiting->count(),
253
+            'oldest_days' => $oldest !== null
254
+                ? (int) CarbonImmutable::parse($oldest, 'UTC')->setTimezone(self::TIMEZONE)->startOfDay()->diffInDays($now->startOfDay())
255
+                : null,
256
+        ];
257
+    }
258
+
259
+    /**
260
+     * What the merchant should look at now, most urgent first: orders to ship, products running out,
261
+     * designs waiting to be published, and the plan.
262
+     *
263
+     * @param  Collection<int, Store>  $stores
264
+     * @param  list<int>  $storeIds
265
+     * @return list<array<string, mixed>>
266
+     */
267
+    private function attention(User $user, Collection $stores, array $storeIds, CarbonImmutable $now): array
268
+    {
269
+        $items = [];
270
+        $shown = $stores->whereIn('id', $storeIds);
271
+
272
+        foreach ($shown as $store) {
273
+            $ship = $this->toShip([$store->id], $now);
274
+
275
+            if ($ship['count'] > 0) {
276
+                $items[] = [
277
+                    'kind' => 'ship',
278
+                    'tone' => 'warning',
279
+                    'title' => $ship['count'] === 1 ? '1 order to ship' : $ship['count'].' orders to ship',
280
+                    'note' => match (true) {
281
+                        $ship['oldest_days'] === 0 => 'Paid today',
282
+                        $ship['oldest_days'] === 1 => 'Oldest waited 1 day',
283
+                        default => 'Oldest waited '.$ship['oldest_days'].' days',
284
+                    },
285
+                    'store' => ['name' => $store->name, 'slug' => $store->slug],
286
+                ];
287
+            }
288
+        }
289
+
290
+        $lowStock = Product::query()
291
+            ->whereIn('store_id', $storeIds)
292
+            ->where('status', ProductStatus::Active)
293
+            ->where('is_bundle', false)
294
+            ->where('stock', '<=', self::LOW_STOCK)
295
+            ->orderBy('stock')
296
+            ->limit(4)
297
+            ->get(['id', 'store_id', 'name', 'stock']);
298
+
299
+        foreach ($lowStock as $product) {
300
+            $store = $stores->firstWhere('id', $product->store_id);
301
+            $items[] = [
302
+                'kind' => 'restock',
303
+                'tone' => 'danger',
304
+                'title' => $product->stock === 0 ? $product->name.' is out of stock' : $product->name.' is almost out',
305
+                'note' => $product->stock === 0 ? 'Shoppers can’t buy it now' : 'Only '.$product->stock.' left',
306
+                'store' => ['name' => $store->name, 'slug' => $store->slug],
307
+                'product_id' => $product->id,
308
+            ];
309
+        }
310
+
311
+        foreach ($shown as $store) {
312
+            if ($store->hasUnpublishedChanges()) {
313
+                $items[] = [
314
+                    'kind' => 'publish',
315
+                    'tone' => 'brand',
316
+                    'title' => 'Design changes not published',
317
+                    'note' => 'Shoppers still see the old design',
318
+                    'store' => ['name' => $store->name, 'slug' => $store->slug],
319
+                ];
320
+            }
321
+        }
322
+
323
+        // Designed but never published. Several of them make one line, so the list stays short.
324
+        $ready = $shown->filter(fn (Store $store) => $store->plan !== null && ! $store->isPublished())->values();
325
+
326
+        if ($ready->count() === 1) {
327
+            $items[] = [
328
+                'kind' => 'publish',
329
+                'tone' => 'brand',
330
+                'title' => $ready[0]->name.' is ready to publish',
331
+                'note' => 'Shoppers can’t see it yet',
332
+                'store' => ['name' => $ready[0]->name, 'slug' => $ready[0]->slug],
333
+            ];
334
+        } elseif ($ready->count() > 1) {
335
+            $names = $ready->pluck('name');
336
+            $items[] = [
337
+                'kind' => 'publish',
338
+                'tone' => 'brand',
339
+                'title' => $ready->count().' stores are not published',
340
+                'note' => $ready->count() === 2
341
+                    ? $names->join(' and ')
342
+                    : $names->take(2)->join(', ').' and '.($ready->count() - 2).' more',
343
+                'store' => ['name' => $ready[0]->name, 'slug' => $ready[0]->slug],
344
+            ];
345
+        }
346
+
347
+        $plan = $user->currentPlan();
348
+
349
+        if ($plan === null) {
350
+            $items[] = ['kind' => 'plan', 'tone' => 'danger', 'title' => 'Your plan has ended', 'note' => 'Your stores are offline until you choose a plan', 'store' => null];
351
+        } elseif (! $plan->isPaid() && $user->trial_ends_at !== null) {
352
+            $days = (int) ceil($now->diffInDays($user->trial_ends_at, false));
353
+
354
+            if ($days <= 7) {
355
+                $items[] = [
356
+                    'kind' => 'plan',
357
+                    'tone' => 'brand',
358
+                    'title' => $days <= 1 ? 'Your trial ends today' : 'Your trial ends in '.$days.' days',
359
+                    'note' => 'Choose a plan to keep your stores online',
360
+                    'store' => null,
361
+                ];
362
+            }
363
+        }
364
+
365
+        return $items;
366
+    }
367
+
368
+    /**
369
+     * The best sellers in the range, by money taken.
370
+     *
371
+     * @param  list<int>  $storeIds
372
+     * @param  Collection<int, Store>  $stores
373
+     * @return list<array<string, mixed>>
374
+     */
375
+    private function topProducts(array $storeIds, CarbonImmutable $start, CarbonImmutable $now, Collection $stores): array
376
+    {
377
+        // One line per product, even when it was sold in several options. Products deleted since keep their old name.
378
+        $rows = OrderItem::query()
379
+            ->join('orders', 'orders.id', '=', 'order_items.order_id')
380
+            ->whereIn('order_items.store_id', $storeIds)
381
+            ->where('orders.status', OrderStatus::Paid)
382
+            ->where('orders.paid_at', '>=', $start->utc())
383
+            ->where('orders.paid_at', '<=', $now->utc())
384
+            ->groupBy('order_items.store_id', 'order_items.product_id')
385
+            ->selectRaw('order_items.store_id, order_items.product_id, MIN(order_items.name) as name, SUM(order_items.quantity) as units, SUM(order_items.line_total) as revenue')
386
+            ->orderByDesc('revenue')
387
+            ->limit(5)
388
+            ->get();
389
+
390
+        $names = Product::query()->whereIn('id', $rows->pluck('product_id')->filter())->pluck('name', 'id');
391
+
392
+        return $rows
393
+            ->map(function (OrderItem $item) use ($stores, $names) {
394
+                $store = $stores->firstWhere('id', $item->store_id);
395
+
396
+                return [
397
+                    'name' => $names[$item->product_id] ?? $item->name,
398
+                    'product_id' => isset($names[$item->product_id]) ? $item->product_id : null,
399
+                    'store' => ['name' => $store?->name, 'slug' => $store?->slug],
400
+                    'units' => (int) $item->getAttribute('units'),
401
+                    'revenue' => round((int) $item->getAttribute('revenue') / 100, 2),
402
+                ];
403
+            })
404
+            ->all();
405
+    }
406
+
407
+    /**
408
+     * The newest paid orders.
409
+     *
410
+     * @param  list<int>  $storeIds
411
+     * @param  Collection<int, Store>  $stores
412
+     * @return list<array<string, mixed>>
413
+     */
414
+    private function recentOrders(array $storeIds, Collection $stores): array
415
+    {
416
+        return Order::query()
417
+            ->whereIn('store_id', $storeIds)
418
+            ->where('status', OrderStatus::Paid)
419
+            ->latest('paid_at')
420
+            ->limit(5)
421
+            ->get()
422
+            ->map(function (Order $order) use ($stores) {
423
+                $store = $stores->firstWhere('id', $order->store_id);
424
+
425
+                return [
426
+                    'id' => $order->id,
427
+                    'number' => $order->number,
428
+                    'customer_name' => $order->customer_name,
429
+                    'state' => $order->shipping_address['state'] ?? null,
430
+                    'total' => $order->total / 100,
431
+                    'shipped' => $order->shipped_at !== null,
432
+                    'paid_at' => $order->paid_at?->toIso8601String(),
433
+                    'store' => ['name' => $store?->name, 'slug' => $store?->slug],
434
+                ];
435
+            })
436
+            ->all();
437
+    }
438
+}

+ 308
- 0
app/Dashboard/StorePulse.php Zobrazit soubor

@@ -0,0 +1,308 @@
1
+<?php
2
+
3
+namespace App\Dashboard;
4
+
5
+use App\Ai\AiException;
6
+use App\Ai\AiManager;
7
+use App\Models\DashboardPulse;
8
+use App\Models\Store;
9
+use App\Models\User;
10
+use App\StorePlan\Ai\JsonAnswer;
11
+use Carbon\CarbonImmutable;
12
+use Illuminate\Support\Facades\Log;
13
+use Illuminate\Support\Str;
14
+
15
+/**
16
+ * The "Store pulse": a two-sentence note at the top of the dashboard about how the stores are doing
17
+ * and what to do first.
18
+ *
19
+ * - Written once per Malaysian day for each view (all stores, or one store), then saved. Opening or
20
+ *   refreshing the dashboard reads the saved note and never asks the AI again.
21
+ * - "Write again" asks for a fresh note, up to config('ai.pulse.daily_rewrites') times a day in all.
22
+ *   It does not count toward the plan's AI changes.
23
+ * - Only numbers, store names and product names go to the AI. Never shoppers' names or addresses.
24
+ * - When the AI cannot answer, the note is written from the numbers instead, so the card never breaks.
25
+ * - Merchants with no sales yet get no note: the dashboard shows the first-sale steps instead.
26
+ * - The buttons under the note are worked out by us from the numbers, not by the AI.
27
+ */
28
+class StorePulse
29
+{
30
+    public function __construct(
31
+        private readonly AiManager $ai,
32
+        private readonly OverviewStats $stats,
33
+    ) {}
34
+
35
+    /**
36
+     * Today's note for this view: the saved one, or a new one written now.
37
+     *
38
+     * @return array<string, mixed>|null
39
+     */
40
+    public function today(User $user, ?Store $store, ?CarbonImmutable $now = null): ?array
41
+    {
42
+        $now = $this->now($now);
43
+
44
+        if (! $this->stats->hasSales($user)) {
45
+            return null;
46
+        }
47
+
48
+        $stats = $this->stats->for($user, 'month', $store, $now);
49
+        $pulse = $this->find($user, $store, $now) ?? $this->write($user, $store, $stats, $now);
50
+
51
+        return $this->present($user, $pulse, $stats, $now);
52
+    }
53
+
54
+    /**
55
+     * "Write again": replace today's note with a fresh one, if the daily limit allows.
56
+     *
57
+     * @return bool False when the limit is used up or the AI could not answer. The old note stays.
58
+     */
59
+    public function rewrite(User $user, ?Store $store, ?CarbonImmutable $now = null): bool
60
+    {
61
+        $now = $this->now($now);
62
+
63
+        if ($this->rewritesLeft($user, $now) <= 0 || ! $this->stats->hasSales($user)) {
64
+            return false;
65
+        }
66
+
67
+        $stats = $this->stats->for($user, 'month', $store, $now);
68
+        $pulse = $this->find($user, $store, $now) ?? $this->write($user, $store, $stats, $now);
69
+        $answer = $this->ask($user, $store, $stats);
70
+
71
+        if ($answer === null) {
72
+            return false;
73
+        }
74
+
75
+        $pulse->fill([...$answer, 'rewrites' => $pulse->rewrites + 1])->save();
76
+
77
+        return true;
78
+    }
79
+
80
+    public function rewritesLeft(User $user, ?CarbonImmutable $now = null): int
81
+    {
82
+        $used = (int) DashboardPulse::query()
83
+            ->where('user_id', $user->id)
84
+            ->where('day', $this->now($now)->toDateString())
85
+            ->sum('rewrites');
86
+
87
+        return max(0, $this->limit() - $used);
88
+    }
89
+
90
+    public function limit(): int
91
+    {
92
+        return max(0, (int) config('ai.pulse.daily_rewrites', 3));
93
+    }
94
+
95
+    private function find(User $user, ?Store $store, CarbonImmutable $now): ?DashboardPulse
96
+    {
97
+        return DashboardPulse::query()
98
+            ->where('user_id', $user->id)
99
+            ->where('store_id', $store?->id)
100
+            ->where('day', $now->toDateString())
101
+            ->first();
102
+    }
103
+
104
+    /**
105
+     * @param  array<string, mixed>  $stats
106
+     */
107
+    private function write(User $user, ?Store $store, array $stats, CarbonImmutable $now): DashboardPulse
108
+    {
109
+        $answer = $this->ask($user, $store, $stats) ?? [
110
+            'summary' => $this->fromNumbers($stats, $store),
111
+            'source' => 'numbers',
112
+            'provider' => null,
113
+            'model' => null,
114
+            'input_tokens' => 0,
115
+            'output_tokens' => 0,
116
+        ];
117
+
118
+        // Two tabs opening the dashboard at once could both get here; the second one keeps the first note.
119
+        return DashboardPulse::query()->firstOrCreate(
120
+            ['user_id' => $user->id, 'store_id' => $store?->id, 'day' => $now->toDateString()],
121
+            $answer,
122
+        );
123
+    }
124
+
125
+    /**
126
+     * Ask the AI for a note. Null when it could not give a usable one.
127
+     *
128
+     * @param  array<string, mixed>  $stats
129
+     * @return array<string, mixed>|null
130
+     */
131
+    private function ask(User $user, ?Store $store, array $stats): ?array
132
+    {
133
+        try {
134
+            $response = $this->ai->ask('pulse', $this->system(), $this->prompt($store, $stats));
135
+            $summary = JsonAnswer::decode($response->text)['summary'] ?? null;
136
+        } catch (AiException $exception) {
137
+            Log::warning('Store pulse: the AI could not write a note.', ['user' => $user->id, 'error' => $exception->getMessage()]);
138
+
139
+            return null;
140
+        }
141
+
142
+        if (! is_string($summary) || trim($summary) === '') {
143
+            return null;
144
+        }
145
+
146
+        return [
147
+            'summary' => Str::limit(trim(preg_replace('/\s+/', ' ', strip_tags($summary)) ?? ''), 400),
148
+            'source' => 'ai',
149
+            'provider' => $response->provider,
150
+            'model' => $response->model,
151
+            'input_tokens' => $response->inputTokens,
152
+            'output_tokens' => $response->outputTokens,
153
+        ];
154
+    }
155
+
156
+    private function system(): string
157
+    {
158
+        return <<<'TEXT'
159
+            You write the short daily note at the top of an online seller's dashboard. The seller runs small
160
+            online stores in Malaysia and reads this on their phone.
161
+
162
+            Rules:
163
+            - Use only the facts you are given. Never invent numbers, products, customers or reasons.
164
+            - Two sentences, 45 words at most. Plain, warm, everyday English. No greeting, no emoji, no lists.
165
+            - First say how sales are going, then the one or two most useful things to do today, most urgent first.
166
+            - Money is in ringgit, written like RM 1,240.
167
+            - Answer with JSON only: {"summary": "..."}
168
+            TEXT;
169
+    }
170
+
171
+    /**
172
+     * The facts for the AI. Numbers, store names and product names only.
173
+     *
174
+     * @param  array<string, mixed>  $stats
175
+     */
176
+    private function prompt(?Store $store, array $stats): string
177
+    {
178
+        $lines = [
179
+            'View: '.($store !== null ? 'one store, '.$store->name : 'all stores together'),
180
+            'Sales this month so far: '.$this->money($stats['sales']).' from '.$stats['orders'].' paid orders',
181
+            'Same days last month: '.$this->money($stats['previous_sales']).' from '.$stats['previous_orders'].' paid orders',
182
+        ];
183
+
184
+        if ($store === null && count($stats['by_store']) > 1) {
185
+            foreach ($stats['by_store'] as $each) {
186
+                $lines[] = 'Store '.$each['name'].': '.$this->money($each['sales']).' this month'.($each['is_published'] ? '' : ' (not published)');
187
+            }
188
+        }
189
+
190
+        foreach (array_slice($stats['top_products'], 0, 3) as $product) {
191
+            $lines[] = 'Best seller: '.$product['name'].', '.$product['units'].' sold this month';
192
+        }
193
+
194
+        $lines[] = 'Paid orders waiting to ship: '.$stats['to_ship']['count']
195
+            .($stats['to_ship']['oldest_days'] ? ' (oldest waited '.$stats['to_ship']['oldest_days'].' days)' : '');
196
+
197
+        foreach ($stats['attention'] as $item) {
198
+            if (in_array($item['kind'], ['restock', 'publish', 'plan'], true)) {
199
+                $lines[] = 'Needs attention: '.$item['title'].' ('.$item['note'].')'.($item['store'] !== null && $store === null ? ' in '.$item['store']['name'] : '');
200
+            }
201
+        }
202
+
203
+        $lines[] = 'Today is '.now()->setTimezone(OverviewStats::TIMEZONE)->format('l, j F Y');
204
+
205
+        return "Facts:\n- ".implode("\n- ", $lines);
206
+    }
207
+
208
+    /**
209
+     * The note we write ourselves when the AI cannot.
210
+     *
211
+     * @param  array<string, mixed>  $stats
212
+     */
213
+    private function fromNumbers(array $stats, ?Store $store): string
214
+    {
215
+        $change = $stats['sales_change'];
216
+        $first = 'Sales this month are '.$this->money($stats['sales'])
217
+            .match (true) {
218
+                $change === null => '',
219
+                $change > 0 => ', up '.$change.'% on the same days last month',
220
+                $change < 0 => ', down '.abs($change).'% on the same days last month',
221
+                default => ', the same as last month',
222
+            }.'.';
223
+
224
+        $ship = $stats['to_ship']['count'];
225
+        $restock = collect($stats['attention'])->firstWhere('kind', 'restock');
226
+
227
+        $next = match (true) {
228
+            $ship > 0 && $restock !== null => ' Ship the '.$ship.' waiting '.($ship === 1 ? 'order' : 'orders').' first, then restock '.$this->productName($restock['title']).'.',
229
+            $ship > 0 => ' Ship the '.$ship.' waiting '.($ship === 1 ? 'order' : 'orders').' first.',
230
+            $restock !== null => ' Restock '.$this->productName($restock['title']).' before it runs out.',
231
+            default => ' Nothing urgent today.',
232
+        };
233
+
234
+        return $first.$next;
235
+    }
236
+
237
+    /**
238
+     * Up to three buttons under the note, from the numbers.
239
+     *
240
+     * @param  array<string, mixed>  $stats
241
+     * @return list<array<string, mixed>>
242
+     */
243
+    private function actions(array $stats): array
244
+    {
245
+        $actions = [];
246
+        $attention = collect($stats['attention']);
247
+
248
+        $ship = $attention->where('kind', 'ship');
249
+
250
+        if ($ship->isNotEmpty()) {
251
+            $actions[] = [
252
+                'kind' => 'ship',
253
+                'label' => 'Ship '.$stats['to_ship']['count'].' '.($stats['to_ship']['count'] === 1 ? 'order' : 'orders'),
254
+                // With several stores, the button opens the store with the most waiting.
255
+                'store_slug' => $ship->first()['store']['slug'],
256
+            ];
257
+        }
258
+
259
+        foreach ($attention->where('kind', 'restock')->take(2) as $item) {
260
+            $actions[] = [
261
+                'kind' => 'restock',
262
+                'label' => 'Restock '.$this->productName($item['title']),
263
+                'store_slug' => $item['store']['slug'],
264
+                'product_id' => $item['product_id'],
265
+            ];
266
+        }
267
+
268
+        $publish = $attention->firstWhere('kind', 'publish');
269
+
270
+        if ($publish !== null) {
271
+            $actions[] = ['kind' => 'publish', 'label' => 'Publish '.$publish['store']['name'], 'store_slug' => $publish['store']['slug']];
272
+        }
273
+
274
+        return array_slice($actions, 0, 3);
275
+    }
276
+
277
+    /**
278
+     * @param  array<string, mixed>  $stats
279
+     * @return array<string, mixed>
280
+     */
281
+    private function present(User $user, DashboardPulse $pulse, array $stats, CarbonImmutable $now): array
282
+    {
283
+        return [
284
+            'summary' => $pulse->summary,
285
+            'source' => $pulse->source,
286
+            'written_at' => $pulse->updated_at?->toIso8601String(),
287
+            'actions' => $this->actions($stats),
288
+            'rewrites_left' => $this->rewritesLeft($user, $now),
289
+            'rewrites_limit' => $this->limit(),
290
+        ];
291
+    }
292
+
293
+    /** "Sambal hijau is almost out" → "Sambal hijau". */
294
+    private function productName(string $title): string
295
+    {
296
+        return (string) preg_replace('/ is (almost out|out of stock)$/', '', $title);
297
+    }
298
+
299
+    private function money(float|int $amount): string
300
+    {
301
+        return 'RM '.number_format($amount, $amount == floor($amount) ? 0 : 2);
302
+    }
303
+
304
+    private function now(?CarbonImmutable $now): CarbonImmutable
305
+    {
306
+        return ($now ?? CarbonImmutable::now())->setTimezone(OverviewStats::TIMEZONE);
307
+    }
308
+}

+ 75
- 0
app/Http/Controllers/DashboardController.php Zobrazit soubor

@@ -0,0 +1,75 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Dashboard\OverviewStats;
6
+use App\Dashboard\StorePulse;
7
+use App\Models\Store;
8
+use App\Storefront\Storefront;
9
+use Illuminate\Http\RedirectResponse;
10
+use Illuminate\Http\Request;
11
+use Inertia\Inertia;
12
+use Inertia\Response;
13
+
14
+/**
15
+ * The Overview page: how the merchant's stores are doing, what needs attention, and the daily AI note.
16
+ */
17
+class DashboardController extends Controller
18
+{
19
+    public function index(Request $request, OverviewStats $stats, StorePulse $pulse): Response
20
+    {
21
+        $user = $request->user();
22
+        $store = $this->chosenStore($request);
23
+        $range = in_array($request->query('range'), OverviewStats::RANGES, true) ? (string) $request->query('range') : '30d';
24
+        $hasSales = $stats->hasSales($user);
25
+
26
+        return Inertia::render('dashboard', [
27
+            'filters' => ['range' => $range, 'store' => $store?->slug],
28
+            'stores' => $user->stores()->orderBy('created_at')->get(['name', 'slug'])->map(fn (Store $each) => ['name' => $each->name, 'slug' => $each->slug]),
29
+            'hasSales' => $hasSales,
30
+            // Until the first sale, the page shows the steps to get there instead of empty charts.
31
+            'gettingStarted' => $hasSales ? null : $stats->gettingStarted($user),
32
+            // The address of the first live store, for the "share your link" box before the first sale.
33
+            'liveUrl' => $hasSales ? null : $this->firstLiveUrl($request),
34
+            'stats' => $hasSales ? $stats->for($user, $range, $store) : null,
35
+            // Loaded just after the page shows, because writing a new note can take a few seconds.
36
+            // Once written it is saved for the day, so this is quick on every later visit.
37
+            'pulse' => $hasSales ? Inertia::defer(fn () => $pulse->today($user, $store)) : null,
38
+        ]);
39
+    }
40
+
41
+    /**
42
+     * "Write again" on the Store pulse card.
43
+     */
44
+    public function rewritePulse(Request $request, StorePulse $pulse): RedirectResponse
45
+    {
46
+        $user = $request->user();
47
+
48
+        if ($pulse->rewritesLeft($user) <= 0) {
49
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('You have used today’s :count fresh notes. A new note comes tomorrow.', ['count' => $pulse->limit()])]);
50
+        } elseif (! $pulse->rewrite($user, $this->chosenStore($request))) {
51
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('The AI could not write a new note just now. Try again later.')]);
52
+        }
53
+
54
+        return back();
55
+    }
56
+
57
+    private function firstLiveUrl(Request $request): ?string
58
+    {
59
+        $live = $request->user()->stores()->published()->orderBy('created_at')->first();
60
+
61
+        return $live !== null ? Storefront::liveUrl($live, $request) : null;
62
+    }
63
+
64
+    /**
65
+     * The store picked in the filter, if it is one of the merchant's own. Anything else means all stores.
66
+     */
67
+    private function chosenStore(Request $request): ?Store
68
+    {
69
+        $slug = $request->input('store');
70
+
71
+        return is_string($slug) && $slug !== ''
72
+            ? $request->user()->stores()->where('slug', $slug)->first()
73
+            : null;
74
+    }
75
+}

+ 0
- 15
app/Http/Controllers/StoreController.php Zobrazit soubor

@@ -23,21 +23,6 @@ use Inertia\Response;
23 23
 
24 24
 class StoreController extends Controller
25 25
 {
26
-    /**
27
-     * Show the dashboard with the user's own stores.
28
-     */
29
-    public function index(Request $request, UsageLimits $usage): Response
30
-    {
31
-        return Inertia::render('dashboard', [
32
-            'usage' => $usage->for($request->user()),
33
-            'stores' => $request->user()
34
-                ->stores()
35
-                ->latest()
36
-                ->get()
37
-                ->map(fn (Store $store) => $this->present($store)),
38
-        ]);
39
-    }
40
-
41 26
     /**
42 27
      * Show the "create a store" form.
43 28
      */

+ 27
- 0
app/Http/Middleware/HandleInertiaRequests.php Zobrazit soubor

@@ -2,6 +2,10 @@
2 2
 
3 3
 namespace App\Http\Middleware;
4 4
 
5
+use App\Billing\UsageLimits;
6
+use App\Enums\OrderStatus;
7
+use App\Models\Store;
8
+use App\Models\User;
5 9
 use Illuminate\Http\Request;
6 10
 use Inertia\Middleware;
7 11
 
@@ -42,6 +46,29 @@ class HandleInertiaRequests extends Middleware
42 46
                 'user' => $request->user(),
43 47
             ],
44 48
             'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
49
+            // The store tree and the plan box in the sidebar of every dashboard page.
50
+            'sidebar' => fn () => $request->user() !== null ? $this->sidebar($request->user()) : null,
51
+        ];
52
+    }
53
+
54
+    /**
55
+     * @return array{stores: list<array<string, mixed>>, usage: array<string, mixed>}
56
+     */
57
+    private function sidebar(User $user): array
58
+    {
59
+        return [
60
+            'stores' => $user->stores()
61
+                ->orderBy('created_at')
62
+                ->withCount(['orders as to_ship' => fn ($query) => $query->where('status', OrderStatus::Paid)->whereNull('shipped_at')])
63
+                ->get()
64
+                ->map(fn (Store $store) => [
65
+                    'name' => $store->name,
66
+                    'slug' => $store->slug,
67
+                    'is_published' => $store->isPublished(),
68
+                    'to_ship' => (int) $store->getAttribute('to_ship'),
69
+                ])
70
+                ->all(),
71
+            'usage' => app(UsageLimits::class)->for($user),
45 72
         ];
46 73
     }
47 74
 }

+ 49
- 0
app/Models/DashboardPulse.php Zobrazit soubor

@@ -0,0 +1,49 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Carbon\CarbonInterface;
6
+use Illuminate\Database\Eloquent\Model;
7
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
+
9
+/**
10
+ * The short daily note at the top of the dashboard ("Store pulse"). See App\Dashboard\StorePulse.
11
+ *
12
+ * @property int $id
13
+ * @property int $user_id
14
+ * @property int|null $store_id Null for the note about all stores
15
+ * @property string $day The Malaysian day, as YYYY-MM-DD
16
+ * @property string $summary
17
+ * @property string $source "ai" or "numbers"
18
+ * @property int $rewrites
19
+ * @property string|null $provider
20
+ * @property string|null $model
21
+ * @property int $input_tokens
22
+ * @property int $output_tokens
23
+ * @property CarbonInterface|null $created_at
24
+ * @property CarbonInterface|null $updated_at
25
+ */
26
+class DashboardPulse extends Model
27
+{
28
+    protected $guarded = ['id'];
29
+
30
+    /**
31
+     * @return BelongsTo<User, $this>
32
+     */
33
+    public function user(): BelongsTo
34
+    {
35
+        return $this->belongsTo(User::class);
36
+    }
37
+
38
+    /**
39
+     * @return array<string, string>
40
+     */
41
+    protected function casts(): array
42
+    {
43
+        return [
44
+            'rewrites' => 'integer',
45
+            'input_tokens' => 'integer',
46
+            'output_tokens' => 'integer',
47
+        ];
48
+    }
49
+}

+ 16
- 0
config/ai.php Zobrazit soubor

@@ -36,6 +36,22 @@ return [
36 36
             'model' => env('AI_EDIT_MODEL') ?: 'deepseek-chat',
37 37
             'max_tokens' => 6000,
38 38
         ],
39
+
40
+        // The short daily note at the top of the dashboard ("Store pulse"). A cheap model is enough.
41
+        'pulse' => [
42
+            'provider' => env('AI_PULSE_PROVIDER') ?: 'deepseek',
43
+            'model' => env('AI_PULSE_MODEL') ?: 'deepseek-chat',
44
+            'max_tokens' => 400,
45
+        ],
46
+    ],
47
+
48
+    /*
49
+     * The dashboard note is written at most once a day per view (all stores, or one store) and saved,
50
+     * so refreshing the dashboard costs nothing. "Write again" asks for a fresh note; this is how many
51
+     * times a merchant may press it per day, across all views. It does not count toward AI changes.
52
+     */
53
+    'pulse' => [
54
+        'daily_rewrites' => (int) env('AI_PULSE_DAILY_REWRITES', 3),
39 55
     ],
40 56
 
41 57
     'providers' => [

+ 39
- 0
database/migrations/2026_11_22_000001_create_dashboard_pulses_table.php Zobrazit soubor

@@ -0,0 +1,39 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        // The short daily note at the top of the dashboard ("Store pulse"). One per merchant, per day,
12
+        // per view (all stores, or one store). Saved so refreshing the dashboard never asks the AI again.
13
+        Schema::create('dashboard_pulses', function (Blueprint $table) {
14
+            $table->id();
15
+            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
16
+            // Null means the note covers all of the merchant's stores.
17
+            $table->foreignId('store_id')->nullable()->constrained()->cascadeOnDelete();
18
+            // The Malaysian day the note is for.
19
+            $table->date('day');
20
+            $table->string('summary', 600);
21
+            // "ai" when the AI wrote it, "numbers" when the AI could not and we wrote it from the numbers.
22
+            $table->string('source', 10);
23
+            // How many times the merchant pressed "Write again" for this note. Counts toward the daily limit.
24
+            $table->unsignedSmallInteger('rewrites')->default(0);
25
+            $table->string('provider', 40)->nullable();
26
+            $table->string('model', 80)->nullable();
27
+            $table->unsignedInteger('input_tokens')->default(0);
28
+            $table->unsignedInteger('output_tokens')->default(0);
29
+            $table->timestamps();
30
+
31
+            $table->unique(['user_id', 'store_id', 'day']);
32
+        });
33
+    }
34
+
35
+    public function down(): void
36
+    {
37
+        Schema::dropIfExists('dashboard_pulses');
38
+    }
39
+};

+ 2
- 0
phpunit.xml Zobrazit soubor

@@ -32,6 +32,8 @@
32 32
         <env name="AI_GENERATE_MODEL" value="test-generate-model"/>
33 33
         <env name="AI_EDIT_PROVIDER" value="fake"/>
34 34
         <env name="AI_EDIT_MODEL" value="test-edit-model"/>
35
+        <env name="AI_PULSE_PROVIDER" value="fake"/>
36
+        <env name="AI_PULSE_MODEL" value="test-pulse-model"/>
35 37
         <env name="AI_FAKE_DELAY" value="0"/>
36 38
         <env name="ANTHROPIC_API_KEY" value=""/>
37 39
         <env name="DEEPSEEK_API_KEY" value=""/>

+ 94
- 0
resources/css/app.css Zobrazit soubor

@@ -142,6 +142,100 @@
142 142
     }
143 143
 }
144 144
 
145
+/*
146
+ * Overview page (resources/js/pages/dashboard.tsx). Our own colours from the home page:
147
+ * pandan green, kunyit yellow and bunga red, with a dark version for dark mode.
148
+ */
149
+.overview {
150
+    --ov-paper: #f2f6f1;
151
+    --ov-card: #ffffff;
152
+    --ov-ink: #10241c;
153
+    --ov-muted: #4e6158;
154
+    --ov-line: #d6e1d8;
155
+    --ov-hover: #e7efe9;
156
+    --ov-pandan: #1d6a4c;
157
+    --ov-pandan-ink: #14553c;
158
+    --ov-pandan-soft: #dcebe1;
159
+    --ov-hero: #1d6a4c;
160
+    --ov-pulse: #0f3d2c;
161
+    --ov-kunyit: #f2b33d;
162
+    --ov-kunyit-soft: #fcefcf;
163
+    --ov-kunyit-ink: #7a5208;
164
+    --ov-bunga: #e3573f;
165
+    --ov-bunga-soft: #fbe3de;
166
+    --ov-bunga-ink: #a3321f;
167
+    --ov-prev: #9db0a5;
168
+
169
+    background-color: var(--ov-paper);
170
+    color: var(--ov-ink);
171
+}
172
+
173
+.dark .overview {
174
+    --ov-paper: #0d1712;
175
+    --ov-card: #14221b;
176
+    --ov-ink: #e7f0ea;
177
+    --ov-muted: #9bb0a4;
178
+    --ov-line: #26382e;
179
+    --ov-hover: #1b2d24;
180
+    --ov-pandan: #3fa57a;
181
+    --ov-pandan-ink: #7fd1a9;
182
+    --ov-pandan-soft: #1a3327;
183
+    --ov-hero: #1d6a4c;
184
+    --ov-pulse: #123f2e;
185
+    --ov-kunyit-soft: #3a2e12;
186
+    --ov-kunyit-ink: #f5c866;
187
+    --ov-bunga: #ee6a52;
188
+    --ov-bunga-soft: #3d1e18;
189
+    --ov-bunga-ink: #f79a88;
190
+    --ov-prev: #5e7468;
191
+}
192
+
193
+.ov-heading {
194
+    font-family: 'Plus Jakarta Sans', ui-sans-serif, system-ui, sans-serif;
195
+    letter-spacing: -0.015em;
196
+}
197
+
198
+@media (prefers-reduced-motion: no-preference) {
199
+    .ov-rise {
200
+        animation: ov-rise 0.6s cubic-bezier(0.2, 0.8, 0.2, 1) both;
201
+    }
202
+
203
+    .ov-spin {
204
+        animation: ov-spin 2.6s linear infinite;
205
+    }
206
+
207
+    .ov-caret {
208
+        animation: ov-caret 1s step-end infinite;
209
+    }
210
+
211
+    .ov-lift {
212
+        transition: transform 0.2s;
213
+    }
214
+
215
+    .ov-lift:hover {
216
+        transform: translateY(-3px);
217
+    }
218
+}
219
+
220
+@keyframes ov-rise {
221
+    from {
222
+        opacity: 0;
223
+        transform: translateY(14px);
224
+    }
225
+}
226
+
227
+@keyframes ov-spin {
228
+    to {
229
+        transform: rotate(360deg);
230
+    }
231
+}
232
+
233
+@keyframes ov-caret {
234
+    50% {
235
+        opacity: 0;
236
+    }
237
+}
238
+
145 239
 /*
146 240
  * Storefront. Colours, fonts and corner radius come from the store plan as
147 241
  * --sf-* variables (see resources/js/storefront/theme.ts), so a storefront

+ 1
- 1
resources/js/components/app-header.tsx Zobrazit soubor

@@ -41,7 +41,7 @@ type Props = {
41 41
 
42 42
 const mainNavItems: NavItem[] = [
43 43
     {
44
-        title: 'Dashboard',
44
+        title: 'Overview',
45 45
         href: dashboard(),
46 46
         icon: LayoutGrid,
47 47
     },

+ 12
- 19
resources/js/components/app-sidebar.tsx Zobrazit soubor

@@ -1,9 +1,10 @@
1 1
 import { Link } from '@inertiajs/react';
2
-import { BookOpen, CreditCard, FolderGit2, LayoutGrid } from 'lucide-react';
2
+import { CreditCard, LayoutGrid } from 'lucide-react';
3 3
 import BillingController from '@/actions/App/Http/Controllers/BillingController';
4 4
 import AppLogo from '@/components/app-logo';
5
-import { NavFooter } from '@/components/nav-footer';
6 5
 import { NavMain } from '@/components/nav-main';
6
+import { NavPlan } from '@/components/nav-plan';
7
+import { NavStores } from '@/components/nav-stores';
7 8
 import { NavUser } from '@/components/nav-user';
8 9
 import {
9 10
     Sidebar,
@@ -17,12 +18,15 @@ import {
17 18
 import { dashboard } from '@/routes';
18 19
 import type { NavItem } from '@/types';
19 20
 
20
-const mainNavItems: NavItem[] = [
21
+const overviewItems: NavItem[] = [
21 22
     {
22
-        title: 'Dashboard',
23
+        title: 'Overview',
23 24
         href: dashboard(),
24 25
         icon: LayoutGrid,
25 26
     },
27
+];
28
+
29
+const accountItems: NavItem[] = [
26 30
     {
27 31
         title: 'Billing',
28 32
         href: BillingController.index(),
@@ -30,19 +34,6 @@ const mainNavItems: NavItem[] = [
30 34
     },
31 35
 ];
32 36
 
33
-const footerNavItems: NavItem[] = [
34
-    {
35
-        title: 'Repository',
36
-        href: 'https://github.com/laravel/react-starter-kit',
37
-        icon: FolderGit2,
38
-    },
39
-    {
40
-        title: 'Documentation',
41
-        href: 'https://laravel.com/docs/starter-kits#react',
42
-        icon: BookOpen,
43
-    },
44
-];
45
-
46 37
 export function AppSidebar() {
47 38
     return (
48 39
         <Sidebar collapsible="icon" variant="inset">
@@ -59,11 +50,13 @@ export function AppSidebar() {
59 50
             </SidebarHeader>
60 51
 
61 52
             <SidebarContent>
62
-                <NavMain items={mainNavItems} />
53
+                <NavMain items={overviewItems} />
54
+                <NavStores />
55
+                <NavMain items={accountItems} label="Account" />
63 56
             </SidebarContent>
64 57
 
65 58
             <SidebarFooter>
66
-                <NavFooter items={footerNavItems} className="mt-auto" />
59
+                <NavPlan />
67 60
                 <NavUser />
68 61
             </SidebarFooter>
69 62
         </Sidebar>

+ 9
- 2
resources/js/components/nav-main.tsx Zobrazit soubor

@@ -9,12 +9,19 @@ import {
9 9
 import { useCurrentUrl } from '@/hooks/use-current-url';
10 10
 import type { NavItem } from '@/types';
11 11
 
12
-export function NavMain({ items }: { items: NavItem[] }) {
12
+export function NavMain({
13
+    items,
14
+    label,
15
+}: {
16
+    items: NavItem[];
17
+    /** A small heading above the links. None by default. */
18
+    label?: string;
19
+}) {
13 20
     const { isCurrentUrl } = useCurrentUrl();
14 21
 
15 22
     return (
16 23
         <SidebarGroup className="px-2 py-0">
17
-            <SidebarGroupLabel>Platform</SidebarGroupLabel>
24
+            {label && <SidebarGroupLabel>{label}</SidebarGroupLabel>}
18 25
             <SidebarMenu>
19 26
                 {items.map((item) => (
20 27
                     <SidebarMenuItem key={item.title}>

+ 74
- 0
resources/js/components/nav-plan.tsx Zobrazit soubor

@@ -0,0 +1,74 @@
1
+import { Link, usePage } from '@inertiajs/react';
2
+import BillingController from '@/actions/App/Http/Controllers/BillingController';
3
+import { daysLeft } from '@/components/plan-notice';
4
+import type { UsageCount } from '@/types';
5
+
6
+function Meter({ label, count }: { label: string; count: UsageCount }) {
7
+    const share =
8
+        count.limit > 0 ? Math.min(100, (count.used / count.limit) * 100) : 100;
9
+
10
+    return (
11
+        <div className="grid gap-1">
12
+            <div className="flex justify-between text-xs text-sidebar-foreground/70">
13
+                <span>{label}</span>
14
+                <span className="tabular-nums">
15
+                    {count.used} of {count.limit}
16
+                </span>
17
+            </div>
18
+            <div className="h-1.5 overflow-hidden rounded-full bg-sidebar-accent">
19
+                <div
20
+                    className={
21
+                        share >= 90
22
+                            ? 'h-full rounded-full bg-amber-500'
23
+                            : 'h-full rounded-full bg-emerald-600 dark:bg-emerald-500'
24
+                    }
25
+                    style={{ width: `${share}%` }}
26
+                />
27
+            </div>
28
+        </div>
29
+    );
30
+}
31
+
32
+/**
33
+ * The plan box at the bottom of the sidebar: which plan, trial days left, and how much is used.
34
+ * Hidden when the sidebar is folded to icons.
35
+ */
36
+export function NavPlan() {
37
+    const { sidebar } = usePage().props;
38
+
39
+    if (!sidebar) {
40
+        return null;
41
+    }
42
+
43
+    const { usage } = sidebar;
44
+    const days = daysLeft(usage.trial_ends_at);
45
+
46
+    return (
47
+        <div className="mx-2 grid gap-2.5 rounded-lg border border-sidebar-border p-3 text-sm group-data-[collapsible=icon]:hidden">
48
+            <div className="flex items-baseline justify-between gap-2">
49
+                <span className="font-medium">
50
+                    {!usage.active
51
+                        ? 'No plan'
52
+                        : usage.on_trial
53
+                          ? 'Free trial'
54
+                          : usage.plan_name}
55
+                </span>
56
+                {(usage.on_trial || !usage.active) && (
57
+                    <Link
58
+                        href={BillingController.index.url()}
59
+                        className="text-xs font-medium text-emerald-700 hover:underline dark:text-emerald-400"
60
+                    >
61
+                        Choose plan
62
+                    </Link>
63
+                )}
64
+            </div>
65
+            {usage.active && usage.on_trial && (
66
+                <p className="-mt-1.5 text-xs text-sidebar-foreground/70">
67
+                    {days === 1 ? '1 day left' : `${days} days left`}
68
+                </p>
69
+            )}
70
+            <Meter label="Stores" count={usage.stores} />
71
+            <Meter label="AI changes" count={usage.edits} />
72
+        </div>
73
+    );
74
+}

+ 252
- 0
resources/js/components/nav-stores.tsx Zobrazit soubor

@@ -0,0 +1,252 @@
1
+import { Link, usePage } from '@inertiajs/react';
2
+import {
3
+    ChevronRight,
4
+    Package,
5
+    Palette,
6
+    PlusCircle,
7
+    ReceiptText,
8
+    Settings,
9
+    Tag,
10
+} from 'lucide-react';
11
+import { useEffect, useState } from 'react';
12
+import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
13
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
14
+import ProductController from '@/actions/App/Http/Controllers/ProductController';
15
+import StoreController from '@/actions/App/Http/Controllers/StoreController';
16
+import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
17
+import {
18
+    Collapsible,
19
+    CollapsibleContent,
20
+    CollapsibleTrigger,
21
+} from '@/components/ui/collapsible';
22
+import {
23
+    SidebarGroup,
24
+    SidebarGroupLabel,
25
+    SidebarMenu,
26
+    SidebarMenuButton,
27
+    SidebarMenuItem,
28
+    SidebarMenuSub,
29
+    SidebarMenuSubButton,
30
+    SidebarMenuSubItem,
31
+    useSidebar,
32
+} from '@/components/ui/sidebar';
33
+import { useCurrentUrl } from '@/hooks/use-current-url';
34
+import { cn } from '@/lib/utils';
35
+import { create } from '@/routes/stores';
36
+import type { SidebarStore } from '@/types';
37
+
38
+/** Tile colours: our pandan, kunyit and bunga, then three more so neighbouring stores rarely match. */
39
+const tileColours = [
40
+    'bg-[#1D6A4C] text-white',
41
+    'bg-[#F2B33D] text-[#3D2A05]',
42
+    'bg-[#E3573F] text-white',
43
+    'bg-[#2F7F8F] text-white',
44
+    'bg-[#7A5AA6] text-white',
45
+    'bg-[#B4632A] text-white',
46
+];
47
+
48
+/** The same store always gets the same colour, worked out from its web address. */
49
+function tileColour(slug: string): string {
50
+    let hash = 0;
51
+
52
+    for (const char of slug) {
53
+        hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
54
+    }
55
+
56
+    return tileColours[hash % tileColours.length];
57
+}
58
+
59
+/**
60
+ * A store's mark in the sidebar: the first letter of its name on a coloured tile, with a small dot
61
+ * in the corner (green live, yellow draft). It stays readable when the sidebar is folded to icons.
62
+ */
63
+function StoreTile({ store }: { store: SidebarStore }) {
64
+    const letter = (
65
+        store.name.match(/[\p{L}\p{N}]/u)?.[0] ?? '?'
66
+    ).toUpperCase();
67
+
68
+    return (
69
+        <span
70
+            className={cn(
71
+                'relative grid size-5 shrink-0 place-items-center rounded-[5px] text-[11px] leading-none font-bold',
72
+                'group-data-[collapsible=icon]:-m-0.5',
73
+                tileColour(store.slug),
74
+            )}
75
+            aria-hidden="true"
76
+        >
77
+            {letter}
78
+            <span
79
+                className={cn(
80
+                    'absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2 ring-sidebar',
81
+                    store.is_published ? 'bg-emerald-500' : 'bg-amber-400',
82
+                )}
83
+            />
84
+        </span>
85
+    );
86
+}
87
+
88
+/** The store the current page belongs to, from an address like /stores/sambal-nenek/orders. */
89
+function currentStoreSlug(path: string): string | null {
90
+    const match = path.match(/^\/stores\/([^/]+)/);
91
+
92
+    return match && match[1] !== 'create' ? match[1] : null;
93
+}
94
+
95
+/**
96
+ * "Your stores" in the sidebar: Create store first, then one branch per store with its pages.
97
+ * The branch of the store being viewed opens by itself.
98
+ */
99
+export function NavStores() {
100
+    const { sidebar } = usePage().props;
101
+    const { currentUrl, isCurrentUrl } = useCurrentUrl();
102
+    const current = currentStoreSlug(currentUrl);
103
+    const stores = sidebar?.stores ?? [];
104
+
105
+    return (
106
+        <SidebarGroup className="px-2 py-0">
107
+            <SidebarGroupLabel>Your stores</SidebarGroupLabel>
108
+            <SidebarMenu>
109
+                <SidebarMenuItem>
110
+                    <SidebarMenuButton
111
+                        asChild
112
+                        isActive={isCurrentUrl(create())}
113
+                        tooltip={{ children: 'Create store' }}
114
+                        className="font-medium text-emerald-700 hover:text-emerald-800 dark:text-emerald-400 dark:hover:text-emerald-300"
115
+                    >
116
+                        <Link href={create()} prefetch>
117
+                            <PlusCircle />
118
+                            <span>Create store</span>
119
+                        </Link>
120
+                    </SidebarMenuButton>
121
+                </SidebarMenuItem>
122
+
123
+                {stores.map((store) => (
124
+                    <StoreBranch
125
+                        key={store.slug}
126
+                        store={store}
127
+                        isCurrent={store.slug === current}
128
+                    />
129
+                ))}
130
+            </SidebarMenu>
131
+        </SidebarGroup>
132
+    );
133
+}
134
+
135
+function StoreBranch({
136
+    store,
137
+    isCurrent,
138
+}: {
139
+    store: SidebarStore;
140
+    isCurrent: boolean;
141
+}) {
142
+    const [open, setOpen] = useState(isCurrent);
143
+    const { state, isMobile } = useSidebar();
144
+    const { isCurrentUrl, isCurrentOrParentUrl } = useCurrentUrl();
145
+
146
+    // The sidebar stays on screen between pages, so open the branch when its store's page is opened.
147
+    useEffect(() => {
148
+        if (isCurrent) {
149
+            setOpen(true);
150
+        }
151
+    }, [isCurrent]);
152
+
153
+    const pages = [
154
+        {
155
+            label: 'Design',
156
+            href: StoreController.show.url(store.slug),
157
+            icon: Palette,
158
+            exact: true,
159
+        },
160
+        {
161
+            label: 'Products',
162
+            href: ProductController.index.url(store.slug),
163
+            icon: Package,
164
+        },
165
+        {
166
+            label: 'Orders',
167
+            href: OrderController.index.url(store.slug),
168
+            icon: ReceiptText,
169
+            badge: store.to_ship,
170
+        },
171
+        {
172
+            label: 'Discounts',
173
+            href: DiscountCodeController.index.url(store.slug),
174
+            icon: Tag,
175
+        },
176
+        {
177
+            label: 'Settings',
178
+            href: StoreSettingsController.edit.url(store.slug),
179
+            icon: Settings,
180
+            exact: true,
181
+        },
182
+    ];
183
+
184
+    // With the sidebar folded to icons there is no room for the pages, so the store icon opens its design.
185
+    if (state === 'collapsed' && !isMobile) {
186
+        return (
187
+            <SidebarMenuItem>
188
+                <SidebarMenuButton
189
+                    asChild
190
+                    isActive={isCurrent}
191
+                    tooltip={{ children: store.name }}
192
+                >
193
+                    <Link href={StoreController.show.url(store.slug)}>
194
+                        <StoreTile store={store} />
195
+                        <span>{store.name}</span>
196
+                    </Link>
197
+                </SidebarMenuButton>
198
+            </SidebarMenuItem>
199
+        );
200
+    }
201
+
202
+    return (
203
+        <Collapsible
204
+            asChild
205
+            open={open}
206
+            onOpenChange={setOpen}
207
+            className="group/collapsible"
208
+        >
209
+            <SidebarMenuItem>
210
+                <CollapsibleTrigger asChild>
211
+                    <SidebarMenuButton
212
+                        tooltip={{ children: store.name }}
213
+                        className={cn(isCurrent && 'font-medium')}
214
+                    >
215
+                        <StoreTile store={store} />
216
+                        <span className="truncate">{store.name}</span>
217
+                        <ChevronRight className="ml-auto text-sidebar-foreground/50 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
218
+                    </SidebarMenuButton>
219
+                </CollapsibleTrigger>
220
+                <CollapsibleContent>
221
+                    <SidebarMenuSub>
222
+                        {pages.map((page) => (
223
+                            <SidebarMenuSubItem key={page.label}>
224
+                                <SidebarMenuSubButton
225
+                                    asChild
226
+                                    isActive={
227
+                                        page.exact
228
+                                            ? isCurrentUrl(page.href)
229
+                                            : isCurrentOrParentUrl(page.href)
230
+                                    }
231
+                                >
232
+                                    <Link href={page.href} prefetch>
233
+                                        <page.icon />
234
+                                        <span>{page.label}</span>
235
+                                        {page.badge ? (
236
+                                            <span
237
+                                                className="ml-auto rounded-full bg-amber-400 px-1.5 text-xs leading-5 font-semibold text-amber-950 tabular-nums"
238
+                                                aria-label={`${page.badge} to ship`}
239
+                                            >
240
+                                                {page.badge}
241
+                                            </span>
242
+                                        ) : null}
243
+                                    </Link>
244
+                                </SidebarMenuSubButton>
245
+                            </SidebarMenuSubItem>
246
+                        ))}
247
+                    </SidebarMenuSub>
248
+                </CollapsibleContent>
249
+            </SidebarMenuItem>
250
+        </Collapsible>
251
+    );
252
+}

+ 90
- 0
resources/js/components/overview/format.ts Zobrazit soubor

@@ -0,0 +1,90 @@
1
+import BillingController from '@/actions/App/Http/Controllers/BillingController';
2
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
3
+import ProductController from '@/actions/App/Http/Controllers/ProductController';
4
+import StoreController from '@/actions/App/Http/Controllers/StoreController';
5
+
6
+/** "RM 12,480" or, with cents, "RM 87.90". */
7
+export function ringgit(amount: number, cents = false): string {
8
+    return (
9
+        'RM ' +
10
+        amount.toLocaleString('en-MY', {
11
+            minimumFractionDigits: cents ? 2 : 0,
12
+            maximumFractionDigits: cents ? 2 : 0,
13
+        })
14
+    );
15
+}
16
+
17
+/** "RM 1.2k" for chart labels. */
18
+export function shortRinggit(amount: number): string {
19
+    return amount >= 1000
20
+        ? `RM ${(amount / 1000).toLocaleString('en-MY', { maximumFractionDigits: 1 })}k`
21
+        : `RM ${Math.round(amount)}`;
22
+}
23
+
24
+/** "2 hours ago", "Yesterday", "20 Nov". */
25
+export function when(iso: string | null): string {
26
+    if (!iso) {
27
+        return '';
28
+    }
29
+
30
+    const date = new Date(iso);
31
+    const minutes = Math.round((Date.now() - date.getTime()) / 60_000);
32
+
33
+    if (minutes < 1) {
34
+        return 'Just now';
35
+    }
36
+
37
+    if (minutes < 60) {
38
+        return `${minutes} min ago`;
39
+    }
40
+
41
+    if (minutes < 60 * 24 && date.getDate() === new Date().getDate()) {
42
+        const hours = Math.round(minutes / 60);
43
+
44
+        return hours === 1 ? '1 hour ago' : `${hours} hours ago`;
45
+    }
46
+
47
+    const yesterday = new Date();
48
+    yesterday.setDate(yesterday.getDate() - 1);
49
+
50
+    if (date.toDateString() === yesterday.toDateString()) {
51
+        return 'Yesterday';
52
+    }
53
+
54
+    return date.toLocaleDateString('en-MY', { day: 'numeric', month: 'short' });
55
+}
56
+
57
+/** Where a "Needs attention" item or a pulse button leads. */
58
+export function actionHref(
59
+    kind: string,
60
+    storeSlug: string | null | undefined,
61
+    productId?: number | null,
62
+): string {
63
+    if (kind === 'plan' || !storeSlug) {
64
+        return BillingController.index.url();
65
+    }
66
+
67
+    if (kind === 'ship') {
68
+        return OrderController.index.url(storeSlug);
69
+    }
70
+
71
+    if (kind === 'restock' && productId) {
72
+        return ProductController.edit.url({
73
+            slug: storeSlug,
74
+            product: productId,
75
+        });
76
+    }
77
+
78
+    if (kind === 'restock') {
79
+        return ProductController.index.url(storeSlug);
80
+    }
81
+
82
+    return StoreController.show.url(storeSlug);
83
+}
84
+
85
+export function prefersReducedMotion(): boolean {
86
+    return (
87
+        typeof window !== 'undefined' &&
88
+        window.matchMedia('(prefers-reduced-motion: reduce)').matches
89
+    );
90
+}

+ 261
- 0
resources/js/components/overview/kpi-cards.tsx Zobrazit soubor

@@ -0,0 +1,261 @@
1
+import { Link } from '@inertiajs/react';
2
+import {
3
+    ReceiptText,
4
+    ShoppingBag,
5
+    TrendingDown,
6
+    TrendingUp,
7
+    Truck,
8
+} from 'lucide-react';
9
+import type { ReactNode } from 'react';
10
+import { useId } from 'react';
11
+import { actionHref, ringgit } from '@/components/overview/format';
12
+import { useCountUp } from '@/components/overview/use-count-up';
13
+import { cn } from '@/lib/utils';
14
+import type { OverviewStats } from '@/types';
15
+
16
+/** A small trend line under a number. */
17
+function Sparkline({ values, light }: { values: number[]; light?: boolean }) {
18
+    const gradient = useId();
19
+
20
+    if (values.length < 2) {
21
+        return <div className="h-9" />;
22
+    }
23
+
24
+    const max = Math.max(...values);
25
+    const min = Math.min(...values);
26
+    const points = values.map(
27
+        (value, i) =>
28
+            [
29
+                (i / (values.length - 1)) * 200,
30
+                32 - ((value - min) / (max - min || 1)) * 26,
31
+            ] as const,
32
+    );
33
+    const line = points
34
+        .map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`)
35
+        .join(' ');
36
+    const stroke = light ? '#FFFFFF' : 'var(--ov-pandan)';
37
+
38
+    return (
39
+        <svg
40
+            viewBox="0 0 200 36"
41
+            preserveAspectRatio="none"
42
+            className="mt-2 block h-9 w-full"
43
+            aria-hidden="true"
44
+        >
45
+            <defs>
46
+                <linearGradient id={gradient} x1="0" x2="0" y1="0" y2="1">
47
+                    <stop
48
+                        offset="0"
49
+                        stopColor={stroke}
50
+                        stopOpacity={light ? 0.25 : 0.18}
51
+                    />
52
+                    <stop offset="1" stopColor={stroke} stopOpacity="0" />
53
+                </linearGradient>
54
+            </defs>
55
+            <polygon
56
+                points={`0,36 ${line} 200,36`}
57
+                fill={`url(#${gradient})`}
58
+            />
59
+            <polyline
60
+                points={line}
61
+                fill="none"
62
+                stroke={stroke}
63
+                strokeWidth="2"
64
+                strokeLinejoin="round"
65
+                vectorEffect="non-scaling-stroke"
66
+            />
67
+        </svg>
68
+    );
69
+}
70
+
71
+function Change({
72
+    value,
73
+    suffix,
74
+    light,
75
+}: {
76
+    value: number | null;
77
+    suffix: string;
78
+    light?: boolean;
79
+}) {
80
+    if (value === null) {
81
+        return (
82
+            <span className={light ? 'text-white/75' : 'text-(--ov-muted)'}>
83
+                Nothing to compare yet
84
+            </span>
85
+        );
86
+    }
87
+
88
+    const up = value >= 0;
89
+    const Icon = up ? TrendingUp : TrendingDown;
90
+
91
+    return (
92
+        <span className="inline-flex flex-wrap items-center gap-1.5">
93
+            <span
94
+                className={cn(
95
+                    'inline-flex items-center gap-1 rounded-full px-2 font-semibold tabular-nums',
96
+                    light
97
+                        ? up
98
+                            ? 'bg-white/16 text-white'
99
+                            : 'bg-[#E3573F] text-white'
100
+                        : up
101
+                          ? 'text-(--ov-pandan-ink)'
102
+                          : 'text-(--ov-bunga-ink)',
103
+                )}
104
+            >
105
+                <Icon className="size-3.5" aria-hidden="true" />
106
+                {up ? '+' : ''}
107
+                {value}
108
+                {suffix}
109
+            </span>
110
+        </span>
111
+    );
112
+}
113
+
114
+function Card({
115
+    label,
116
+    icon,
117
+    value,
118
+    footer,
119
+    className,
120
+    delay,
121
+    children,
122
+}: {
123
+    label: string;
124
+    icon: ReactNode;
125
+    value: string;
126
+    footer: ReactNode;
127
+    className?: string;
128
+    delay: number;
129
+    children?: ReactNode;
130
+}) {
131
+    return (
132
+        <div
133
+            className={cn(
134
+                'ov-rise ov-lift flex min-w-0 flex-col rounded-[18px] border border-(--ov-line) bg-(--ov-card) px-5 pt-4 pb-3.5',
135
+                className,
136
+            )}
137
+            style={{ animationDelay: `${delay}ms` }}
138
+        >
139
+            <div className="flex items-center gap-2 text-sm font-medium opacity-80 [&_svg]:size-4">
140
+                {icon}
141
+                {label}
142
+            </div>
143
+            <div className="ov-heading mt-1.5 text-[clamp(1.5rem,2.4vw,2rem)] leading-tight font-extrabold whitespace-nowrap tabular-nums">
144
+                {value}
145
+            </div>
146
+            <div className="mt-0.5 text-sm">{footer}</div>
147
+            {children}
148
+        </div>
149
+    );
150
+}
151
+
152
+/** The four big numbers: sales, paid orders, average order, and orders to ship now. */
153
+export default function KpiCards({ stats }: { stats: OverviewStats }) {
154
+    const sales = useCountUp(stats.sales);
155
+    const orders = useCountUp(stats.orders);
156
+    const average = useCountUp(stats.average);
157
+    const toShip = useCountUp(stats.to_ship.count);
158
+    const ordersChange = stats.orders - stats.previous_orders;
159
+    const shipStore = stats.attention.find((item) => item.kind === 'ship')
160
+        ?.store?.slug;
161
+
162
+    return (
163
+        <section
164
+            aria-label="Key numbers"
165
+            className="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4"
166
+        >
167
+            <Card
168
+                label="Total sales"
169
+                icon={<TrendingUp aria-hidden="true" />}
170
+                value={ringgit(Math.round(sales))}
171
+                className="border-(--ov-hero) bg-(--ov-hero) text-white"
172
+                delay={160}
173
+                footer={
174
+                    <span className="flex flex-wrap items-center gap-1.5 text-white/80">
175
+                        <Change value={stats.sales_change} suffix="%" light />
176
+                        {stats.sales_change !== null && stats.compare_label}
177
+                    </span>
178
+                }
179
+            >
180
+                <Sparkline
181
+                    values={stats.series.map((point) => point.sales)}
182
+                    light
183
+                />
184
+            </Card>
185
+
186
+            <Card
187
+                label="Paid orders"
188
+                icon={<ReceiptText aria-hidden="true" />}
189
+                value={String(Math.round(orders))}
190
+                delay={220}
191
+                footer={
192
+                    <span className="flex flex-wrap items-center gap-1.5 text-(--ov-muted)">
193
+                        <Change
194
+                            value={
195
+                                stats.previous_orders > 0 || stats.orders > 0
196
+                                    ? ordersChange
197
+                                    : null
198
+                            }
199
+                            suffix=""
200
+                        />
201
+                        {ordersChange < 0
202
+                            ? 'fewer than before'
203
+                            : 'more than before'}
204
+                    </span>
205
+                }
206
+            >
207
+                <Sparkline values={stats.series.map((point) => point.orders)} />
208
+            </Card>
209
+
210
+            <Card
211
+                label="Average order"
212
+                icon={<ShoppingBag aria-hidden="true" />}
213
+                value={ringgit(Math.round(average * 100) / 100, true)}
214
+                delay={280}
215
+                footer={
216
+                    <span className="text-(--ov-muted)">
217
+                        {stats.previous_average > 0
218
+                            ? `${ringgit(stats.previous_average, true)} before`
219
+                            : 'per paid order'}
220
+                    </span>
221
+                }
222
+            />
223
+
224
+            <Card
225
+                label="To ship now"
226
+                icon={<Truck aria-hidden="true" />}
227
+                value={String(Math.round(toShip))}
228
+                className={
229
+                    stats.to_ship.count > 0
230
+                        ? 'border-transparent bg-(--ov-kunyit-soft) text-(--ov-ink)'
231
+                        : undefined
232
+                }
233
+                delay={340}
234
+                footer={
235
+                    <span
236
+                        className={
237
+                            stats.to_ship.count > 0
238
+                                ? 'text-(--ov-kunyit-ink)'
239
+                                : 'text-(--ov-muted)'
240
+                        }
241
+                    >
242
+                        {stats.to_ship.count === 0
243
+                            ? 'All orders are sent'
244
+                            : stats.to_ship.oldest_days
245
+                              ? `Oldest waited ${stats.to_ship.oldest_days} ${stats.to_ship.oldest_days === 1 ? 'day' : 'days'}`
246
+                              : 'Paid today'}
247
+                    </span>
248
+                }
249
+            >
250
+                {stats.to_ship.count > 0 && (
251
+                    <Link
252
+                        href={actionHref('ship', shipStore)}
253
+                        className="mt-auto pt-3 text-sm font-semibold text-(--ov-kunyit-ink) hover:underline"
254
+                    >
255
+                        Ship orders →
256
+                    </Link>
257
+                )}
258
+            </Card>
259
+        </section>
260
+    );
261
+}

+ 199
- 0
resources/js/components/overview/pulse-card.tsx Zobrazit soubor

@@ -0,0 +1,199 @@
1
+import { Link, router } from '@inertiajs/react';
2
+import { Package, RefreshCw, Sparkles, Truck, UploadCloud } from 'lucide-react';
3
+import { useEffect, useState } from 'react';
4
+import DashboardController from '@/actions/App/Http/Controllers/DashboardController';
5
+import { actionHref, prefersReducedMotion } from '@/components/overview/format';
6
+import { cn } from '@/lib/utils';
7
+import type { StorePulse } from '@/types';
8
+
9
+const icons = { ship: Truck, restock: Package, publish: UploadCloud };
10
+
11
+/** The note types itself out once, the first time it appears. */
12
+function useTyped(text: string): string {
13
+    const [shown, setShown] = useState(() =>
14
+        prefersReducedMotion() ? text : '',
15
+    );
16
+
17
+    useEffect(() => {
18
+        if (prefersReducedMotion()) {
19
+            setShown(text);
20
+
21
+            return;
22
+        }
23
+
24
+        let count = 0;
25
+        setShown('');
26
+        const timer = window.setInterval(() => {
27
+            count = Math.min(text.length, count + 2);
28
+            setShown(text.slice(0, count));
29
+
30
+            if (count >= text.length) {
31
+                window.clearInterval(timer);
32
+            }
33
+        }, 16);
34
+
35
+        return () => window.clearInterval(timer);
36
+    }, [text]);
37
+
38
+    return shown;
39
+}
40
+
41
+function Orb() {
42
+    return (
43
+        <div
44
+            className="relative grid size-11 shrink-0 place-items-center rounded-full bg-[#F2B33D]/15 text-[#F2B33D]"
45
+            aria-hidden="true"
46
+        >
47
+            <Sparkles className="size-5" />
48
+            <span className="ov-spin absolute -inset-1 rounded-full border-[2.5px] border-[#F2B33D] border-r-transparent border-b-transparent" />
49
+        </div>
50
+    );
51
+}
52
+
53
+/**
54
+ * The "Store pulse" card: a short AI note on how the stores are doing, with buttons for what to do first.
55
+ * The note is saved for the day, so refreshing the page does not ask the AI again.
56
+ */
57
+export default function PulseCard({
58
+    pulse,
59
+    store,
60
+}: {
61
+    pulse: StorePulse;
62
+    store: string | null;
63
+}) {
64
+    const typed = useTyped(pulse.summary);
65
+    const [writing, setWriting] = useState(false);
66
+    const done = typed.length >= pulse.summary.length;
67
+    const time = pulse.written_at
68
+        ? new Date(pulse.written_at).toLocaleTimeString('en-MY', {
69
+              hour: 'numeric',
70
+              minute: '2-digit',
71
+          })
72
+        : null;
73
+
74
+    const writeAgain = () => {
75
+        router.post(
76
+            DashboardController.rewritePulse.url(),
77
+            { store },
78
+            {
79
+                preserveScroll: true,
80
+                onStart: () => setWriting(true),
81
+                onFinish: () => setWriting(false),
82
+            },
83
+        );
84
+    };
85
+
86
+    return (
87
+        <section
88
+            aria-label="Store pulse"
89
+            className="ov-rise grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 rounded-[20px] bg-(--ov-pulse) p-5 text-[#E7F0EA] sm:p-6"
90
+            style={{ animationDelay: '80ms' }}
91
+        >
92
+            <div className="row-span-3 max-sm:col-span-2 max-sm:row-span-1">
93
+                <Orb />
94
+            </div>
95
+
96
+            <div className="flex flex-wrap items-start gap-x-4 gap-y-1 max-sm:col-span-2">
97
+                <div className="min-w-0">
98
+                    <h2 className="ov-heading text-lg font-bold">
99
+                        Store pulse
100
+                    </h2>
101
+                    <p className="text-xs text-[#E7F0EA]/65">
102
+                        {pulse.source === 'ai'
103
+                            ? `Written by AI${time ? ` today at ${time}` : ''}`
104
+                            : 'Written from your numbers. The AI was not available.'}
105
+                    </p>
106
+                </div>
107
+
108
+                <div className="ml-auto text-right">
109
+                    {pulse.rewrites_left > 0 ? (
110
+                        <button
111
+                            type="button"
112
+                            onClick={writeAgain}
113
+                            disabled={writing}
114
+                            className="inline-flex items-center gap-1.5 rounded-full px-2 py-1 text-sm font-medium text-[#E7F0EA]/85 hover:bg-white/10 hover:text-white disabled:opacity-60"
115
+                        >
116
+                            <RefreshCw
117
+                                className={cn(
118
+                                    'size-4',
119
+                                    writing && 'animate-spin',
120
+                                )}
121
+                                aria-hidden="true"
122
+                            />
123
+                            {writing ? 'Writing…' : 'Write again'}
124
+                        </button>
125
+                    ) : (
126
+                        <span className="inline-flex items-center gap-1.5 px-2 py-1 text-sm text-[#E7F0EA]/55">
127
+                            <RefreshCw className="size-4" aria-hidden="true" />
128
+                            Write again
129
+                        </span>
130
+                    )}
131
+                    <p
132
+                        className="px-2 text-xs text-[#E7F0EA]/60 tabular-nums"
133
+                        data-test="pulse-rewrites-left"
134
+                    >
135
+                        {pulse.rewrites_left > 0
136
+                            ? `${pulse.rewrites_left} of ${pulse.rewrites_limit} left today`
137
+                            : 'None left today. New note tomorrow.'}
138
+                    </p>
139
+                </div>
140
+            </div>
141
+
142
+            <p
143
+                className="min-h-[3.2em] max-w-[70ch] text-base leading-relaxed max-sm:col-span-2"
144
+                aria-live="polite"
145
+            >
146
+                {typed}
147
+                {!done && (
148
+                    <span
149
+                        className="ov-caret ml-0.5 inline-block h-[1.05em] w-0.5 translate-y-0.5 bg-[#F2B33D]"
150
+                        aria-hidden="true"
151
+                    />
152
+                )}
153
+            </p>
154
+
155
+            {pulse.actions.length > 0 && (
156
+                <div className="flex flex-wrap gap-2 max-sm:col-span-2">
157
+                    {pulse.actions.map((action) => {
158
+                        const Icon = icons[action.kind];
159
+
160
+                        return (
161
+                            <Link
162
+                                key={action.label}
163
+                                href={actionHref(
164
+                                    action.kind,
165
+                                    action.store_slug,
166
+                                    action.product_id,
167
+                                )}
168
+                                className="inline-flex items-center gap-1.5 rounded-full bg-white/12 px-3.5 py-2 text-sm font-semibold transition hover:-translate-y-px hover:bg-[#F2B33D] hover:text-[#3D2A05]"
169
+                            >
170
+                                <Icon className="size-4" aria-hidden="true" />
171
+                                {action.label}
172
+                            </Link>
173
+                        );
174
+                    })}
175
+                </div>
176
+            )}
177
+        </section>
178
+    );
179
+}
180
+
181
+/** Shown for a moment while today's note loads (or is written for the first time). */
182
+export function PulseLoading() {
183
+    return (
184
+        <section
185
+            aria-label="Store pulse"
186
+            className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-3 rounded-[20px] bg-(--ov-pulse) p-5 text-[#E7F0EA] sm:p-6"
187
+        >
188
+            <Orb />
189
+            <div className="grid gap-2.5">
190
+                <p className="ov-heading text-lg font-bold">Store pulse</p>
191
+                <p className="text-sm text-[#E7F0EA]/70">
192
+                    Writing today’s note…
193
+                </p>
194
+                <div className="h-3 w-4/5 animate-pulse rounded-full bg-white/10" />
195
+                <div className="h-3 w-3/5 animate-pulse rounded-full bg-white/10" />
196
+            </div>
197
+        </section>
198
+    );
199
+}

+ 260
- 0
resources/js/components/overview/sales-chart.tsx Zobrazit soubor

@@ -0,0 +1,260 @@
1
+import type { PointerEvent } from 'react';
2
+import { useEffect, useId, useRef, useState } from 'react';
3
+import {
4
+    prefersReducedMotion,
5
+    ringgit,
6
+    shortRinggit,
7
+} from '@/components/overview/format';
8
+import type { OverviewStats } from '@/types';
9
+
10
+const LEFT = 56;
11
+const RIGHT = 12;
12
+const TOP = 14;
13
+const BOTTOM = 30;
14
+
15
+/** A round step for the side labels, so they read RM 0, 200, 400… */
16
+function niceStep(max: number): number {
17
+    const raw = Math.max(max, 1) / 4;
18
+    const power = 10 ** Math.floor(Math.log10(raw));
19
+
20
+    return (
21
+        [1, 2, 2.5, 5, 10].map((f) => f * power).find((s) => s >= raw) ?? raw
22
+    );
23
+}
24
+
25
+/**
26
+ * Sales over the chosen range, with the period before as a dashed line. Drawn at the real pixel
27
+ * width of its box, so the labels stay readable on a phone. Point at it to see each day.
28
+ */
29
+export default function SalesChart({ stats }: { stats: OverviewStats }) {
30
+    const box = useRef<HTMLDivElement>(null);
31
+    const line = useRef<SVGPathElement>(null);
32
+    const gradient = useId();
33
+    const [width, setWidth] = useState(640);
34
+    const [hover, setHover] = useState<number | null>(null);
35
+
36
+    useEffect(() => {
37
+        const element = box.current;
38
+
39
+        if (!element) {
40
+            return;
41
+        }
42
+
43
+        const observer = new ResizeObserver(([entry]) =>
44
+            setWidth(Math.max(280, Math.round(entry.contentRect.width))),
45
+        );
46
+        observer.observe(element);
47
+
48
+        return () => observer.disconnect();
49
+    }, []);
50
+
51
+    const points = stats.series;
52
+    const count = points.length;
53
+    const height = width < 500 ? 210 : 260;
54
+
55
+    // The line draws itself when the data changes.
56
+    useEffect(() => {
57
+        const path = line.current;
58
+
59
+        if (!path || prefersReducedMotion()) {
60
+            return;
61
+        }
62
+
63
+        const length = path.getTotalLength();
64
+        path.style.transition = 'none';
65
+        path.style.strokeDasharray = `${length}`;
66
+        path.style.strokeDashoffset = `${length}`;
67
+        path.getBoundingClientRect();
68
+        path.style.transition =
69
+            'stroke-dashoffset 1.1s cubic-bezier(.2,.8,.2,1)';
70
+        path.style.strokeDashoffset = '0';
71
+    }, [stats.range, stats.sales, count]);
72
+
73
+    const top = Math.max(
74
+        ...points.map((p) => Math.max(p.sales, p.previous)),
75
+        0,
76
+    );
77
+    const step = niceStep(top);
78
+    const yMax = step * 4;
79
+    const x = (i: number) =>
80
+        LEFT + (count <= 1 ? 0 : (i / (count - 1)) * (width - LEFT - RIGHT));
81
+    const y = (value: number) =>
82
+        TOP + (1 - value / yMax) * (height - TOP - BOTTOM);
83
+    const path = (key: 'sales' | 'previous') =>
84
+        points
85
+            .map(
86
+                (p, i) =>
87
+                    `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[key]).toFixed(1)}`,
88
+            )
89
+            .join('');
90
+
91
+    // Side labels must not crowd: keep about 72px between bottom labels.
92
+    const pxPer = (width - LEFT - RIGHT) / Math.max(1, count - 1);
93
+    const every = Math.max(1, Math.ceil(72 / pxPer));
94
+    const last = count - 1;
95
+
96
+    const onMove = (event: PointerEvent<SVGRectElement>) => {
97
+        const rect =
98
+            event.currentTarget.ownerSVGElement!.getBoundingClientRect();
99
+        const sx = ((event.clientX - rect.left) / rect.width) * width;
100
+        setHover(
101
+            Math.max(
102
+                0,
103
+                Math.min(
104
+                    last,
105
+                    Math.round(((sx - LEFT) / (width - LEFT - RIGHT)) * last),
106
+                ),
107
+            ),
108
+        );
109
+    };
110
+
111
+    const hovered = hover !== null ? points[hover] : null;
112
+
113
+    return (
114
+        <div ref={box} className="relative">
115
+            <svg
116
+                viewBox={`0 0 ${width} ${height}`}
117
+                className="block h-auto w-full overflow-visible"
118
+                role="img"
119
+                aria-label={`Sales ${stats.label.toLowerCase()}: ${ringgit(stats.sales)} in total`}
120
+            >
121
+                <defs>
122
+                    <linearGradient id={gradient} x1="0" x2="0" y1="0" y2="1">
123
+                        <stop
124
+                            offset="0"
125
+                            stopColor="var(--ov-pandan)"
126
+                            stopOpacity="0.22"
127
+                        />
128
+                        <stop
129
+                            offset="1"
130
+                            stopColor="var(--ov-pandan)"
131
+                            stopOpacity="0"
132
+                        />
133
+                    </linearGradient>
134
+                </defs>
135
+
136
+                {[0, 1, 2, 3, 4].map((k) => (
137
+                    <g key={k}>
138
+                        <line
139
+                            x1={LEFT}
140
+                            x2={width - RIGHT}
141
+                            y1={y(step * k)}
142
+                            y2={y(step * k)}
143
+                            stroke="var(--ov-line)"
144
+                        />
145
+                        <text
146
+                            x={LEFT - 8}
147
+                            y={y(step * k) + 4}
148
+                            textAnchor="end"
149
+                            className="fill-(--ov-muted) text-[11px] tabular-nums"
150
+                        >
151
+                            {shortRinggit(step * k)}
152
+                        </text>
153
+                    </g>
154
+                ))}
155
+
156
+                {points.map((p, i) =>
157
+                    (i % every === 0 && (last - i) * pxPer >= 72) ||
158
+                    i === last ? (
159
+                        <text
160
+                            key={i}
161
+                            x={x(i)}
162
+                            y={height - 8}
163
+                            textAnchor={
164
+                                i === 0
165
+                                    ? 'start'
166
+                                    : i === last
167
+                                      ? 'end'
168
+                                      : 'middle'
169
+                            }
170
+                            className="fill-(--ov-muted) text-[11px]"
171
+                        >
172
+                            {p.label}
173
+                        </text>
174
+                    ) : null,
175
+                )}
176
+
177
+                <path
178
+                    d={path('previous')}
179
+                    fill="none"
180
+                    stroke="var(--ov-prev)"
181
+                    strokeWidth="2"
182
+                    strokeDasharray="5 5"
183
+                />
184
+                <path
185
+                    d={`${path('sales')}L${x(last).toFixed(1)},${y(0)}L${x(0)},${y(0)}Z`}
186
+                    fill={`url(#${gradient})`}
187
+                />
188
+                <path
189
+                    ref={line}
190
+                    d={path('sales')}
191
+                    fill="none"
192
+                    stroke="var(--ov-pandan)"
193
+                    strokeWidth="3"
194
+                    strokeLinejoin="round"
195
+                    strokeLinecap="round"
196
+                />
197
+                <circle
198
+                    cx={x(last)}
199
+                    cy={y(points[last]?.sales ?? 0)}
200
+                    r="5"
201
+                    fill="var(--ov-pandan)"
202
+                    stroke="var(--ov-card)"
203
+                    strokeWidth="2.5"
204
+                />
205
+
206
+                {hovered && hover !== null && (
207
+                    <>
208
+                        <line
209
+                            x1={x(hover)}
210
+                            x2={x(hover)}
211
+                            y1={TOP}
212
+                            y2={height - BOTTOM}
213
+                            stroke="var(--ov-muted)"
214
+                            strokeOpacity="0.5"
215
+                        />
216
+                        <circle
217
+                            cx={x(hover)}
218
+                            cy={y(hovered.sales)}
219
+                            r="4.5"
220
+                            fill="var(--ov-pandan)"
221
+                            stroke="var(--ov-card)"
222
+                            strokeWidth="2"
223
+                        />
224
+                    </>
225
+                )}
226
+
227
+                <rect
228
+                    x={LEFT}
229
+                    y={TOP}
230
+                    width={width - LEFT - RIGHT}
231
+                    height={height - TOP - BOTTOM}
232
+                    fill="transparent"
233
+                    onPointerMove={onMove}
234
+                    onPointerLeave={() => setHover(null)}
235
+                />
236
+            </svg>
237
+
238
+            {hovered && hover !== null && (
239
+                <div
240
+                    className="pointer-events-none absolute rounded-lg bg-(--ov-ink) px-2.5 py-2 text-xs whitespace-nowrap text-(--ov-paper)"
241
+                    style={{
242
+                        left: Math.max(70, Math.min(width - 70, x(hover))),
243
+                        top: y(hovered.sales) - 8,
244
+                        transform: 'translate(-50%, -100%)',
245
+                    }}
246
+                >
247
+                    {hovered.label}
248
+                    <br />
249
+                    <b className="text-sm tabular-nums">
250
+                        {ringgit(hovered.sales, hovered.sales % 1 !== 0)}
251
+                    </b>{' '}
252
+                    <span className="opacity-70">
253
+                        before:{' '}
254
+                        {ringgit(hovered.previous, hovered.previous % 1 !== 0)}
255
+                    </span>
256
+                </div>
257
+            )}
258
+        </div>
259
+    );
260
+}

+ 544
- 0
resources/js/components/overview/sections.tsx Zobrazit soubor

@@ -0,0 +1,544 @@
1
+import { Link } from '@inertiajs/react';
2
+import {
3
+    AlertTriangle,
4
+    CheckCircle2,
5
+    Circle,
6
+    CreditCard,
7
+    PackageX,
8
+    Store as StoreIcon,
9
+    Truck,
10
+    UploadCloud,
11
+} from 'lucide-react';
12
+import type { ReactNode } from 'react';
13
+import { useEffect, useState } from 'react';
14
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
15
+import ProductController from '@/actions/App/Http/Controllers/ProductController';
16
+import StoreController from '@/actions/App/Http/Controllers/StoreController';
17
+import { actionHref, ringgit, when } from '@/components/overview/format';
18
+import { cn } from '@/lib/utils';
19
+import { create } from '@/routes/stores';
20
+import type { AttentionItem, GettingStarted, OverviewStats } from '@/types';
21
+
22
+/** A white box with a heading, used by every section below the big numbers. */
23
+export function Panel({
24
+    title,
25
+    aside,
26
+    delay,
27
+    className,
28
+    children,
29
+}: {
30
+    title: string;
31
+    aside?: ReactNode;
32
+    delay: number;
33
+    className?: string;
34
+    children: ReactNode;
35
+}) {
36
+    return (
37
+        <section
38
+            aria-label={title}
39
+            className={cn(
40
+                'ov-rise min-w-0 rounded-[18px] border border-(--ov-line) bg-(--ov-card) p-5 sm:p-6',
41
+                className,
42
+            )}
43
+            style={{ animationDelay: `${delay}ms` }}
44
+        >
45
+            <div className="mb-4 flex items-baseline justify-between gap-3">
46
+                <h2 className="ov-heading text-[17px] font-bold">{title}</h2>
47
+                {aside && (
48
+                    <div className="text-sm whitespace-nowrap text-(--ov-muted)">
49
+                        {aside}
50
+                    </div>
51
+                )}
52
+            </div>
53
+            {children}
54
+        </section>
55
+    );
56
+}
57
+
58
+const tones = {
59
+    warning: 'bg-(--ov-kunyit-soft) text-(--ov-kunyit-ink)',
60
+    danger: 'bg-(--ov-bunga-soft) text-(--ov-bunga-ink)',
61
+    brand: 'bg-(--ov-pandan-soft) text-(--ov-pandan-ink)',
62
+};
63
+
64
+const attentionIcon = (item: AttentionItem) =>
65
+    ({
66
+        ship: Truck,
67
+        restock: item.title.includes('out of stock') ? PackageX : AlertTriangle,
68
+        publish: UploadCloud,
69
+        plan: CreditCard,
70
+    })[item.kind];
71
+
72
+const attentionButton = {
73
+    ship: 'Ship',
74
+    restock: 'Restock',
75
+    publish: 'Open',
76
+    plan: 'Choose plan',
77
+};
78
+
79
+/** Everything that needs the merchant now, in one list, each with its own button. */
80
+export function AttentionList({
81
+    items,
82
+    showStore,
83
+}: {
84
+    items: AttentionItem[];
85
+    showStore: boolean;
86
+}) {
87
+    if (items.length === 0) {
88
+        return (
89
+            <div className="grid justify-items-center gap-2 rounded-2xl bg-(--ov-paper) px-4 py-10 text-center">
90
+                <CheckCircle2
91
+                    className="size-8 text-(--ov-pandan)"
92
+                    aria-hidden="true"
93
+                />
94
+                <p className="font-semibold">All clear</p>
95
+                <p className="text-sm text-(--ov-muted)">
96
+                    No orders waiting and nothing running low.
97
+                </p>
98
+            </div>
99
+        );
100
+    }
101
+
102
+    return (
103
+        <ul className="grid gap-2.5">
104
+            {items.map((item, index) => {
105
+                const Icon = attentionIcon(item);
106
+
107
+                return (
108
+                    <li
109
+                        key={index}
110
+                        className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 rounded-2xl bg-(--ov-paper) p-3"
111
+                    >
112
+                        <span
113
+                            className={cn(
114
+                                'grid size-9 place-items-center rounded-[10px]',
115
+                                tones[item.tone],
116
+                            )}
117
+                        >
118
+                            <Icon className="size-[18px]" aria-hidden="true" />
119
+                        </span>
120
+                        <div className="min-w-0">
121
+                            <p className="text-sm leading-snug font-semibold">
122
+                                {item.title}
123
+                            </p>
124
+                            <p className="text-xs text-(--ov-muted)">
125
+                                {showStore &&
126
+                                item.store &&
127
+                                item.kind !== 'publish'
128
+                                    ? `${item.store.name} · `
129
+                                    : ''}
130
+                                {item.note}
131
+                            </p>
132
+                        </div>
133
+                        <Link
134
+                            href={actionHref(
135
+                                item.kind,
136
+                                item.store?.slug,
137
+                                item.product_id,
138
+                            )}
139
+                            className="rounded-full border border-(--ov-line) bg-(--ov-card) px-3 py-1.5 text-xs font-semibold whitespace-nowrap transition-colors hover:border-(--ov-pandan) hover:text-(--ov-pandan-ink)"
140
+                        >
141
+                            {attentionButton[item.kind]}
142
+                        </Link>
143
+                    </li>
144
+                );
145
+            })}
146
+        </ul>
147
+    );
148
+}
149
+
150
+/** Bars that grow from zero after the page shows. */
151
+function useGrow(): boolean {
152
+    const [grown, setGrown] = useState(false);
153
+
154
+    useEffect(() => {
155
+        const frame = requestAnimationFrame(() =>
156
+            requestAnimationFrame(() => setGrown(true)),
157
+        );
158
+
159
+        return () => cancelAnimationFrame(frame);
160
+    }, []);
161
+
162
+    return grown;
163
+}
164
+
165
+const storeColours = [
166
+    'var(--ov-pandan)',
167
+    'var(--ov-kunyit)',
168
+    'var(--ov-bunga)',
169
+    '#4C8C9E',
170
+    '#8A6FB8',
171
+];
172
+
173
+/** Each store's share of sales in the range. Stores not published yet sit at the bottom, faded. */
174
+export function StoreSales({ stats }: { stats: OverviewStats }) {
175
+    const grown = useGrow();
176
+    const max = Math.max(...stats.by_store.map((store) => store.sales), 0);
177
+    const anySelected = stats.by_store.some((store) => store.selected);
178
+    // The best seller gets green, the next yellow, then red, whatever order the stores are in.
179
+    const rank = [...stats.by_store]
180
+        .sort((a, b) => b.sales - a.sales)
181
+        .map((store) => store.slug);
182
+
183
+    return (
184
+        <div className="grid gap-3.5">
185
+            {stats.by_store.map((store) => (
186
+                <Link
187
+                    key={store.slug}
188
+                    href={StoreController.show.url(store.slug)}
189
+                    className={cn(
190
+                        'grid gap-1.5 rounded-lg transition-opacity hover:opacity-100',
191
+                        (!store.is_published && store.sales === 0) ||
192
+                            (anySelected && !store.selected)
193
+                            ? 'opacity-55'
194
+                            : '',
195
+                    )}
196
+                >
197
+                    <div className="flex justify-between gap-3 text-sm">
198
+                        <span
199
+                            className={cn(
200
+                                'truncate',
201
+                                store.selected && 'font-semibold',
202
+                            )}
203
+                        >
204
+                            {store.name}
205
+                        </span>
206
+                        <span className="shrink-0 text-(--ov-muted) tabular-nums">
207
+                            {!store.is_published && store.sales === 0
208
+                                ? 'Not published yet'
209
+                                : `${ringgit(store.sales)} · ${store.share}%`}
210
+                        </span>
211
+                    </div>
212
+                    <div className="h-2.5 overflow-hidden rounded-full bg-(--ov-hover)">
213
+                        <div
214
+                            className="h-full rounded-full transition-[width] duration-1000 ease-out"
215
+                            style={{
216
+                                width:
217
+                                    grown && max > 0
218
+                                        ? `${(store.sales / max) * 100}%`
219
+                                        : '0%',
220
+                                background:
221
+                                    storeColours[
222
+                                        rank.indexOf(store.slug) %
223
+                                            storeColours.length
224
+                                    ],
225
+                            }}
226
+                        />
227
+                    </div>
228
+                </Link>
229
+            ))}
230
+        </div>
231
+    );
232
+}
233
+
234
+const thumbTones = [
235
+    'bg-(--ov-pandan-soft) text-(--ov-pandan-ink)',
236
+    'bg-(--ov-kunyit-soft) text-(--ov-kunyit-ink)',
237
+    'bg-(--ov-bunga-soft) text-(--ov-bunga-ink)',
238
+];
239
+
240
+/** The best sellers in the range. */
241
+export function TopProducts({
242
+    stats,
243
+    showStore,
244
+}: {
245
+    stats: OverviewStats;
246
+    showStore: boolean;
247
+}) {
248
+    if (stats.top_products.length === 0) {
249
+        return (
250
+            <p className="text-sm text-(--ov-muted)">
251
+                No sales in this time yet.
252
+            </p>
253
+        );
254
+    }
255
+
256
+    return (
257
+        <ul className="grid gap-3">
258
+            {stats.top_products.map((product, index) => {
259
+                const inner = (
260
+                    <>
261
+                        <span
262
+                            className={cn(
263
+                                'ov-heading grid size-10 place-items-center rounded-[10px] text-[15px] font-extrabold',
264
+                                thumbTones[index % thumbTones.length],
265
+                            )}
266
+                            aria-hidden="true"
267
+                        >
268
+                            {product.name.charAt(0).toUpperCase()}
269
+                        </span>
270
+                        <span className="min-w-0">
271
+                            <span className="block truncate text-sm font-medium">
272
+                                {product.name}
273
+                            </span>
274
+                            <span className="block text-xs text-(--ov-muted) tabular-nums">
275
+                                {product.units} sold
276
+                                {showStore && product.store.name
277
+                                    ? ` · ${product.store.name}`
278
+                                    : ''}
279
+                            </span>
280
+                        </span>
281
+                        <span className="text-right text-sm font-semibold tabular-nums">
282
+                            {ringgit(product.revenue)}
283
+                        </span>
284
+                    </>
285
+                );
286
+
287
+                return (
288
+                    <li
289
+                        key={`${product.store.slug}-${product.product_id ?? product.name}`}
290
+                    >
291
+                        {product.product_id && product.store.slug ? (
292
+                            <Link
293
+                                href={ProductController.edit.url({
294
+                                    slug: product.store.slug,
295
+                                    product: product.product_id,
296
+                                })}
297
+                                className="grid grid-cols-[40px_minmax(0,1fr)_auto] items-center gap-3 rounded-lg hover:bg-(--ov-paper)"
298
+                            >
299
+                                {inner}
300
+                            </Link>
301
+                        ) : (
302
+                            <div className="grid grid-cols-[40px_minmax(0,1fr)_auto] items-center gap-3">
303
+                                {inner}
304
+                            </div>
305
+                        )}
306
+                    </li>
307
+                );
308
+            })}
309
+        </ul>
310
+    );
311
+}
312
+
313
+/** The newest paid orders, as a table that scrolls sideways on a phone. */
314
+export function RecentOrders({
315
+    stats,
316
+    showStore,
317
+}: {
318
+    stats: OverviewStats;
319
+    showStore: boolean;
320
+}) {
321
+    if (stats.recent_orders.length === 0) {
322
+        return <p className="text-sm text-(--ov-muted)">No paid orders yet.</p>;
323
+    }
324
+
325
+    return (
326
+        <div className="-mx-5 overflow-x-auto px-5 sm:-mx-6 sm:px-6">
327
+            <table className="w-full min-w-[600px] border-collapse text-sm">
328
+                <thead>
329
+                    <tr className="text-left text-xs text-(--ov-muted)">
330
+                        <th className="pr-3 pb-2.5 font-medium">Order</th>
331
+                        <th className="pr-3 pb-2.5 font-medium">Customer</th>
332
+                        {showStore && (
333
+                            <th className="pr-3 pb-2.5 font-medium">Store</th>
334
+                        )}
335
+                        <th className="pr-3 pb-2.5 font-medium">Delivers to</th>
336
+                        <th className="pr-3 pb-2.5 text-right font-medium">
337
+                            Total
338
+                        </th>
339
+                        <th className="pr-3 pb-2.5 font-medium">Status</th>
340
+                        <th className="pb-2.5 font-medium">Paid</th>
341
+                    </tr>
342
+                </thead>
343
+                <tbody>
344
+                    {stats.recent_orders.map((order) => (
345
+                        <tr
346
+                            key={order.id}
347
+                            className="border-t border-(--ov-line) transition-colors hover:bg-(--ov-paper)"
348
+                        >
349
+                            <td className="py-3 pr-3 text-(--ov-muted) tabular-nums">
350
+                                <Link
351
+                                    href={OrderController.show.url({
352
+                                        slug: order.store.slug,
353
+                                        order: order.id,
354
+                                    })}
355
+                                    className="hover:text-(--ov-ink) hover:underline"
356
+                                >
357
+                                    #{order.number}
358
+                                </Link>
359
+                            </td>
360
+                            <td className="py-3 pr-3 whitespace-nowrap">
361
+                                {order.customer_name}
362
+                            </td>
363
+                            {showStore && (
364
+                                <td className="py-3 pr-3 whitespace-nowrap">
365
+                                    {order.store.name}
366
+                                </td>
367
+                            )}
368
+                            <td className="py-3 pr-3 whitespace-nowrap">
369
+                                {order.state ?? '—'}
370
+                            </td>
371
+                            <td className="py-3 pr-3 text-right whitespace-nowrap tabular-nums">
372
+                                {ringgit(order.total, true)}
373
+                            </td>
374
+                            <td className="py-3 pr-3">
375
+                                <span
376
+                                    className={cn(
377
+                                        'inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold whitespace-nowrap',
378
+                                        order.shipped
379
+                                            ? 'bg-(--ov-pandan-soft) text-(--ov-pandan-ink)'
380
+                                            : 'bg-[#F2B33D] text-[#3D2A05]',
381
+                                    )}
382
+                                >
383
+                                    {order.shipped ? 'Shipped' : 'To ship'}
384
+                                </span>
385
+                            </td>
386
+                            <td className="py-3 whitespace-nowrap text-(--ov-muted)">
387
+                                {when(order.paid_at)}
388
+                            </td>
389
+                        </tr>
390
+                    ))}
391
+                </tbody>
392
+            </table>
393
+        </div>
394
+    );
395
+}
396
+
397
+/** Until the first sale: the four steps to get there, each with a button. */
398
+export function GettingStartedCard({ data }: { data: GettingStarted }) {
399
+    const slug = data.store?.slug;
400
+    const steps = [
401
+        {
402
+            key: 'create',
403
+            title: 'Create your store',
404
+            note: 'Tell us about your brand.',
405
+            done: data.steps.create,
406
+            action: { label: 'Create store', href: create.url() },
407
+        },
408
+        {
409
+            key: 'design',
410
+            title: 'Let AI design it',
411
+            note: data.store
412
+                ? `A full design for ${data.store.name}.`
413
+                : 'A full design in about a minute.',
414
+            done: data.steps.design,
415
+            action: slug
416
+                ? {
417
+                      label: 'Design store',
418
+                      href: StoreController.show.url(slug),
419
+                  }
420
+                : null,
421
+        },
422
+        {
423
+            key: 'products',
424
+            title: 'Add your products',
425
+            note: 'Name, price, photo and stock.',
426
+            done: data.steps.products,
427
+            action: slug
428
+                ? {
429
+                      label: 'Add products',
430
+                      href: ProductController.create.url(slug),
431
+                  }
432
+                : null,
433
+        },
434
+        {
435
+            key: 'publish',
436
+            title: 'Publish your store',
437
+            note: 'Then share the link on WhatsApp.',
438
+            done: data.steps.publish,
439
+            action: slug
440
+                ? { label: 'Publish', href: StoreController.show.url(slug) }
441
+                : null,
442
+        },
443
+    ];
444
+    const done = steps.filter((step) => step.done).length;
445
+    const grown = useGrow();
446
+    const next = steps.find((step) => !step.done);
447
+
448
+    return (
449
+        <section
450
+            aria-label="Get your first sale"
451
+            className="ov-rise grid gap-5 rounded-[20px] bg-(--ov-pulse) p-6 text-[#E7F0EA]"
452
+            style={{ animationDelay: '80ms' }}
453
+        >
454
+            <div className="grid gap-2.5">
455
+                <h2 className="ov-heading text-2xl font-extrabold">
456
+                    Get your first sale
457
+                </h2>
458
+                <p className="text-sm text-[#E7F0EA]/75 tabular-nums">
459
+                    {done} of {steps.length} steps done
460
+                </p>
461
+                <div className="h-2 max-w-md overflow-hidden rounded-full bg-white/15">
462
+                    <div
463
+                        className="h-full rounded-full bg-[#F2B33D] transition-[width] duration-1000 ease-out"
464
+                        style={{
465
+                            width: grown
466
+                                ? `${(done / steps.length) * 100}%`
467
+                                : '0%',
468
+                        }}
469
+                    />
470
+                </div>
471
+            </div>
472
+            <ol className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
473
+                {steps.map((step) => (
474
+                    <li
475
+                        key={step.key}
476
+                        className={cn(
477
+                            'flex flex-col gap-2 rounded-2xl bg-white/8 p-4',
478
+                            step.done && 'opacity-70',
479
+                        )}
480
+                    >
481
+                        {step.done ? (
482
+                            <CheckCircle2
483
+                                className="size-6 text-[#F2B33D]"
484
+                                aria-hidden="true"
485
+                            />
486
+                        ) : (
487
+                            <Circle
488
+                                className="size-6 text-[#F2B33D]"
489
+                                aria-hidden="true"
490
+                            />
491
+                        )}
492
+                        <b className="text-sm">
493
+                            {step.title}
494
+                            {step.done && (
495
+                                <span className="sr-only"> (done)</span>
496
+                            )}
497
+                        </b>
498
+                        <span className="flex-1 text-xs text-[#E7F0EA]/75">
499
+                            {step.note}
500
+                        </span>
501
+                        {!step.done && step.action && step === next && (
502
+                            <Link
503
+                                href={step.action.href}
504
+                                className="self-start rounded-full bg-[#F2B33D] px-3.5 py-1.5 text-xs font-semibold text-[#3D2A05] hover:bg-[#f5c25f]"
505
+                            >
506
+                                {step.action.label}
507
+                            </Link>
508
+                        )}
509
+                    </li>
510
+                ))}
511
+            </ol>
512
+        </section>
513
+    );
514
+}
515
+
516
+/** Where the sales chart goes before there are any sales. */
517
+export function EmptySales({ storeUrl }: { storeUrl: string | null }) {
518
+    return (
519
+        <div className="grid justify-items-center gap-2 rounded-2xl border-2 border-dashed border-(--ov-line) px-5 py-10 text-center text-(--ov-muted)">
520
+            <StoreIcon
521
+                className="size-8 text-(--ov-pandan)"
522
+                aria-hidden="true"
523
+            />
524
+            <p className="text-base font-semibold text-(--ov-ink)">
525
+                Your sales chart starts with your first order
526
+            </p>
527
+            <p className="text-sm">
528
+                {storeUrl
529
+                    ? 'Share your store link with friends and customers.'
530
+                    : 'Publish your store, then share its link with friends and customers.'}
531
+            </p>
532
+            {storeUrl && (
533
+                <a
534
+                    href={storeUrl}
535
+                    target="_blank"
536
+                    rel="noreferrer"
537
+                    className="mt-1 rounded-lg border border-(--ov-line) bg-(--ov-paper) px-3 py-1.5 text-sm text-(--ov-ink) hover:border-(--ov-pandan)"
538
+                >
539
+                    {storeUrl.replace(/^https?:\/\//, '')}
540
+                </a>
541
+            )}
542
+        </div>
543
+    );
544
+}

+ 41
- 0
resources/js/components/overview/use-count-up.ts Zobrazit soubor

@@ -0,0 +1,41 @@
1
+import { useEffect, useRef, useState } from 'react';
2
+import { prefersReducedMotion } from '@/components/overview/format';
3
+
4
+/** A number that counts up (or down) to its new value, so changes are easy to notice. */
5
+export function useCountUp(target: number, duration = 900): number {
6
+    const [value, setValue] = useState(() =>
7
+        prefersReducedMotion() ? target : 0,
8
+    );
9
+    const from = useRef(value);
10
+
11
+    useEffect(() => {
12
+        if (prefersReducedMotion()) {
13
+            from.current = target;
14
+            setValue(target);
15
+
16
+            return;
17
+        }
18
+
19
+        const start = performance.now();
20
+        const begin = from.current;
21
+        let frame = 0;
22
+
23
+        const step = (now: number) => {
24
+            const progress = Math.min(1, (now - start) / duration);
25
+            const eased = 1 - Math.pow(1 - progress, 3);
26
+            const next = begin + (target - begin) * eased;
27
+            from.current = next;
28
+            setValue(next);
29
+
30
+            if (progress < 1) {
31
+                frame = requestAnimationFrame(step);
32
+            }
33
+        };
34
+
35
+        frame = requestAnimationFrame(step);
36
+
37
+        return () => cancelAnimationFrame(frame);
38
+    }, [target, duration]);
39
+
40
+    return value;
41
+}

+ 1
- 1
resources/js/pages/billing/index.tsx Zobrazit soubor

@@ -333,7 +333,7 @@ export default function BillingIndex({
333 333
 
334 334
 BillingIndex.layout = {
335 335
     breadcrumbs: [
336
-        { title: 'Dashboard', href: dashboard() },
336
+        { title: 'Overview', href: dashboard() },
337 337
         { title: 'Billing', href: '#' },
338 338
     ],
339 339
 };

+ 324
- 92
resources/js/pages/dashboard.tsx Zobrazit soubor

@@ -1,117 +1,349 @@
1
-import { Head, Link } from '@inertiajs/react';
2
-import { Plus, Store as StoreIcon } from 'lucide-react';
3
-import { Badge } from '@/components/ui/badge';
4
-import { Button } from '@/components/ui/button';
1
+import { Deferred, Head, router, usePage } from '@inertiajs/react';
2
+import { ReceiptText, ShoppingBag, TrendingUp, Truck } from 'lucide-react';
3
+import { fontsUrl } from '@/components/home/brand';
4
+import KpiCards from '@/components/overview/kpi-cards';
5
+import PulseCard, { PulseLoading } from '@/components/overview/pulse-card';
6
+import SalesChart from '@/components/overview/sales-chart';
5 7
 import {
6
-    Card,
7
-    CardContent,
8
-    CardDescription,
9
-    CardHeader,
10
-    CardTitle,
11
-} from '@/components/ui/card';
8
+    AttentionList,
9
+    EmptySales,
10
+    GettingStartedCard,
11
+    Panel,
12
+    RecentOrders,
13
+    StoreSales,
14
+    TopProducts,
15
+} from '@/components/overview/sections';
16
+import { cn } from '@/lib/utils';
12 17
 import { dashboard } from '@/routes';
13
-import { create, show } from '@/routes/stores';
14
-import PlanNotice from '@/components/plan-notice';
15
-import type { Store, Usage } from '@/types';
18
+import type {
19
+    GettingStarted,
20
+    OverviewRange,
21
+    OverviewStats,
22
+    StorePulse,
23
+} from '@/types';
24
+
25
+type Props = {
26
+    filters: { range: OverviewRange; store: string | null };
27
+    stores: { name: string; slug: string }[];
28
+    hasSales: boolean;
29
+    gettingStarted: GettingStarted | null;
30
+    liveUrl: string | null;
31
+    stats: OverviewStats | null;
32
+    /** Loaded just after the page (see DashboardController). Null until the first sale. */
33
+    pulse?: StorePulse | null;
34
+};
35
+
36
+const ranges: { value: OverviewRange; label: string }[] = [
37
+    { value: 'today', label: 'Today' },
38
+    { value: '7d', label: '7 days' },
39
+    { value: '30d', label: '30 days' },
40
+    { value: 'month', label: 'This month' },
41
+];
42
+
43
+function greeting(): string {
44
+    const hour = Number(
45
+        new Intl.DateTimeFormat('en-MY', {
46
+            hour: 'numeric',
47
+            hourCycle: 'h23',
48
+            timeZone: 'Asia/Kuala_Lumpur',
49
+        }).format(new Date()),
50
+    );
51
+
52
+    return hour < 12
53
+        ? 'Good morning'
54
+        : hour < 18
55
+          ? 'Good afternoon'
56
+          : 'Good evening';
57
+}
58
+
59
+/** Time range buttons and the store picker. Changing either reloads the numbers. */
60
+function Filters({ filters, stores }: Pick<Props, 'filters' | 'stores'>) {
61
+    const go = (next: Partial<Props['filters']>) => {
62
+        const query = { ...filters, ...next };
63
+        router.get(
64
+            dashboard.url({
65
+                query: {
66
+                    range: query.range === '30d' ? undefined : query.range,
67
+                    store: query.store ?? undefined,
68
+                },
69
+            }),
70
+            {},
71
+            { preserveState: true, preserveScroll: true, replace: true },
72
+        );
73
+    };
16 74
 
17
-export default function Dashboard({
18
-    stores,
19
-    usage,
20
-}: {
21
-    stores: Store[];
22
-    usage: Usage;
23
-}) {
24 75
     return (
25
-        <>
26
-            <Head title="Dashboard" />
76
+        <div className="flex flex-wrap items-center gap-2.5">
77
+            <div
78
+                role="group"
79
+                aria-label="Time range"
80
+                className="inline-flex rounded-full border border-(--ov-line) bg-(--ov-card) p-[3px]"
81
+            >
82
+                {ranges.map((range) => (
83
+                    <button
84
+                        key={range.value}
85
+                        type="button"
86
+                        aria-pressed={filters.range === range.value}
87
+                        onClick={() => go({ range: range.value })}
88
+                        className={cn(
89
+                            'rounded-full px-3 py-1.5 text-[13px] whitespace-nowrap transition-colors sm:px-3.5',
90
+                            filters.range === range.value
91
+                                ? 'bg-(--ov-ink) font-semibold text-(--ov-paper)'
92
+                                : 'text-(--ov-muted) hover:text-(--ov-ink)',
93
+                        )}
94
+                    >
95
+                        {range.label}
96
+                    </button>
97
+                ))}
98
+            </div>
27 99
 
28
-            <div className="flex h-full flex-1 flex-col gap-6 p-4">
29
-                <PlanNotice usage={usage} />
100
+            {stores.length > 1 && (
101
+                <>
102
+                    <label htmlFor="overview-store" className="sr-only">
103
+                        Store
104
+                    </label>
105
+                    <select
106
+                        id="overview-store"
107
+                        value={filters.store ?? ''}
108
+                        onChange={(event) =>
109
+                            go({ store: event.target.value || null })
110
+                        }
111
+                        className="rounded-full border border-(--ov-line) bg-(--ov-card) py-[7px] pr-8 pl-3.5 text-[13px] text-(--ov-ink)"
112
+                    >
113
+                        <option value="">All stores</option>
114
+                        {stores.map((store) => (
115
+                            <option key={store.slug} value={store.slug}>
116
+                                {store.name}
117
+                            </option>
118
+                        ))}
119
+                    </select>
120
+                </>
121
+            )}
122
+        </div>
123
+    );
124
+}
30 125
 
31
-                <div className="flex flex-wrap items-center justify-between gap-4">
32
-                    <div>
33
-                        <h1 className="text-xl font-semibold">Your stores</h1>
34
-                        <p className="text-sm text-muted-foreground">
35
-                            Create a store, then let AI design it for you.
36
-                        </p>
37
-                    </div>
126
+/** Before the first sale: the same four boxes, at zero, with a word on what will show there. */
127
+function ZeroCards() {
128
+    const cards = [
129
+        {
130
+            label: 'Total sales',
131
+            value: 'RM 0',
132
+            note: 'Your first sale shows here',
133
+            icon: TrendingUp,
134
+            hero: true,
135
+        },
136
+        {
137
+            label: 'Paid orders',
138
+            value: '0',
139
+            note: 'No orders yet',
140
+            icon: ReceiptText,
141
+        },
142
+        {
143
+            label: 'Average order',
144
+            value: 'RM 0',
145
+            note: 'per paid order',
146
+            icon: ShoppingBag,
147
+        },
148
+        {
149
+            label: 'To ship now',
150
+            value: '0',
151
+            note: 'Nothing to send',
152
+            icon: Truck,
153
+        },
154
+    ];
38 155
 
39
-                    {stores.length > 0 && (
40
-                        <Button asChild>
41
-                            <Link href={create()}>
42
-                                <Plus />
43
-                                Create store
44
-                            </Link>
45
-                        </Button>
156
+    return (
157
+        <section
158
+            aria-label="Key numbers"
159
+            className="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4"
160
+        >
161
+            {cards.map((card, index) => (
162
+                <div
163
+                    key={card.label}
164
+                    className={cn(
165
+                        'ov-rise rounded-[18px] border px-5 py-4',
166
+                        card.hero
167
+                            ? 'border-(--ov-hero) bg-(--ov-hero) text-white'
168
+                            : 'border-(--ov-line) bg-(--ov-card)',
46 169
                     )}
170
+                    style={{ animationDelay: `${160 + index * 60}ms` }}
171
+                >
172
+                    <div className="flex items-center gap-2 text-sm font-medium opacity-80">
173
+                        <card.icon className="size-4" aria-hidden="true" />
174
+                        {card.label}
175
+                    </div>
176
+                    <div className="ov-heading mt-1.5 text-[clamp(1.5rem,2.4vw,2rem)] font-extrabold">
177
+                        {card.value}
178
+                    </div>
179
+                    <div
180
+                        className={cn(
181
+                            'text-sm',
182
+                            card.hero ? 'text-white/80' : 'text-(--ov-muted)',
183
+                        )}
184
+                    >
185
+                        {card.note}
186
+                    </div>
47 187
                 </div>
188
+            ))}
189
+        </section>
190
+    );
191
+}
48 192
 
49
-                {stores.length === 0 ? (
50
-                    <div className="flex flex-1 flex-col items-center justify-center gap-4 rounded-xl border border-dashed p-10 text-center">
51
-                        <div className="flex size-12 items-center justify-center rounded-full bg-muted">
52
-                            <StoreIcon className="size-6 text-muted-foreground" />
53
-                        </div>
193
+/**
194
+ * The Overview page. Top to bottom: the AI note, four big numbers, the sales chart beside
195
+ * "Needs attention", sales by store beside top products, and the newest orders.
196
+ * Before the first sale it shows the steps to get there instead.
197
+ */
198
+export default function Dashboard({
199
+    filters,
200
+    stores,
201
+    hasSales,
202
+    gettingStarted,
203
+    liveUrl,
204
+    stats,
205
+}: Props) {
206
+    const { auth } = usePage().props;
207
+    const firstName = (auth.user?.name ?? '').split(' ')[0];
208
+    const showStore = filters.store === null && stores.length > 1;
209
+
210
+    return (
211
+        <>
212
+            <Head title="Overview">
213
+                <link rel="stylesheet" href={fontsUrl} />
214
+            </Head>
215
+
216
+            <div className="overview flex-1 px-4 pt-6 pb-14 sm:px-6 lg:px-8">
217
+                <div className="mx-auto flex w-full max-w-[1200px] flex-col gap-6">
218
+                    <div className="ov-rise flex flex-wrap items-end justify-between gap-4">
54 219
                         <div>
55
-                            <h2 className="font-medium">No stores yet</h2>
56
-                            <p className="mt-1 max-w-sm text-sm text-muted-foreground">
57
-                                Tell us about your brand and we will set up your
58
-                                first online store.
220
+                            <h1 className="ov-heading text-[clamp(1.45rem,2.4vw,1.75rem)] font-extrabold">
221
+                                {hasSales
222
+                                    ? `${greeting()}${firstName ? `, ${firstName}` : ''}`
223
+                                    : `Welcome${firstName ? `, ${firstName}` : ''}`}
224
+                            </h1>
225
+                            <p className="mt-0.5 text-(--ov-muted)">
226
+                                {hasSales
227
+                                    ? stats?.label === 'Today, by hour'
228
+                                        ? 'Here’s how today is going.'
229
+                                        : 'Here’s how your stores are doing.'
230
+                                    : 'A few steps and your store is ready for its first order.'}
59 231
                             </p>
60 232
                         </div>
61
-                        <Button asChild>
62
-                            <Link href={create()}>
63
-                                <Plus />
64
-                                Create your first store
65
-                            </Link>
66
-                        </Button>
67
-                    </div>
68
-                ) : (
69
-                    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
70
-                        {stores.map((store) => (
71
-                            <Link
72
-                                key={store.id}
73
-                                href={show(store.slug)}
74
-                                className="rounded-xl focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none"
75
-                            >
76
-                                <Card className="h-full transition-colors hover:bg-accent/40">
77
-                                    <CardHeader>
78
-                                        <div className="flex items-start justify-between gap-3">
79
-                                            <CardTitle className="leading-snug">
80
-                                                {store.name}
81
-                                            </CardTitle>
82
-                                            <Badge
83
-                                                variant={
84
-                                                    store.status === 'published'
85
-                                                        ? 'default'
86
-                                                        : 'secondary'
87
-                                                }
88
-                                            >
89
-                                                {store.status_label}
90
-                                            </Badge>
91
-                                        </div>
92
-                                        <CardDescription>
93
-                                            {store.category_label}
94
-                                        </CardDescription>
95
-                                    </CardHeader>
96
-                                    <CardContent>
97
-                                        <p className="line-clamp-3 text-sm text-muted-foreground">
98
-                                            {store.description}
99
-                                        </p>
100
-                                    </CardContent>
101
-                                </Card>
102
-                            </Link>
103
-                        ))}
233
+                        {hasSales && (
234
+                            <Filters filters={filters} stores={stores} />
235
+                        )}
104 236
                     </div>
105
-                )}
237
+
238
+                    {hasSales && stats ? (
239
+                        <>
240
+                            <Deferred data="pulse" fallback={<PulseLoading />}>
241
+                                <PulseSlot store={filters.store} />
242
+                            </Deferred>
243
+
244
+                            <KpiCards stats={stats} />
245
+
246
+                            <div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
247
+                                <Panel
248
+                                    title="Sales"
249
+                                    delay={400}
250
+                                    aside={
251
+                                        <span className="flex flex-wrap justify-end gap-x-4 gap-y-1">
252
+                                            <span className="inline-flex items-center gap-1.5">
253
+                                                <i className="inline-block h-[3px] w-4 rounded bg-(--ov-pandan)" />
254
+                                                This period
255
+                                            </span>
256
+                                            <span className="inline-flex items-center gap-1.5">
257
+                                                <i className="inline-block w-4 border-t-2 border-dashed border-(--ov-prev)" />
258
+                                                Before
259
+                                            </span>
260
+                                        </span>
261
+                                    }
262
+                                >
263
+                                    <p className="-mt-3 mb-3 text-sm text-(--ov-muted)">
264
+                                        {stats.label}
265
+                                    </p>
266
+                                    <SalesChart stats={stats} />
267
+                                </Panel>
268
+
269
+                                <Panel
270
+                                    title="Needs attention"
271
+                                    delay={460}
272
+                                    aside={
273
+                                        stats.attention.length > 0
274
+                                            ? `${stats.attention.length} ${stats.attention.length === 1 ? 'thing' : 'things'}`
275
+                                            : null
276
+                                    }
277
+                                >
278
+                                    <AttentionList
279
+                                        items={stats.attention}
280
+                                        showStore={showStore}
281
+                                    />
282
+                                </Panel>
283
+                            </div>
284
+
285
+                            <div className="grid gap-4 md:grid-cols-2">
286
+                                {stores.length > 1 && (
287
+                                    <Panel
288
+                                        title="Sales by store"
289
+                                        delay={520}
290
+                                        aside={stats.label}
291
+                                    >
292
+                                        <StoreSales stats={stats} />
293
+                                    </Panel>
294
+                                )}
295
+                                <Panel
296
+                                    title="Top products"
297
+                                    delay={580}
298
+                                    aside={stats.label}
299
+                                    className={
300
+                                        stores.length > 1
301
+                                            ? undefined
302
+                                            : 'md:col-span-2'
303
+                                    }
304
+                                >
305
+                                    <TopProducts
306
+                                        stats={stats}
307
+                                        showStore={showStore}
308
+                                    />
309
+                                </Panel>
310
+                            </div>
311
+
312
+                            <Panel title="Recent orders" delay={640}>
313
+                                <RecentOrders
314
+                                    stats={stats}
315
+                                    showStore={showStore}
316
+                                />
317
+                            </Panel>
318
+                        </>
319
+                    ) : (
320
+                        <>
321
+                            {gettingStarted && (
322
+                                <GettingStartedCard data={gettingStarted} />
323
+                            )}
324
+                            <ZeroCards />
325
+                            <Panel title="Sales" delay={400}>
326
+                                <EmptySales storeUrl={liveUrl} />
327
+                            </Panel>
328
+                        </>
329
+                    )}
330
+                </div>
106 331
             </div>
107 332
         </>
108 333
     );
109 334
 }
110 335
 
336
+/** The pulse card, once its data has arrived. Nothing shows when there is no note. */
337
+function PulseSlot({ store }: { store: string | null }) {
338
+    const { pulse } = usePage<Props>().props;
339
+
340
+    return pulse ? <PulseCard pulse={pulse} store={store} /> : null;
341
+}
342
+
111 343
 Dashboard.layout = {
112 344
     breadcrumbs: [
113 345
         {
114
-            title: 'Dashboard',
346
+            title: 'Overview',
115 347
             href: dashboard(),
116 348
         },
117 349
     ],

+ 5
- 0
resources/js/pages/legal/privacy.tsx Zobrazit soubor

@@ -135,6 +135,11 @@ export default function Privacy(details: LegalDetails) {
135 135
                             'your store’s current design and words, and your products’ names, prices, descriptions and the names of their photos.',
136 136
                         ]}
137 137
                     />
138
+                    <p>
139
+                        Once a day, to write the short note on your dashboard,
140
+                        we also send them your stores’ sales totals, order
141
+                        counts, stock warnings and best-selling product names.
142
+                    </p>
138 143
                     <p>
139 144
                         We do <strong>not</strong> send them your password, card
140 145
                         details, or shoppers’ names, contact details, addresses

+ 1
- 1
resources/js/pages/stores/collections/form.tsx Zobrazit soubor

@@ -243,7 +243,7 @@ export default function CollectionForm({
243 243
 
244 244
 CollectionForm.layout = {
245 245
     breadcrumbs: [
246
-        { title: 'Dashboard', href: dashboard() },
246
+        { title: 'Overview', href: dashboard() },
247 247
         { title: 'Collection', href: '#' },
248 248
     ],
249 249
 };

+ 1
- 1
resources/js/pages/stores/create.tsx Zobrazit soubor

@@ -174,7 +174,7 @@ export default function CreateStore({
174 174
 CreateStore.layout = {
175 175
     breadcrumbs: [
176 176
         {
177
-            title: 'Dashboard',
177
+            title: 'Overview',
178 178
             href: dashboard(),
179 179
         },
180 180
         {

+ 1
- 1
resources/js/pages/stores/discounts/automatic-form.tsx Zobrazit soubor

@@ -382,7 +382,7 @@ export default function AutomaticDiscountForm({
382 382
 
383 383
 AutomaticDiscountForm.layout = {
384 384
     breadcrumbs: [
385
-        { title: 'Dashboard', href: dashboard() },
385
+        { title: 'Overview', href: dashboard() },
386 386
         { title: 'Automatic discount', href: '#' },
387 387
     ],
388 388
 };

+ 1
- 1
resources/js/pages/stores/discounts/form.tsx Zobrazit soubor

@@ -289,7 +289,7 @@ export default function DiscountForm({
289 289
 
290 290
 DiscountForm.layout = {
291 291
     breadcrumbs: [
292
-        { title: 'Dashboard', href: dashboard() },
292
+        { title: 'Overview', href: dashboard() },
293 293
         { title: 'Discount code', href: '#' },
294 294
     ],
295 295
 };

+ 1
- 1
resources/js/pages/stores/discounts/index.tsx Zobrazit soubor

@@ -275,7 +275,7 @@ function AutomaticDiscounts({
275 275
 
276 276
 DiscountsIndex.layout = {
277 277
     breadcrumbs: [
278
-        { title: 'Dashboard', href: dashboard() },
278
+        { title: 'Overview', href: dashboard() },
279 279
         { title: 'Discounts', href: '#' },
280 280
     ],
281 281
 };

+ 1
- 1
resources/js/pages/stores/orders/index.tsx Zobrazit soubor

@@ -140,7 +140,7 @@ export default function OrdersIndex({
140 140
 
141 141
 OrdersIndex.layout = {
142 142
     breadcrumbs: [
143
-        { title: 'Dashboard', href: dashboard() },
143
+        { title: 'Overview', href: dashboard() },
144 144
         { title: 'Orders', href: '#' },
145 145
     ],
146 146
 };

+ 1
- 1
resources/js/pages/stores/orders/show.tsx Zobrazit soubor

@@ -292,7 +292,7 @@ export default function ShowOrder({
292 292
 
293 293
 ShowOrder.layout = {
294 294
     breadcrumbs: [
295
-        { title: 'Dashboard', href: dashboard() },
295
+        { title: 'Overview', href: dashboard() },
296 296
         { title: 'Order', href: '#' },
297 297
     ],
298 298
 };

+ 1
- 1
resources/js/pages/stores/products/create.tsx Zobrazit soubor

@@ -38,7 +38,7 @@ export default function CreateProduct({
38 38
 
39 39
 CreateProduct.layout = {
40 40
     breadcrumbs: [
41
-        { title: 'Dashboard', href: dashboard() },
41
+        { title: 'Overview', href: dashboard() },
42 42
         { title: 'Add product', href: '#' },
43 43
     ],
44 44
 };

+ 1
- 1
resources/js/pages/stores/products/edit.tsx Zobrazit soubor

@@ -111,7 +111,7 @@ export default function EditProduct({
111 111
 
112 112
 EditProduct.layout = {
113 113
     breadcrumbs: [
114
-        { title: 'Dashboard', href: dashboard() },
114
+        { title: 'Overview', href: dashboard() },
115 115
         { title: 'Edit product', href: '#' },
116 116
     ],
117 117
 };

+ 1
- 1
resources/js/pages/stores/products/index.tsx Zobrazit soubor

@@ -208,7 +208,7 @@ export default function ProductsIndex({
208 208
 
209 209
 ProductsIndex.layout = {
210 210
     breadcrumbs: [
211
-        { title: 'Dashboard', href: dashboard() },
211
+        { title: 'Overview', href: dashboard() },
212 212
         { title: 'Products', href: '#' },
213 213
     ],
214 214
 };

+ 1
- 1
resources/js/pages/stores/settings.tsx Zobrazit soubor

@@ -266,7 +266,7 @@ export default function StoreSettings({
266 266
 
267 267
 StoreSettings.layout = {
268 268
     breadcrumbs: [
269
-        { title: 'Dashboard', href: dashboard() },
269
+        { title: 'Overview', href: dashboard() },
270 270
         { title: 'Settings', href: '#' },
271 271
     ],
272 272
 };

+ 1
- 1
resources/js/pages/stores/show.tsx Zobrazit soubor

@@ -437,7 +437,7 @@ function FailedNotice({ generation }: { generation: StoreGeneration }) {
437 437
 ShowStore.layout = {
438 438
     breadcrumbs: [
439 439
         {
440
-            title: 'Dashboard',
440
+            title: 'Overview',
441 441
             href: dashboard(),
442 442
         },
443 443
         {

+ 2
- 0
resources/js/types/global.d.ts Zobrazit soubor

@@ -1,4 +1,5 @@
1 1
 import type { Auth } from '@/types/auth';
2
+import type { SidebarData } from '@/types/store';
2 3
 
3 4
 declare module 'react' {
4 5
     interface InputHTMLAttributes<T> {
@@ -12,6 +13,7 @@ declare module '@inertiajs/core' {
12 13
             name: string;
13 14
             auth: Auth;
14 15
             sidebarOpen: boolean;
16
+            sidebar: SidebarData | null;
15 17
             [key: string]: unknown;
16 18
         };
17 19
     }

+ 1
- 0
resources/js/types/index.ts Zobrazit soubor

@@ -2,3 +2,4 @@ export type * from './auth';
2 2
 export type * from './navigation';
3 3
 export type * from './ui';
4 4
 export type * from './store';
5
+export type * from './overview';

+ 89
- 0
resources/js/types/overview.ts Zobrazit soubor

@@ -0,0 +1,89 @@
1
+/** The time ranges on the Overview page. */
2
+export type OverviewRange = 'today' | '7d' | '30d' | 'month';
3
+
4
+export type OverviewStoreRef = { name: string; slug: string };
5
+
6
+/** One thing in "Needs attention", most urgent first. */
7
+export type AttentionItem = {
8
+    kind: 'ship' | 'restock' | 'publish' | 'plan';
9
+    tone: 'warning' | 'danger' | 'brand';
10
+    title: string;
11
+    note: string;
12
+    store: OverviewStoreRef | null;
13
+    product_id?: number;
14
+};
15
+
16
+/** The numbers on the Overview page (see App\Dashboard\OverviewStats). Money is in ringgit. */
17
+export type OverviewStats = {
18
+    range: OverviewRange;
19
+    label: string;
20
+    compare_label: string;
21
+    sales: number;
22
+    previous_sales: number;
23
+    /** Percent, or null when there is nothing to compare with. */
24
+    sales_change: number | null;
25
+    orders: number;
26
+    previous_orders: number;
27
+    average: number;
28
+    previous_average: number;
29
+    series: {
30
+        label: string;
31
+        sales: number;
32
+        previous: number;
33
+        orders: number;
34
+    }[];
35
+    to_ship: { count: number; oldest_days: number | null };
36
+    attention: AttentionItem[];
37
+    by_store: {
38
+        name: string;
39
+        slug: string;
40
+        is_published: boolean;
41
+        sales: number;
42
+        share: number;
43
+        selected: boolean;
44
+    }[];
45
+    top_products: {
46
+        name: string;
47
+        product_id: number | null;
48
+        store: OverviewStoreRef;
49
+        units: number;
50
+        revenue: number;
51
+    }[];
52
+    recent_orders: {
53
+        id: number;
54
+        number: number;
55
+        customer_name: string;
56
+        state: string | null;
57
+        total: number;
58
+        shipped: boolean;
59
+        paid_at: string | null;
60
+        store: OverviewStoreRef;
61
+    }[];
62
+};
63
+
64
+/** The Store pulse card (see App\Dashboard\StorePulse). */
65
+export type StorePulse = {
66
+    summary: string;
67
+    /** "numbers" when the AI could not answer and the note was written from the numbers. */
68
+    source: 'ai' | 'numbers';
69
+    written_at: string | null;
70
+    actions: {
71
+        kind: 'ship' | 'restock' | 'publish';
72
+        label: string;
73
+        store_slug: string;
74
+        product_id?: number;
75
+    }[];
76
+    rewrites_left: number;
77
+    rewrites_limit: number;
78
+};
79
+
80
+/** The steps shown until the first sale. */
81
+export type GettingStarted = {
82
+    store: OverviewStoreRef | null;
83
+    steps: {
84
+        create: boolean;
85
+        design: boolean;
86
+        products: boolean;
87
+        publish: boolean;
88
+    };
89
+};

+ 15
- 0
resources/js/types/store.ts Zobrazit soubor

@@ -291,3 +291,18 @@ export type DiscountCode = {
291 291
     active: boolean;
292 292
     status: 'active' | 'off' | 'scheduled' | 'expired' | 'used_up';
293 293
 };
294
+
295
+/** One store in the sidebar's store tree. */
296
+export type SidebarStore = {
297
+    name: string;
298
+    slug: string;
299
+    is_published: boolean;
300
+    /** Paid orders not shipped yet. */
301
+    to_ship: number;
302
+};
303
+
304
+/** Shared with every dashboard page for the sidebar (see HandleInertiaRequests). */
305
+export type SidebarData = {
306
+    stores: SidebarStore[];
307
+    usage: Usage;
308
+};

+ 3
- 1
routes/web.php Zobrazit soubor

@@ -6,6 +6,7 @@ use App\Http\Controllers\BillingController;
6 6
 use App\Http\Controllers\CartController;
7 7
 use App\Http\Controllers\CheckoutController;
8 8
 use App\Http\Controllers\CollectionController;
9
+use App\Http\Controllers\DashboardController;
9 10
 use App\Http\Controllers\DiscountCodeController;
10 11
 use App\Http\Controllers\FeaturedProductController;
11 12
 use App\Http\Controllers\HeroImageController;
@@ -69,7 +70,8 @@ Route::get('terms', [LegalController::class, 'terms'])->name('terms');
69 70
 Route::post('stripe/webhook', StripeWebhookController::class)->name('stripe.webhook');
70 71
 
71 72
 Route::middleware(['auth', 'verified'])->group(function () {
72
-    Route::get('dashboard', [StoreController::class, 'index'])->name('dashboard');
73
+    Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard');
74
+    Route::post('dashboard/pulse', [DashboardController::class, 'rewritePulse'])->middleware('throttle:10,1')->name('dashboard.pulse');
73 75
 
74 76
     Route::get('billing', [BillingController::class, 'index'])->name('billing');
75 77
     Route::post('billing/subscribe', [BillingController::class, 'subscribe'])->name('billing.subscribe');

+ 2
- 2
tests/Feature/Billing/BillingTest.php Zobrazit soubor

@@ -312,8 +312,8 @@ class BillingTest extends TestCase
312 312
 
313 313
         $this->actingAs($user)->get(route('dashboard'))
314 314
             ->assertInertia(fn (Assert $page) => $page
315
-                ->where('usage.stores.used', 3)
316
-                ->where('usage.stores.limit', 3));
315
+                ->where('sidebar.usage.stores.used', 3)
316
+                ->where('sidebar.usage.stores.limit', 3));
317 317
     }
318 318
 
319 319
     public function test_guests_cannot_open_billing()

+ 246
- 0
tests/Feature/Dashboard/OverviewTest.php Zobrazit soubor

@@ -0,0 +1,246 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Dashboard;
4
+
5
+use App\Dashboard\StorePulse;
6
+use App\Enums\StoreStatus;
7
+use App\Models\DashboardPulse;
8
+use App\Models\Order;
9
+use App\Models\OrderItem;
10
+use App\Models\Product;
11
+use App\Models\Store;
12
+use App\Models\User;
13
+use App\StorePlan\SamplePlan;
14
+use Illuminate\Foundation\Testing\RefreshDatabase;
15
+use Inertia\Testing\AssertableInertia as Assert;
16
+use Tests\TestCase;
17
+
18
+class OverviewTest extends TestCase
19
+{
20
+    use RefreshDatabase;
21
+
22
+    private function paidOrder(Store $store, int $total, string $paidAt = 'now', bool $shipped = false): Order
23
+    {
24
+        return Order::factory()->paid()->for($store)->create([
25
+            'total' => $total,
26
+            'paid_at' => now()->modify($paidAt),
27
+            'shipped_at' => $shipped ? now() : null,
28
+        ]);
29
+    }
30
+
31
+    public function test_a_new_merchant_sees_the_first_sale_steps_and_no_ai_note()
32
+    {
33
+        $user = User::factory()->create();
34
+        Store::factory()->for($user)->create(['plan' => SamplePlan::forName('Sambal Nenek')]);
35
+
36
+        $this->actingAs($user)->get(route('dashboard'))
37
+            ->assertInertia(fn (Assert $page) => $page
38
+                ->component('dashboard')
39
+                ->where('hasSales', false)
40
+                ->where('stats', null)
41
+                ->where('pulse', null)
42
+                ->where('gettingStarted.steps.create', true)
43
+                ->where('gettingStarted.steps.design', true)
44
+                ->where('gettingStarted.steps.products', false)
45
+                ->where('gettingStarted.steps.publish', false));
46
+
47
+        $this->assertDatabaseCount('dashboard_pulses', 0);
48
+    }
49
+
50
+    public function test_the_numbers_count_only_paid_orders_of_the_merchants_own_stores()
51
+    {
52
+        $user = User::factory()->create();
53
+        $store = Store::factory()->for($user)->create();
54
+        $this->paidOrder($store, 5000, '-2 days');
55
+        $this->paidOrder($store, 3000, '-1 day', shipped: true);
56
+        Order::factory()->for($store)->create(['total' => 9900]); // Not paid.
57
+        $this->paidOrder(Store::factory()->create(), 7000); // Someone else's store.
58
+        $this->paidOrder($store, 4000, '-40 days'); // Before the 30 days.
59
+
60
+        $this->actingAs($user)->get(route('dashboard'))
61
+            ->assertInertia(fn (Assert $page) => $page
62
+                ->where('hasSales', true)
63
+                ->where('stats.range', '30d')
64
+                ->where('stats.sales', 80)
65
+                ->where('stats.orders', 2)
66
+                ->where('stats.average', 40)
67
+                ->where('stats.previous_sales', 40)
68
+                ->where('stats.sales_change', 100)
69
+                // Waiting to ship counts every unshipped paid order, however old.
70
+                ->where('stats.to_ship.count', 2)
71
+                ->has('stats.series', 30)
72
+                ->has('stats.recent_orders', 3));
73
+    }
74
+
75
+    public function test_the_range_and_store_filters_change_the_numbers()
76
+    {
77
+        $user = User::factory()->create();
78
+        $first = Store::factory()->for($user)->create(['name' => 'First']);
79
+        $second = Store::factory()->for($user)->create(['name' => 'Second']);
80
+        $this->paidOrder($first, 1000);
81
+        $this->paidOrder($second, 2000, '-3 days');
82
+
83
+        $this->actingAs($user)->get(route('dashboard', ['range' => 'today']))
84
+            ->assertInertia(fn (Assert $page) => $page
85
+                ->where('filters.range', 'today')
86
+                ->where('stats.sales', 10));
87
+
88
+        $this->actingAs($user)->get(route('dashboard', ['store' => $second->slug]))
89
+            ->assertInertia(fn (Assert $page) => $page
90
+                ->where('filters.store', $second->slug)
91
+                ->where('stats.sales', 20)
92
+                ->where('stats.by_store.1.selected', true));
93
+
94
+        // A store that is not theirs, or a made-up range, falls back to all stores and 30 days.
95
+        $this->actingAs($user)->get(route('dashboard', ['store' => Store::factory()->create()->slug, 'range' => 'forever']))
96
+            ->assertInertia(fn (Assert $page) => $page
97
+                ->where('filters.store', null)
98
+                ->where('filters.range', '30d')
99
+                ->where('stats.sales', 30));
100
+    }
101
+
102
+    public function test_top_products_join_the_options_of_one_product()
103
+    {
104
+        $user = User::factory()->create();
105
+        $store = Store::factory()->for($user)->create();
106
+        $product = Product::factory()->for($store)->create(['name' => 'Sambal Hijau']);
107
+        $order = $this->paidOrder($store, 3000);
108
+
109
+        foreach (['Sambal Hijau (250g)', 'Sambal Hijau (500g)'] as $name) {
110
+            $item = new OrderItem([
111
+                'product_id' => $product->id,
112
+                'name' => $name,
113
+                'unit_price' => 1500,
114
+                'quantity' => 1,
115
+                'line_total' => 1500,
116
+            ]);
117
+            $item->forceFill(['store_id' => $store->id, 'order_id' => $order->id, 'product_id' => $product->id])->save();
118
+        }
119
+
120
+        $this->actingAs($user)->get(route('dashboard'))
121
+            ->assertInertia(fn (Assert $page) => $page
122
+                ->has('stats.top_products', 1)
123
+                ->where('stats.top_products.0.name', 'Sambal Hijau')
124
+                ->where('stats.top_products.0.units', 2)
125
+                ->where('stats.top_products.0.revenue', 30));
126
+    }
127
+
128
+    public function test_needs_attention_lists_orders_to_ship_low_stock_and_unpublished_stores()
129
+    {
130
+        $user = User::factory()->create();
131
+        $store = Store::factory()->for($user)->create(['name' => 'Kedai']);
132
+        $this->paidOrder($store, 1000, '-2 days');
133
+        Product::factory()->for($store)->create(['name' => 'Kerepek', 'stock' => 2]);
134
+        Product::factory()->for($store)->create(['name' => 'Plenty', 'stock' => 40]);
135
+        Store::factory()->for($user)->count(2)->create(['plan' => SamplePlan::forName('Draft')]);
136
+
137
+        $this->actingAs($user)->get(route('dashboard'))
138
+            ->assertInertia(fn (Assert $page) => $page
139
+                ->has('stats.attention', 3)
140
+                ->where('stats.attention.0.kind', 'ship')
141
+                ->where('stats.attention.0.note', 'Oldest waited 2 days')
142
+                ->where('stats.attention.1.title', 'Kerepek is almost out')
143
+                // Several stores waiting to be published make one line.
144
+                ->where('stats.attention.2.title', '2 stores are not published'));
145
+    }
146
+
147
+    public function test_the_sidebar_lists_the_stores_with_orders_to_ship()
148
+    {
149
+        $user = User::factory()->create();
150
+        $store = Store::factory()->for($user)->create([
151
+            'status' => StoreStatus::Published,
152
+            'plan' => SamplePlan::forName('Kedai'),
153
+            'published_plan' => SamplePlan::forName('Kedai'),
154
+        ]);
155
+        $this->paidOrder($store, 1000);
156
+        $this->paidOrder($store, 1000, shipped: true);
157
+
158
+        $this->actingAs($user)->get(route('billing'))
159
+            ->assertInertia(fn (Assert $page) => $page
160
+                ->has('sidebar.stores', 1)
161
+                ->where('sidebar.stores.0.slug', $store->slug)
162
+                ->where('sidebar.stores.0.is_published', true)
163
+                ->where('sidebar.stores.0.to_ship', 1)
164
+                ->has('sidebar.usage'));
165
+    }
166
+
167
+    public function test_the_ai_note_is_written_once_a_day_and_then_read_from_the_database()
168
+    {
169
+        $user = User::factory()->create();
170
+        $this->paidOrder(Store::factory()->for($user)->create(), 2500);
171
+
172
+        $this->actingAs($user)->get(route('dashboard'))
173
+            ->assertInertia(fn (Assert $page) => $page
174
+                ->missing('pulse')
175
+                ->loadDeferredProps(fn (Assert $reload) => $reload
176
+                    ->where('pulse.source', 'ai')
177
+                    ->where('pulse.rewrites_left', 3)
178
+                    ->where('pulse.rewrites_limit', 3)
179
+                    ->where('pulse.actions.0.kind', 'ship')
180
+                    ->where('pulse.actions.0.label', 'Ship 1 order')));
181
+
182
+        $this->assertDatabaseCount('dashboard_pulses', 1);
183
+
184
+        // Refreshing reads the saved note. Had the AI been asked again, this text would be replaced.
185
+        DashboardPulse::query()->update(['summary' => 'Saved note.']);
186
+        $pulse = app(StorePulse::class)->today($user, null);
187
+
188
+        $this->assertSame('Saved note.', $pulse['summary']);
189
+        $this->assertDatabaseCount('dashboard_pulses', 1);
190
+    }
191
+
192
+    public function test_write_again_replaces_the_note_until_the_daily_limit()
193
+    {
194
+        config(['ai.pulse.daily_rewrites' => 2]);
195
+        $user = User::factory()->create();
196
+        $this->paidOrder(Store::factory()->for($user)->create(), 2500);
197
+        app(StorePulse::class)->today($user, null);
198
+        DashboardPulse::query()->update(['summary' => 'Old note.']);
199
+
200
+        $this->actingAs($user)->post(route('dashboard.pulse'))->assertRedirect();
201
+        $this->assertStringStartsWith('Fake AI', DashboardPulse::query()->value('summary'));
202
+
203
+        $this->actingAs($user)->post(route('dashboard.pulse'));
204
+        $this->assertSame(2, DashboardPulse::query()->value('rewrites'));
205
+        $this->assertSame(0, app(StorePulse::class)->rewritesLeft($user));
206
+
207
+        // The limit is used up: the note stays and the merchant is told why.
208
+        DashboardPulse::query()->update(['summary' => 'Kept note.']);
209
+        $this->actingAs($user)->post(route('dashboard.pulse'))
210
+            ->assertInertiaFlash('toast.type', 'error');
211
+        $this->assertSame('Kept note.', DashboardPulse::query()->value('summary'));
212
+        $this->assertSame(2, DashboardPulse::query()->value('rewrites'));
213
+    }
214
+
215
+    public function test_the_note_is_written_from_the_numbers_when_the_ai_is_not_available()
216
+    {
217
+        config(['ai.tasks.pulse.provider' => 'missing']);
218
+        $user = User::factory()->create();
219
+        $store = Store::factory()->for($user)->create();
220
+        $this->paidOrder($store, 12000, '-1 day');
221
+
222
+        $pulse = app(StorePulse::class)->today($user, null);
223
+
224
+        $this->assertSame('numbers', $pulse['source']);
225
+        $this->assertSame('Sales this month are RM 120. Ship the 1 waiting order first.', $pulse['summary']);
226
+
227
+        // "Write again" fails without using up a turn.
228
+        $this->assertFalse(app(StorePulse::class)->rewrite($user, null));
229
+        $this->assertSame(3, app(StorePulse::class)->rewritesLeft($user));
230
+    }
231
+
232
+    public function test_each_store_view_has_its_own_note_and_others_stores_cannot_be_picked()
233
+    {
234
+        $user = User::factory()->create();
235
+        $store = Store::factory()->for($user)->create();
236
+        $this->paidOrder($store, 2500);
237
+
238
+        app(StorePulse::class)->today($user, null);
239
+        app(StorePulse::class)->today($user, $store);
240
+
241
+        $this->assertDatabaseCount('dashboard_pulses', 2);
242
+
243
+        $this->actingAs($user)->post(route('dashboard.pulse'), ['store' => Store::factory()->create()->slug]);
244
+        $this->assertSame(1, (int) DashboardPulse::query()->whereNull('store_id')->value('rewrites'));
245
+    }
246
+}

Načítá se…
Zrušit
Uložit