| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- <?php
-
- namespace App\Dashboard;
-
- use App\Ai\AiException;
- use App\Ai\AiManager;
- use App\Models\DashboardPulse;
- use App\Models\Store;
- use App\Models\User;
- use App\StorePlan\Ai\JsonAnswer;
- use Carbon\CarbonImmutable;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Str;
-
- /**
- * The "Store pulse": a two-sentence note at the top of the dashboard about how the stores are doing
- * and what to do first.
- *
- * - Written once per Malaysian day for each view (all stores, or one store), then saved. Opening or
- * refreshing the dashboard reads the saved note and never asks the AI again.
- * - "Write again" asks for a fresh note, up to config('ai.pulse.daily_rewrites') times a day in all.
- * It does not count toward the plan's AI changes.
- * - Only numbers, store names and product names go to the AI. Never shoppers' names or addresses.
- * - When the AI cannot answer, the note is written from the numbers instead, so the card never breaks.
- * - Merchants with no sales yet get no note: the dashboard shows the first-sale steps instead.
- * - The buttons under the note are worked out by us from the numbers, not by the AI.
- */
- class StorePulse
- {
- public function __construct(
- private readonly AiManager $ai,
- private readonly OverviewStats $stats,
- ) {}
-
- /**
- * Today's note for this view: the saved one, or a new one written now.
- *
- * @return array<string, mixed>|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<string, mixed> $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<string, mixed> $stats
- * @return array<string, mixed>|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<string, mixed> $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<string, mixed> $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<string, mixed> $stats
- * @return list<array<string, mixed>>
- */
- 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<string, mixed> $stats
- * @return array<string, mixed>
- */
- 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);
- }
- }
|