// +---------------------------------------------------------------------- declare (strict_types = 1); namespace app\api\controller; use app\api\model\coupon\CouponGenRedeemCodes; use app\api\model\coupon\CouponRedeemCodes as CouponRedeemCodesModel; use app\api\model\UserCoupon as UserCouponModel; use app\api\service\User as UserService; use app\common\exception\BaseException; use think\cache\driver\Redis; /** * 用户优惠券 * Class Coupon * @package app\api\controller */ class MyCoupon extends Controller { /** * 用户优惠券列表 * @return mixed * @throws BaseException * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public function list() { $userId = UserService::getCurrentLoginUserId(); $model = new UserCouponModel; $list = $model->getList($userId, $this->request->param()); return $this->renderSuccess(compact('list')); } /** * 领取优惠券 * @param int $couponId * @return array|\think\response\Json * @throws BaseException */ public function receive(int $coupon_id) { $model = new UserCouponModel; if ($model->receive($coupon_id)) { return $this->renderSuccess([], '领取成功'); } return $this->renderError($model->getError() ?: '领取失败'); } /** * 兑换优惠券 * @param string $redeemCode * @return array|\think\response\Json * @throws BaseException */ public function exchange(string $redeemCode) { $CouponRedeemCodesModel = new CouponRedeemCodesModel; $genModel = new CouponGenRedeemCodes(); $CouponRedeemCodes = $CouponRedeemCodesModel->with(['couponGenRedeemCodes'])->where('redeem_code',$redeemCode)->find(); if(!$CouponRedeemCodes){ return $this->renderError('错误,请重输入'); } if ($CouponRedeemCodes['couponGenRedeemCodes']['amount'] - $CouponRedeemCodes['couponGenRedeemCodes']['used_amount']<=0){ $CouponRedeemCodesModel->where('id', $CouponRedeemCodes->id)->update(['is_delete'=>1]); if($CouponRedeemCodes['couponGenRedeemCodes']['give_type'] == 1){ return $this->renderError('领完啦'); }else{ return $this->renderError('兑换码已失效'); } } $model = new UserCouponModel; if ($model->receive($CouponRedeemCodes['coupon_id'],true)) { if($CouponRedeemCodes['couponGenRedeemCodes']['give_type'] == 2){ //更改激活码使用信息 $CouponRedeemCodes->is_delete = 1; $CouponRedeemCodes->save(); } //使用数量加一 $genModel->where('id', $CouponRedeemCodes->coupon_gen_redeem_codes_id) ->where('used_amount','<',$CouponRedeemCodes['couponGenRedeemCodes']['amount']) ->inc('used_amount') ->update(); return $this->renderSuccess([], '兑换成功'); } return $this->renderError($model->getError() ?: '兑换失败'); } }