FreeGiftItem.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace Longyi\FreeGift\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  5. use Longyi\FreeGift\Config\Gift;
  6. use Longyi\FreeGift\Contracts\FreeGiftItem as FreeGiftItemContract;
  7. use Webkul\CartRule\Models\CartRule;
  8. use Webkul\Checkout\Models\Cart;
  9. use Webkul\Checkout\Models\CartItem;
  10. /**
  11. * 赠品在购物车中的状态(每个 购物车 + SKU + 规则 一行)。
  12. *
  13. * 对应 Amasty 的 amasty_ampromo_items_storage。
  14. */
  15. class FreeGiftItem extends Model implements FreeGiftItemContract
  16. {
  17. /**
  18. * The table associated with the model.
  19. *
  20. * @var string
  21. */
  22. protected $table = 'free_gift_items';
  23. /**
  24. * The attributes that are mass assignable.
  25. *
  26. * @var array
  27. */
  28. protected $fillable = [
  29. 'cart_id',
  30. 'cart_item_id',
  31. 'product_id',
  32. 'sku',
  33. 'rule_id',
  34. 'rule_type',
  35. 'allowed_qty',
  36. 'reserved_qty',
  37. 'discount_amount',
  38. 'auto_add',
  39. 'is_item_deleted',
  40. ];
  41. /**
  42. * The attributes that should be cast.
  43. *
  44. * @var array
  45. */
  46. protected $casts = [
  47. 'cart_id' => 'integer',
  48. 'cart_item_id' => 'integer',
  49. 'product_id' => 'integer',
  50. 'rule_id' => 'integer',
  51. 'rule_type' => 'integer',
  52. 'allowed_qty' => 'float',
  53. 'reserved_qty' => 'float',
  54. 'auto_add' => 'boolean',
  55. 'is_item_deleted' => 'boolean',
  56. ];
  57. /**
  58. * 所属购物车。
  59. */
  60. public function cart(): BelongsTo
  61. {
  62. return $this->belongsTo(Cart::class, 'cart_id');
  63. }
  64. /**
  65. * 对应的购物车行。
  66. */
  67. public function cart_item(): BelongsTo
  68. {
  69. return $this->belongsTo(CartItem::class, 'cart_item_id');
  70. }
  71. /**
  72. * 赠送该赠品的规则。
  73. */
  74. public function cart_rule(): BelongsTo
  75. {
  76. return $this->belongsTo(CartRule::class, 'rule_id');
  77. }
  78. /**
  79. * 规则是否允许「一组合计送 N 个」。
  80. */
  81. public function isOneOf(): bool
  82. {
  83. return (int) $this->rule_type === Gift::TYPE_ONE;
  84. }
  85. /**
  86. * 规则是否允许「每个 SKU 各送 N 个」。
  87. */
  88. public function isAllOf(): bool
  89. {
  90. return (int) $this->rule_type === Gift::TYPE_ALL;
  91. }
  92. /**
  93. * 用户是否手动删除过该赠品(删除后不再自动加购,直到购物车清空)。
  94. */
  95. public function isDeleted(): bool
  96. {
  97. return (bool) $this->is_item_deleted;
  98. }
  99. /**
  100. * 还差几个需要补进购物车。
  101. */
  102. public function getQtyToProcessAttribute(): float
  103. {
  104. return max(0, (float) $this->allowed_qty - (float) $this->reserved_qty);
  105. }
  106. }