37 lines
1.0 KiB
PHP
37 lines
1.0 KiB
PHP
<?php
|
|
|
|
namespace App\Helper;
|
|
|
|
use Carbon\Carbon;
|
|
use Modules\Restaurant\Models\Purchase;
|
|
|
|
class PurchaseHelper
|
|
{
|
|
/**
|
|
* Generate a unique purchase invoice number for a restaurant.
|
|
*
|
|
* Format: PUR-{YYYYMMDD}-{RestaurantId}-{AutoIncrement}
|
|
*/
|
|
public static function generateInvoiceNumber(int $restaurantId): string
|
|
{
|
|
$today = Carbon::now()->format('Ymd');
|
|
|
|
// Get last purchase today for this restaurant
|
|
$lastPurchase = Purchase::where('restaurant_id', $restaurantId)
|
|
->whereDate('created_at', Carbon::today())
|
|
->lockForUpdate() // prevent concurrency issues
|
|
->orderBy('id', 'desc')
|
|
->first();
|
|
|
|
$lastIncrement = 0;
|
|
|
|
if ($lastPurchase && preg_match('/PUR-\d{8}-\d+-([\d]+)/', $lastPurchase->invoice_no, $matches)) {
|
|
$lastIncrement = (int) $matches[1];
|
|
}
|
|
|
|
$newIncrement = $lastIncrement + 1;
|
|
|
|
return "PUR-{$today}-{$restaurantId}-".str_pad($newIncrement, 4, '0', STR_PAD_LEFT);
|
|
}
|
|
}
|