UserCouponLogic.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\api\logic;
  3. use app\common\logic\BaseLogic;
  4. use app\common\model\coupon\CouponCategory;
  5. use app\common\model\coupon\CouponRules;
  6. use app\common\model\coupon\UserCoupon;
  7. use think\db\Query;
  8. use think\db\Where;
  9. use think\facade\Db;
  10. /**
  11. * @author 林海涛
  12. * @date 2024/7/18 下午4:49
  13. */
  14. class UserCouponLogic extends BaseLogic
  15. {
  16. public static function add($params)
  17. {
  18. Db::startTrans();
  19. try{
  20. $errMsgArr = [];
  21. $rules = CouponRules::whereIn('id',$params['coupon_ids'])->lock(true)->select();
  22. $userCoupon = UserCoupon::where('user_id',$params['user_id'])
  23. ->whereIn('coupon_id',$params['coupon_ids'])
  24. ->where('voucher_count','>',0)
  25. ->select();
  26. $updateData = [];
  27. $createData = [];
  28. foreach($rules as $v) {
  29. if ($v->expire_time < time()) {
  30. $errMsgArr[] = $v->event_name .'已过期';
  31. continue;
  32. }
  33. if($v->voucher_status == 2){
  34. $errMsgArr[] = $v->event_name .'已设置为过期';
  35. continue;
  36. }
  37. if($userCoupon->where('coupon_id',$v->id)->count()){
  38. $errMsgArr[] = $v->event_name . '已领取';
  39. continue;
  40. }
  41. $updateData[$v->id] = ['voucher_count' => --$v->voucher_count];
  42. $createData[] = ['user_id'=>$params['user_id'],'coupon_id' => $v->id,'voucher_count' =>1];
  43. }
  44. CouponRules::updateWhenCase($updateData);
  45. if(!empty($createData)){
  46. (new UserCoupon())->saveAll($createData);
  47. }
  48. Db::commit();
  49. return $errMsgArr;
  50. }catch(\Exception $e){
  51. Db::rollback();
  52. self::setError($e->getMessage());
  53. return false;
  54. }
  55. }
  56. /**
  57. * @param $params
  58. * @return array|false
  59. */
  60. public static function categoryCouponList($params)
  61. {
  62. try{
  63. $data = CouponRules::whereIn('id',CouponCategory::where('goods_category_id',$params['goods_category_id'])->group('coupon_id')->column('coupon_id'))
  64. ->where(['coupon_type'=>1])
  65. ->field(['id', 'amount', 'coupon_type','amount_require', 'begin_use', 'discount_ratio', 'event_name', 'expire_time', 'max_deductible_price', 'mold_type', 'server_category_name', 'voucher_status', 'voucher_count'])
  66. ->order(['id' => 'desc'])
  67. ->select()
  68. ->toArray();
  69. foreach($data as $k => $v){
  70. $v['begin_use'] = $v['begin_use'] ? date('Y-m-d H:i:s',$v['begin_use']) :null;
  71. $v['expire_time'] = $v['begin_use'] ?date('Y-m-d H:i:s',$v['expire_time']) :null;
  72. $data[$k] = $v;
  73. }
  74. return $data;
  75. }catch(\Exception $e){
  76. Db::rollback();
  77. self::setError($e->getMessage());
  78. return false;
  79. }
  80. }
  81. }