AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

OverviewStats.php 17KB

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