AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

OverviewStats.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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()->with('stripeAccount')->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. // The merchant's own Stripe account is ready, so shoppers can pay.
  114. 'payments' => $stores->contains(fn (Store $store) => (bool) $store->stripeAccount?->charges_enabled),
  115. 'publish' => $stores->contains(fn (Store $store) => $store->isPublished()),
  116. ],
  117. ];
  118. }
  119. /**
  120. * Where the range starts, where the period before it starts, and how many points the chart has.
  121. *
  122. * @return array{0: CarbonImmutable, 1: CarbonImmutable, 2: int}
  123. */
  124. private function period(string $range, CarbonImmutable $now): array
  125. {
  126. $today = $now->startOfDay();
  127. return match ($range) {
  128. 'today' => [$today, $today->subDay(), $now->hour + 1],
  129. '7d' => [$today->subDays(6), $today->subDays(13), 7],
  130. '30d' => [$today->subDays(29), $today->subDays(59), 30],
  131. 'month' => [$now->startOfMonth(), $now->startOfMonth()->subMonthNoOverflow(), $now->day],
  132. };
  133. }
  134. /**
  135. * The same moment in the period before. Orders after it are left out, so a half-finished
  136. * day is compared with the same half of the day before.
  137. */
  138. private function shift(string $range, CarbonImmutable $moment): CarbonImmutable
  139. {
  140. return match ($range) {
  141. 'today' => $moment->subDay(),
  142. '7d' => $moment->subDays(7),
  143. '30d' => $moment->subDays(30),
  144. 'month' => $moment->subMonthNoOverflow(),
  145. };
  146. }
  147. private function label(string $range, CarbonImmutable $now): string
  148. {
  149. return match ($range) {
  150. 'today' => 'Today, by hour',
  151. '7d' => 'Last 7 days',
  152. '30d' => 'Last 30 days',
  153. 'month' => $now->day === 1 ? $now->format('j F') : '1 to '.$now->format('j F'),
  154. };
  155. }
  156. /**
  157. * The change in percent, or null when there is nothing to compare with.
  158. */
  159. private function change(float $now, float $before): ?int
  160. {
  161. return $before > 0 ? (int) round(($now - $before) / $before * 100) : null;
  162. }
  163. /**
  164. * One point per hour (today) or per day, for this period and the one before.
  165. *
  166. * @param Collection<int, Order> $current
  167. * @param Collection<int, Order> $previous
  168. * @return list<array{label: string, sales: float, previous: float, orders: int}>
  169. */
  170. private function series(string $range, int $buckets, CarbonImmutable $start, CarbonImmutable $previousStart, Collection $current, Collection $previous): array
  171. {
  172. $index = function (Order $order, CarbonImmutable $from) use ($range): int {
  173. $paid = CarbonImmutable::parse($order->paid_at)->setTimezone(self::TIMEZONE);
  174. return $range === 'today'
  175. ? $paid->hour
  176. : (int) $from->diffInDays($paid->startOfDay());
  177. };
  178. $points = [];
  179. for ($i = 0; $i < $buckets; $i++) {
  180. $moment = $range === 'today' ? $start->addHours($i) : $start->addDays($i);
  181. $points[$i] = [
  182. 'label' => $range === 'today' ? strtolower($moment->format('ga')) : $moment->format('j M'),
  183. 'sales' => 0.0,
  184. 'previous' => 0.0,
  185. 'orders' => 0,
  186. ];
  187. }
  188. foreach ($current as $order) {
  189. $i = $index($order, $start);
  190. if (isset($points[$i])) {
  191. $points[$i]['sales'] += $order->total / 100;
  192. $points[$i]['orders']++;
  193. }
  194. }
  195. foreach ($previous as $order) {
  196. $i = $index($order, $previousStart);
  197. if (isset($points[$i])) {
  198. $points[$i]['previous'] += $order->total / 100;
  199. }
  200. }
  201. return array_map(fn (array $point) => [
  202. ...$point,
  203. 'sales' => round($point['sales'], 2),
  204. 'previous' => round($point['previous'], 2),
  205. ], array_values($points));
  206. }
  207. /**
  208. * Paid orders not shipped yet, and how many days the oldest has waited.
  209. *
  210. * @param list<int> $storeIds
  211. * @return array{count: int, oldest_days: int|null}
  212. */
  213. private function toShip(array $storeIds, CarbonImmutable $now): array
  214. {
  215. $waiting = Order::query()
  216. ->whereIn('store_id', $storeIds)
  217. ->where('status', OrderStatus::Paid)
  218. ->whereNull('shipped_at');
  219. $oldest = (clone $waiting)->min('paid_at');
  220. return [
  221. 'count' => $waiting->count(),
  222. 'oldest_days' => $oldest !== null
  223. ? (int) CarbonImmutable::parse($oldest, 'UTC')->setTimezone(self::TIMEZONE)->startOfDay()->diffInDays($now->startOfDay())
  224. : null,
  225. ];
  226. }
  227. /**
  228. * What the merchant should look at now, most urgent first: orders to ship, products running out,
  229. * live stores that cannot take payments, designs waiting to be published, and the plan.
  230. *
  231. * @param Collection<int, Store> $stores
  232. * @param list<int> $storeIds
  233. * @return list<array<string, mixed>>
  234. */
  235. private function attention(User $user, Collection $stores, array $storeIds, CarbonImmutable $now): array
  236. {
  237. $items = [];
  238. $shown = $stores->whereIn('id', $storeIds);
  239. foreach ($shown as $store) {
  240. $ship = $this->toShip([$store->id], $now);
  241. if ($ship['count'] > 0) {
  242. $items[] = [
  243. 'kind' => 'ship',
  244. 'tone' => 'warning',
  245. 'title' => $ship['count'] === 1 ? '1 order to ship' : $ship['count'].' orders to ship',
  246. 'note' => match (true) {
  247. $ship['oldest_days'] === 0 => 'Paid today',
  248. $ship['oldest_days'] === 1 => 'Oldest waited 1 day',
  249. default => 'Oldest waited '.$ship['oldest_days'].' days',
  250. },
  251. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  252. ];
  253. }
  254. }
  255. $lowStock = Product::query()
  256. ->whereIn('store_id', $storeIds)
  257. ->where('status', ProductStatus::Active)
  258. ->where('is_bundle', false)
  259. ->where('stock', '<=', self::LOW_STOCK)
  260. ->orderBy('stock')
  261. ->limit(4)
  262. ->get(['id', 'store_id', 'name', 'stock']);
  263. foreach ($lowStock as $product) {
  264. $store = $stores->firstWhere('id', $product->store_id);
  265. $items[] = [
  266. 'kind' => 'restock',
  267. 'tone' => 'danger',
  268. 'title' => $product->stock === 0 ? $product->name.' is out of stock' : $product->name.' is almost out',
  269. 'note' => $product->stock === 0 ? 'Shoppers can’t buy it now' : 'Only '.$product->stock.' left',
  270. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  271. 'product_id' => $product->id,
  272. ];
  273. }
  274. // A live store that cannot take payments loses every order, so this comes before design work.
  275. foreach ($shown->loadMissing('stripeAccount') as $store) {
  276. if ($store->isPublished() && ! $store->stripeAccount?->charges_enabled) {
  277. $items[] = [
  278. 'kind' => 'payments',
  279. 'tone' => 'danger',
  280. 'title' => 'Can’t take payments yet',
  281. 'note' => 'Connect Stripe so shoppers can pay',
  282. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  283. ];
  284. }
  285. }
  286. foreach ($shown as $store) {
  287. if ($store->hasUnpublishedChanges()) {
  288. $items[] = [
  289. 'kind' => 'publish',
  290. 'tone' => 'brand',
  291. 'title' => 'Design changes not published',
  292. 'note' => 'Shoppers still see the old design',
  293. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  294. ];
  295. }
  296. }
  297. // Designed but never published. Several of them make one line, so the list stays short.
  298. $ready = $shown->filter(fn (Store $store) => $store->plan !== null && ! $store->isPublished())->values();
  299. if ($ready->count() === 1) {
  300. $items[] = [
  301. 'kind' => 'publish',
  302. 'tone' => 'brand',
  303. 'title' => $ready[0]->name.' is ready to publish',
  304. 'note' => 'Shoppers can’t see it yet',
  305. 'store' => ['name' => $ready[0]->name, 'slug' => $ready[0]->slug],
  306. ];
  307. } elseif ($ready->count() > 1) {
  308. $names = $ready->pluck('name');
  309. $items[] = [
  310. 'kind' => 'publish',
  311. 'tone' => 'brand',
  312. 'title' => $ready->count().' stores are not published',
  313. 'note' => $ready->count() === 2
  314. ? $names->join(' and ')
  315. : $names->take(2)->join(', ').' and '.($ready->count() - 2).' more',
  316. 'store' => ['name' => $ready[0]->name, 'slug' => $ready[0]->slug],
  317. ];
  318. }
  319. $plan = $user->currentPlan();
  320. if ($plan === null) {
  321. $items[] = ['kind' => 'plan', 'tone' => 'danger', 'title' => 'Your plan has ended', 'note' => 'Your stores are offline until you choose a plan', 'store' => null];
  322. } elseif (! $plan->isPaid() && $user->trial_ends_at !== null) {
  323. $days = (int) ceil($now->diffInDays($user->trial_ends_at, false));
  324. if ($days <= 7) {
  325. $items[] = [
  326. 'kind' => 'plan',
  327. 'tone' => 'brand',
  328. 'title' => $days <= 1 ? 'Your trial ends today' : 'Your trial ends in '.$days.' days',
  329. 'note' => 'Choose a plan to keep your stores online',
  330. 'store' => null,
  331. ];
  332. }
  333. }
  334. return $items;
  335. }
  336. /**
  337. * The best sellers in the range, by money taken.
  338. *
  339. * @param list<int> $storeIds
  340. * @param Collection<int, Store> $stores
  341. * @return list<array<string, mixed>>
  342. */
  343. private function topProducts(array $storeIds, CarbonImmutable $start, CarbonImmutable $now, Collection $stores): array
  344. {
  345. // One line per product, even when it was sold in several options. Products deleted since keep their old name.
  346. $rows = OrderItem::query()
  347. ->join('orders', 'orders.id', '=', 'order_items.order_id')
  348. ->whereIn('order_items.store_id', $storeIds)
  349. ->where('orders.status', OrderStatus::Paid)
  350. ->where('orders.paid_at', '>=', $start->utc())
  351. ->where('orders.paid_at', '<=', $now->utc())
  352. ->groupBy('order_items.store_id', 'order_items.product_id')
  353. ->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')
  354. ->orderByDesc('revenue')
  355. ->limit(5)
  356. ->get();
  357. $names = Product::query()->whereIn('id', $rows->pluck('product_id')->filter())->pluck('name', 'id');
  358. return $rows
  359. ->map(function (OrderItem $item) use ($stores, $names) {
  360. $store = $stores->firstWhere('id', $item->store_id);
  361. return [
  362. 'name' => $names[$item->product_id] ?? $item->name,
  363. 'product_id' => isset($names[$item->product_id]) ? $item->product_id : null,
  364. 'store' => ['name' => $store?->name, 'slug' => $store?->slug],
  365. 'units' => (int) $item->getAttribute('units'),
  366. 'revenue' => round((int) $item->getAttribute('revenue') / 100, 2),
  367. ];
  368. })
  369. ->all();
  370. }
  371. /**
  372. * The newest paid orders.
  373. *
  374. * @param list<int> $storeIds
  375. * @param Collection<int, Store> $stores
  376. * @return list<array<string, mixed>>
  377. */
  378. private function recentOrders(array $storeIds, Collection $stores): array
  379. {
  380. return Order::query()
  381. ->whereIn('store_id', $storeIds)
  382. ->where('status', OrderStatus::Paid)
  383. ->latest('paid_at')
  384. ->limit(5)
  385. ->get()
  386. ->map(function (Order $order) use ($stores) {
  387. $store = $stores->firstWhere('id', $order->store_id);
  388. return [
  389. 'id' => $order->id,
  390. 'number' => $order->number,
  391. 'customer_name' => $order->customer_name,
  392. 'state' => $order->shipping_address['state'] ?? null,
  393. 'total' => $order->total / 100,
  394. 'shipped' => $order->shipped_at !== null,
  395. 'paid_at' => $order->paid_at?->toIso8601String(),
  396. 'store' => ['name' => $store?->name, 'slug' => $store?->slug],
  397. ];
  398. })
  399. ->all();
  400. }
  401. }