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.

StorePulse.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. namespace App\Dashboard;
  3. use App\Ai\AiException;
  4. use App\Ai\AiManager;
  5. use App\Models\DashboardPulse;
  6. use App\Models\Store;
  7. use App\Models\User;
  8. use App\StorePlan\Ai\JsonAnswer;
  9. use Carbon\CarbonImmutable;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Str;
  12. /**
  13. * The "Store pulse": a two-sentence note at the top of the dashboard about how the stores are doing
  14. * and what to do first.
  15. *
  16. * - Written once per Malaysian day for each view (all stores, or one store), then saved. Opening or
  17. * refreshing the dashboard reads the saved note and never asks the AI again.
  18. * - "Write again" asks for a fresh note, up to config('ai.pulse.daily_rewrites') times a day in all.
  19. * It does not count toward the plan's AI changes.
  20. * - Only numbers, store names and product names go to the AI. Never shoppers' names or addresses.
  21. * - When the AI cannot answer, the note is written from the numbers instead, so the card never breaks.
  22. * - Merchants with no sales yet get no note: the dashboard shows the first-sale steps instead.
  23. * - The buttons under the note are worked out by us from the numbers, not by the AI.
  24. */
  25. class StorePulse
  26. {
  27. public function __construct(
  28. private readonly AiManager $ai,
  29. private readonly OverviewStats $stats,
  30. ) {}
  31. /**
  32. * Today's note for this view: the saved one, or a new one written now.
  33. *
  34. * @return array<string, mixed>|null
  35. */
  36. public function today(User $user, ?Store $store, ?CarbonImmutable $now = null): ?array
  37. {
  38. $now = $this->now($now);
  39. if (! $this->stats->hasSales($user)) {
  40. return null;
  41. }
  42. $stats = $this->stats->for($user, 'month', $store, $now);
  43. $pulse = $this->find($user, $store, $now) ?? $this->write($user, $store, $stats, $now);
  44. return $this->present($user, $pulse, $stats, $now);
  45. }
  46. /**
  47. * "Write again": replace today's note with a fresh one, if the daily limit allows.
  48. *
  49. * @return bool False when the limit is used up or the AI could not answer. The old note stays.
  50. */
  51. public function rewrite(User $user, ?Store $store, ?CarbonImmutable $now = null): bool
  52. {
  53. $now = $this->now($now);
  54. if ($this->rewritesLeft($user, $now) <= 0 || ! $this->stats->hasSales($user)) {
  55. return false;
  56. }
  57. $stats = $this->stats->for($user, 'month', $store, $now);
  58. $pulse = $this->find($user, $store, $now) ?? $this->write($user, $store, $stats, $now);
  59. $answer = $this->ask($user, $store, $stats);
  60. if ($answer === null) {
  61. return false;
  62. }
  63. $pulse->fill([...$answer, 'rewrites' => $pulse->rewrites + 1])->save();
  64. return true;
  65. }
  66. public function rewritesLeft(User $user, ?CarbonImmutable $now = null): int
  67. {
  68. $used = (int) DashboardPulse::query()
  69. ->where('user_id', $user->id)
  70. ->where('day', $this->now($now)->toDateString())
  71. ->sum('rewrites');
  72. return max(0, $this->limit() - $used);
  73. }
  74. public function limit(): int
  75. {
  76. return max(0, (int) config('ai.pulse.daily_rewrites', 3));
  77. }
  78. private function find(User $user, ?Store $store, CarbonImmutable $now): ?DashboardPulse
  79. {
  80. return DashboardPulse::query()
  81. ->where('user_id', $user->id)
  82. ->where('store_id', $store?->id)
  83. ->where('day', $now->toDateString())
  84. ->first();
  85. }
  86. /**
  87. * @param array<string, mixed> $stats
  88. */
  89. private function write(User $user, ?Store $store, array $stats, CarbonImmutable $now): DashboardPulse
  90. {
  91. $answer = $this->ask($user, $store, $stats) ?? [
  92. 'summary' => $this->fromNumbers($stats, $store),
  93. 'source' => 'numbers',
  94. 'provider' => null,
  95. 'model' => null,
  96. 'input_tokens' => 0,
  97. 'output_tokens' => 0,
  98. ];
  99. // Two tabs opening the dashboard at once could both get here; the second one keeps the first note.
  100. return DashboardPulse::query()->firstOrCreate(
  101. ['user_id' => $user->id, 'store_id' => $store?->id, 'day' => $now->toDateString()],
  102. $answer,
  103. );
  104. }
  105. /**
  106. * Ask the AI for a note. Null when it could not give a usable one.
  107. *
  108. * @param array<string, mixed> $stats
  109. * @return array<string, mixed>|null
  110. */
  111. private function ask(User $user, ?Store $store, array $stats): ?array
  112. {
  113. try {
  114. $response = $this->ai->ask('pulse', $this->system(), $this->prompt($store, $stats));
  115. $summary = JsonAnswer::decode($response->text)['summary'] ?? null;
  116. } catch (AiException $exception) {
  117. Log::warning('Store pulse: the AI could not write a note.', ['user' => $user->id, 'error' => $exception->getMessage()]);
  118. return null;
  119. }
  120. if (! is_string($summary) || trim($summary) === '') {
  121. return null;
  122. }
  123. return [
  124. 'summary' => Str::limit(trim(preg_replace('/\s+/', ' ', strip_tags($summary)) ?? ''), 400),
  125. 'source' => 'ai',
  126. 'provider' => $response->provider,
  127. 'model' => $response->model,
  128. 'input_tokens' => $response->inputTokens,
  129. 'output_tokens' => $response->outputTokens,
  130. ];
  131. }
  132. private function system(): string
  133. {
  134. return <<<'TEXT'
  135. You write the short daily note at the top of an online seller's dashboard. The seller runs small
  136. online stores in Malaysia and reads this on their phone.
  137. Rules:
  138. - Use only the facts you are given. Never invent numbers, products, customers or reasons.
  139. - Two sentences, 45 words at most. Plain, warm, everyday English. No greeting, no emoji, no lists.
  140. - First say how sales are going, then the one or two most useful things to do today, most urgent first.
  141. - Money is in ringgit, written like RM 1,240.
  142. - Answer with JSON only: {"summary": "..."}
  143. TEXT;
  144. }
  145. /**
  146. * The facts for the AI. Numbers, store names and product names only.
  147. *
  148. * @param array<string, mixed> $stats
  149. */
  150. private function prompt(?Store $store, array $stats): string
  151. {
  152. $lines = [
  153. 'View: '.($store !== null ? 'one store, '.$store->name : 'all stores together'),
  154. 'Sales this month so far: '.$this->money($stats['sales']).' from '.$stats['orders'].' paid orders',
  155. 'Same days last month: '.$this->money($stats['previous_sales']).' from '.$stats['previous_orders'].' paid orders',
  156. ];
  157. if ($store === null && count($stats['by_store']) > 1) {
  158. foreach ($stats['by_store'] as $each) {
  159. $lines[] = 'Store '.$each['name'].': '.$this->money($each['sales']).' this month'.($each['is_published'] ? '' : ' (not published)');
  160. }
  161. }
  162. foreach (array_slice($stats['top_products'], 0, 3) as $product) {
  163. $lines[] = 'Best seller: '.$product['name'].', '.$product['units'].' sold this month';
  164. }
  165. $lines[] = 'Paid orders waiting to ship: '.$stats['to_ship']['count']
  166. .($stats['to_ship']['oldest_days'] ? ' (oldest waited '.$stats['to_ship']['oldest_days'].' days)' : '');
  167. foreach ($stats['attention'] as $item) {
  168. if (in_array($item['kind'], ['restock', 'publish', 'plan'], true)) {
  169. $lines[] = 'Needs attention: '.$item['title'].' ('.$item['note'].')'.($item['store'] !== null && $store === null ? ' in '.$item['store']['name'] : '');
  170. }
  171. }
  172. $lines[] = 'Today is '.now()->setTimezone(OverviewStats::TIMEZONE)->format('l, j F Y');
  173. return "Facts:\n- ".implode("\n- ", $lines);
  174. }
  175. /**
  176. * The note we write ourselves when the AI cannot.
  177. *
  178. * @param array<string, mixed> $stats
  179. */
  180. private function fromNumbers(array $stats, ?Store $store): string
  181. {
  182. $change = $stats['sales_change'];
  183. $first = 'Sales this month are '.$this->money($stats['sales'])
  184. .match (true) {
  185. $change === null => '',
  186. $change > 0 => ', up '.$change.'% on the same days last month',
  187. $change < 0 => ', down '.abs($change).'% on the same days last month',
  188. default => ', the same as last month',
  189. }.'.';
  190. $ship = $stats['to_ship']['count'];
  191. $restock = collect($stats['attention'])->firstWhere('kind', 'restock');
  192. $next = match (true) {
  193. $ship > 0 && $restock !== null => ' Ship the '.$ship.' waiting '.($ship === 1 ? 'order' : 'orders').' first, then restock '.$this->productName($restock['title']).'.',
  194. $ship > 0 => ' Ship the '.$ship.' waiting '.($ship === 1 ? 'order' : 'orders').' first.',
  195. $restock !== null => ' Restock '.$this->productName($restock['title']).' before it runs out.',
  196. default => ' Nothing urgent today.',
  197. };
  198. return $first.$next;
  199. }
  200. /**
  201. * Up to three buttons under the note, from the numbers.
  202. *
  203. * @param array<string, mixed> $stats
  204. * @return list<array<string, mixed>>
  205. */
  206. private function actions(array $stats): array
  207. {
  208. $actions = [];
  209. $attention = collect($stats['attention']);
  210. $ship = $attention->where('kind', 'ship');
  211. if ($ship->isNotEmpty()) {
  212. $actions[] = [
  213. 'kind' => 'ship',
  214. 'label' => 'Ship '.$stats['to_ship']['count'].' '.($stats['to_ship']['count'] === 1 ? 'order' : 'orders'),
  215. // With several stores, the button opens the store with the most waiting.
  216. 'store_slug' => $ship->first()['store']['slug'],
  217. ];
  218. }
  219. foreach ($attention->where('kind', 'restock')->take(2) as $item) {
  220. $actions[] = [
  221. 'kind' => 'restock',
  222. 'label' => 'Restock '.$this->productName($item['title']),
  223. 'store_slug' => $item['store']['slug'],
  224. 'product_id' => $item['product_id'],
  225. ];
  226. }
  227. $publish = $attention->firstWhere('kind', 'publish');
  228. if ($publish !== null) {
  229. $actions[] = ['kind' => 'publish', 'label' => 'Publish '.$publish['store']['name'], 'store_slug' => $publish['store']['slug']];
  230. }
  231. return array_slice($actions, 0, 3);
  232. }
  233. /**
  234. * @param array<string, mixed> $stats
  235. * @return array<string, mixed>
  236. */
  237. private function present(User $user, DashboardPulse $pulse, array $stats, CarbonImmutable $now): array
  238. {
  239. return [
  240. 'summary' => $pulse->summary,
  241. 'source' => $pulse->source,
  242. 'written_at' => $pulse->updated_at?->toIso8601String(),
  243. 'actions' => $this->actions($stats),
  244. 'rewrites_left' => $this->rewritesLeft($user, $now),
  245. 'rewrites_limit' => $this->limit(),
  246. ];
  247. }
  248. /** "Sambal hijau is almost out" → "Sambal hijau". */
  249. private function productName(string $title): string
  250. {
  251. return (string) preg_replace('/ is (almost out|out of stock)$/', '', $title);
  252. }
  253. private function money(float|int $amount): string
  254. {
  255. return 'RM '.number_format($amount, $amount == floor($amount) ? 0 : 2);
  256. }
  257. private function now(?CarbonImmutable $now): CarbonImmutable
  258. {
  259. return ($now ?? CarbonImmutable::now())->setTimezone(OverviewStats::TIMEZONE);
  260. }
  261. }