AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatActions.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  114. 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
  115. 'stock' => ['required', 'integer', 'min:0', 'max:1000000'],
  116. 'status' => ['nullable', 'in:active,draft'],
  117. ]);
  118. $data['status'] ??= ProductStatus::Active->value;
  119. $summary = "Add the product \"{$data['name']}\" at ".self::money(self::sen($data['price']))
  120. .self::wasPrice($data['compare_at_price'] ?? null)
  121. .", {$data['stock']} in stock, "
  122. .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
  123. .self::descriptionNote($data['description'] ?? null);
  124. return [
  125. 'input' => $data,
  126. 'summary' => $summary,
  127. 'run' => function () use ($store, $data): void {
  128. $store->products()->create([
  129. 'name' => $data['name'],
  130. 'description' => self::cleanText($data['description'] ?? null),
  131. 'price' => self::sen($data['price']),
  132. 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
  133. 'stock' => (int) $data['stock'],
  134. 'status' => $data['status'],
  135. ]);
  136. },
  137. ];
  138. }
  139. /**
  140. * @param array<string, mixed> $input
  141. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  142. */
  143. private static function updateProduct(Store $store, array $input): array
  144. {
  145. $data = self::validate($input, [
  146. 'product' => ['required', 'string'],
  147. 'variant' => ['nullable', 'string', 'max:90'],
  148. 'name' => ['sometimes', 'string', 'min:2', 'max:120'],
  149. 'description' => ['sometimes', 'nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
  150. 'price' => ['sometimes', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  151. 'compare_at_price' => ['sometimes', 'nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
  152. 'stock' => ['sometimes', 'integer', 'min:0', 'max:1000000'],
  153. 'status' => ['sometimes', 'in:active,draft'],
  154. ]);
  155. $product = self::findProduct($store, $data['product'], 'product');
  156. $priceFields = array_intersect(['price', 'compare_at_price', 'stock'], array_keys($data));
  157. $productFields = array_intersect(['name', 'description', 'status'], array_keys($data));
  158. if ($priceFields === [] && $productFields === []) {
  159. self::fail('product', 'Say what to change: name, description, price, compare_at_price, stock or status.');
  160. }
  161. $variant = null;
  162. if (filled($data['variant'] ?? null)) {
  163. if (! $product->hasVariants()) {
  164. self::fail('variant', "\"{$product->name}\" has no options. Leave out \"variant\".");
  165. }
  166. $variant = self::findVariant($product, $data['variant'], 'variant');
  167. } elseif ($product->hasVariants() && $priceFields !== []) {
  168. 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().'".');
  169. }
  170. if ($product->isBundle() && array_key_exists('stock', $data)) {
  171. self::fail('stock', "\"{$product->name}\" is a bundle. Its stock comes from the products inside it.");
  172. }
  173. // The "was" price must stay above the price, whichever of the two changes.
  174. $owner = $variant ?? $product;
  175. $newPrice = array_key_exists('price', $data) ? self::sen($data['price']) : $owner->price;
  176. $newCompare = array_key_exists('compare_at_price', $data)
  177. ? (filled($data['compare_at_price']) ? self::sen($data['compare_at_price']) : null)
  178. : $owner->compare_at_price;
  179. if ($newCompare !== null && $newCompare <= $newPrice) {
  180. self::fail('compare_at_price', 'The "was" price must be higher than the price.');
  181. }
  182. $changes = [];
  183. if (array_key_exists('name', $data) && $data['name'] !== $product->name) {
  184. $changes[] = "name to \"{$data['name']}\"";
  185. }
  186. if ($newPrice !== $owner->price) {
  187. $changes[] = 'price '.self::money($owner->price).' → '.self::money($newPrice);
  188. }
  189. if ($newCompare !== $owner->compare_at_price) {
  190. $changes[] = $newCompare === null
  191. ? 'remove the "was" price'
  192. : '"was" price '.($owner->compare_at_price !== null ? self::money($owner->compare_at_price).' → ' : '').self::money($newCompare);
  193. }
  194. if (array_key_exists('stock', $data) && (int) $data['stock'] !== $owner->stock) {
  195. $changes[] = "stock {$owner->stock} → {$data['stock']}";
  196. }
  197. if (array_key_exists('status', $data) && $data['status'] !== $product->status->value) {
  198. $changes[] = $data['status'] === 'active' ? 'show it in the store' : 'hide it (draft)';
  199. }
  200. $description = array_key_exists('description', $data) ? self::cleanText($data['description']) : $product->description;
  201. // The full new text goes in the sentence, so the merchant reads exactly what will be saved.
  202. if ($description !== $product->description) {
  203. $changes[] = $description === null ? 'remove the description' : "description: \"{$description}\"";
  204. }
  205. if ($changes === []) {
  206. self::fail('product', 'These values are already set. Nothing would change.');
  207. }
  208. $label = $product->name.($variant !== null ? ' ('.$variant->name().')' : '');
  209. return [
  210. 'input' => $data,
  211. 'summary' => "Change \"{$label}\": ".implode(', ', $changes),
  212. 'run' => function () use ($product, $variant, $data, $newPrice, $newCompare): void {
  213. $owner = $variant ?? $product;
  214. $owner->price = $newPrice;
  215. $owner->compare_at_price = $newCompare;
  216. if (array_key_exists('stock', $data)) {
  217. $owner->stock = (int) $data['stock'];
  218. }
  219. $owner->save();
  220. if (array_key_exists('name', $data)) {
  221. $product->name = $data['name'];
  222. }
  223. if (array_key_exists('description', $data)) {
  224. $product->description = self::cleanText($data['description']);
  225. }
  226. if (array_key_exists('status', $data)) {
  227. $product->status = ProductStatus::from($data['status']);
  228. }
  229. $product->save();
  230. $product->syncFromVariants();
  231. },
  232. ];
  233. }
  234. /**
  235. * @param array<string, mixed> $input
  236. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  237. */
  238. private static function createDiscount(Store $store, array $input): array
  239. {
  240. $input['code'] = DiscountCode::normalize((string) ($input['code'] ?? ''));
  241. $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT;
  242. // The same rules as the Discounts form. The chat names some fields more plainly.
  243. $form = [
  244. 'code' => $input['code'],
  245. 'type' => $input['discount_type'] ?? null,
  246. 'value' => $input['value'] ?? null,
  247. 'minimum_subtotal' => $input['minimum_spend'] ?? null,
  248. 'starts_on' => $input['starts_on'] ?? null,
  249. 'ends_on' => $input['ends_on'] ?? null,
  250. 'usage_limit' => $input['usage_limit'] ?? null,
  251. 'active' => true,
  252. ];
  253. $validator = Validator::make($form, DiscountCodeRules::rules($store, $percent), DiscountCodeRules::messages($percent));
  254. if ($validator->fails()) {
  255. $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend'];
  256. $messages = [];
  257. foreach ($validator->errors()->toArray() as $field => $errors) {
  258. $messages[$renamed[$field] ?? $field] = $errors;
  259. }
  260. throw ValidationException::withMessages($messages);
  261. }
  262. $data = $validator->validated();
  263. $amount = $percent ? $data['value'].'% off' : self::money(self::sen($data['value'])).' off';
  264. $details = array_filter([
  265. filled($data['minimum_subtotal'] ?? null) ? 'when spending at least '.self::money(self::sen($data['minimum_subtotal'])) : null,
  266. filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null,
  267. filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null,
  268. filled($data['usage_limit'] ?? null) ? "up to {$data['usage_limit']} uses" : null,
  269. ]);
  270. return [
  271. 'input' => array_intersect_key($input, array_flip(['code', 'discount_type', 'value', 'minimum_spend', 'starts_on', 'ends_on', 'usage_limit'])),
  272. 'summary' => "Create the discount code {$data['code']}: {$amount}".($details !== [] ? ', '.implode(', ', $details) : ''),
  273. 'run' => function () use ($store, $data): void {
  274. $code = new DiscountCode;
  275. $code->store_id = $store->id;
  276. DiscountCodeRules::fill($code, $data);
  277. $code->save();
  278. },
  279. ];
  280. }
  281. /**
  282. * Switch a code on or off, or change its last day or number of uses.
  283. *
  284. * @param array<string, mixed> $input
  285. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  286. */
  287. private static function updateDiscount(Store $store, array $input): array
  288. {
  289. $data = self::validate($input, [
  290. 'code' => ['required', 'string'],
  291. 'active' => ['sometimes', 'boolean'],
  292. 'ends_on' => ['sometimes', 'nullable', 'date_format:Y-m-d'],
  293. 'usage_limit' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:1000000'],
  294. ]);
  295. $code = $store->discountCodes()->where('code', DiscountCode::normalize($data['code']))->first();
  296. if ($code === null) {
  297. self::fail('code', 'This store has no such code. Use one from the list of discount codes.');
  298. }
  299. $changes = [];
  300. if (array_key_exists('active', $data) && (bool) $data['active'] !== $code->active) {
  301. $changes[] = $data['active'] ? 'switch it on' : 'switch it off';
  302. }
  303. $endsAt = $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d');
  304. if (array_key_exists('ends_on', $data) && $data['ends_on'] !== $endsAt) {
  305. $startsAt = $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d');
  306. if ($data['ends_on'] !== null && $startsAt !== null && $data['ends_on'] < $startsAt) {
  307. self::fail('ends_on', 'The last day cannot be before the first day.');
  308. }
  309. $changes[] = $data['ends_on'] === null ? 'no last day' : "last day {$data['ends_on']}";
  310. }
  311. if (array_key_exists('usage_limit', $data) && $data['usage_limit'] !== $code->usage_limit) {
  312. $changes[] = $data['usage_limit'] === null ? 'no limit on uses' : "up to {$data['usage_limit']} uses";
  313. }
  314. if ($changes === []) {
  315. self::fail('code', 'Nothing would change. Say what to change: active, ends_on or usage_limit.');
  316. }
  317. return [
  318. 'input' => $data,
  319. 'summary' => "Change the discount code {$code->code}: ".implode(', ', $changes),
  320. 'run' => function () use ($code, $data): void {
  321. $form = [
  322. 'code' => $code->code,
  323. 'type' => $code->type,
  324. 'value' => $code->type === DiscountCode::PERCENT ? $code->value : $code->value / 100,
  325. 'minimum_subtotal' => $code->minimum_subtotal !== null ? $code->minimum_subtotal / 100 : null,
  326. 'starts_on' => $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'),
  327. 'ends_on' => array_key_exists('ends_on', $data) ? $data['ends_on'] : $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'),
  328. 'usage_limit' => array_key_exists('usage_limit', $data) ? $data['usage_limit'] : $code->usage_limit,
  329. 'active' => array_key_exists('active', $data) ? (bool) $data['active'] : $code->active,
  330. ];
  331. DiscountCodeRules::fill($code, $form);
  332. $code->save();
  333. },
  334. ];
  335. }
  336. /**
  337. * @param array<string, mixed> $input
  338. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  339. */
  340. private static function createBundle(Store $store, array $input): array
  341. {
  342. $data = self::validate($input, [
  343. 'name' => ['required', 'string', 'min:2', 'max:120'],
  344. 'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
  345. 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  346. 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
  347. 'status' => ['nullable', 'in:active,draft'],
  348. 'items' => ['required', 'array', 'list', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_ITEMS],
  349. 'items.*.product' => ['required', 'string'],
  350. 'items.*.variant' => ['nullable', 'string', 'max:90'],
  351. 'items.*.quantity' => ['nullable', 'integer', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_QUANTITY],
  352. ]);
  353. $data['status'] ??= ProductStatus::Active->value;
  354. $items = [];
  355. $labels = [];
  356. $stock = null;
  357. foreach ($data['items'] as $index => $item) {
  358. $product = self::findProduct($store, $item['product'], "items.$index.product");
  359. if ($product->isBundle()) {
  360. self::fail("items.$index.product", 'A bundle cannot hold another bundle.');
  361. }
  362. $variant = null;
  363. if ($product->hasVariants()) {
  364. if (! filled($item['variant'] ?? null)) {
  365. self::fail("items.$index.variant", "\"{$product->name}\" has options. Name the one that goes in the bundle, such as \"".$product->variants->first()?->name().'".');
  366. }
  367. $variant = self::findVariant($product, $item['variant'], "items.$index.variant");
  368. }
  369. $key = $product->id.'-'.$variant?->id;
  370. if (isset($items[$key])) {
  371. self::fail("items.$index.product", 'This product is already in the bundle. Raise its quantity instead.');
  372. }
  373. $quantity = (int) ($item['quantity'] ?? 1);
  374. $items[$key] = ['product_id' => $product->id, 'variant_id' => $variant?->id, 'quantity' => $quantity];
  375. $labels[] = $quantity.' × '.$product->name.($variant !== null ? ' ('.$variant->name().')' : '');
  376. $left = intdiv(max(0, $variant !== null ? $variant->stock : $product->stock), $quantity);
  377. $stock = $stock === null ? $left : min($stock, $left);
  378. }
  379. $summary = "Create the bundle \"{$data['name']}\" at ".self::money(self::sen($data['price']))
  380. .self::wasPrice($data['compare_at_price'] ?? null)
  381. .': '.implode(', ', $labels)
  382. .". Enough stock for {$stock} now, "
  383. .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
  384. .self::descriptionNote($data['description'] ?? null);
  385. return [
  386. 'input' => $data,
  387. 'summary' => $summary,
  388. 'run' => function () use ($store, $data, $items): void {
  389. $bundle = $store->products()->make([
  390. 'name' => $data['name'],
  391. 'description' => self::cleanText($data['description'] ?? null),
  392. 'price' => self::sen($data['price']),
  393. 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
  394. 'stock' => 0,
  395. 'status' => $data['status'],
  396. ]);
  397. $bundle->is_bundle = true;
  398. $bundle->save();
  399. BundleItem::replaceFor($bundle, array_values($items));
  400. },
  401. ];
  402. }
  403. /**
  404. * A discount with no code, such as "Raya Sale: buy 2 or more, get 10% off", for all or some products.
  405. *
  406. * @param array<string, mixed> $input
  407. * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
  408. */
  409. private static function createAutomaticDiscount(Store $store, array $input): array
  410. {
  411. $slugs = $input['products'] ?? null;
  412. if ($slugs !== null && (! is_array($slugs) || ! array_is_list($slugs) || $slugs === [])) {
  413. self::fail('products', 'Give a list of web-address names, or null for every product.');
  414. }
  415. $products = [];
  416. foreach ($slugs ?? [] as $index => $slug) {
  417. $products[] = self::findProduct($store, (string) $slug, "products.$index");
  418. }
  419. $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT;
  420. $form = [
  421. 'name' => $input['name'] ?? null,
  422. 'type' => $input['discount_type'] ?? null,
  423. 'value' => $input['value'] ?? null,
  424. 'minimum_quantity' => $input['minimum_quantity'] ?? null,
  425. 'minimum_subtotal' => $input['minimum_spend'] ?? null,
  426. 'applies_to' => $slugs === null ? 'all' : 'chosen',
  427. 'product_ids' => array_map(fn (Product $product) => $product->id, $products),
  428. 'starts_on' => $input['starts_on'] ?? null,
  429. 'ends_on' => $input['ends_on'] ?? null,
  430. 'active' => true,
  431. ];
  432. $validator = Validator::make($form, AutomaticDiscountRules::rules($store, $percent), AutomaticDiscountRules::messages($percent));
  433. if ($validator->fails()) {
  434. $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend', 'product_ids' => 'products'];
  435. $messages = [];
  436. foreach ($validator->errors()->toArray() as $field => $errors) {
  437. $messages[$renamed[$field] ?? $field] = $errors;
  438. }
  439. throw ValidationException::withMessages($messages);
  440. }
  441. $data = $validator->validated();
  442. $preview = new AutomaticDiscount;
  443. AutomaticDiscountRules::fill($preview, $data);
  444. $details = array_filter([
  445. $products !== [] ? 'only on '.implode(', ', array_map(fn (Product $product) => $product->name, $products)) : 'on every product',
  446. filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null,
  447. filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null,
  448. ]);
  449. return [
  450. 'input' => array_intersect_key($input, array_flip(['name', 'discount_type', 'value', 'minimum_quantity', 'minimum_spend', 'products', 'starts_on', 'ends_on'])),
  451. 'summary' => "Start the automatic discount \"{$preview->name}\": {$preview->describe()}, ".implode(', ', $details).'. No code needed',
  452. 'run' => function () use ($store, $data): void {
  453. $offer = new AutomaticDiscount;
  454. $offer->store_id = $store->id;
  455. AutomaticDiscountRules::fill($offer, $data);
  456. $offer->save();
  457. },
  458. ];
  459. }
  460. /**
  461. * @param array<string, mixed> $input
  462. * @param array<string, list<mixed>> $rules
  463. * @return array<string, mixed>
  464. *
  465. * @throws ValidationException
  466. */
  467. private static function validate(array $input, array $rules): array
  468. {
  469. return Validator::make($input, $rules)->validate();
  470. }
  471. /**
  472. * Any product of the store, found by its web-address name (or, failing that, its exact name).
  473. */
  474. private static function findProduct(Store $store, string $slug, string $field): Product
  475. {
  476. $product = $store->products()->with('variants')->where('slug', $slug)->first()
  477. ?? $store->products()->with('variants')->where('name', $slug)->first();
  478. if ($product === null) {
  479. self::fail($field, "This store has no product \"{$slug}\". Use a web-address name from the product list.");
  480. }
  481. return $product;
  482. }
  483. /**
  484. * One of a product's choices, such as "100ml" or "500g / Pedas". Letter case and spaces are ignored.
  485. */
  486. private static function findVariant(Product $product, string $name, string $field): ProductVariant
  487. {
  488. $wanted = self::plain($name);
  489. $variant = $product->variants->first(fn (ProductVariant $variant) => self::plain($variant->name()) === $wanted);
  490. if ($variant === null) {
  491. self::fail($field, "\"{$product->name}\" has no choice \"{$name}\". Its choices are: ".$product->variants->map->name()->implode(', ').'.');
  492. }
  493. return $variant;
  494. }
  495. private static function descriptionNote(mixed $description): string
  496. {
  497. $text = self::cleanText($description);
  498. return $text === null ? '' : ". Description: \"{$text}\"";
  499. }
  500. /**
  501. * Trimmed text, or null when empty.
  502. */
  503. private static function cleanText(mixed $text): ?string
  504. {
  505. $text = trim((string) $text);
  506. return $text === '' ? null : $text;
  507. }
  508. private static function plain(string $text): string
  509. {
  510. return mb_strtolower((string) preg_replace('/\s+/', '', $text));
  511. }
  512. /**
  513. * @throws ValidationException
  514. */
  515. private static function fail(string $field, string $message): never
  516. {
  517. throw ValidationException::withMessages([$field => $message]);
  518. }
  519. private static function wasPrice(mixed $compare): string
  520. {
  521. return filled($compare) ? ' (was '.self::money(self::sen($compare)).')' : '';
  522. }
  523. private static function money(int $sen): string
  524. {
  525. return 'RM '.number_format($sen / 100, 2);
  526. }
  527. private static function sen(mixed $ringgit): int
  528. {
  529. return (int) round(((float) $ringgit) * 100);
  530. }
  531. }