star-cloud/app/Models/Transaction/PickupCode.php
sky121113 6b9b577978 [FEAT] 取貨碼功能強化與 UI 重構
1. 取貨碼模組新增 Slug 機制與公開憑證頁面,支援外部連結訪問。
2. 狀態篩選下拉選單重構為極簡奢華風組件 (x-searchable-select),並優化後端空值處理。
3. 機台分佈地圖新增「依型號分類」功能,提升管理便利性。
4. 新增 B660 取貨碼驗證 API 端點供機台通訊使用。
5. 更新多語言語系檔 (zh_TW.json) 確保介面一致性。
2026-04-29 10:39:35 +08:00

91 lines
1.9 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',
'slug',
'expires_at',
'used_at',
'status',
'created_by',
];
/**
* 獲取公開取貨連結
*/
public function getTicketUrlAttribute()
{
return $this->slug ? route('pickup.ticket', $this->slug) : route('pickup.ticket', $this->code);
}
/**
* Boot the model.
*/
protected static function booted()
{
static::creating(function ($pickupCode) {
$pickupCode->slug = \Illuminate\Support\Str::random(16);
});
}
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();
}
/**
* 產生唯一的取貨碼 (8位)
*/
public static function generateUniqueCode(int $machineId): string
{
do {
$code = str_pad(rand(0, 99999999), 8, '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;
}
}