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', ]; /** * 仅查询已过期的优惠券 */ 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()) { return NumericHelper::trimTrailingZero(bcdiv($value, 10, 1)); } return NumericHelper::trimTrailingZero(bcdiv($value, 100, 2)); } /** * 获取此优惠券的面值 * * @return string */ public function getCouponThresholdFormatAttribute(): string { return NumericHelper::trimTrailingZero( bcdiv($this->attributes['coupon_threshold'], 100, 2) ); } }