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

ChatActions.php 33KB

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