|null */ public function today(User $user, ?Store $store, ?CarbonImmutable $now = null): ?array { $now = $this->now($now); if (! $this->stats->hasSales($user)) { return null; } $stats = $this->stats->for($user, 'month', $store, $now); $pulse = $this->find($user, $store, $now) ?? $this->write($user, $store, $stats, $now); return $this->present($user, $pulse, $stats, $now); } /** * "Write again": replace today's note with a fresh one, if the daily limit allows. * * @return bool False when the limit is used up or the AI could not answer. The old note stays. */ public function rewrite(User $user, ?Store $store, ?CarbonImmutable $now = null): bool { $now = $this->now($now); if ($this->rewritesLeft($user, $now) <= 0 || ! $this->stats->hasSales($user)) { return false; } $stats = $this->stats->for($user, 'month', $store, $now); $pulse = $this->find($user, $store, $now) ?? $this->write($user, $store, $stats, $now); $answer = $this->ask($user, $store, $stats); if ($answer === null) { return false; } $pulse->fill([...$answer, 'rewrites' => $pulse->rewrites + 1])->save(); return true; } public function rewritesLeft(User $user, ?CarbonImmutable $now = null): int { $used = (int) DashboardPulse::query() ->where('user_id', $user->id) ->where('day', $this->now($now)->toDateString()) ->sum('rewrites'); return max(0, $this->limit() - $used); } public function limit(): int { return max(0, (int) config('ai.pulse.daily_rewrites', 3)); } private function find(User $user, ?Store $store, CarbonImmutable $now): ?DashboardPulse { return DashboardPulse::query() ->where('user_id', $user->id) ->where('store_id', $store?->id) ->where('day', $now->toDateString()) ->first(); } /** * @param array $stats */ private function write(User $user, ?Store $store, array $stats, CarbonImmutable $now): DashboardPulse { $answer = $this->ask($user, $store, $stats) ?? [ 'summary' => $this->fromNumbers($stats, $store), 'source' => 'numbers', 'provider' => null, 'model' => null, 'input_tokens' => 0, 'output_tokens' => 0, ]; // Two tabs opening the dashboard at once could both get here; the second one keeps the first note. return DashboardPulse::query()->firstOrCreate( ['user_id' => $user->id, 'store_id' => $store?->id, 'day' => $now->toDateString()], $answer, ); } /** * Ask the AI for a note. Null when it could not give a usable one. * * @param array $stats * @return array|null */ private function ask(User $user, ?Store $store, array $stats): ?array { try { $response = $this->ai->ask('pulse', $this->system(), $this->prompt($store, $stats)); $summary = JsonAnswer::decode($response->text)['summary'] ?? null; } catch (AiException $exception) { Log::warning('Store pulse: the AI could not write a note.', ['user' => $user->id, 'error' => $exception->getMessage()]); return null; } if (! is_string($summary) || trim($summary) === '') { return null; } return [ 'summary' => Str::limit(trim(preg_replace('/\s+/', ' ', strip_tags($summary)) ?? ''), 400), 'source' => 'ai', 'provider' => $response->provider, 'model' => $response->model, 'input_tokens' => $response->inputTokens, 'output_tokens' => $response->outputTokens, ]; } private function system(): string { return <<<'TEXT' You write the short daily note at the top of an online seller's dashboard. The seller runs small online stores in Malaysia and reads this on their phone. Rules: - Use only the facts you are given. Never invent numbers, products, customers or reasons. - Two sentences, 45 words at most. Plain, warm, everyday English. No greeting, no emoji, no lists. - First say how sales are going, then the one or two most useful things to do today, most urgent first. - Money is in ringgit, written like RM 1,240. - Answer with JSON only: {"summary": "..."} TEXT; } /** * The facts for the AI. Numbers, store names and product names only. * * @param array $stats */ private function prompt(?Store $store, array $stats): string { $lines = [ 'View: '.($store !== null ? 'one store, '.$store->name : 'all stores together'), 'Sales this month so far: '.$this->money($stats['sales']).' from '.$stats['orders'].' paid orders', 'Same days last month: '.$this->money($stats['previous_sales']).' from '.$stats['previous_orders'].' paid orders', ]; if ($store === null && count($stats['by_store']) > 1) { foreach ($stats['by_store'] as $each) { $lines[] = 'Store '.$each['name'].': '.$this->money($each['sales']).' this month'.($each['is_published'] ? '' : ' (not published)'); } } foreach (array_slice($stats['top_products'], 0, 3) as $product) { $lines[] = 'Best seller: '.$product['name'].', '.$product['units'].' sold this month'; } $lines[] = 'Paid orders waiting to ship: '.$stats['to_ship']['count'] .($stats['to_ship']['oldest_days'] ? ' (oldest waited '.$stats['to_ship']['oldest_days'].' days)' : ''); foreach ($stats['attention'] as $item) { if (in_array($item['kind'], ['restock', 'publish', 'plan'], true)) { $lines[] = 'Needs attention: '.$item['title'].' ('.$item['note'].')'.($item['store'] !== null && $store === null ? ' in '.$item['store']['name'] : ''); } } $lines[] = 'Today is '.now()->setTimezone(OverviewStats::TIMEZONE)->format('l, j F Y'); return "Facts:\n- ".implode("\n- ", $lines); } /** * The note we write ourselves when the AI cannot. * * @param array $stats */ private function fromNumbers(array $stats, ?Store $store): string { $change = $stats['sales_change']; $first = 'Sales this month are '.$this->money($stats['sales']) .match (true) { $change === null => '', $change > 0 => ', up '.$change.'% on the same days last month', $change < 0 => ', down '.abs($change).'% on the same days last month', default => ', the same as last month', }.'.'; $ship = $stats['to_ship']['count']; $restock = collect($stats['attention'])->firstWhere('kind', 'restock'); $next = match (true) { $ship > 0 && $restock !== null => ' Ship the '.$ship.' waiting '.($ship === 1 ? 'order' : 'orders').' first, then restock '.$this->productName($restock['title']).'.', $ship > 0 => ' Ship the '.$ship.' waiting '.($ship === 1 ? 'order' : 'orders').' first.', $restock !== null => ' Restock '.$this->productName($restock['title']).' before it runs out.', default => ' Nothing urgent today.', }; return $first.$next; } /** * Up to three buttons under the note, from the numbers. * * @param array $stats * @return list> */ private function actions(array $stats): array { $actions = []; $attention = collect($stats['attention']); $ship = $attention->where('kind', 'ship'); if ($ship->isNotEmpty()) { $actions[] = [ 'kind' => 'ship', 'label' => 'Ship '.$stats['to_ship']['count'].' '.($stats['to_ship']['count'] === 1 ? 'order' : 'orders'), // With several stores, the button opens the store with the most waiting. 'store_slug' => $ship->first()['store']['slug'], ]; } foreach ($attention->where('kind', 'restock')->take(2) as $item) { $actions[] = [ 'kind' => 'restock', 'label' => 'Restock '.$this->productName($item['title']), 'store_slug' => $item['store']['slug'], 'product_id' => $item['product_id'], ]; } $publish = $attention->firstWhere('kind', 'publish'); if ($publish !== null) { $actions[] = ['kind' => 'publish', 'label' => 'Publish '.$publish['store']['name'], 'store_slug' => $publish['store']['slug']]; } return array_slice($actions, 0, 3); } /** * @param array $stats * @return array */ private function present(User $user, DashboardPulse $pulse, array $stats, CarbonImmutable $now): array { return [ 'summary' => $pulse->summary, 'source' => $pulse->source, 'written_at' => $pulse->updated_at?->toIso8601String(), 'actions' => $this->actions($stats), 'rewrites_left' => $this->rewritesLeft($user, $now), 'rewrites_limit' => $this->limit(), ]; } /** "Sambal hijau is almost out" → "Sambal hijau". */ private function productName(string $title): string { return (string) preg_replace('/ is (almost out|out of stock)$/', '', $title); } private function money(float|int $amount): string { return 'RM '.number_format($amount, $amount == floor($amount) ? 0 : 2); } private function now(?CarbonImmutable $now): CarbonImmutable { return ($now ?? CarbonImmutable::now())->setTimezone(OverviewStats::TIMEZONE); } }