'boolean', ]; /** * 折扣类型:固定折扣 */ const DISCOUNT_TYPE_FIXED = 1; /** * 折扣类型:百分比折扣 */ const DISCOUNT_TYPE_PERCENTAGE = 2; /** * 获取折扣类型文本 * * @return string */ public function getDiscountTypeTextAttribute(): string { return match ($this->discount_type) { self::DISCOUNT_TYPE_FIXED => '固定折扣', self::DISCOUNT_TYPE_PERCENTAGE => '百分比折扣', default => '未知', }; } /** * 获取该促销活动关联的商品 * * @return BelongsToMany */ public function items(): BelongsToMany { return $this->belongsToMany( ShopItem::class, 'shop_promotion_items', 'promotion_id', 'shop_item_id' )->withPivot('custom_discount_value') ->withTimestamps(); } /** * 获取促销活动的商品关联记录 * * @return HasMany */ public function promotionItems(): HasMany { return $this->hasMany(ShopPromotionItem::class, 'promotion_id'); } /** * 检查促销活动是否有效 * * @return bool */ public function isValid(): bool { if (!$this->is_active) { return false; } $now = now(); if ($this->start_time && $now < $this->start_time) { return false; } if ($this->end_time && $now > $this->end_time) { return false; } return true; } /** * 计算折扣后的价格 * * @param int $originalPrice 原价 * @param int|null $customDiscountValue 自定义折扣值 * @return int 折扣后的价格 */ public function calculateDiscountedPrice(int $originalPrice, ?int $customDiscountValue = null): int { $discountValue = $customDiscountValue ?? $this->discount_value; if ($this->discount_type === self::DISCOUNT_TYPE_FIXED) { return max(0, $originalPrice - $discountValue); } elseif ($this->discount_type === self::DISCOUNT_TYPE_PERCENTAGE) { return (int)($originalPrice * (100 - $discountValue) / 100); } return $originalPrice; } }