AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatActions.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. namespace App\Commerce;
  3. use App\Enums\ProductStatus;
  4. use App\Http\Requests\Products\SaveProductRequest;
  5. use App\Models\BundleItem;
  6. use App\Models\DiscountCode;
  7. use App\Models\Product;
  8. use App\Models\ProductVariant;
  9. use App\Models\Store;
  10. use Closure;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Validator;
  13. use Illuminate\Validation\ValidationException;
  14. /**
  15. * Store changes asked for in the chat, such as "make a 10% code RAYA10" or "set the moisturiser to RM 35".
  16. *
  17. * The AI only proposes them. check() makes sure each one is allowed and writes a plain sentence for the
  18. * merchant. Nothing changes until the merchant confirms; then apply() checks everything again (the store
  19. * may have changed in between) and does all of them, or none.
  20. *
  21. * The rules are the same as the Products and Discounts forms, so chat can never do what a form would refuse.
  22. */
  23. final class ChatActions
  24. {
  25. public const int MAX_ACTIONS = 5;
  26. public const array TYPES = ['create_product', 'update_product', 'create_discount', 'update_discount', 'create_bundle'];
  27. /**
  28. * Check the actions in an AI answer. Returns each with its cleaned input and a sentence for the merchant.
  29. *
  30. * @return list<array{type: string, input: array<string, mixed>, summary: string}>
  31. *
  32. * @throws ValidationException With keys such as "actions.0.price", so the AI can correct them.
  33. */
  34. public static function check(Store $store, mixed $actions): array
  35. {
  36. if ($actions === null || $actions === []) {
  37. return [];
  38. }
  39. if (! is_array($actions) || ! array_is_list($actions)) {
  40. throw ValidationException::withMessages(['actions' => 'Must be a list of actions.']);
  41. }
  42. if (count($actions) > self::MAX_ACTIONS) {
  43. throw ValidationException::withMessages(['actions' => 'At most '.self::MAX_ACTIONS.' actions at a time.']);
  44. }
  45. $checked = [];
  46. foreach ($actions as $index => $action) {
  47. $prepared = self::prepare($store, $action, $index);
  48. $checked[] = ['type' => $prepared['type'], 'input' => $prepared['input'], 'summary' => $prepared['summary']];
  49. }
  50. return $checked;
  51. }
  52. /**
  53. * Do actions the merchant confirmed, in order, all or nothing. Each is checked again first.
  54. *
  55. * @param list<array{type: string, input: array<string, mixed>, summary: string}> $actions
  56. *
  57. * @throws ValidationException When one is no longer allowed. Nothing is changed then.
  58. */
  59. public static function apply(Store $store, array $actions): void
  60. {
  61. DB::transaction(function () use ($store, $actions): void {
  62. foreach ($actions as $index => $action) {
  63. // Each one sees what the ones before it did, such as a product created a step earlier.
  64. (self::prepare($store, ['type' => $action['type'], ...$action['input']], $index)['run'])();
  65. }
  66. BundleStock::refresh($store->id);
  67. });
  68. }
  69. /**
  70. * @return array{type: string, input: array<string, mixed>, summary: string, run: Closure(): void}
  71. *
  72. * @throws ValidationException
  73. */
  74. private static function prepare(Store $store, mixed $action, int $index): array
  75. {
  76. $type = is_array($action) ? ($action['type'] ?? null) : null;
  77. if (! is_string($type) || ! in_array($type, self::TYPES, true)) {
  78. throw ValidationException::withMessages(["actions.$index.type" => 'Must be one of: '.implode(', ', self::TYPES).'.']);
  79. }
  80. unset($action['type']);
  81. try {
  82. $prepared = match ($type) {
  83. 'create_product' => self::createProduct($store, $action),
  84. 'update_product' => self::updateProduct($store, $action),
  85. 'create_discount' => self::createDiscount($store, $action),
  86. 'update_discount' => self::updateDiscount($store, $action),
  87. 'create_bundle' => self::createBundle($store, $action),
  88. };
  89. } catch (ValidationException $e) {
  90. // "price" becomes "actions.2.price", so it is clear which action has the problem.
  91. $messages = [];
  92. foreach ($e->errors() as $field => $errors) {
  93. $messages["actions.$index.$field"] = $errors;
  94. }
  95. throw ValidationException::withMessages($messages);
  96. }
  97. return ['type' => $type, ...$prepared];
  98. }
  99. /**
  100. * @param array<string, mixed> $input
  101. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  102. */
  103. private static function createProduct(Store $store, array $input): array
  104. {
  105. $data = self::validate($input, [
  106. 'name' => ['required', 'string', 'min:2', 'max:120'],
  107. 'description' => ['nullable', 'string', 'max:5000'],
  108. 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  109. 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
  110. 'stock' => ['required', 'integer', 'min:0', 'max:1000000'],
  111. 'status' => ['nullable', 'in:active,draft'],
  112. ]);
  113. $data['status'] ??= ProductStatus::Active->value;
  114. $summary = "Add the product \"{$data['name']}\" at ".self::money(self::sen($data['price']))
  115. .self::wasPrice($data['compare_at_price'] ?? null)
  116. .", {$data['stock']} in stock, "
  117. .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft');
  118. return [
  119. 'input' => $data,
  120. 'summary' => $summary,
  121. 'run' => function () use ($store, $data): void {
  122. $store->products()->create([
  123. 'name' => $data['name'],
  124. 'description' => $data['description'] ?? null,
  125. 'price' => self::sen($data['price']),
  126. 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
  127. 'stock' => (int) $data['stock'],
  128. 'status' => $data['status'],
  129. ]);
  130. },
  131. ];
  132. }
  133. /**
  134. * @param array<string, mixed> $input
  135. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  136. */
  137. private static function updateProduct(Store $store, array $input): array
  138. {
  139. $data = self::validate($input, [
  140. 'product' => ['required', 'string'],
  141. 'variant' => ['nullable', 'string', 'max:90'],
  142. 'name' => ['sometimes', 'string', 'min:2', 'max:120'],
  143. 'price' => ['sometimes', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  144. 'compare_at_price' => ['sometimes', 'nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
  145. 'stock' => ['sometimes', 'integer', 'min:0', 'max:1000000'],
  146. 'status' => ['sometimes', 'in:active,draft'],
  147. ]);
  148. $product = self::findProduct($store, $data['product'], 'product');
  149. $priceFields = array_intersect(['price', 'compare_at_price', 'stock'], array_keys($data));
  150. $productFields = array_intersect(['name', 'status'], array_keys($data));
  151. if ($priceFields === [] && $productFields === []) {
  152. self::fail('product', 'Say what to change: name, price, compare_at_price, stock or status.');
  153. }
  154. $variant = null;
  155. if (filled($data['variant'] ?? null)) {
  156. if (! $product->hasVariants()) {
  157. self::fail('variant', "\"{$product->name}\" has no options. Leave out \"variant\".");
  158. }
  159. $variant = self::findVariant($product, $data['variant'], 'variant');
  160. } elseif ($product->hasVariants() && $priceFields !== []) {
  161. self::fail('variant', "\"{$product->name}\" has options, so price and stock belong to one choice. Name it in \"variant\", such as \"".$product->variants->first()?->name().'".');
  162. }
  163. if ($product->isBundle() && array_key_exists('stock', $data)) {
  164. self::fail('stock', "\"{$product->name}\" is a bundle. Its stock comes from the products inside it.");
  165. }
  166. // The "was" price must stay above the price, whichever of the two changes.
  167. $owner = $variant ?? $product;
  168. $newPrice = array_key_exists('price', $data) ? self::sen($data['price']) : $owner->price;
  169. $newCompare = array_key_exists('compare_at_price', $data)
  170. ? (filled($data['compare_at_price']) ? self::sen($data['compare_at_price']) : null)
  171. : $owner->compare_at_price;
  172. if ($newCompare !== null && $newCompare <= $newPrice) {
  173. self::fail('compare_at_price', 'The "was" price must be higher than the price.');
  174. }
  175. $changes = [];
  176. if (array_key_exists('name', $data) && $data['name'] !== $product->name) {
  177. $changes[] = "name to \"{$data['name']}\"";
  178. }
  179. if ($newPrice !== $owner->price) {
  180. $changes[] = 'price '.self::money($owner->price).' → '.self::money($newPrice);
  181. }
  182. if ($newCompare !== $owner->compare_at_price) {
  183. $changes[] = $newCompare === null
  184. ? 'remove the "was" price'
  185. : '"was" price '.($owner->compare_at_price !== null ? self::money($owner->compare_at_price).' → ' : '').self::money($newCompare);
  186. }
  187. if (array_key_exists('stock', $data) && (int) $data['stock'] !== $owner->stock) {
  188. $changes[] = "stock {$owner->stock} → {$data['stock']}";
  189. }
  190. if (array_key_exists('status', $data) && $data['status'] !== $product->status->value) {
  191. $changes[] = $data['status'] === 'active' ? 'show it in the store' : 'hide it (draft)';
  192. }
  193. if ($changes === []) {
  194. self::fail('product', 'These values are already set. Nothing would change.');
  195. }
  196. $label = $product->name.($variant !== null ? ' ('.$variant->name().')' : '');
  197. return [
  198. 'input' => $data,
  199. 'summary' => "Change \"{$label}\": ".implode(', ', $changes),
  200. 'run' => function () use ($product, $variant, $data, $newPrice, $newCompare): void {
  201. $owner = $variant ?? $product;
  202. $owner->price = $newPrice;
  203. $owner->compare_at_price = $newCompare;
  204. if (array_key_exists('stock', $data)) {
  205. $owner->stock = (int) $data['stock'];
  206. }
  207. $owner->save();
  208. if (array_key_exists('name', $data)) {
  209. $product->name = $data['name'];
  210. }
  211. if (array_key_exists('status', $data)) {
  212. $product->status = ProductStatus::from($data['status']);
  213. }
  214. $product->save();
  215. $product->syncFromVariants();
  216. },
  217. ];
  218. }
  219. /**
  220. * @param array<string, mixed> $input
  221. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  222. */
  223. private static function createDiscount(Store $store, array $input): array
  224. {
  225. $input['code'] = DiscountCode::normalize((string) ($input['code'] ?? ''));
  226. $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT;
  227. // The same rules as the Discounts form. The chat names some fields more plainly.
  228. $form = [
  229. 'code' => $input['code'],
  230. 'type' => $input['discount_type'] ?? null,
  231. 'value' => $input['value'] ?? null,
  232. 'minimum_subtotal' => $input['minimum_spend'] ?? null,
  233. 'starts_on' => $input['starts_on'] ?? null,
  234. 'ends_on' => $input['ends_on'] ?? null,
  235. 'usage_limit' => $input['usage_limit'] ?? null,
  236. 'active' => true,
  237. ];
  238. $validator = Validator::make($form, DiscountCodeRules::rules($store, $percent), DiscountCodeRules::messages($percent));
  239. if ($validator->fails()) {
  240. $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend'];
  241. $messages = [];
  242. foreach ($validator->errors()->toArray() as $field => $errors) {
  243. $messages[$renamed[$field] ?? $field] = $errors;
  244. }
  245. throw ValidationException::withMessages($messages);
  246. }
  247. $data = $validator->validated();
  248. $amount = $percent ? $data['value'].'% off' : self::money(self::sen($data['value'])).' off';
  249. $details = array_filter([
  250. filled($data['minimum_subtotal'] ?? null) ? 'when spending at least '.self::money(self::sen($data['minimum_subtotal'])) : null,
  251. filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null,
  252. filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null,
  253. filled($data['usage_limit'] ?? null) ? "up to {$data['usage_limit']} uses" : null,
  254. ]);
  255. return [
  256. 'input' => array_intersect_key($input, array_flip(['code', 'discount_type', 'value', 'minimum_spend', 'starts_on', 'ends_on', 'usage_limit'])),
  257. 'summary' => "Create the discount code {$data['code']}: {$amount}".($details !== [] ? ', '.implode(', ', $details) : ''),
  258. 'run' => function () use ($store, $data): void {
  259. $code = new DiscountCode;
  260. $code->store_id = $store->id;
  261. DiscountCodeRules::fill($code, $data);
  262. $code->save();
  263. },
  264. ];
  265. }
  266. /**
  267. * Switch a code on or off, or change its last day or number of uses.
  268. *
  269. * @param array<string, mixed> $input
  270. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  271. */
  272. private static function updateDiscount(Store $store, array $input): array
  273. {
  274. $data = self::validate($input, [
  275. 'code' => ['required', 'string'],
  276. 'active' => ['sometimes', 'boolean'],
  277. 'ends_on' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
  278. 'usage_limit' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:1000000'],
  279. ]);
  280. $code = $store->discountCodes()->where('code', DiscountCode::normalize($data['code']))->first();
  281. if ($code === null) {
  282. self::fail('code', 'This store has no such code. Use one from the list of discount codes.');
  283. }
  284. $changes = [];
  285. if (array_key_exists('active', $data) && (bool) $data['active'] !== $code->active) {
  286. $changes[] = $data['active'] ? 'switch it on' : 'switch it off';
  287. }
  288. $endsAt = $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d');
  289. if (array_key_exists('ends_on', $data) && $data['ends_on'] !== $endsAt) {
  290. $startsAt = $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d');
  291. if ($data['ends_on'] !== null && $startsAt !== null && $data['ends_on'] < $startsAt) {
  292. self::fail('ends_on', 'The last day cannot be before the first day.');
  293. }
  294. $changes[] = $data['ends_on'] === null ? 'no last day' : "last day {$data['ends_on']}";
  295. }
  296. if (array_key_exists('usage_limit', $data) && $data['usage_limit'] !== $code->usage_limit) {
  297. $changes[] = $data['usage_limit'] === null ? 'no limit on uses' : "up to {$data['usage_limit']} uses";
  298. }
  299. if ($changes === []) {
  300. self::fail('code', 'Nothing would change. Say what to change: active, ends_on or usage_limit.');
  301. }
  302. return [
  303. 'input' => $data,
  304. 'summary' => "Change the discount code {$code->code}: ".implode(', ', $changes),
  305. 'run' => function () use ($code, $data): void {
  306. $form = [
  307. 'code' => $code->code,
  308. 'type' => $code->type,
  309. 'value' => $code->type === DiscountCode::PERCENT ? $code->value : $code->value / 100,
  310. 'minimum_subtotal' => $code->minimum_subtotal !== null ? $code->minimum_subtotal / 100 : null,
  311. 'starts_on' => $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'),
  312. 'ends_on' => array_key_exists('ends_on', $data) ? $data['ends_on'] : $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'),
  313. 'usage_limit' => array_key_exists('usage_limit', $data) ? $data['usage_limit'] : $code->usage_limit,
  314. 'active' => array_key_exists('active', $data) ? (bool) $data['active'] : $code->active,
  315. ];
  316. DiscountCodeRules::fill($code, $form);
  317. $code->save();
  318. },
  319. ];
  320. }
  321. /**
  322. * @param array<string, mixed> $input
  323. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  324. */
  325. private static function createBundle(Store $store, array $input): array
  326. {
  327. $data = self::validate($input, [
  328. 'name' => ['required', 'string', 'min:2', 'max:120'],
  329. 'description' => ['nullable', 'string', 'max:5000'],
  330. 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  331. 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
  332. 'status' => ['nullable', 'in:active,draft'],
  333. 'items' => ['required', 'array', 'list', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_ITEMS],
  334. 'items.*.product' => ['required', 'string'],
  335. 'items.*.variant' => ['nullable', 'string', 'max:90'],
  336. 'items.*.quantity' => ['nullable', 'integer', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_QUANTITY],
  337. ]);
  338. $data['status'] ??= ProductStatus::Active->value;
  339. $items = [];
  340. $labels = [];
  341. $stock = null;
  342. foreach ($data['items'] as $index => $item) {
  343. $product = self::findProduct($store, $item['product'], "items.$index.product");
  344. if ($product->isBundle()) {
  345. self::fail("items.$index.product", 'A bundle cannot hold another bundle.');
  346. }
  347. $variant = null;
  348. if ($product->hasVariants()) {
  349. if (! filled($item['variant'] ?? null)) {
  350. self::fail("items.$index.variant", "\"{$product->name}\" has options. Name the one that goes in the bundle, such as \"".$product->variants->first()?->name().'".');
  351. }
  352. $variant = self::findVariant($product, $item['variant'], "items.$index.variant");
  353. }
  354. $key = $product->id.'-'.$variant?->id;
  355. if (isset($items[$key])) {
  356. self::fail("items.$index.product", 'This product is already in the bundle. Raise its quantity instead.');
  357. }
  358. $quantity = (int) ($item['quantity'] ?? 1);
  359. $items[$key] = ['product_id' => $product->id, 'variant_id' => $variant?->id, 'quantity' => $quantity];
  360. $labels[] = $quantity.' × '.$product->name.($variant !== null ? ' ('.$variant->name().')' : '');
  361. $left = intdiv(max(0, $variant !== null ? $variant->stock : $product->stock), $quantity);
  362. $stock = $stock === null ? $left : min($stock, $left);
  363. }
  364. $summary = "Create the bundle \"{$data['name']}\" at ".self::money(self::sen($data['price']))
  365. .self::wasPrice($data['compare_at_price'] ?? null)
  366. .': '.implode(', ', $labels)
  367. .". Enough stock for {$stock} now, "
  368. .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft');
  369. return [
  370. 'input' => $data,
  371. 'summary' => $summary,
  372. 'run' => function () use ($store, $data, $items): void {
  373. $bundle = $store->products()->make([
  374. 'name' => $data['name'],
  375. 'description' => $data['description'] ?? null,
  376. 'price' => self::sen($data['price']),
  377. 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
  378. 'stock' => 0,
  379. 'status' => $data['status'],
  380. ]);
  381. $bundle->is_bundle = true;
  382. $bundle->save();
  383. BundleItem::replaceFor($bundle, array_values($items));
  384. },
  385. ];
  386. }
  387. /**
  388. * @param array<string, mixed> $input
  389. * @param array<string, list<mixed>> $rules
  390. * @return array<string, mixed>
  391. *
  392. * @throws ValidationException
  393. */
  394. private static function validate(array $input, array $rules): array
  395. {
  396. return Validator::make($input, $rules)->validate();
  397. }
  398. /**
  399. * Any product of the store, found by its web-address name (or, failing that, its exact name).
  400. */
  401. private static function findProduct(Store $store, string $slug, string $field): Product
  402. {
  403. $product = $store->products()->with('variants')->where('slug', $slug)->first()
  404. ?? $store->products()->with('variants')->where('name', $slug)->first();
  405. if ($product === null) {
  406. self::fail($field, "This store has no product \"{$slug}\". Use a web-address name from the product list.");
  407. }
  408. return $product;
  409. }
  410. /**
  411. * One of a product's choices, such as "100ml" or "500g / Pedas". Letter case and spaces are ignored.
  412. */
  413. private static function findVariant(Product $product, string $name, string $field): ProductVariant
  414. {
  415. $wanted = self::plain($name);
  416. $variant = $product->variants->first(fn (ProductVariant $variant) => self::plain($variant->name()) === $wanted);
  417. if ($variant === null) {
  418. self::fail($field, "\"{$product->name}\" has no choice \"{$name}\". Its choices are: ".$product->variants->map->name()->implode(', ').'.');
  419. }
  420. return $variant;
  421. }
  422. private static function plain(string $text): string
  423. {
  424. return mb_strtolower((string) preg_replace('/\s+/', '', $text));
  425. }
  426. /**
  427. * @throws ValidationException
  428. */
  429. private static function fail(string $field, string $message): never
  430. {
  431. throw ValidationException::withMessages([$field => $message]);
  432. }
  433. private static function wasPrice(mixed $compare): string
  434. {
  435. return filled($compare) ? ' (was '.self::money(self::sen($compare)).')' : '';
  436. }
  437. private static function money(int $sen): string
  438. {
  439. return 'RM '.number_format($sen / 100, 2);
  440. }
  441. private static function sen(mixed $ringgit): int
  442. {
  443. return (int) round(((float) $ringgit) * 100);
  444. }
  445. }