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