6
0
Fork 0
jiqu-library-server/app/Models/UserCoupon.php

165 lines
3.4 KiB
PHP

<?php
namespace App\Models;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserCoupon extends Model
{
use HasFactory;
use Filterable;
/**
* @var array
*/
protected $attributes = [
'is_use' => false,
];
/**
* @var array
*/
protected $casts = [
'is_use' => 'bool',
'use_start_at' => 'datetime',
'use_end_at' => 'datetime',
];
/**
* @var array
*/
protected $fillable = [
'user_id',
'coupon_id',
'coupon_name',
'coupon_type',
'coupon_amount',
'coupon_threshold',
'use_start_at',
'use_end_at',
'is_use',
'created_at',
'updated_at',
'activity_id',
];
/**
* 仅查询已过期的优惠券
*/
public function scopeOnlyExpired($query)
{
return $query->where('is_use', false)->where('use_end_at', '<=', now());
}
/**
* 仅查询已使用的优惠券
*/
public function scopeOnlyUsed($query)
{
return $query->where('is_use', true);
}
/**
* 仅查询未使用的优惠券
*/
public function scopeOnlyUnuse($query)
{
return $query->where('is_use', false)->where('use_end_at', '>', now());
}
/**
* 仅查询可用的优惠券
*/
public function scopeOnlyAvailable($query)
{
$time = now();
return $query->where('is_use', false)->where('use_start_at', '<', $time)->where('use_end_at', '>', $time);
}
/**
* 优惠券可用范围规则
*/
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;
}
/**
* 确认此优惠券是否支持商品使用
*
* @param \App\Models\ProductSku $sku
* @return bool
*/
public function isSupport(ProductSku $sku): bool
{
if ($this->ranges->count() === 0) {
return true;
}
foreach ($this->ranges as $range) {
if (
($range->isTypeCategory() && in_array($sku->category_id, $range->rangeIds))
|| ($range->isTypeProduct() && in_array($sku->id, $range->rangeIds))
) {
return true;
}
}
return false;
}
/**
* 将此优惠券标记为已使用
*/
public function markAsUse()
{
$this->forceFill([
'is_use' => true,
])->save();
}
/**
* 获取此优惠券的面值
*
* @return string
*/
public function getCouponAmountFormatAttribute(): string
{
$value = $this->attributes['coupon_amount'];
// 如果是折扣券
if ($this->isDiscountCoupon()) {
$value = bcdiv($value, 10, 1);
} else {
$value = bcdiv($value, 100, 2);
}
return trim_trailing_zeros($value);
}
/**
* 获取此优惠券的面值
*
* @return string
*/
public function getCouponThresholdFormatAttribute(): string
{
return trim_trailing_zeros(
bcdiv($this->attributes['coupon_threshold'], 100, 2)
);
}
}