, summary: string}> * * @throws ValidationException With keys such as "actions.0.price", so the AI can correct them. */ public static function check(Store $store, mixed $actions): array { if ($actions === null || $actions === []) { return []; } if (! is_array($actions) || ! array_is_list($actions)) { throw ValidationException::withMessages(['actions' => 'Must be a list of actions.']); } if (count($actions) > self::MAX_ACTIONS) { throw ValidationException::withMessages(['actions' => 'At most '.self::MAX_ACTIONS.' actions at a time.']); } $checked = []; foreach ($actions as $index => $action) { $prepared = self::prepare($store, $action, $index); $checked[] = ['type' => $prepared['type'], 'input' => $prepared['input'], 'summary' => $prepared['summary']]; } return $checked; } /** * Do actions the merchant confirmed, in order, all or nothing. Each is checked again first. * * @param list, summary: string}> $actions * * @throws ValidationException When one is no longer allowed. Nothing is changed then. */ public static function apply(Store $store, array $actions): void { DB::transaction(function () use ($store, $actions): void { foreach ($actions as $index => $action) { // Each one sees what the ones before it did, such as a product created a step earlier. (self::prepare($store, ['type' => $action['type'], ...$action['input']], $index)['run'])(); } BundleStock::refresh($store->id); }); } /** * @return array{type: string, input: array, summary: string, run: Closure(): void} * * @throws ValidationException */ private static function prepare(Store $store, mixed $action, int $index): array { $type = is_array($action) ? ($action['type'] ?? null) : null; if (! is_string($type) || ! in_array($type, self::TYPES, true)) { throw ValidationException::withMessages(["actions.$index.type" => 'Must be one of: '.implode(', ', self::TYPES).'.']); } unset($action['type']); try { $prepared = match ($type) { 'create_product' => self::createProduct($store, $action), 'update_product' => self::updateProduct($store, $action), 'create_discount' => self::createDiscount($store, $action), 'update_discount' => self::updateDiscount($store, $action), 'create_bundle' => self::createBundle($store, $action), }; } catch (ValidationException $e) { // "price" becomes "actions.2.price", so it is clear which action has the problem. $messages = []; foreach ($e->errors() as $field => $errors) { $messages["actions.$index.$field"] = $errors; } throw ValidationException::withMessages($messages); } return ['type' => $type, ...$prepared]; } /** * @param array $input * @return array{input: array, summary: string, run: Closure(): void} */ private static function createProduct(Store $store, array $input): array { $data = self::validate($input, [ 'name' => ['required', 'string', 'min:2', 'max:120'], 'description' => ['nullable', 'string', 'max:5000'], 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'], 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'], 'stock' => ['required', 'integer', 'min:0', 'max:1000000'], 'status' => ['nullable', 'in:active,draft'], ]); $data['status'] ??= ProductStatus::Active->value; $summary = "Add the product \"{$data['name']}\" at ".self::money(self::sen($data['price'])) .self::wasPrice($data['compare_at_price'] ?? null) .", {$data['stock']} in stock, " .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft'); return [ 'input' => $data, 'summary' => $summary, 'run' => function () use ($store, $data): void { $store->products()->create([ 'name' => $data['name'], 'description' => $data['description'] ?? null, 'price' => self::sen($data['price']), 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null, 'stock' => (int) $data['stock'], 'status' => $data['status'], ]); }, ]; } /** * @param array $input * @return array{input: array, summary: string, run: Closure(): void} */ private static function updateProduct(Store $store, array $input): array { $data = self::validate($input, [ 'product' => ['required', 'string'], 'variant' => ['nullable', 'string', 'max:90'], 'name' => ['sometimes', 'string', 'min:2', 'max:120'], 'price' => ['sometimes', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'], 'compare_at_price' => ['sometimes', 'nullable', 'numeric', 'decimal:0,2', 'max:999999.99'], 'stock' => ['sometimes', 'integer', 'min:0', 'max:1000000'], 'status' => ['sometimes', 'in:active,draft'], ]); $product = self::findProduct($store, $data['product'], 'product'); $priceFields = array_intersect(['price', 'compare_at_price', 'stock'], array_keys($data)); $productFields = array_intersect(['name', 'status'], array_keys($data)); if ($priceFields === [] && $productFields === []) { self::fail('product', 'Say what to change: name, price, compare_at_price, stock or status.'); } $variant = null; if (filled($data['variant'] ?? null)) { if (! $product->hasVariants()) { self::fail('variant', "\"{$product->name}\" has no options. Leave out \"variant\"."); } $variant = self::findVariant($product, $data['variant'], 'variant'); } elseif ($product->hasVariants() && $priceFields !== []) { 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().'".'); } if ($product->isBundle() && array_key_exists('stock', $data)) { self::fail('stock', "\"{$product->name}\" is a bundle. Its stock comes from the products inside it."); } // The "was" price must stay above the price, whichever of the two changes. $owner = $variant ?? $product; $newPrice = array_key_exists('price', $data) ? self::sen($data['price']) : $owner->price; $newCompare = array_key_exists('compare_at_price', $data) ? (filled($data['compare_at_price']) ? self::sen($data['compare_at_price']) : null) : $owner->compare_at_price; if ($newCompare !== null && $newCompare <= $newPrice) { self::fail('compare_at_price', 'The "was" price must be higher than the price.'); } $changes = []; if (array_key_exists('name', $data) && $data['name'] !== $product->name) { $changes[] = "name to \"{$data['name']}\""; } if ($newPrice !== $owner->price) { $changes[] = 'price '.self::money($owner->price).' → '.self::money($newPrice); } if ($newCompare !== $owner->compare_at_price) { $changes[] = $newCompare === null ? 'remove the "was" price' : '"was" price '.($owner->compare_at_price !== null ? self::money($owner->compare_at_price).' → ' : '').self::money($newCompare); } if (array_key_exists('stock', $data) && (int) $data['stock'] !== $owner->stock) { $changes[] = "stock {$owner->stock} → {$data['stock']}"; } if (array_key_exists('status', $data) && $data['status'] !== $product->status->value) { $changes[] = $data['status'] === 'active' ? 'show it in the store' : 'hide it (draft)'; } if ($changes === []) { self::fail('product', 'These values are already set. Nothing would change.'); } $label = $product->name.($variant !== null ? ' ('.$variant->name().')' : ''); return [ 'input' => $data, 'summary' => "Change \"{$label}\": ".implode(', ', $changes), 'run' => function () use ($product, $variant, $data, $newPrice, $newCompare): void { $owner = $variant ?? $product; $owner->price = $newPrice; $owner->compare_at_price = $newCompare; if (array_key_exists('stock', $data)) { $owner->stock = (int) $data['stock']; } $owner->save(); if (array_key_exists('name', $data)) { $product->name = $data['name']; } if (array_key_exists('status', $data)) { $product->status = ProductStatus::from($data['status']); } $product->save(); $product->syncFromVariants(); }, ]; } /** * @param array $input * @return array{input: array, summary: string, run: Closure(): void} */ private static function createDiscount(Store $store, array $input): array { $input['code'] = DiscountCode::normalize((string) ($input['code'] ?? '')); $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT; // The same rules as the Discounts form. The chat names some fields more plainly. $form = [ 'code' => $input['code'], 'type' => $input['discount_type'] ?? null, 'value' => $input['value'] ?? null, 'minimum_subtotal' => $input['minimum_spend'] ?? null, 'starts_on' => $input['starts_on'] ?? null, 'ends_on' => $input['ends_on'] ?? null, 'usage_limit' => $input['usage_limit'] ?? null, 'active' => true, ]; $validator = Validator::make($form, DiscountCodeRules::rules($store, $percent), DiscountCodeRules::messages($percent)); if ($validator->fails()) { $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend']; $messages = []; foreach ($validator->errors()->toArray() as $field => $errors) { $messages[$renamed[$field] ?? $field] = $errors; } throw ValidationException::withMessages($messages); } $data = $validator->validated(); $amount = $percent ? $data['value'].'% off' : self::money(self::sen($data['value'])).' off'; $details = array_filter([ filled($data['minimum_subtotal'] ?? null) ? 'when spending at least '.self::money(self::sen($data['minimum_subtotal'])) : null, filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null, filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null, filled($data['usage_limit'] ?? null) ? "up to {$data['usage_limit']} uses" : null, ]); return [ 'input' => array_intersect_key($input, array_flip(['code', 'discount_type', 'value', 'minimum_spend', 'starts_on', 'ends_on', 'usage_limit'])), 'summary' => "Create the discount code {$data['code']}: {$amount}".($details !== [] ? ', '.implode(', ', $details) : ''), 'run' => function () use ($store, $data): void { $code = new DiscountCode; $code->store_id = $store->id; DiscountCodeRules::fill($code, $data); $code->save(); }, ]; } /** * Switch a code on or off, or change its last day or number of uses. * * @param array $input * @return array{input: array, summary: string, run: Closure(): void} */ private static function updateDiscount(Store $store, array $input): array { $data = self::validate($input, [ 'code' => ['required', 'string'], 'active' => ['sometimes', 'boolean'], 'ends_on' => ['sometimes', 'nullable', 'date_format:Y-m-d'], 'usage_limit' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:1000000'], ]); $code = $store->discountCodes()->where('code', DiscountCode::normalize($data['code']))->first(); if ($code === null) { self::fail('code', 'This store has no such code. Use one from the list of discount codes.'); } $changes = []; if (array_key_exists('active', $data) && (bool) $data['active'] !== $code->active) { $changes[] = $data['active'] ? 'switch it on' : 'switch it off'; } $endsAt = $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'); if (array_key_exists('ends_on', $data) && $data['ends_on'] !== $endsAt) { $startsAt = $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'); if ($data['ends_on'] !== null && $startsAt !== null && $data['ends_on'] < $startsAt) { self::fail('ends_on', 'The last day cannot be before the first day.'); } $changes[] = $data['ends_on'] === null ? 'no last day' : "last day {$data['ends_on']}"; } if (array_key_exists('usage_limit', $data) && $data['usage_limit'] !== $code->usage_limit) { $changes[] = $data['usage_limit'] === null ? 'no limit on uses' : "up to {$data['usage_limit']} uses"; } if ($changes === []) { self::fail('code', 'Nothing would change. Say what to change: active, ends_on or usage_limit.'); } return [ 'input' => $data, 'summary' => "Change the discount code {$code->code}: ".implode(', ', $changes), 'run' => function () use ($code, $data): void { $form = [ 'code' => $code->code, 'type' => $code->type, 'value' => $code->type === DiscountCode::PERCENT ? $code->value : $code->value / 100, 'minimum_subtotal' => $code->minimum_subtotal !== null ? $code->minimum_subtotal / 100 : null, 'starts_on' => $code->starts_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'), 'ends_on' => array_key_exists('ends_on', $data) ? $data['ends_on'] : $code->ends_at?->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d'), 'usage_limit' => array_key_exists('usage_limit', $data) ? $data['usage_limit'] : $code->usage_limit, 'active' => array_key_exists('active', $data) ? (bool) $data['active'] : $code->active, ]; DiscountCodeRules::fill($code, $form); $code->save(); }, ]; } /** * @param array $input * @return array{input: array, summary: string, run: Closure(): void} */ private static function createBundle(Store $store, array $input): array { $data = self::validate($input, [ 'name' => ['required', 'string', 'min:2', 'max:120'], 'description' => ['nullable', 'string', 'max:5000'], 'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'], 'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'], 'status' => ['nullable', 'in:active,draft'], 'items' => ['required', 'array', 'list', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_ITEMS], 'items.*.product' => ['required', 'string'], 'items.*.variant' => ['nullable', 'string', 'max:90'], 'items.*.quantity' => ['nullable', 'integer', 'min:1', 'max:'.SaveProductRequest::MAX_BUNDLE_QUANTITY], ]); $data['status'] ??= ProductStatus::Active->value; $items = []; $labels = []; $stock = null; foreach ($data['items'] as $index => $item) { $product = self::findProduct($store, $item['product'], "items.$index.product"); if ($product->isBundle()) { self::fail("items.$index.product", 'A bundle cannot hold another bundle.'); } $variant = null; if ($product->hasVariants()) { if (! filled($item['variant'] ?? null)) { self::fail("items.$index.variant", "\"{$product->name}\" has options. Name the one that goes in the bundle, such as \"".$product->variants->first()?->name().'".'); } $variant = self::findVariant($product, $item['variant'], "items.$index.variant"); } $key = $product->id.'-'.$variant?->id; if (isset($items[$key])) { self::fail("items.$index.product", 'This product is already in the bundle. Raise its quantity instead.'); } $quantity = (int) ($item['quantity'] ?? 1); $items[$key] = ['product_id' => $product->id, 'variant_id' => $variant?->id, 'quantity' => $quantity]; $labels[] = $quantity.' × '.$product->name.($variant !== null ? ' ('.$variant->name().')' : ''); $left = intdiv(max(0, $variant !== null ? $variant->stock : $product->stock), $quantity); $stock = $stock === null ? $left : min($stock, $left); } $summary = "Create the bundle \"{$data['name']}\" at ".self::money(self::sen($data['price'])) .self::wasPrice($data['compare_at_price'] ?? null) .': '.implode(', ', $labels) .". Enough stock for {$stock} now, " .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft'); return [ 'input' => $data, 'summary' => $summary, 'run' => function () use ($store, $data, $items): void { $bundle = $store->products()->make([ 'name' => $data['name'], 'description' => $data['description'] ?? null, 'price' => self::sen($data['price']), 'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null, 'stock' => 0, 'status' => $data['status'], ]); $bundle->is_bundle = true; $bundle->save(); BundleItem::replaceFor($bundle, array_values($items)); }, ]; } /** * @param array $input * @param array> $rules * @return array * * @throws ValidationException */ private static function validate(array $input, array $rules): array { return Validator::make($input, $rules)->validate(); } /** * Any product of the store, found by its web-address name (or, failing that, its exact name). */ private static function findProduct(Store $store, string $slug, string $field): Product { $product = $store->products()->with('variants')->where('slug', $slug)->first() ?? $store->products()->with('variants')->where('name', $slug)->first(); if ($product === null) { self::fail($field, "This store has no product \"{$slug}\". Use a web-address name from the product list."); } return $product; } /** * One of a product's choices, such as "100ml" or "500g / Pedas". Letter case and spaces are ignored. */ private static function findVariant(Product $product, string $name, string $field): ProductVariant { $wanted = self::plain($name); $variant = $product->variants->first(fn (ProductVariant $variant) => self::plain($variant->name()) === $wanted); if ($variant === null) { self::fail($field, "\"{$product->name}\" has no choice \"{$name}\". Its choices are: ".$product->variants->map->name()->implode(', ').'.'); } return $variant; } private static function plain(string $text): string { return mb_strtolower((string) preg_replace('/\s+/', '', $text)); } /** * @throws ValidationException */ private static function fail(string $field, string $message): never { throw ValidationException::withMessages([$field => $message]); } private static function wasPrice(mixed $compare): string { return filled($compare) ? ' (was '.self::money(self::sen($compare)).')' : ''; } private static function money(int $sen): string { return 'RM '.number_format($sen / 100, 2); } private static function sen(mixed $ringgit): int { return (int) round(((float) $ringgit) * 100); } }