|
|
<?php
namespace App\Service;
use Hyperf\Di\Annotation\Inject;use Hyperf\DbConnection\Db;use App\Model\Coupon;use App\Model\CouponUserRecType;use App\Model\CouponRec;use App\Constants\LogLabel;use App\Commons\Log;use Hyperf\Utils\ApplicationContext;use App\TaskWorker\SSDBTask;use App\Constants\SsdbKeysPrefix;use Exception;
class CouponRebateService implements CouponRebateServiceInterface{ /** * @Inject * @var Log */ protected $log;
/** * 领取优惠券 * 返券活动领取 * 一次可领取多张优惠券 * 一个用户不可重复领取 */ public function userReceiveCoupon($params) { $userId = $params["user_id"]; $receiveType = $params["receive_type"]; $ids = $params["ids"]; $sendUserId = $params["send_user_id"]; $phone = $params["phone"]; $now = time(); $idsData = is_array($ids) ? $ids : explode(',',$ids);
// status: 0领取成功 >0领取失败
$result = [ 'status' => 1, 'coupon_text' => '继续努力~' ];
// 错误日志记录
$errorData = [ 'coupon_ids' =>$ids, 'user_id' =>$userId, 'receiveType' =>$receiveType, 'sendUserId' =>$sendUserId, 'phone' =>$phone ];
$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); $receiveSsdb = [];
// 判断是否已全部领取
$couponActivity = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0); $userReceiveCouponIds = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId); if($userReceiveCouponIds !== false){ $ids = array_diff($idsData, $userReceiveCouponIds); $receiveSsdb = $userReceiveCouponIds; }else{ $ids = $idsData; }
if(count($ids) > 0){ try{ Db::transaction( function() use ($ids,$receiveType,$userId,$sendUserId,$phone,$now,&$result,&$errorData,&$receiveSsdb) { $success = []; $fail = []; //读写锁,完全控制,性能低
$coupons = Coupon::whereIn('id', $ids)->lockForUpdate() ->select('id','title','status','inventory','inventory_use','start_time','end_time','full_amount','discounts','active_type') ->get(); foreach($coupons as $coupon){ $errorData['coupon_id'] = $coupon->id; //如果优惠卷库存小于等于已领取的数量 或者 未在活动时间内可领取, 否则返回领取失败的优惠券
if ( $coupon->status == 1 && $coupon->inventory > $coupon->inventory_use && $coupon->start_time <= $now && $coupon->end_time >= $now && $coupon->active_type == 2 ) { // 查询一次能领取的数量
$couponReceiveType = CouponUserRecType::where('system_coupon_user_id',$coupon->id)->select('one_receive_number'); if (env('SUB_CHANNEL') == 1) { $couponReceiveType->where('receive_type',$receiveType); } $couponReceiveType = $couponReceiveType->first(); // 优惠券可领取数量 >= 本次领取数量
if($coupon->inventory - $coupon->inventory_use >= $couponReceiveType->one_receive_number){ // 判断是否领取过 存在记录则领取过
$isReceive = CouponRec::select('id') ->where('system_coupon_user_id',$coupon->id) ->where('user_id',$userId) ->exists(); if(!$isReceive){ //记录已领取的数量
$coupon->inventory_use += $couponReceiveType->number; $couponReceive = new CouponRec; $couponReceive->user_id = $userId; $couponReceive->system_coupon_user_id = $coupon->id; $couponReceive->order_main_id = 0; $couponReceive->receive_time = $now; $couponReceive->number = $couponReceiveType->one_receive_number; $couponReceive->number_remain = $couponReceiveType->one_receive_number; $couponReceive->status = 0; $couponReceive->update_time = $now; $couponReceive->receive_type = $receiveType; $couponReceive->send_user_id = $sendUserId; $couponReceive->phone = $phone; if ( $couponReceive->save() && $coupon->save() ) { $success[] = $coupon; $receiveSsdb[] = $coupon->id; } }else{ $fail[] = $coupon; $receiveSsdb[] = $coupon->id; $result['status'] = 3; $result['coupon_text'] = '您已领取!赶快去下单吧~'; $errorData['msg'] = '用户已经领取了优惠券'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); } }else{ $fail[] = $coupon; $errorData['remain_receive_number'] = $coupon->inventory - $coupon->inventory_use; $errorData['one_receive_number'] = $couponReceiveType->one_receive_number; $errorData['msg'] = '优惠券剩余数量不足'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); } }else{ $fail[] = $coupon; $errorData['msg'] = '优惠券已经过期或者被禁用或者已领完'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); } } $result['data'] = [ 'success' => $success, 'fail' => $fail ]; if(count($success) > 0){ $result['status'] = 0; $result['coupon_text'] = '恭喜您领取成功!'; } }); } catch (Exception $e){ $errorData['msg'] = $e->getMessage(); $this->log->event( LogLabel::COUPON_LOG, $errorData ); }
if(count($receiveSsdb) > 0){ $saveSsdb = []; foreach($receiveSsdb as $kssdb => $vssdb){ $saveSsdb[] = $kssdb; $saveSsdb[] = $vssdb; } // 记录到ssdb
if(false === $ssdb->exec('multi_hset',SsdbKeysPrefix::COUPON_REBATE_RECEIVE . $couponActivity . $userId, $saveSsdb)){ $errorData['msg'] = '记录领取优惠券到ssdb失败'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); }; } }else{ $result['status'] = 2; $result['coupon_text'] = '您已领取!赶快去下单吧~'; } return $result; }
/* * 判断用户是否已领取过优惠券 * */ public function isCouponRebate($user_id) { $res = Db::table('ims_system_coupon_user as u') ->leftjoin('ims_system_coupon_user_receive as r', 'u.id', '=', 'r.system_coupon_user_id') ->where([ ['r.user_id', '=', $user_id], ['r.receive_type', '=', 4], ['u.active_type', '=', 2], ]) ->select('r.id') ->first(); return $res; }
/* *获取活动信息 */ public function getActiveInfo() { $time = time(); $res = Db::table('ims_system_coupon_user') ->where([ ['status', '=', 1], ['active_type', '=', 2], ['start_time', '<=', $time], ['end_time', '>', $time], ]) ->whereRaw('inventory > inventory_use') ->orderBy('addtime', 'desc') ->get(); return $res; } /** * 将优惠券绑定活动 * 领取优惠券 COUPON_REBATE_FORWARD 可多张 * 返还优惠券 COUPON_REBATE_REPAY 只一张 */ public function tieCouponActive($couponActivity, $couponForward, $couponRepay) { $result = [ 'forward' => true, 'repay' => true, 'activity' => true, ];
$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class); // $rrss1 = $ssdb->exec('hgetall', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity);
// $rrss2 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity,0);
// $rrss3 = $ssdb->exec('hget', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY,0);
// return [$rrss1,$rrss2,$rrss3];
// 记录活动本次 activity_type 活动标志值
if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_ACTIVITY, [0,$couponActivity])) {
$this->log->event( LogLabel::COUPON_LOG, [ 'coupon_activity' => $couponActivity, 'msg' => '记录活动标志值(activity_type)到ssdb失败' ] ); $result['activity'] = false; };
// 记录领取类型优惠券
$forwardData = []; foreach ($couponForward as $kForward => $vForward) { $forwardData[] = $kForward; $forwardData[] = $vForward; }
if (false === $ssdb->exec('multi_hset', SsdbKeysPrefix::COUPON_REBATE_FORWARD . $couponActivity, $forwardData)) {
$this->log->event( LogLabel::COUPON_LOG, [ 'coupon_activity' => $couponActivity, 'coupon_forward' => $forwardData, 'msg' => '绑定-领取-优惠券到ssdb失败' ] ); $result['forward'] = false; };
// 记录返还类型优惠券
if (false === $ssdb->exec('hset', SsdbKeysPrefix::COUPON_REBATE_REPAY . $couponActivity, [0,$couponRepay])) {
$this->log->event( LogLabel::COUPON_LOG, [ 'coupon_activity' => $couponActivity, 'coupon_Repay' => $couponRepay, 'msg' => '绑定-返还-优惠券到ssdb失败' ] ); $result['repay'] = false; };
return $result; }
/* * 支付成功 返券 */ public function couponRebate($order_id) { //$ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
// $active_id = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_ACTIVITY);
// $rebate_id = $ssdb->exec('get',SsdbKeysPrefix::COUPON_REBATE_REPAY.$active_id);
$rebate_id = 56; //判断该优惠券是否有库存
$inventory = Db::table('ims_system_coupon_user') ->where('id',$rebate_id) ->whereRaw('inventory > inventory_use') ->exists(); if(!$inventory){ return '库存不足'; } /* 判断优惠券类型是否为转发活动优惠券 */ $coupon = Db::table('ims_system_coupon_user_receive as r') ->leftjoin('ims_system_coupon_user_use as u', 'u.user_receive_id', '=', 'r.id') ->where([ ['u.order_main_id', '=', $order_id], ['r.send_user_id', '>', 0], ['r.rebate_type', '=', 1], ['r.receive_type', '=', 4], ['u.status', '=', 1], ]) ->select('r.id', 'r.user_id', 'r.send_user_id', 'u.system_coupon_id') ->first(); /* 如果使用的优惠券为转发活动优惠券 则给赠送者返一张优惠券*/ if (isset($coupon->send_user_id) && ($coupon->send_user_id) > 0) { //是否已返过券
$exists_coupon_rebate = Db::table('ims_system_coupon_user_receive') ->where([ ['system_coupon_user_id' ,'=', $rebate_id], ['user_id' ,'=', $coupon->send_user_id], ['receive_type' ,'=', 5], ['status' ,'=', 0], ]) ->exists(); //开启事务
Db::beginTransaction(); try { /* * 如果已有该优惠券 则领取数量 和 可用数量 自增1 * 否则新增一条返券记录 */ if($exists_coupon_rebate){ var_dump(222); Db::table('ims_system_coupon_user_receive') ->where([ ['user_id' ,'=', $coupon->send_user_id], ['receive_type' ,'=', 5], ]) ->increment('number'); Db::table('ims_system_coupon_user_receive') ->where([ ['user_id' ,'=', $coupon->send_user_id], ['receive_type' ,'=', 5], ]) ->increment('number_remain'); }else { var_dump(111111222); $nowTime = time(); Db::table('ims_system_coupon_user_receive')->insert([ [ 'user_id' => $coupon->send_user_id, 'system_coupon_user_id' => $rebate_id, 'receive_type' => 5, 'status' => 0, 'number' => 1, 'number_remain' => 1, 'order_main_id' => $order_id, 'receive_time' => $nowTime, 'update_time' => $nowTime, 'created_at' => $nowTime, 'updated_at' => $nowTime, ] ]); } //首次返券更新rebate_type字段 防止重复返券
Db::table('ims_system_coupon_user_receive') ->where([ ['user_id','=',$coupon->user_id], ['receive_type','=',4], ]) ->update(['rebate_type' => 2]); //更新库存操作
Db::table('ims_system_coupon_user') ->where('id', $rebate_id) ->increment('inventory_use'); // 提交
Db::commit(); } catch (\Exception $e) { // 回滚
Db::rollBack(); $errorData['order_main_id'] = $order_id; $errorData['msg'] = '返券失败'; $this->log->event( LogLabel::COUPON_LOG, $errorData ); } }
return '返券成功'; }}
|