diff --git a/app/Classes/Modules/Transactions/Services/GeneratesTransactionBillNumber.php b/app/Classes/Modules/Transactions/Services/GeneratesTransactionBillNumber.php index 4505707e..943da696 100644 --- a/app/Classes/Modules/Transactions/Services/GeneratesTransactionBillNumber.php +++ b/app/Classes/Modules/Transactions/Services/GeneratesTransactionBillNumber.php @@ -3,6 +3,7 @@ namespace App\Classes\Modules\Transactions\Services; +use App\Classes\Exceptions\InternalServerErrorException; use Carbon\Carbon; class GeneratesTransactionBillNumber @@ -27,14 +28,21 @@ class GeneratesTransactionBillNumber * @return string */ public function execute(string $prefix, ?Carbon $date = null): string { - if(!$date){ - $date = carbon::now(); + if (!$date) { + $date = Carbon::now(); } - $billNumber = $prefix.$date->format('Y').$date->format('m').'-'.mt_rand(10000, 99999); - - return !$this->checksIfTransactionBillNumberExists->execute($billNumber) ? $billNumber : self::execute($prefix); + $attempt = 0; + while ($attempt < 10) { // Retry up to 10 times + $billNumber = $prefix . $date->format('Y') . $date->format('m') . '-' . microtime(true); + if (!$this->checksIfTransactionBillNumberExists->execute($billNumber)) { + return $billNumber; + } + $attempt++; + } + throw new InternalServerErrorException("Unable to generate unique bill number after {$attempt} attempts."); } -} \ No newline at end of file + +}