*/ 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 */ 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 $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} */ 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 $current * @param Collection $previous * @return list */ 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 $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 $stores * @param list $storeIds * @return list> */ 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 $storeIds * @param Collection $stores * @return list> */ 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 $storeIds * @param Collection $stores * @return list> */ 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(); } }