codes.txt

This commit is contained in:
Mekan1206
2026-06-03 21:24:00 +05:00
parent c74330cfaf
commit fa3202288f
9 changed files with 341 additions and 17 deletions

View File

@@ -2,12 +2,16 @@
namespace App\Services;
use App\Exceptions\CouponPoolExhaustedException;
use App\Models\Coupon;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Str;
class CouponService
{
public function __construct(
private CouponCodePool $couponCodePool,
) {}
public function findOrCreateForPhone(string $phone): Coupon
{
$existing = Coupon::query()->where('phone', $phone)->first();
@@ -22,24 +26,22 @@ class CouponService
private function createWithUniqueCode(string $phone): Coupon
{
for ($attempt = 0; $attempt < 10; $attempt++) {
$code = $this->couponCodePool->pickRandom();
if ($code === null) {
throw new CouponPoolExhaustedException;
}
try {
return Coupon::query()->create([
'phone' => $phone,
'code' => $this->generateCouponCode(),
'code' => $code,
]);
} catch (UniqueConstraintViolationException) {
continue;
}
}
throw new \RuntimeException('Unable to generate a unique coupon code.');
}
private function generateCouponCode(): string
{
$x = random_int(1, 9);
$yyyy = Str::upper(Str::random(4));
return "{$x}_{$yyyy}";
throw new CouponPoolExhaustedException;
}
}