star-cloud/app/Models/Transaction/PickupCode.php
sky121113 78321ad693 [FEAT] 取貨碼功能優化與 QR Code 生成標準化
1. 修復 PickupCode 與 PassCode 模型中 User 命名空間錯誤。
2. 建立統一的 x-qr-code 組件,取代外部 API 並收斂至系統後端路由。
3. 優化取貨碼管理介面:將機台與商品貨道資訊拆分欄位,並動態顯示關聯商品名稱。
4. 補全 status-badge 組件中已使用、已過期與已取消的狀態樣式。
5. 修復取貨碼產生過程中的 Carbon 型別錯誤與 company_id 缺失問題。
2026-04-28 17:25:59 +08:00

72 lines
1.5 KiB
PHP

<?php
namespace App\Models\Transaction;
use App\Models\Machine\Machine;
use App\Models\System\User;
use App\Traits\TenantScoped;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class PickupCode extends Model
{
use TenantScoped;
protected $fillable = [
'company_id',
'machine_id',
'slot_no',
'code',
'expires_at',
'used_at',
'status',
'created_by',
];
protected $casts = [
'expires_at' => 'datetime',
'used_at' => 'datetime',
];
/**
* 關聯機台
*/
public function machine(): BelongsTo
{
return $this->belongsTo(Machine::class);
}
/**
* 關聯建立者
*/
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
/**
* 判斷是否可用
*/
public function isValid(): bool
{
return $this->status === 'active' && $this->expires_at->isFuture();
}
/**
* 產生唯一的取貨碼 (4位)
*/
public static function generateUniqueCode(int $machineId): string
{
do {
$code = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
$exists = self::where('machine_id', $machineId)
->where('code', $code)
->where('status', 'active')
->where('expires_at', '>', now())
->exists();
} while ($exists);
return $code;
}
}