104 lines
2.2 KiB
PHP
104 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Helpers\Numeric as NumericHelper;
|
|
use EloquentFilter\Filterable;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class UserCoupon extends Model
|
|
{
|
|
use HasFactory;
|
|
use Filterable;
|
|
|
|
protected $fillable = [
|
|
'user_id',
|
|
'coupon_id',
|
|
'coupon_name',
|
|
'coupon_type',
|
|
'coupon_amount',
|
|
'coupon_threshold',
|
|
'use_start_at',
|
|
'use_end_at',
|
|
'status',
|
|
'created_at',
|
|
'updated_at',
|
|
];
|
|
|
|
/**
|
|
* 仅查询已过期的优惠券
|
|
*/
|
|
public function scopeIsExpired($query)
|
|
{
|
|
return $query->where('status', 0)->where('use_end_at', '<=', now());
|
|
}
|
|
|
|
/**
|
|
* 仅查询已使用的优惠券
|
|
*/
|
|
public function scopeIsUsed($query)
|
|
{
|
|
return $query->where('status', 1);
|
|
}
|
|
|
|
/**
|
|
* 仅查询未使用的优惠券
|
|
*/
|
|
public function scopeIsUnuse($query)
|
|
{
|
|
$time = now();
|
|
|
|
return $query->where('status', 0)->where('use_start_at', '<', $time)->where('use_end_at', '>', $time);
|
|
}
|
|
|
|
/**
|
|
* 优惠券可用范围规则
|
|
*
|
|
* @return void
|
|
*/
|
|
public function ranges()
|
|
{
|
|
return $this->hasMany(CouponRange::class, 'coupon_id', 'coupon_id');
|
|
}
|
|
|
|
/**
|
|
* 确认此优惠券是否是折扣券
|
|
*
|
|
* @return bool
|
|
*/
|
|
public function isDiscountCoupon(): bool
|
|
{
|
|
return $this->coupon_type === Coupon::TYPE_DISCOUNT;
|
|
}
|
|
|
|
/**
|
|
* 获取此优惠券的面值
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getCouponAmountFormatAttribute(): string
|
|
{
|
|
$value = $this->attributes['coupon_amount'];
|
|
|
|
// 如果是折扣券
|
|
if ($this->isDiscountCoupon()) {
|
|
return NumericHelper::trimZero(bcdiv($value, 10, 1));
|
|
}
|
|
|
|
return NumericHelper::trimZero(bcdiv($value, 100, 2));
|
|
}
|
|
|
|
/**
|
|
* 获取此优惠券的面值
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getCouponThresholdFormatAttribute(): string
|
|
{
|
|
return NumericHelper::trimZero(
|
|
bcdiv($this->attributes['coupon_threshold'], 100, 2)
|
|
);
|
|
}
|
|
}
|