GiftCards.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. <?php
  2. namespace Longyi\Gift\Models;
  3. use Illuminate\Support\Str;
  4. use Longyi\Gift\Models\GiftCardUsageLog;
  5. use Illuminate\Database\Eloquent\Factories\HasFactory;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Longyi\Gift\Contracts\GiftCards as GiftCardsContract;
  8. use Longyi\RewardPoints\Config\TransactionType;
  9. use Longyi\RewardPoints\Repositories\RewardPointRepository;
  10. use function Symfony\Component\Translation\t;
  11. use Illuminate\Support\Facades\DB;
  12. use Carbon\Carbon;
  13. class GiftCards extends Model implements GiftCardsContract
  14. {
  15. use HasFactory;
  16. /**
  17. * 未使用(可用)。
  18. */
  19. public const STATUS_UNUSED = 1;
  20. /**
  21. * 已使用(余额已用完)。
  22. */
  23. public const STATUS_USED = 2;
  24. /**
  25. * 已过期(超过 expirationdate,由 gift-cards:expire 定时任务写入)。
  26. */
  27. public const STATUS_EXPIRED = 3;
  28. /**
  29. * 「已经领过」的状态:未使用 + 已过期(已用完的不算)。
  30. *
  31. * 礼品卡过期后状态会从「未使用」变成「已过期」,但业务上依然算领过,
  32. * 不能再拿积分重复兑换同一渠道的礼品卡 —— 所以前台列表和兑换接口统一用这个范围。
  33. */
  34. public const CLAIMED_STATUSES = [self::STATUS_UNUSED, self::STATUS_EXPIRED];
  35. protected $table = 'gift_cards';
  36. protected $fillable = [
  37. 'giftcard_number',
  38. 'giftcard_amount',
  39. 'used_giftcard_amount',
  40. 'remaining_giftcard_amount',
  41. 'customer_id',
  42. 'channel',
  43. 'expirationdate',
  44. 'giftcard_status',
  45. ];
  46. protected $casts = [
  47. 'giftcard_amount' => 'decimal:2',
  48. 'used_giftcard_amount' => 'decimal:2',
  49. 'remaining_giftcard_amount' => 'decimal:2',
  50. 'customer_id' => 'integer',
  51. 'expirationdate' => 'datetime',
  52. 'channel' => 'string',
  53. ];
  54. protected static function boot()
  55. {
  56. parent::boot();
  57. static::created(function ($giftCard) {
  58. GiftCardUsageLog::create([
  59. 'giftcard_number' => $giftCard->giftcard_number,
  60. 'customer_id' => $giftCard->customer_id,
  61. 'balance_before' => $giftCard->giftcard_amount,
  62. 'balance_after' => $giftCard->giftcard_amount,
  63. 'action_type' => GiftCardUsageLog::ACTION_ADD,
  64. 'status' => 'completed',
  65. 'notes' => $giftCard->channel ?: '',
  66. ]);
  67. });
  68. }
  69. public static function setGiftCardCode($giftcard)
  70. {
  71. if (!$giftcard) {
  72. return false;
  73. }
  74. $cart = cart()->getCart();
  75. $cart->giftcard_number = $giftcard->giftcard_number;
  76. $cart->save();
  77. return true;
  78. }
  79. public static function removeGiftCardCode()
  80. {
  81. $cart = cart()->getCart();
  82. $giftcardAmount = $cart->giftcard_amount ?? 0;
  83. // 清除购物车中的礼品卡标记
  84. $cart->giftcard_number = null;
  85. $cart->giftcard_amount = null;
  86. $cart->base_giftcard_amount = null;
  87. // 恢复购物车总额
  88. $cart->grand_total += $giftcardAmount;
  89. $cart->base_grand_total += $giftcardAmount;
  90. $cart->save();
  91. return true;
  92. }
  93. /**
  94. * Add a new gift card for a customer.
  95. *
  96. * @param int $customerId The ID of the customer to receive the gift card.
  97. * @param float $giftcardAmount The initial amount/balance of the gift card.
  98. * @param int $num Maximum number of gift cards allowed for this channel (0 means unlimited).
  99. * @param int $expirationdate Number of days until the gift card expires (default: 30 days).
  100. * @param string $channel The source channel or campaign identifier (default: 'activity_26_04_21').
  101. * @param string $notes Additional notes or description for the gift card creation.
  102. * @return void
  103. * @throws \Exception If customerId is empty, giftcardAmount is empty, or gift card limit exceeded.
  104. */
  105. public static function addGiftCard($customerId, $giftcardAmount, $num = 0, $expirationdate = 30, $channel = 'activity_26_04_21', $notes = '拉新活动添加')
  106. {
  107. if (empty($customerId)) {
  108. throw new \Exception('customerId is empty');
  109. }
  110. if (empty($giftcardAmount)) {
  111. throw new \Exception('giftcardAmount is empty');
  112. }
  113. // $num > 0 表示该渠道最多允许「已领过」(未使用 + 已过期)这么多张,超出就报错
  114. if ($num > 0) {
  115. $claimedNum = GiftCards::where('customer_id', $customerId)
  116. ->where('channel', $channel)
  117. ->whereIn('giftcard_status', self::CLAIMED_STATUSES)
  118. ->count();
  119. if ($claimedNum >= $num) {
  120. throw new \Exception("Gift card limit reached for channel {$channel} (max: {$num}).");
  121. }
  122. }
  123. $expirationDate = self::calculateExpirationDate($expirationdate);
  124. static::create([
  125. 'giftcard_number' => self::generateGiftCardNumber(),
  126. 'giftcard_amount' => $giftcardAmount,
  127. 'used_giftcard_amount' => 0,
  128. 'remaining_giftcard_amount' => $giftcardAmount,
  129. 'customer_id' => $customerId,
  130. 'expirationdate' => $expirationDate,
  131. 'giftcard_status' => self::STATUS_UNUSED,
  132. 'channel' => $channel,
  133. 'notes' => $notes
  134. ]);
  135. }
  136. /**
  137. * Calculate expiration date from various input types.
  138. *
  139. * @param mixed $expirationdate Days (int), date string, or Carbon instance
  140. * @return \Carbon\Carbon Calculated expiration date
  141. * @throws \Exception If the input type is invalid
  142. */
  143. protected static function calculateExpirationDate($expirationdate): Carbon
  144. {
  145. if ($expirationdate instanceof Carbon) {
  146. return $expirationdate;
  147. }
  148. if (is_string($expirationdate)) {
  149. try {
  150. return Carbon::parse($expirationdate);
  151. } catch (\Exception $e) {
  152. throw new \Exception("Invalid date format: {$expirationdate}. Use Y-m-d format.");
  153. }
  154. }
  155. if (is_int($expirationdate) || is_float($expirationdate)) {
  156. if ($expirationdate <= 0) {
  157. throw new \Exception('Expiration days must be greater than 0');
  158. }
  159. return now()->addDays((int) $expirationdate);
  160. }
  161. throw new \Exception('Invalid expiration date type. Must be integer (days), string (Y-m-d), or Carbon instance.');
  162. }
  163. /**
  164. * 这张礼品卡是否已过期。
  165. *
  166. * 状态已被定时任务标成「已过期」,或者过期时间已经过去,都算过期;
  167. * expirationdate 为空的卡视为永久有效。
  168. */
  169. public function isExpired(): bool
  170. {
  171. if ((int) $this->giftcard_status === self::STATUS_EXPIRED) {
  172. return true;
  173. }
  174. return $this->expirationdate !== null && $this->expirationdate->isPast();
  175. }
  176. public static function generateGiftCardNumber()
  177. {
  178. do {
  179. // Generate a random string of characters
  180. $randomString = Str::upper(Str::random(16));
  181. // Format the string into groups of four separated by dashes
  182. $code = implode('-', str_split($randomString, 4));
  183. // Check if the code already exists in the database
  184. $exists = GiftCards::where('giftcard_number', $code)->exists();
  185. } while ($exists);
  186. return $code;
  187. }
  188. public function giftcards()
  189. {
  190. return [
  191. 1 => [
  192. 'id' => 1,
  193. 'name' => 'Gift Card 1',
  194. 'amount' => 20.00,
  195. 'points' => 20,
  196. 'num' => 0,
  197. 'expirationdate' => 30,
  198. 'channel' => 'activity_26_04_21',
  199. 'notes' => ''
  200. ],
  201. 2 => [
  202. 'id' => 2,
  203. 'name' => 'Gift Card 2',
  204. 'amount' => 30.00,
  205. 'points' => 30,
  206. 'num' => 0,
  207. 'expirationdate' => 30,
  208. 'channel' => 'activity_26_04_21',
  209. 'notes' => ''
  210. ],
  211. 3 => [
  212. 'id' => 3,
  213. 'name' => 'Gift Card 3',
  214. 'amount' => 40.00,
  215. 'points' => 40,
  216. 'num' => 0,
  217. 'expirationdate' => 30,
  218. 'channel' => 'activity_26_04_21',
  219. 'notes' => ''
  220. ],
  221. 4 => [
  222. 'id' => 4,
  223. 'name' => 'Gift Card 4',
  224. 'amount' => 50.00,
  225. 'points' => 50,
  226. 'num' => 0,
  227. 'expirationdate' => 30,
  228. 'channel' => 'activity_26_04_21',
  229. 'notes' => ''
  230. ],
  231. ];
  232. }
  233. /**
  234. * Add a gift card for a customer using points
  235. *
  236. * @param int $id Gift card ID from giftcards() array
  237. * @param int $customerId Customer ID
  238. * @return array|true
  239. */
  240. public function add($id, $customerId)
  241. {
  242. if (empty($customerId)) {
  243. throw new \Exception('customer id is empty');
  244. }
  245. if (empty($id)) {
  246. throw new \Exception('gift card id is empty');
  247. }
  248. $gifts = $this->giftcards();
  249. $giftInfo = $gifts[$id] ?? null;
  250. if (!$giftInfo) {
  251. throw new \Exception("gift card not found (ID: {$id})");
  252. }
  253. $points = $giftInfo['points'] ?? 0;
  254. if ($points <= 0) {
  255. throw new \Exception("gift card points configuration error (points: {$points})");
  256. }
  257. try {
  258. DB::beginTransaction();
  259. self::addGiftCard(
  260. $customerId,
  261. $giftInfo['amount'],
  262. $giftInfo['num'],
  263. $giftInfo['expirationdate'],
  264. $giftInfo['channel'],
  265. $giftInfo['notes']
  266. );
  267. $rewardPointRepository = app(RewardPointRepository::class);
  268. $rewardPointRepository->deductPoints(
  269. $customerId,
  270. $points,
  271. TransactionType::GIFT_CARD_REDEEM,
  272. 'Gift Card Redeem'
  273. );
  274. DB::commit();
  275. return true;
  276. } catch (\Exception $e) {
  277. DB::rollBack();
  278. throw $e;
  279. }
  280. }
  281. }