| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438 |
- <?php
-
- namespace App\Dashboard;
-
- use App\Enums\OrderStatus;
- use App\Enums\ProductStatus;
- use App\Models\Order;
- use App\Models\OrderItem;
- use App\Models\Product;
- use App\Models\Store;
- use App\Models\User;
- use Carbon\CarbonImmutable;
- use Illuminate\Support\Collection;
-
- /**
- * The numbers on the dashboard's Overview page, for one merchant.
- *
- * - Only paid orders count as sales. The day an order counts for is the Malaysian day it was paid.
- * - Sales are what shoppers paid in total, shipping included. Money leaves this class in ringgit.
- * - Every range is compared with the same length of time just before it. "This month" is compared
- * with the same days of last month, so the comparison is fair on the 5th as on the 28th.
- */
- class OverviewStats
- {
- public const string TIMEZONE = 'Asia/Kuala_Lumpur';
-
- /** @var list<string> */
- public const array RANGES = ['today', '7d', '30d', 'month'];
-
- /** A product with this many or fewer left shows in "Needs attention". */
- public const int LOW_STOCK = 5;
-
- /**
- * @return array<string, mixed>
- */
- public function for(User $user, string $range, ?Store $store, ?CarbonImmutable $now = null): array
- {
- $now = ($now ?? CarbonImmutable::now())->setTimezone(self::TIMEZONE);
- $range = in_array($range, self::RANGES, true) ? $range : '30d';
-
- /** @var Collection<int, Store> $stores */
- $stores = $user->stores()->orderBy('created_at')->get();
- $storeIds = $store !== null ? [$store->id] : $stores->pluck('id')->all();
-
- [$start, $previousStart, $buckets] = $this->period($range, $now);
- $previousEnd = $this->shift($range, $now);
-
- $orders = Order::query()
- ->whereIn('store_id', $stores->pluck('id'))
- ->where('status', OrderStatus::Paid)
- ->where('paid_at', '>=', $previousStart->utc())
- ->where('paid_at', '<=', $now->utc())
- ->get(['id', 'store_id', 'total', 'paid_at']);
-
- $current = $orders->filter(fn (Order $order) => $order->paid_at >= $start);
- $previous = $orders->filter(fn (Order $order) => $order->paid_at < $start && $order->paid_at <= $previousEnd);
- $mine = fn (Collection $list) => $list->whereIn('store_id', $storeIds);
-
- $sales = $mine($current)->sum('total') / 100;
- $previousSales = $mine($previous)->sum('total') / 100;
- $count = $mine($current)->count();
- $previousCount = $mine($previous)->count();
-
- return [
- 'range' => $range,
- 'label' => $this->label($range, $now),
- 'compare_label' => match ($range) {
- 'today' => 'vs yesterday at this time',
- '7d' => 'vs the 7 days before',
- '30d' => 'vs the 30 days before',
- 'month' => 'vs the same days last month',
- },
- 'sales' => round($sales, 2),
- 'previous_sales' => round($previousSales, 2),
- 'sales_change' => $this->change($sales, $previousSales),
- 'orders' => $count,
- 'previous_orders' => $previousCount,
- 'average' => $count > 0 ? round($sales / $count, 2) : 0,
- 'previous_average' => $previousCount > 0 ? round($previousSales / $previousCount, 2) : 0,
- 'series' => $this->series($range, $buckets, $start, $previousStart, $mine($current), $mine($previous)),
- 'to_ship' => $this->toShip($storeIds, $now),
- 'attention' => $this->attention($user, $stores, $storeIds, $now),
- 'by_store' => $stores->map(function (Store $each) use ($current, $store) {
- $storeSales = $current->where('store_id', $each->id)->sum('total') / 100;
- $allSales = $current->sum('total') / 100;
-
- return [
- 'name' => $each->name,
- 'slug' => $each->slug,
- 'is_published' => $each->isPublished(),
- 'sales' => round($storeSales, 2),
- 'share' => $allSales > 0 ? (int) round($storeSales / $allSales * 100) : 0,
- 'selected' => $store?->id === $each->id,
- ];
- })->values()->all(),
- 'top_products' => $this->topProducts($storeIds, $start, $now, $stores),
- 'recent_orders' => $this->recentOrders($storeIds, $stores),
- ];
- }
-
- /**
- * Whether any of the merchant's stores has ever had a paid order. Until then the dashboard shows
- * the "Get your first sale" steps instead of empty charts.
- */
- public function hasSales(User $user): bool
- {
- return Order::query()
- ->whereIn('store_id', $user->stores()->select('id'))
- ->where('status', OrderStatus::Paid)
- ->exists();
- }
-
- /**
- * The four steps to a first sale, and which are done.
- *
- * @return array{store: array{name: string, slug: string}|null, steps: array<string, bool>}
- */
- public function gettingStarted(User $user): array
- {
- $stores = $user->stores()->orderBy('created_at')->get();
- $first = $stores->first();
-
- return [
- 'store' => $first !== null ? ['name' => $first->name, 'slug' => $first->slug] : null,
- 'steps' => [
- 'create' => $stores->isNotEmpty(),
- 'design' => $stores->contains(fn (Store $store) => $store->plan !== null),
- 'products' => Product::query()->whereIn('store_id', $stores->pluck('id'))->where('status', ProductStatus::Active)->exists(),
- 'publish' => $stores->contains(fn (Store $store) => $store->isPublished()),
- ],
- ];
- }
-
- /**
- * Where the range starts, where the period before it starts, and how many points the chart has.
- *
- * @return array{0: CarbonImmutable, 1: CarbonImmutable, 2: int}
- */
- private function period(string $range, CarbonImmutable $now): array
- {
- $today = $now->startOfDay();
-
- return match ($range) {
- 'today' => [$today, $today->subDay(), $now->hour + 1],
- '7d' => [$today->subDays(6), $today->subDays(13), 7],
- '30d' => [$today->subDays(29), $today->subDays(59), 30],
- 'month' => [$now->startOfMonth(), $now->startOfMonth()->subMonthNoOverflow(), $now->day],
- };
- }
-
- /**
- * The same moment in the period before. Orders after it are left out, so a half-finished
- * day is compared with the same half of the day before.
- */
- private function shift(string $range, CarbonImmutable $moment): CarbonImmutable
- {
- return match ($range) {
- 'today' => $moment->subDay(),
- '7d' => $moment->subDays(7),
- '30d' => $moment->subDays(30),
- 'month' => $moment->subMonthNoOverflow(),
- };
- }
-
- private function label(string $range, CarbonImmutable $now): string
- {
- return match ($range) {
- 'today' => 'Today, by hour',
- '7d' => 'Last 7 days',
- '30d' => 'Last 30 days',
- 'month' => $now->day === 1 ? $now->format('j F') : '1 to '.$now->format('j F'),
- };
- }
-
- /**
- * The change in percent, or null when there is nothing to compare with.
- */
- private function change(float $now, float $before): ?int
- {
- return $before > 0 ? (int) round(($now - $before) / $before * 100) : null;
- }
-
- /**
- * One point per hour (today) or per day, for this period and the one before.
- *
- * @param Collection<int, Order> $current
- * @param Collection<int, Order> $previous
- * @return list<array{label: string, sales: float, previous: float, orders: int}>
- */
- private function series(string $range, int $buckets, CarbonImmutable $start, CarbonImmutable $previousStart, Collection $current, Collection $previous): array
- {
- $index = function (Order $order, CarbonImmutable $from) use ($range): int {
- $paid = CarbonImmutable::parse($order->paid_at)->setTimezone(self::TIMEZONE);
-
- return $range === 'today'
- ? $paid->hour
- : (int) $from->diffInDays($paid->startOfDay());
- };
-
- $points = [];
-
- for ($i = 0; $i < $buckets; $i++) {
- $moment = $range === 'today' ? $start->addHours($i) : $start->addDays($i);
- $points[$i] = [
- 'label' => $range === 'today' ? strtolower($moment->format('ga')) : $moment->format('j M'),
- 'sales' => 0.0,
- 'previous' => 0.0,
- 'orders' => 0,
- ];
- }
-
- foreach ($current as $order) {
- $i = $index($order, $start);
-
- if (isset($points[$i])) {
- $points[$i]['sales'] += $order->total / 100;
- $points[$i]['orders']++;
- }
- }
-
- foreach ($previous as $order) {
- $i = $index($order, $previousStart);
-
- if (isset($points[$i])) {
- $points[$i]['previous'] += $order->total / 100;
- }
- }
-
- return array_map(fn (array $point) => [
- ...$point,
- 'sales' => round($point['sales'], 2),
- 'previous' => round($point['previous'], 2),
- ], array_values($points));
- }
-
- /**
- * Paid orders not shipped yet, and how many days the oldest has waited.
- *
- * @param list<int> $storeIds
- * @return array{count: int, oldest_days: int|null}
- */
- private function toShip(array $storeIds, CarbonImmutable $now): array
- {
- $waiting = Order::query()
- ->whereIn('store_id', $storeIds)
- ->where('status', OrderStatus::Paid)
- ->whereNull('shipped_at');
-
- $oldest = (clone $waiting)->min('paid_at');
-
- return [
- 'count' => $waiting->count(),
- 'oldest_days' => $oldest !== null
- ? (int) CarbonImmutable::parse($oldest, 'UTC')->setTimezone(self::TIMEZONE)->startOfDay()->diffInDays($now->startOfDay())
- : null,
- ];
- }
-
- /**
- * What the merchant should look at now, most urgent first: orders to ship, products running out,
- * designs waiting to be published, and the plan.
- *
- * @param Collection<int, Store> $stores
- * @param list<int> $storeIds
- * @return list<array<string, mixed>>
- */
- private function attention(User $user, Collection $stores, array $storeIds, CarbonImmutable $now): array
- {
- $items = [];
- $shown = $stores->whereIn('id', $storeIds);
-
- foreach ($shown as $store) {
- $ship = $this->toShip([$store->id], $now);
-
- if ($ship['count'] > 0) {
- $items[] = [
- 'kind' => 'ship',
- 'tone' => 'warning',
- 'title' => $ship['count'] === 1 ? '1 order to ship' : $ship['count'].' orders to ship',
- 'note' => match (true) {
- $ship['oldest_days'] === 0 => 'Paid today',
- $ship['oldest_days'] === 1 => 'Oldest waited 1 day',
- default => 'Oldest waited '.$ship['oldest_days'].' days',
- },
- 'store' => ['name' => $store->name, 'slug' => $store->slug],
- ];
- }
- }
-
- $lowStock = Product::query()
- ->whereIn('store_id', $storeIds)
- ->where('status', ProductStatus::Active)
- ->where('is_bundle', false)
- ->where('stock', '<=', self::LOW_STOCK)
- ->orderBy('stock')
- ->limit(4)
- ->get(['id', 'store_id', 'name', 'stock']);
-
- foreach ($lowStock as $product) {
- $store = $stores->firstWhere('id', $product->store_id);
- $items[] = [
- 'kind' => 'restock',
- 'tone' => 'danger',
- 'title' => $product->stock === 0 ? $product->name.' is out of stock' : $product->name.' is almost out',
- 'note' => $product->stock === 0 ? 'Shoppers can’t buy it now' : 'Only '.$product->stock.' left',
- 'store' => ['name' => $store->name, 'slug' => $store->slug],
- 'product_id' => $product->id,
- ];
- }
-
- foreach ($shown as $store) {
- if ($store->hasUnpublishedChanges()) {
- $items[] = [
- 'kind' => 'publish',
- 'tone' => 'brand',
- 'title' => 'Design changes not published',
- 'note' => 'Shoppers still see the old design',
- 'store' => ['name' => $store->name, 'slug' => $store->slug],
- ];
- }
- }
-
- // Designed but never published. Several of them make one line, so the list stays short.
- $ready = $shown->filter(fn (Store $store) => $store->plan !== null && ! $store->isPublished())->values();
-
- if ($ready->count() === 1) {
- $items[] = [
- 'kind' => 'publish',
- 'tone' => 'brand',
- 'title' => $ready[0]->name.' is ready to publish',
- 'note' => 'Shoppers can’t see it yet',
- 'store' => ['name' => $ready[0]->name, 'slug' => $ready[0]->slug],
- ];
- } elseif ($ready->count() > 1) {
- $names = $ready->pluck('name');
- $items[] = [
- 'kind' => 'publish',
- 'tone' => 'brand',
- 'title' => $ready->count().' stores are not published',
- 'note' => $ready->count() === 2
- ? $names->join(' and ')
- : $names->take(2)->join(', ').' and '.($ready->count() - 2).' more',
- 'store' => ['name' => $ready[0]->name, 'slug' => $ready[0]->slug],
- ];
- }
-
- $plan = $user->currentPlan();
-
- if ($plan === null) {
- $items[] = ['kind' => 'plan', 'tone' => 'danger', 'title' => 'Your plan has ended', 'note' => 'Your stores are offline until you choose a plan', 'store' => null];
- } elseif (! $plan->isPaid() && $user->trial_ends_at !== null) {
- $days = (int) ceil($now->diffInDays($user->trial_ends_at, false));
-
- if ($days <= 7) {
- $items[] = [
- 'kind' => 'plan',
- 'tone' => 'brand',
- 'title' => $days <= 1 ? 'Your trial ends today' : 'Your trial ends in '.$days.' days',
- 'note' => 'Choose a plan to keep your stores online',
- 'store' => null,
- ];
- }
- }
-
- return $items;
- }
-
- /**
- * The best sellers in the range, by money taken.
- *
- * @param list<int> $storeIds
- * @param Collection<int, Store> $stores
- * @return list<array<string, mixed>>
- */
- private function topProducts(array $storeIds, CarbonImmutable $start, CarbonImmutable $now, Collection $stores): array
- {
- // One line per product, even when it was sold in several options. Products deleted since keep their old name.
- $rows = OrderItem::query()
- ->join('orders', 'orders.id', '=', 'order_items.order_id')
- ->whereIn('order_items.store_id', $storeIds)
- ->where('orders.status', OrderStatus::Paid)
- ->where('orders.paid_at', '>=', $start->utc())
- ->where('orders.paid_at', '<=', $now->utc())
- ->groupBy('order_items.store_id', 'order_items.product_id')
- ->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')
- ->orderByDesc('revenue')
- ->limit(5)
- ->get();
-
- $names = Product::query()->whereIn('id', $rows->pluck('product_id')->filter())->pluck('name', 'id');
-
- return $rows
- ->map(function (OrderItem $item) use ($stores, $names) {
- $store = $stores->firstWhere('id', $item->store_id);
-
- return [
- 'name' => $names[$item->product_id] ?? $item->name,
- 'product_id' => isset($names[$item->product_id]) ? $item->product_id : null,
- 'store' => ['name' => $store?->name, 'slug' => $store?->slug],
- 'units' => (int) $item->getAttribute('units'),
- 'revenue' => round((int) $item->getAttribute('revenue') / 100, 2),
- ];
- })
- ->all();
- }
-
- /**
- * The newest paid orders.
- *
- * @param list<int> $storeIds
- * @param Collection<int, Store> $stores
- * @return list<array<string, mixed>>
- */
- private function recentOrders(array $storeIds, Collection $stores): array
- {
- return Order::query()
- ->whereIn('store_id', $storeIds)
- ->where('status', OrderStatus::Paid)
- ->latest('paid_at')
- ->limit(5)
- ->get()
- ->map(function (Order $order) use ($stores) {
- $store = $stores->firstWhere('id', $order->store_id);
-
- return [
- 'id' => $order->id,
- 'number' => $order->number,
- 'customer_name' => $order->customer_name,
- 'state' => $order->shipping_address['state'] ?? null,
- 'total' => $order->total / 100,
- 'shipped' => $order->shipped_at !== null,
- 'paid_at' => $order->paid_at?->toIso8601String(),
- 'store' => ['name' => $store?->name, 'slug' => $store?->slug],
- ];
- })
- ->all();
- }
- }
|