AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatActions.php 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. <?php
  2. namespace App\Commerce;
  3. use App\Enums\ProductStatus;
  4. use App\Http\Requests\Products\SaveProductRequest;
  5. use App\Models\AutomaticDiscount;
  6. use App\Models\BundleItem;
  7. use App\Models\DiscountCode;
  8. use App\Models\Product;
  9. use App\Models\ProductVariant;
  10. use App\Models\Store;
  11. use Closure;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Validator;
  14. use Illuminate\Validation\ValidationException;
  15. /**
  16. * Store changes asked for in the chat, such as "make a 10% code RAYA10" or "set the moisturiser to RM 35".
  17. *
  18. * The AI only proposes them. check() makes sure each one is allowed and writes a plain sentence for the
  19. * merchant. Nothing changes until the merchant confirms; then apply() checks everything again (the store
  20. * may have changed in between) and does all of them, or none.
  21. *
  22. * The rules are the same as the Products and Discounts forms, so chat can never do what a form would refuse.
  23. */
  24. final class ChatActions
  25. {
  26. /** Ten, so "write descriptions for all my products" fits in one message for a small store. */
  27. public const int MAX_ACTIONS = 10;
  28. /** Product descriptions written in the chat stay short enough to read on the confirm card. */
  29. public const int MAX_DESCRIPTION = 1500;
  30. public const array TYPES = ['create_product', 'update_product', 'create_discount', 'update_discount', 'create_bundle', 'create_automatic_discount'];
  31. /**
  32. * Check the actions in an AI answer. Returns each with its cleaned input and a sentence for the merchant.
  33. *
  34. * @return list<array{type: string, input: array<string, mixed>, summary: string}>
  35. *
  36. * @throws ValidationException With keys such as "actions.0.price", so the AI can correct them.
  37. */
  38. public static function check(Store $store, mixed $actions): array
  39. {
  40. if ($actions === null || $actions === []) {
  41. return [];
  42. }
  43. if (! is_array($actions) || ! array_is_list($actions)) {
  44. throw ValidationException::withMessages(['actions' => 'Must be a list of actions.']);
  45. }
  46. if (count($actions) > self::MAX_ACTIONS) {
  47. throw ValidationException::withMessages(['actions' => 'At most '.self::MAX_ACTIONS.' actions at a time.']);
  48. }
  49. $checked = [];
  50. foreach ($actions as $index => $action) {
  51. $prepared = self::prepare($store, $action, $index);
  52. $checked[] = ['type' => $prepared['type'], 'input' => $prepared['input'], 'summary' => $prepared['summary']];
  53. }
  54. return $checked;
  55. }
  56. /**
  57. * Do actions the merchant confirmed, in order, all or nothing. Each is checked again first.
  58. *
  59. * @param list<array{type: string, input: array<string, mixed>, summary: string}> $actions
  60. *
  61. * @throws ValidationException When one is no longer allowed. Nothing is changed then.
  62. */
  63. public static function apply(Store $store, array $actions): void
  64. {
  65. DB::transaction(function () use ($store, $actions): void {
  66. foreach ($actions as $index => $action) {
  67. // Each one sees what the ones before it did, such as a product created a step earlier.
  68. (self::prepare($store, ['type' => $action['type'], ...$action['input']], $index)['run'])();
  69. }
  70. BundleStock::refresh($store->id);
  71. });
  72. }
  73. /**
  74. * @return array{type: string, input: array<string, mixed>, summary: string, run: Closure(): void}
  75. *
  76. * @throws ValidationException
  77. */
  78. private static function prepare(Store $store, mixed $action, int $index): array
  79. {
  80. $type = is_array($action) ? ($action['type'] ?? null) : null;
  81. if (! is_string($type) || ! in_array($type, self::TYPES, true)) {
  82. throw ValidationException::withMessages(["actions.$index.type" => 'Must be one of: '.implode(', ', self::TYPES).'.']);
  83. }
  84. unset($action['type']);
  85. try {
  86. $prepared = match ($type) {
  87. 'create_product' => self::createProduct($store, $action),
  88. 'update_product' => self::updateProduct($store, $action),
  89. 'create_discount' => self::createDiscount($store, $action),
  90. 'update_discount' => self::updateDiscount($store, $action),
  91. 'create_bundle' => self::createBundle($store, $action),
  92. 'create_automatic_discount' => self::createAutomaticDiscount($store, $action),
  93. };
  94. } catch (ValidationException $e) {
  95. // "price" becomes "actions.2.price", so it is clear which action has the problem.
  96. $messages = [];
  97. foreach ($e->errors() as $field => $errors) {
  98. $messages["actions.$index.$field"] = $errors;
  99. }
  100. throw ValidationException::withMessages($messages);
  101. }
  102. return ['type' => $type, ...$prepared];
  103. }
  104. /**
  105. * @param array<string, mixed> $input
  106. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  107. */
  108. private static function createProduct(Store $store, array $input): array
  109. {
  110. $data = self::validate($input, [
  111. 'name' => ['required', 'string', 'min:2', 'max:120'],
  112. 'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
  113. 'details' => ['sometimes', 'nullable', 'array', 'list', 'max:'.Product::MAX_DETAILS],
  114. 'details.*.title' => ['required', 'string', 'max:60'],
  115. 'details.*.body' => ['required', 'string', 'max:2000'],
  116. 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  117. 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
  118. 'stock' => ['required', 'integer', 'min:0', 'max:1000000'],
  119. 'status' => ['nullable', 'in:active,draft'],
  120. ]);
  121. $data['status'] ??= ProductStatus::Active->value;
  122. $summary = "Add the product \"{$data['name']}\" at ".self::money(self::sen($data['price']))
  123. .self::wasPrice($data['compare_at_price'] ?? null)
  124. .", {$data['stock']} in stock, "
  125. .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
  126. .self::descriptionNote($data['description'] ?? null)
  127. .(self::cleanDetails($data['details'] ?? null) !== null ? '. Sections '.self::detailsNote((array) self::cleanDetails($data['details'] ?? null)) : '');
  128. return [
  129. 'input' => $data,
  130. 'summary' => $summary,
  131. 'run' => function () use ($store, $data): void {
  132. $store->products()->create([
  133. 'name' => $data['name'],
  134. 'description' => self::cleanText($data['description'] ?? null),
  135. 'details' => self::cleanDetails($data['details'] ?? null),
  136. 'price' => self::sen($data['price']),
  137. 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
  138. 'stock' => (int) $data['stock'],
  139. 'status' => $data['status'],
  140. ]);
  141. },
  142. ];
  143. }
  144. /**
  145. * @param array<string, mixed> $input
  146. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  147. */
  148. private static function updateProduct(Store $store, array $input): array
  149. {
  150. $data = self::validate($input, [
  151. 'product' => ['required', 'string'],
  152. 'variant' => ['nullable', 'string', 'max:90'],
  153. 'name' => ['sometimes', 'string', 'min:2', 'max:120'],
  154. 'description' => ['sometimes', 'nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
  155. 'details' => ['sometimes', 'nullable', 'array', 'list', 'max:'.Product::MAX_DETAILS],
  156. 'details.*.title' => ['required', 'string', 'max:60'],
  157. 'details.*.body' => ['required', 'string', 'max:2000'],
  158. 'remove_details' => ['sometimes', 'array', 'list', 'max:'.Product::MAX_DETAILS],
  159. 'remove_details.*' => ['string', 'max:60'],
  160. 'price' => ['sometimes', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  161. 'compare_at_price' => ['sometimes', 'nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
  162. 'stock' => ['sometimes', 'integer', 'min:0', 'max:1000000'],
  163. 'status' => ['sometimes', 'in:active,draft'],
  164. ]);
  165. $product = self::findProduct($store, $data['product'], 'product');
  166. $priceFields = array_intersect(['price', 'compare_at_price', 'stock'], array_keys($data));
  167. $productFields = array_intersect(['name', 'description', 'details', 'remove_details', 'status'], array_keys($data));
  168. if ($priceFields === [] && $productFields === []) {
  169. self::fail('product', 'Say what to change: name, description, details, price, compare_at_price, stock or status.');
  170. }
  171. $variant = null;
  172. if (filled($data['variant'] ?? null)) {
  173. if (! $product->hasVariants()) {
  174. self::fail('variant', "\"{$product->name}\" has no options. Leave out \"variant\".");
  175. }
  176. $variant = self::findVariant($product, $data['variant'], 'variant');
  177. } elseif ($product->hasVariants() && $priceFields !== []) {
  178. 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().'".');
  179. }
  180. if ($product->isBundle() && array_key_exists('stock', $data)) {
  181. self::fail('stock', "\"{$product->name}\" is a bundle. Its stock comes from the products inside it.");
  182. }
  183. // The "was" price must stay above the price, whichever of the two changes.
  184. $owner = $variant ?? $product;
  185. $newPrice = array_key_exists('price', $data) ? self::sen($data['price']) : $owner->price;
  186. $newCompare = array_key_exists('compare_at_price', $data)
  187. ? (filled($data['compare_at_price']) ? self::sen($data['compare_at_price']) : null)
  188. : $owner->compare_at_price;
  189. if ($newCompare !== null && $newCompare <= $newPrice) {
  190. self::fail('compare_at_price', 'The "was" price must be higher than the price.');
  191. }
  192. $changes = [];
  193. if (array_key_exists('name', $data) && $data['name'] !== $product->name) {
  194. $changes[] = "name to \"{$data['name']}\"";
  195. }
  196. if ($newPrice !== $owner->price) {
  197. $changes[] = 'price '.self::money($owner->price).' → '.self::money($newPrice);
  198. }
  199. if ($newCompare !== $owner->compare_at_price) {
  200. $changes[] = $newCompare === null
  201. ? 'remove the "was" price'
  202. : '"was" price '.($owner->compare_at_price !== null ? self::money($owner->compare_at_price).' → ' : '').self::money($newCompare);
  203. }
  204. if (array_key_exists('stock', $data) && (int) $data['stock'] !== $owner->stock) {
  205. $changes[] = "stock {$owner->stock} → {$data['stock']}";
  206. }
  207. if (array_key_exists('status', $data) && $data['status'] !== $product->status->value) {
  208. $changes[] = $data['status'] === 'active' ? 'show it in the store' : 'hide it (draft)';
  209. }
  210. $description = array_key_exists('description', $data) ? self::cleanText($data['description']) : $product->description;
  211. // The full new text goes in the sentence, so the merchant reads exactly what will be saved.
  212. if ($description !== $product->description) {
  213. $changes[] = $description === null ? 'remove the description' : "description: \"{$description}\"";
  214. }
  215. // Sections merge by title: a known title is rewritten, a new one is added, "remove_details" takes some out.
  216. // The AI never sees the full text of the others, so it must not wipe them.
  217. $details = self::mergeDetails($product->details, self::cleanDetails($data['details'] ?? null), $data['remove_details'] ?? []);
  218. if ($details !== null && count($details) > Product::MAX_DETAILS) {
  219. self::fail('details', 'A product can have at most '.Product::MAX_DETAILS.' sections. Remove one first with "remove_details".');
  220. }
  221. // Only the sections that change are spelled out, in full.
  222. if ($details !== $product->details) {
  223. $written = self::cleanDetails($data['details'] ?? null);
  224. if ($written !== null) {
  225. $changes[] = 'sections '.self::detailsNote($written);
  226. }
  227. foreach ($data['remove_details'] ?? [] as $title) {
  228. $changes[] = "remove the section \"{$title}\"";
  229. }
  230. }
  231. if ($changes === []) {
  232. self::fail('product', 'These values are already set. Nothing would change.');
  233. }
  234. $label = $product->name.($variant !== null ? ' ('.$variant->name().')' : '');
  235. return [
  236. 'input' => $data,
  237. 'summary' => "Change \"{$label}\": ".implode(', ', $changes),
  238. 'run' => function () use ($product, $variant, $data, $newPrice, $newCompare, $details): void {
  239. $owner = $variant ?? $product;
  240. $owner->price = $newPrice;
  241. $owner->compare_at_price = $newCompare;
  242. if (array_key_exists('stock', $data)) {
  243. $owner->stock = (int) $data['stock'];
  244. }
  245. $owner->save();
  246. if (array_key_exists('name', $data)) {
  247. $product->name = $data['name'];
  248. }
  249. if (array_key_exists('description', $data)) {
  250. $product->description = self::cleanText($data['description']);
  251. }
  252. $product->details = $details;
  253. if (array_key_exists('status', $data)) {
  254. $product->status = ProductStatus::from($data['status']);
  255. }
  256. $product->save();
  257. $product->syncFromVariants();
  258. },
  259. ];
  260. }
  261. /**
  262. * @param array<string, mixed> $input
  263. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  264. */
  265. private static function createDiscount(Store $store, array $input): array
  266. {
  267. $input['code'] = DiscountCode::normalize((string) ($input['code'] ?? ''));
  268. $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT;
  269. // The same rules as the Discounts form. The chat names some fields more plainly.
  270. $form = [
  271. 'code' => $input['code'],
  272. 'type' => $input['discount_type'] ?? null,
  273. 'value' => $input['value'] ?? null,
  274. 'minimum_subtotal' => $input['minimum_spend'] ?? null,
  275. 'starts_on' => $input['starts_on'] ?? null,
  276. 'ends_on' => $input['ends_on'] ?? null,
  277. 'usage_limit' => $input['usage_limit'] ?? null,
  278. 'active' => true,
  279. ];
  280. $validator = Validator::make($form, DiscountCodeRules::rules($store, $percent), DiscountCodeRules::messages($percent));
  281. if ($validator->fails()) {
  282. $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend'];
  283. $messages = [];
  284. foreach ($validator->errors()->toArray() as $field => $errors) {
  285. $messages[$renamed[$field] ?? $field] = $errors;
  286. }
  287. throw ValidationException::withMessages($messages);
  288. }
  289. $data = $validator->validated();
  290. $amount = $percent ? $data['value'].'% off' : self::money(self::sen($data['value'])).' off';
  291. $details = array_filter([
  292. filled($data['minimum_subtotal'] ?? null) ? 'when spending at least '.self::money(self::sen($data['minimum_subtotal'])) : null,
  293. filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null,
  294. filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null,
  295. filled($data['usage_limit'] ?? null) ? "up to {$data['usage_limit']} uses" : null,
  296. ]);
  297. return [
  298. 'input' => array_intersect_key($input, array_flip(['code', 'discount_type', 'value', 'minimum_spend', 'starts_on', 'ends_on', 'usage_limit'])),
  299. 'summary' => "Create the discount code {$data['code']}: {$amount}".($details !== [] ? ', '.implode(', ', $details) : ''),
  300. 'run' => function () use ($store, $data): void {
  301. $code = new DiscountCode;
  302. $code->store_id = $store->id;
  303. DiscountCodeRules::fill($code, $data);
  304. $code->save();
  305. },
  306. ];
  307. }
  308. /**
  309. * Switch a code on or off, or change its last day or number of uses.
  310. *
  311. * @param array<string, mixed> $input
  312. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  313. */
  314. private static function updateDiscount(Store $store, array $input): array
  315. {
  316. $data = self::validate($input, [
  317. 'code' => ['required', 'string'],
  318. 'active' => ['sometimes', 'boolean'],
  319. 'ends_on' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
  320. 'usage_limit' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:1000000'],
  321. ]);
  322. $code = $store->discountCodes()->where('code', DiscountCode::normalize($data['code']))->first();
  323. if ($code === null) {
  324. self::fail('code', 'This store has no such code. Use one from the list of discount codes.');
  325. }
  326. $changes = [];
  327. if (array_key_exists('active', $data) && (bool) $data['active'] !== $code->active) {
  328. $changes[] = $data['active'] ? 'switch it on' : 'switch it off';
  329. }
  330. $endsAt = $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d');
  331. if (array_key_exists('ends_on', $data) && $data['ends_on'] !== $endsAt) {
  332. $startsAt = $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d');
  333. if ($data['ends_on'] !== null && $startsAt !== null && $data['ends_on'] < $startsAt) {
  334. self::fail('ends_on', 'The last day cannot be before the first day.');
  335. }
  336. $changes[] = $data['ends_on'] === null ? 'no last day' : "last day {$data['ends_on']}";
  337. }
  338. if (array_key_exists('usage_limit', $data) && $data['usage_limit'] !== $code->usage_limit) {
  339. $changes[] = $data['usage_limit'] === null ? 'no limit on uses' : "up to {$data['usage_limit']} uses";
  340. }
  341. if ($changes === []) {
  342. self::fail('code', 'Nothing would change. Say what to change: active, ends_on or usage_limit.');
  343. }
  344. return [
  345. 'input' => $data,
  346. 'summary' => "Change the discount code {$code->code}: ".implode(', ', $changes),
  347. 'run' => function () use ($code, $data): void {
  348. $form = [
  349. 'code' => $code->code,
  350. 'type' => $code->type,
  351. 'value' => $code->type === DiscountCode::PERCENT ? $code->value : $code->value / 100,
  352. 'minimum_subtotal' => $code->minimum_subtotal !== null ? $code->minimum_subtotal / 100 : null,
  353. 'starts_on' => $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'),
  354. 'ends_on' => array_key_exists('ends_on', $data) ? $data['ends_on'] : $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'),
  355. 'usage_limit' => array_key_exists('usage_limit', $data) ? $data['usage_limit'] : $code->usage_limit,
  356. 'active' => array_key_exists('active', $data) ? (bool) $data['active'] : $code->active,
  357. ];
  358. DiscountCodeRules::fill($code, $form);
  359. $code->save();
  360. },
  361. ];
  362. }
  363. /**
  364. * @param array<string, mixed> $input
  365. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  366. */
  367. private static function createBundle(Store $store, array $input): array
  368. {
  369. $data = self::validate($input, [
  370. 'name' => ['required', 'string', 'min:2', 'max:120'],
  371. 'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
  372. 'details' => ['sometimes', 'nullable', 'array', 'list', 'max:'.Product::MAX_DETAILS],
  373. 'details.*.title' => ['required', 'string', 'max:60'],
  374. 'details.*.body' => ['required', 'string', 'max:2000'],
  375. 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  376. 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
  377. 'status' => ['nullable', 'in:active,draft'],
  378. 'items' => ['required', 'array', 'list', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_ITEMS],
  379. 'items.*.product' => ['required', 'string'],
  380. 'items.*.variant' => ['nullable', 'string', 'max:90'],
  381. 'items.*.quantity' => ['nullable', 'integer', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_QUANTITY],
  382. ]);
  383. $data['status'] ??= ProductStatus::Active->value;
  384. $items = [];
  385. $labels = [];
  386. $stock = null;
  387. foreach ($data['items'] as $index => $item) {
  388. $product = self::findProduct($store, $item['product'], "items.$index.product");
  389. if ($product->isBundle()) {
  390. self::fail("items.$index.product", 'A bundle cannot hold another bundle.');
  391. }
  392. $variant = null;
  393. if ($product->hasVariants()) {
  394. if (! filled($item['variant'] ?? null)) {
  395. self::fail("items.$index.variant", "\"{$product->name}\" has options. Name the one that goes in the bundle, such as \"".$product->variants->first()?->name().'".');
  396. }
  397. $variant = self::findVariant($product, $item['variant'], "items.$index.variant");
  398. }
  399. $key = $product->id.'-'.$variant?->id;
  400. if (isset($items[$key])) {
  401. self::fail("items.$index.product", 'This product is already in the bundle. Raise its quantity instead.');
  402. }
  403. $quantity = (int) ($item['quantity'] ?? 1);
  404. $items[$key] = ['product_id' => $product->id, 'variant_id' => $variant?->id, 'quantity' => $quantity];
  405. $labels[] = $quantity.' × '.$product->name.($variant !== null ? ' ('.$variant->name().')' : '');
  406. $left = intdiv(max(0, $variant !== null ? $variant->stock : $product->stock), $quantity);
  407. $stock = $stock === null ? $left : min($stock, $left);
  408. }
  409. $summary = "Create the bundle \"{$data['name']}\" at ".self::money(self::sen($data['price']))
  410. .self::wasPrice($data['compare_at_price'] ?? null)
  411. .': '.implode(', ', $labels)
  412. .". Enough stock for {$stock} now, "
  413. .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
  414. .self::descriptionNote($data['description'] ?? null)
  415. .(self::cleanDetails($data['details'] ?? null) !== null ? '. Sections '.self::detailsNote((array) self::cleanDetails($data['details'] ?? null)) : '');
  416. return [
  417. 'input' => $data,
  418. 'summary' => $summary,
  419. 'run' => function () use ($store, $data, $items): void {
  420. $bundle = $store->products()->make([
  421. 'name' => $data['name'],
  422. 'description' => self::cleanText($data['description'] ?? null),
  423. 'details' => self::cleanDetails($data['details'] ?? null),
  424. 'price' => self::sen($data['price']),
  425. 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
  426. 'stock' => 0,
  427. 'status' => $data['status'],
  428. ]);
  429. $bundle->is_bundle = true;
  430. $bundle->save();
  431. BundleItem::replaceFor($bundle, array_values($items));
  432. },
  433. ];
  434. }
  435. /**
  436. * A discount with no code, such as "Raya Sale: buy 2 or more, get 10% off", for all or some products.
  437. *
  438. * @param array<string, mixed> $input
  439. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  440. */
  441. private static function createAutomaticDiscount(Store $store, array $input): array
  442. {
  443. $slugs = $input['products'] ?? null;
  444. if ($slugs !== null && (! is_array($slugs) || ! array_is_list($slugs) || $slugs === [])) {
  445. self::fail('products', 'Give a list of web-address names, or null for every product.');
  446. }
  447. $products = [];
  448. foreach ($slugs ?? [] as $index => $slug) {
  449. $products[] = self::findProduct($store, (string) $slug, "products.$index");
  450. }
  451. $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT;
  452. $form = [
  453. 'name' => $input['name'] ?? null,
  454. 'type' => $input['discount_type'] ?? null,
  455. 'value' => $input['value'] ?? null,
  456. 'minimum_quantity' => $input['minimum_quantity'] ?? null,
  457. 'minimum_subtotal' => $input['minimum_spend'] ?? null,
  458. 'applies_to' => $slugs === null ? 'all' : 'chosen',
  459. 'product_ids' => array_map(fn (Product $product) => $product->id, $products),
  460. 'starts_on' => $input['starts_on'] ?? null,
  461. 'ends_on' => $input['ends_on'] ?? null,
  462. 'active' => true,
  463. ];
  464. $validator = Validator::make($form, AutomaticDiscountRules::rules($store, $percent), AutomaticDiscountRules::messages($percent));
  465. if ($validator->fails()) {
  466. $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend', 'product_ids' => 'products'];
  467. $messages = [];
  468. foreach ($validator->errors()->toArray() as $field => $errors) {
  469. $messages[$renamed[$field] ?? $field] = $errors;
  470. }
  471. throw ValidationException::withMessages($messages);
  472. }
  473. $data = $validator->validated();
  474. $preview = new AutomaticDiscount;
  475. AutomaticDiscountRules::fill($preview, $data);
  476. $details = array_filter([
  477. $products !== [] ? 'only on '.implode(', ', array_map(fn (Product $product) => $product->name, $products)) : 'on every product',
  478. filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null,
  479. filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null,
  480. ]);
  481. return [
  482. 'input' => array_intersect_key($input, array_flip(['name', 'discount_type', 'value', 'minimum_quantity', 'minimum_spend', 'products', 'starts_on', 'ends_on'])),
  483. 'summary' => "Start the automatic discount \"{$preview->name}\": {$preview->describe()}, ".implode(', ', $details).'. No code needed',
  484. 'run' => function () use ($store, $data): void {
  485. $offer = new AutomaticDiscount;
  486. $offer->store_id = $store->id;
  487. AutomaticDiscountRules::fill($offer, $data);
  488. $offer->save();
  489. },
  490. ];
  491. }
  492. /**
  493. * @param array<string, mixed> $input
  494. * @param array<string, list<mixed>> $rules
  495. * @return array<string, mixed>
  496. *
  497. * @throws ValidationException
  498. */
  499. private static function validate(array $input, array $rules): array
  500. {
  501. return Validator::make($input, $rules)->validate();
  502. }
  503. /**
  504. * Any product of the store, found by its web-address name (or, failing that, its exact name).
  505. */
  506. private static function findProduct(Store $store, string $slug, string $field): Product
  507. {
  508. $product = $store->products()->with('variants')->where('slug', $slug)->first()
  509. ?? $store->products()->with('variants')->where('name', $slug)->first();
  510. if ($product === null) {
  511. self::fail($field, "This store has no product \"{$slug}\". Use a web-address name from the product list.");
  512. }
  513. return $product;
  514. }
  515. /**
  516. * One of a product's choices, such as "100ml" or "500g / Pedas". Letter case and spaces are ignored.
  517. */
  518. private static function findVariant(Product $product, string $name, string $field): ProductVariant
  519. {
  520. $wanted = self::plain($name);
  521. $variant = $product->variants->first(fn (ProductVariant $variant) => self::plain($variant->name()) === $wanted);
  522. if ($variant === null) {
  523. self::fail($field, "\"{$product->name}\" has no choice \"{$name}\". Its choices are: ".$product->variants->map->name()->implode(', ').'.');
  524. }
  525. return $variant;
  526. }
  527. /**
  528. * Trimmed sections without empty ones, or null when none are left.
  529. *
  530. * @return list<array{title: string, body: string}>|null
  531. */
  532. private static function cleanDetails(mixed $details): ?array
  533. {
  534. $clean = [];
  535. foreach (is_array($details) ? $details : [] as $row) {
  536. $title = trim((string) ($row['title'] ?? ''));
  537. $body = trim((string) ($row['body'] ?? ''));
  538. if ($title !== '' && $body !== '') {
  539. $clean[] = ['title' => $title, 'body' => $body];
  540. }
  541. }
  542. return $clean === [] ? null : $clean;
  543. }
  544. /**
  545. * The product's sections after a chat change: same title (letter case ignored) replaces, new titles are added
  546. * at the end, and titles in $remove are taken out.
  547. *
  548. * @param list<array{title: string, body: string}>|null $current
  549. * @param list<array{title: string, body: string}>|null $changes
  550. * @param list<string> $remove
  551. * @return list<array{title: string, body: string}>|null
  552. */
  553. private static function mergeDetails(?array $current, ?array $changes, array $remove): ?array
  554. {
  555. $key = fn (string $title) => mb_strtolower(trim($title));
  556. $removed = array_map($key, $remove);
  557. $merged = [];
  558. foreach ($current ?? [] as $row) {
  559. if (! in_array($key($row['title']), $removed, true)) {
  560. $merged[$key($row['title'])] = $row;
  561. }
  562. }
  563. foreach ($changes ?? [] as $row) {
  564. $merged[$key($row['title'])] = $row;
  565. }
  566. return $merged === [] ? null : array_values($merged);
  567. }
  568. /**
  569. * Each section in full: "How to use": "Apply ...", so the merchant reads what will be saved.
  570. *
  571. * @param list<array{title: string, body: string}> $details
  572. */
  573. private static function detailsNote(array $details): string
  574. {
  575. return implode('; ', array_map(fn (array $row) => "\"{$row['title']}\": \"{$row['body']}\"", $details));
  576. }
  577. private static function descriptionNote(mixed $description): string
  578. {
  579. $text = self::cleanText($description);
  580. return $text === null ? '' : ". Description: \"{$text}\"";
  581. }
  582. /**
  583. * Trimmed text, or null when empty.
  584. */
  585. private static function cleanText(mixed $text): ?string
  586. {
  587. $text = trim((string) $text);
  588. return $text === '' ? null : $text;
  589. }
  590. private static function plain(string $text): string
  591. {
  592. return mb_strtolower((string) preg_replace('/\s+/', '', $text));
  593. }
  594. /**
  595. * @throws ValidationException
  596. */
  597. private static function fail(string $field, string $message): never
  598. {
  599. throw ValidationException::withMessages([$field => $message]);
  600. }
  601. private static function wasPrice(mixed $compare): string
  602. {
  603. return filled($compare) ? ' (was '.self::money(self::sen($compare)).')' : '';
  604. }
  605. private static function money(int $sen): string
  606. {
  607. return 'RM '.number_format($sen / 100, 2);
  608. }
  609. private static function sen(mixed $ringgit): int
  610. {
  611. return (int) round(((float) $ringgit) * 100);
  612. }
  613. }