48 lines
1.3 KiB
PHP
48 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Helper;
|
|
|
|
use Carbon\Carbon;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Modules\Restaurant\Models\Order;
|
|
|
|
class OrderHelper
|
|
{
|
|
/**
|
|
* Generate a unique order number for the restaurant.
|
|
*
|
|
* Format: ORD-{YYYYMMDD}-{RestaurantId}-{AutoIncrement}
|
|
*/
|
|
public static function generateOrderNumber(int $restaurantId): string
|
|
{
|
|
$today = Carbon::now()->format('Ymd');
|
|
|
|
// Fetch last order (including soft-deleted)
|
|
$lastOrder = DB::table('orders')
|
|
->where('restaurant_id', $restaurantId)
|
|
->whereDate('created_at', Carbon::today())
|
|
->orderByDesc('id')
|
|
->first();
|
|
|
|
$lastIncrement = 0;
|
|
|
|
if ($lastOrder && preg_match('/ORD-\d{8}-\d+-([\d]+)/', $lastOrder->order_number, $matches)) {
|
|
$lastIncrement = (int) $matches[1];
|
|
}
|
|
|
|
$newIncrement = $lastIncrement + 1;
|
|
|
|
// Ensure unique, retry if needed (handles rare race conditions)
|
|
do {
|
|
$orderNumber = sprintf('ORD-%s-%d-%04d', $today, $restaurantId, $newIncrement);
|
|
$exists = Order::withTrashed()->where('order_number', $orderNumber)->exists();
|
|
|
|
if ($exists) {
|
|
$newIncrement++;
|
|
}
|
|
} while ($exists);
|
|
|
|
return $orderNumber;
|
|
}
|
|
}
|