diff --git a/app/Services/NameService.php b/app/Services/NameService.php index 1de908dc..4439092e 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 392e3e6f..7bad9d34 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; + } }