star-cloud/app/Models/Transaction/PassCode.php
terrylee 6bb08a13ce feat(sales): 取貨碼/通行碼批次新增(最多1000筆)+ 批次清單 CSV 下載
- 取貨碼沿用「商品版」綁定(product_id,相容舊 slot_no)批次產碼
- 通行碼批次產碼;名稱自動加 #1..#N 流水
- 新增 batch_no 欄位標記同一批,提供批次下載路由與 UTF-8 BOM CSV
- 數量>1 時忽略自訂碼、系統產生不重複隨機碼;單筆行為不變
- 產生後顯示可重複下載清單橫幅;新增 zh_TW/en/ja 翻譯鍵

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 14:00:57 +08:00

103 lines
2.2 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 PassCode extends Model
{
use TenantScoped;
protected $fillable = [
'company_id',
'machine_id',
'name',
'code',
'slug',
'batch_no',
'expires_at',
'status',
'created_by',
];
protected $casts = [
'expires_at' => 'datetime',
];
/**
* 獲取公開通行連結
*/
public function getTicketUrlAttribute()
{
return $this->slug ? route('pass-code.ticket', $this->slug) : null;
}
/**
* Boot the model.
*/
protected static function booted()
{
static::creating(function ($passCode) {
if (!$passCode->slug) {
$passCode->slug = \Illuminate\Support\Str::random(16);
}
});
}
/**
* 關聯機台
*/
public function machine(): BelongsTo
{
return $this->belongsTo(Machine::class);
}
/**
* 關聯建立者
*/
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
/**
* 判斷是否可用
*/
public function isValid(): bool
{
if ($this->status !== 'active') {
return false;
}
if ($this->expires_at && $this->expires_at->isPast()) {
return false;
}
return true;
}
/**
* 產生唯一的通行碼 (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(function($query) {
$query->whereNull('expires_at')
->orWhere('expires_at', '>', now());
})
->exists();
} while ($exists);
return $code;
}
}