Files
chatroom/app/Models/HolidayEvent.php

107 lines
2.5 KiB
PHP

<?php
/**
* 文件功能:节日福利活动模型
*
* 管理员在后台配置的定时发放金币活动,
* 支持随机/定额两种分配方式,支持一次性或周期性重复。
*
* @author ChatRoom Laravel
*
* @version 1.0.0
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class HolidayEvent extends Model
{
protected $fillable = [
'name',
'description',
'total_amount',
'max_claimants',
'distribute_type',
'min_amount',
'max_amount',
'fixed_amount',
'send_at',
'expire_minutes',
'repeat_type',
'cron_expr',
'target_type',
'target_value',
'status',
'enabled',
'triggered_at',
'expires_at',
'claimed_count',
'claimed_amount',
];
/**
* 属性类型转换。
*/
protected function casts(): array
{
return [
'send_at' => 'datetime',
'triggered_at' => 'datetime',
'expires_at' => 'datetime',
'enabled' => 'boolean',
'total_amount' => 'integer',
'max_claimants' => 'integer',
'min_amount' => 'integer',
'max_amount' => 'integer',
'fixed_amount' => 'integer',
'expire_minutes' => 'integer',
'claimed_count' => 'integer',
'claimed_amount' => 'integer',
];
}
/**
* 本次活动的所有领取记录。
*/
public function claims(): HasMany
{
return $this->hasMany(HolidayClaim::class, 'event_id');
}
/**
* 判断活动是否在领取有效期内。
*/
public function isClaimable(): bool
{
return $this->status === 'active'
&& $this->expires_at
&& $this->expires_at->isFuture();
}
/**
* 判断是否还有剩余领取名额。
*/
public function hasQuota(): bool
{
if ($this->max_claimants === 0) {
return true; // 不限人数
}
return $this->claimed_count < $this->max_claimants;
}
/**
* 查询待触发的活动(定时任务调用)。
*/
public static function pendingToTrigger(): \Illuminate\Database\Eloquent\Collection
{
return static::query()
->where('status', 'pending')
->where('enabled', true)
->where('send_at', '<=', now())
->get();
}
}