From caeb5064a975f3482a3bf5319d8f3732aab19474 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Witold=20Wis=CC=81niewski?= Date: Mon, 28 Oct 2024 10:19:44 +0100 Subject: [PATCH] Added random number order code --- app/Services/NameService.php | 6 ++++++ app/Services/OrderService.php | 11 ++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/Services/NameService.php b/app/Services/NameService.php index 1de908dc2..4439092ed 100644 --- a/app/Services/NameService.php +++ b/app/Services/NameService.php @@ -25,6 +25,7 @@ public function generate(): string return $this->render($pattern, [ 'r' => Str::of(Str::random())->upper(), + 'n' => $this->generateRandomDigits(), 'year' => date('Y'), 'month' => date('n'), @@ -92,4 +93,9 @@ private function render(string $pattern, array $params): string return $number; } + + private function generateRandomDigits(int $count = 3, int $min = 10000, int $max = 99999): string + { + return implode('', array_map(fn () => mt_rand($min, $max), range(1, $count))); + } } diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php index 392e3e6f1..7bad9d345 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -179,7 +179,7 @@ public function store(OrderDto $dto): Order /** @var Order $order */ $order = Order::query()->create( [ - 'code' => $this->nameService->generate(), + 'code' => $this->generateUniqueOrderCode(), 'currency' => $currency->value, 'shipping_price_initial' => Money::zero($currency->value), 'shipping_price' => Money::zero($currency->value), @@ -692,4 +692,13 @@ private function resolveShippingPlace( default => null, }; } + + private function generateUniqueOrderCode(): string + { + do { + $code = $this->nameService->generate(); + } while (Order::query()->where('code', '=', $code)->exists()); + + return $code; + } }