star-cloud/app/Models/Transaction/PickupCode.php
sky121113 fc93a0fb8c [FEAT] 實作封閉迴圈交易審核與 API 規格標準化
1. 新增 B680 員工卡驗證 API 並更新相關技術文件 (SKILL.md, api-docs.php)。
2. 重構取貨碼與通行碼之日誌追蹤系統,新增 PickupCodeLog 與 PassCodeLog 模型及資料表遷移。
3. 修正 B660 API 路由方法,統一使用 POST 進行驗證。
4. 優化後台銷售中心介面,將「紀錄」頁籤統一為「使用紀錄」並優化狀態顯示組件。
5. 更新多語系 zh_TW.json 以符合新的 UI 命名規範。
6. 調整 Order 模型與 TransactionService 以支援更精確的封閉迴圈交易審核。
2026-05-05 17:50:26 +08:00

100 lines
2.1 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',
'order_id',
];
/**
* 獲取公開取貨連結
*/
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 order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
/**
* 判斷是否可用
*/
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;
}
}