Files
portal-api/app/Helpers/OrderHelper.php
T
2026-09-27 11:42:40 +07:00

46 lines
1.2 KiB
PHP

<?php
namespace App\Helpers;
use App\Enums\Product\ProductBillingCycle;
use App\Models\Invoice;
use App\Models\Order;
use Illuminate\Support\Str;
class OrderHelper
{
/**
* Generate a unique prefixed number.
*
* Examples:
* generateOrderNumber() → ORD-A1B2C3D4
* generateOrderNumber('INV') → INV-A1B2C3D4
*
* Uniqueness is guaranteed by checking the correct column on each model.
*/
public static function generateOrderNumber(string $prefix = 'ORD'): string
{
do {
$number = $prefix . '-' . strtoupper(Str::random(8));
$exists = match ($prefix) {
'INV' => Invoice::where('invoice_number', $number)->exists(),
default => Order::where('order_num', $number)->exists(),
};
} while ($exists);
return $number;
}
/**
* @throws \InvalidArgumentException
*/
public static function cycleToMonths(?string $cycle): int
{
$enum = ProductBillingCycle::tryFrom($cycle ?? '')
?? throw new \InvalidArgumentException("Unknown billing cycle: " . ($cycle ?? 'null'));
return $enum === ProductBillingCycle::ONE_TIME ? 1 : $enum->months();
}
}