5,//等待使用 'alreadyUsed' => 4,//已使用 'expire' => 3,//已过期 ]; private $isGrant = false; /** * MCoupon constructor. * @param $onlineUserId * @param $onlineEnterpriseId * @throws \Exception */ public function __construct($onlineUserId, $onlineEnterpriseId) { $this->onlineUserId = $onlineUserId; $this->onlineEnterpriseId = $onlineEnterpriseId; parent::__construct($this->onlineEnterpriseId, $onlineUserId); $this->objDCoupon = new DCoupon('default'); $this->objDCoupon->setTable($this->objDCoupon->get_Table() . '_' . $this->onlineEnterpriseId); $this->objDUserCoupon = new DUserCoupon(); $this->objDUserCoupon->setTable($this->objDUserCoupon->get_Table() . '_' . $this->onlineEnterpriseId); $this->objDVipCardOrder = new DVipCardOrder(); $this->objDVipCardOrder->setTable($this->objDVipCardOrder->get_Table() . '_' . $this->onlineEnterpriseId); //$this->objDCoupon->setSearchIndex('coupon_search')->setType('coupon'); } /** * @param $params * @return ResultWrapper */ public function add($params) { $dbResult = $this->objDCoupon->insert($params); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } //self::updateEsData($dbResult, $params); return ResultWrapper::success($dbResult); } /** * 更新ES * @param $id * @param $params */ public function updateEsData($id, $params) { $esData = [ 'enterpriseId' => $this->onlineEnterpriseId,//enterpriseId, 'id' => $id,//自增id, 'startTime' => $params['startTime'],//优惠券生效开始时间 'endTime' => $params['endTime'],//结束时间 'name' => $params['name'],//优惠券名称 'couponType' => $params['couponType'],//优惠券类型 'reducePrice' => $params['reducePrice'],//满减券-减免金额(面值) 'minPrice' => $params['minPrice'],//最低消费金额 0.00不限金额 'remark' => $params['remark'],//使用说明 'grantType' => $params['grantType'],//发放方式(10主动领取 20定向发放 30注册领取 40在线支付赠送) 'totalNum' => $params['totalNum'],//发放总数量(-1为不限制) 'allowNum' => $params['allowNum'],//每人限制领取数量(-1为不限制) 'customerSourceId' => isset($params['customerSourceId']) ? $params['customerSourceId'] : '',//领取范围 'mustCondition' => isset($params['mustCondition']) ? $params['mustCondition'] : '0.00',//(40在线支付赠送)-满X金额发放 0.00所有在线支付不限金额可领取这个优惠券 'grantStartTime' => $params['grantStartTime'],//发放开始时间 'grantEndTime' => $params['grantEndTime'],//发放结束时间 'useShop' => $params['useShop'],//使用范围 'applyRange' => $params['applyRange'],//商品适用范围 'categoryCollect' => isset($params['categoryCollect']) ? $params['categoryCollect'] : '',//分类集合 'brandCollect' => isset($params['brandCollect']) ? $params['brandCollect'] : '',//品牌集合 'goodsCollect' => isset($params['goodsCollect']) ? $params['goodsCollect'] : '', 'receiveNum' => isset($params['receiveNum']) ? $params['receiveNum'] : 0,//品牌集合 'deleteStatus' => StatusCode::$standard,//删除状态 'auditStatus' => StatusCode::$auditStatus['auditing'], 'createTime' => $params['createTime'], 'updateTime' => $params['updateTime'], ]; $_id = self::createEsDocumentId($id); $result = $this->objDCoupon->addUpSearchIndexDocument($esData, $_id); if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) { //echo "es操作成功"; //return; } else { //echo "es操作失败"; } } private function createEsDocumentId($id) { return 'EnterpriseId_' . $this->onlineEnterpriseId . '_id_' . $id; } /** * 详情 * @param $id * @return ResultWrapper * @throws \Exception */ public function getInfo($id) { $dbResult = $this->objDCoupon->get_by('id', $id); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } $formatResult = self::format($dbResult); if (!$formatResult->isSuccess()){ return ResultWrapper::fail($formatResult->getData(),$formatResult->getErrorCode()); } $format = $formatResult->getData(); return ResultWrapper::success($format); } /** * 列表 * @param $selectParams * @param $field * @return ResultWrapper */ public function getAll($selectParams, $field = '*') { $limit = $selectParams['limit']; unset($selectParams['limit']); $offset = $selectParams['offset']; unset($selectParams['offset']); $selectParams['deleteStatus'] = StatusCode::$standard; $dbResult = $this->objDCoupon->select($selectParams, $field, 'createTime DESC', $limit, $offset); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } $total = $this->objDCoupon->count($selectParams); $return = [ 'data' => self::formatAll($dbResult), 'total' => ($total) ? intval($total) : 0, ]; $this->isGrant = true; return ResultWrapper::success($return); } /** * 更新审核状态 * @param $params * @return ResultWrapper */ public function updateAuditStatus($params) { $dbResult = $this->objDCoupon->update(['auditStatus' => $params['auditStatus']], $params['id']); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } /*$_id = self::createEsDocumentId($params['id']); $this->objDCoupon->esupdateTypeFieldVaule([ 'auditStatus' => $params['auditStatus'] ], $_id);*/ return ResultWrapper::success($dbResult); } /** * 删除 * @param $id * @return ResultWrapper */ public function del($id) { $dbResult = $this->objDCoupon->update(['deleteStatus' => StatusCode::$delete], $id); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } /*$_id = self::createEsDocumentId($id); $this->objDCoupon->esupdateTypeFieldVaule([ 'deleteStatus' => StatusCode::$delete ], $_id);*/ return ResultWrapper::success($dbResult); } /** * 编辑 * @param $params * @param $id * @return ResultWrapper */ public function edit($params, $id) { $dbResult = $this->objDCoupon->update($params, $id); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } /*$_id = self::createEsDocumentId($id); $this->objDCoupon->esupdateTypeFieldVaule($params, $_id);*/ return ResultWrapper::success($dbResult); } /** * 格式化列表页数据 */ private function formatAll($data) { if (empty($data)) return $data; foreach ($data as &$val) { if ($val['totalNum'] < 0) { $val['totalNum'] = '不限量'; $val['usableNum'] = '不限量'; } else { $val['usableNum'] = bcsub($val['totalNum'], $val['receiveNum'], 0); } $val['useShopName'] = ($val['useShop'] == 0) ? ['全店铺'] : array_values(self::getNameByShopId(explode(',', $val['useShop']))); $val['vipCardId'] = 0;//非会员卡优惠券 } return $data; } /** * @param $data * @return ResultWrapper * @throws \Exception */ private function format($data) { if (empty($data)) return ResultWrapper::success([]); $data['useShopName'] = ($data['useShop'] == 0) ? ['全店铺'] : array_values(self::getNameByShopId(explode(',', $data['useShop']))); if ($data['grantType'] == StatusCode::$grantType['receive']) { $objMCustomerSource = new MCustomerSource($this->onlineEnterpriseId); $dbResult = $objMCustomerSource->getCustomer(explode(',', $data['customerSourceId'])); $customer = $dbResult->getData(); $data['customerTypeName'] = !empty($customer) ? array_column($customer, 'name') : (object)[]; } if ($data['customerIds'] == 0){ $data['customerNames'] = ['全部']; }else{ $objDCustomer = new DCustomer(); $objDCustomer->setTable('qianniao_customer_'.$this->onlineEnterpriseId); $fields = 'id,name'; $sql = 'SELECT '.$fields.' FROM qianniao_customer_'.$this->onlineEnterpriseId.' WHERE id in('.$data['customerIds'].')'; $result = $objDCustomer->query($sql); if ($result === false){ $result = []; } $map = []; foreach ($result as $item){ $map[] = $item['name']; } $data['customerNames'] = $map; } switch ($data['applyRange']) { case StatusCode::$applyRange['appointCategory']: $data['categoryCollectName'] = array_values(parent::getCategoryNameByIds($this->onlineEnterpriseId, explode(',', $data['categoryCollect']))); break; case StatusCode::$applyRange['appointBrand']: $objMGoodsBrand = new MGoodsBrand($this->onlineUserId,$this->onlineEnterpriseId); $brandResult = $objMGoodsBrand->getBrandNameByIds(explode(',', $data['brandCollect'])); if (!$brandResult->isSuccess()){ return ResultWrapper::fail($brandResult->getData(),$brandResult->getErrorCode()); } $brandMap = $brandResult->getData(); $data['brandCollectName'] = array_values($brandMap); break; case StatusCode::$applyRange['goodsCollect']: $goodsListFormatResult = self::getGoodsByIds(explode(',', $data['goodsCollect'])); if (!$goodsListFormatResult->isSuccess()){ return ResultWrapper::fail($goodsListFormatResult->getData(),$goodsListFormatResult->getErrorCode()); } $data['goodsCollectList'] = $goodsListFormatResult->getData(); break; } return ResultWrapper::success($data); } /** * Doc: (des="格式化优惠券指定商品") * User: XMing * Date: 2020/9/21 * Time: 3:11 下午 * @param array $ids * @throws \Exception * @return ResultWrapper */ private function getGoodsByIds($ids) { $objMGoods = new MGoods($this->onlineEnterpriseId,true,$this->onlineUserId); $goodsListResult = $objMGoods->getAllGoods(['offset' => 0,'limit' => count($ids),'id' => $ids]); if (!$goodsListResult->isSuccess()){ return ResultWrapper::fail($goodsListResult->getData(),$goodsListResult->getErrorCode()); } $goodsList = $goodsListResult->getData()['data']; $map = []; foreach ($goodsList as $value){ $map[] = [ 'id' => $value['id'], 'basicGoodsId' => $value['basicGoodsId'], 'shopId' => $value['shopId'], 'shopName' => $value['shopName'], 'title' => $value['title'], 'images' => $value['images'], 'code' => $value['code'], 'inventorTotal' => $value['inventorTotal'] ]; } return ResultWrapper::success($map); } /** * * @param $shopIds * @return array */ public function getNameByShopId($shopIds) { $objGoodsBasicRelevantCache = new GoodsBasicRelevant($this->onlineEnterpriseId); $result = []; foreach ($shopIds as $shopId) { if (!empty($shopId)) $result[] = $objGoodsBasicRelevantCache->getNameByShopId($shopId); } return $result; } /** * 搜索 * @param $selectParams * @return ResultWrapper */ public function search($selectParams) { /*$defaultDSL = [ 'from' => $selectParams['offset'], 'size' => $selectParams['limit'], 'sort' => [ 'createTime' => [ 'order' => 'desc' ], ], ]; $dsl = []; $dsl['query']['bool']['must'][] = [ 'term' => ['enterpriseId' => $this->onlineEnterpriseId], ]; //名称 if (!empty($selectParams['name'])) { $dsl['query']['bool']['must'][] = [ 'multi_match' => [ 'fields' => ['name'], 'query' => $selectParams['name'], 'fuzziness' => 'AUTO', ], ]; } //使用范围 if (!empty($selectParams['useShop'])) { $dsl['query']['bool']['must'][] = [ 'multi_match' => [ 'fields' => ['useShop'], 'query' => $selectParams['useShop'], 'fuzziness' => 'AUTO', ], ]; } //发放方式 if (!empty($selectParams['grantType'])) { $dsl['query']['bool']['filter'][] = ['term' => ['grantType' => $selectParams['grantType']]]; } //发放方式 if (!empty($selectParams['auditStatus'])) { $dsl['query']['bool']['filter'][] = ['term' => ['auditStatus' => $selectParams['auditStatus']]]; } //商品适用范围 if (!empty($selectParams['applyRange'])) { $dsl['query']['bool']['filter'][] = ['term' => ['applyRange' => $selectParams['applyRange']]]; } //时间 if (!empty($selectParams['start']) && !empty($selectParams['end'])) { $dsl['query']['bool']['must'][] = [ 'range' => [ 'createTime' => [ 'gte' => $selectParams['start'], 'lte' => $selectParams['end'], ] ] ]; } else { if (!empty($selectParams['start'])) { $dsl['query']['bool']['must'][] = [ 'range' => [ 'createTime' => [ 'gte' => $selectParams['start'], ] ] ]; } if (!empty($selectParams['end'])) { $dsl['query']['bool']['must'][] = [ 'range' => [ 'createTime' => [ 'lte' => $selectParams['end'], ] ] ]; } } $dsl = array_merge($defaultDSL, $dsl); $result = $this->objDCoupon->getSearchQueryDsl($dsl); if (isset($result['status']) && $result['status'] == 400) { return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult); } if (!isset($result['hits']) || $result['hits']['total'] == 0) { return ResultWrapper::success([ 'data' => [], 'total' => 0 ]); } $total = $result['hits']['total']; $dbResult = $result['hits']['hits']; $list = []; foreach ($dbResult as $key => &$value) { $data = []; $data = $value['_source']; $list[] = $data; }*/ $fields = '*'; $sql = 'SELECT '.$fields.' FROM qianniao_coupon_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard; if (isset($selectParams['grantType']) && !empty($selectParams['grantType'])){ $sql .= ' AND grantType = '.$selectParams['grantType']; } if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])){ $sql .= ' AND auditStatus = '.$selectParams['auditStatus']; } if (isset($selectParams['applyRange']) && !empty($selectParams['applyRange'])){ $sql .= ' AND applyRange = '.$selectParams['applyRange']; } if (isset($selectParams['useShop']) && !empty($selectParams['useShop'])){ $sql .= ' AND find_in_set('.$selectParams['useShop'].',useShop) '; } if (isset($selectParams['name']) && !empty($selectParams['name'])){ $sql .= ' AND name like "%'.$selectParams['name'].'%"'; } if (isset($selectParams['start']) && !empty($selectParams['start']) && isset($selectParams['end']) && !empty($selectParams['end'])){ $sql .= ' AND createTime BETWEEN '.$selectParams['start'].' AND '.$selectParams['end']; } $sql .= ' ORDER BY createTime DESC '; $count = count((array) $this->objDCoupon->query($sql)); //分页 if (isset($selectParams['offset']) && isset($selectParams['limit']) && !empty($selectParams['limit'])){ $sql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit']; } $dbResult = $this->objDCoupon->query($sql); if ($dbResult === false){ return ResultWrapper::fail($this->objDCoupon->error(),ErrorCode::$dberror); } $return = [ 'data' => self::formatAll($dbResult), 'total' => $count, ]; return ResultWrapper::success($return); } /** * 优惠券列表 * @param $params * @return ResultWrapper * @throws \Exception */ public function couponList($params) { $fields = 'id,startTime,endTime,name,couponType,reducePrice,minPrice,remark,grantType,totalNum,allowNum,customerSourceId,useShop,mustCondition,grantStartTime,grantEndTime,applyRange,categoryCollect,brandCollect,receiveNum'; $nowTime = time(); $sql = 'SELECT ' . $fields . ' FROM qianniao_coupon_' . $this->onlineEnterpriseId . ' WHERE deleteStatus=' . StatusCode::$standard . ' AND enableStatus='.StatusCode::$standard.' AND auditStatus=' . StatusCode::$auditStatus['auditPass'] . ' AND grantStartTime<' . $nowTime . ' AND grantEndTime> ' . $nowTime . ' AND totalNum>receiveNum'; switch ($params['grantType']) { case StatusCode::$grantType['register']://注册领取 $sql .= ' AND grantType=' . StatusCode::$grantType['register']; $dbResult = self::registerCoupon($sql); break; case StatusCode::$grantType['receive']://主动领取 $sql .= ' AND grantType=' . StatusCode::$grantType['receive']; $dbResult = self::receiveCoupon($sql, $params); break; case StatusCode::$grantType['onlinePay']://在线支付领取 $sql .= ' AND grantType=' . StatusCode::$grantType['onlinePay']; $dbResult = self::onlinePayCoupon($sql, $params); break; default: $dbResult = self::registerCoupon($sql); break; } if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } //格式化数据 $result = self::formatAll($dbResult->getData()); return ResultWrapper::success($result); } /** * 获取会员卡发放的优惠券 * * @return array|mixed */ public function vipCoupon() { $objMVipCard = new MVipCard($this->onlineEnterpriseId, $this->onlineUserId, true); $dbResult = $objMVipCard->myVipCardMonthCoupon(); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } $dbResult = $dbResult->getData(); return ResultWrapper::success($dbResult); } //查询会员卡优惠券 public function getVipCardCouponInfo($ids=[]) { $sql = 'SELECT * FROM qianniao_coupon_' . $this->onlineEnterpriseId . ' WHERE deleteStatus=' . StatusCode::$standard . ' AND enableStatus='.StatusCode::$standard.' AND auditStatus=' . StatusCode::$auditStatus['auditPass'] . ' AND id in ('. implode(',',$ids) .') AND couponType='.StatusCode::$couponType['vipCoupon']; $dbResult = $this->objDCoupon->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * 注册领取 * @param $sql * @return ResultWrapper */ private function registerCoupon($sql) { $dbResult = $this->objDCoupon->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * @param $sql * @param $params * @return ResultWrapper */ private function onlinePayCoupon($sql, $params) { if (!isset($params['payAmount'])) { return ResultWrapper::fail('缺少payAmount参数', ErrorCode::$paramError); } $sql .= ' AND mustCondition<=' . $params['payAmount']; $dbResult = $this->objDCoupon->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * 主动领取 * @param $sql * @param $params * @return ResultWrapper * @throws \Exception */ private function receiveCoupon($sql, $params) { //查询当前客户类型 $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); //首页未登录 if (!empty($this->onlineUserId)) { $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $customerType = $dbResult->getData()['type']; unset($dbResult); if (!empty($customerType)) { $sql .= ' AND (FIND_IN_SET(' . $customerType . ',customerSourceId) or customerSourceId = 0) '; } } $dbResult = $this->objDCoupon->query($sql); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } return ResultWrapper::success($dbResult); } /** * 领取优惠券 * @param $params * @return ResultWrapper * @throws \Exception */ public function receive($params) { $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId); $coupon = $this->objDCoupon->get(['id' => $params['couponId']]); if ($coupon === false) return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); if (empty($coupon)) return ResultWrapper::fail('未知的优惠券', ErrorCode::$dberror); //会员卡优惠券验证 if ($params['vipCardId'] != 0) { $where = "vipCardId = " . $params['vipCardId'] . " AND userCenterId = $this->onlineUserId AND payStatus = " . StatusCode::$standard . " AND deleteStatus=" . StatusCode::$standard . ' AND expireTime >= unix_timestamp(now()) AND enableStatus =' . StatusCode::$standard; $userVipCard = $this->objDVipCardOrder->get($where); if ($userVipCard === false) return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror); if (empty($userVipCard)) return ResultWrapper::fail('成为会员才能领取会员卡优惠券', ErrorCode::$paramError); $sql = "select couponId,vipCardId,createTime,userId from qianniao_user_coupon_" . $this->onlineEnterpriseId . " where vipCardId =" . $params['vipCardId'] . " AND FROM_UNIXTIME(createTime,'%Y-%m')='" . date('Y-m') . "' AND userId=" . $this->onlineUserId; $dbResult = $this->objDUserCoupon->query($sql); if ($dbResult === false) return ResultWrapper::fail($this->objDUserCoupon->error(), ErrorCode::$dberror); if (!empty($dbResult)) return ResultWrapper::fail('本月已近领取了', ErrorCode::$paramError); } //不是会员卡优惠券需要限制 if (empty($params['vipCardId'])) { if ($coupon['grantStartTime'] > time() || $coupon['grantEndTime'] < time()) { //不在优惠券发放时间范围 return ResultWrapper::fail('优惠券不在发放时间', ErrorCode::$dberror); } if ($coupon['receiveNum'] >= $coupon['totalNum']) { return ResultWrapper::fail('优惠券抢光了', ErrorCode::$dberror); } $allowNum = $coupon['allowNum'];//每人限制领取 //验证是否可以领取此优惠券 $userCoupon = $objMUserCoupon->getUserCoupon(['couponId' => $coupon['id'], 'userId' => $this->onlineUserId]); if (!$userCoupon->isSuccess()) return ResultWrapper::fail($userCoupon->getData(), ErrorCode::$dberror); $haveNum = count($userCoupon->getData()); if ($haveNum >= $allowNum) { return ResultWrapper::fail('领取达到了上限', ErrorCode::$dberror); } } //查询当前客户类型 $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $customer = $dbResult->getData(); unset($dbResult); //优惠券记录信息 $insert = [ 'couponId' => $coupon['id'], 'name' => $coupon['name'], 'remark' => $coupon['remark'], 'couponType' => $coupon['couponType'], 'reducePrice' => $coupon['reducePrice'], 'minPrice' => $coupon['minPrice'], 'startTime' => $coupon['startTime'], 'endTime' => $coupon['endTime'], 'applyRange' => $coupon['applyRange'], 'categoryCollect' => $coupon['categoryCollect'], 'brandCollect' => $coupon['brandCollect'], 'goodsCollect' => $coupon['goodsCollect'], 'isExpire' => StatusCode::$standard, 'isUse' => StatusCode::$standard, 'userId' => $this->onlineUserId, 'customerId' => $customer['id'], 'useShop' => $coupon['useShop'], 'source' => $coupon['grantType'], 'createTime' => time(), 'updateTime' => time(), 'vipCardId' => $params['vipCardId'], 'isMutex' => isset($coupon['isMutex']) ? $coupon['isMutex'] : StatusCode::$standard, ]; //当优惠券是会员卡优惠券时,过期时间=当前时间+30天 if ($params['vipCardId'] != 0) { $insert['startTime'] = time(); $insert['endTime'] = time() + 30 * 24 * 3600;//到期时间 } $this->objDCoupon->beginTransaction(); //写记录 $dbResult = $objMUserCoupon->add($insert); if (!$dbResult->isSuccess()) { $this->objDCoupon->rollBack(); ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } unset($dbResult); //增加领取量 $sql = 'UPDATE qianniao_coupon_' . $this->onlineEnterpriseId . ' SET receiveNum=receiveNum+1 WHERE id=' . $coupon['id']; $dbResult = $this->objDCoupon->query($sql); if ($dbResult === false) { $this->objDCoupon->rollBack(); ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } $this->objDCoupon->commit(); return ResultWrapper::success($dbResult); } /** * 一键领取优惠券(会员卡) * @param $params * @return ResultWrapper * @throws \Exception */ public function oneKeyReceive($params) { $params['couponId'] = rtrim($params['couponId'], ','); $coupons = $this->objDCoupon->select(['id' => explode(',', $params['couponId'])]); if ($coupons === false) return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); if (empty($coupons)) return ResultWrapper::fail('未知的优惠券', ErrorCode::$dberror); //查询用户对应优惠券的已领取张数 /**$sql = 'SELECT couponId,count(`id`) as num FROM qianniao_user_coupon_' . $this->onlineEnterpriseId . ' WHERE userId=' . $this->onlineUserId . ' AND couponId IN(' . $params['couponId'] . ') GROUP BY couponId'; * $countCoupon = $this->objDUserCoupon->query($sql); * if ($countCoupon === false) return ResultWrapper::fail($this->objDUserCoupon->error(), ErrorCode::$dberror); * $groupNum = [];//优惠券对应领取数量 * if (!empty($countCoupon)) { * foreach ($countCoupon as $count) { * $groupNum[$count['couponId']] = $count['num']; * } * }**/ $sql = "select couponId,vipCardId,createTime,userId from qianniao_user_coupon_" . $this->onlineEnterpriseId . " where vipCardId =" . $params['vipCardId'] . " AND FROM_UNIXTIME(createTime,'%Y-%m')='" . date('Y-m') . "' AND userId=" . $this->onlineUserId; $userCoupon = $this->objDUserCoupon->query($sql); if ($userCoupon === false) return ResultWrapper::fail($this->objDUserCoupon->error(), ErrorCode::$dberror); $allCoupon = array_values(array_column($userCoupon, 'couponId')); //查询当前客户类型 $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $customer = $dbResult->getData(); unset($dbResult); $insert = []; $couponIds = []; foreach ($coupons as $key => $coupon) { /**if ($coupon['grantStartTime'] > time() || $coupon['grantEndTime'] < time()) { * //不在优惠券发放时间范围 * unset($coupons[$key]); * continue; * } * if ($coupon['receiveNum'] >= $coupon['totalNum']) { * //发放完了 * unset($coupons[$key]); * continue; * } * $haveNum = isset($groupNum[$coupon['id']]) ? $groupNum[$coupon['id']] : 0; * if ($haveNum >= $coupon['allowNum']) { * //领取达到了上限 * unset($coupons[$key]); * continue; * }*/ if (!empty($allCoupon)) { if (in_array($coupon['id'], $allCoupon)) { unset($coupons[$key]); continue; } } $insert[] = [ 'couponId' => $coupon['id'], 'name' => $coupon['name'], 'remark' => $coupon['remark'], 'couponType' => $coupon['couponType'], 'reducePrice' => $coupon['reducePrice'], 'minPrice' => $coupon['minPrice'], 'startTime' => empty($params['vipCardId']) ? $coupon['startTime'] : time(), 'endTime' => empty($params['vipCardId']) ? $coupon['endTime'] : time() + 30 * 24 * 3600,//到期时间 'applyRange' => $coupon['applyRange'], 'categoryCollect' => $coupon['categoryCollect'], 'brandCollect' => $coupon['brandCollect'], 'goodsCollect' => $coupon['goodsCollect'], 'isExpire' => StatusCode::$standard, 'isUse' => StatusCode::$standard, 'userId' => $this->onlineUserId, 'customerId' => $customer['id'], 'useShop' => $coupon['useShop'], 'source' => $coupon['grantType'], 'createTime' => time(), 'updateTime' => time(), 'vipCardId' => $params['vipCardId'], 'isMutex' => isset($coupon['isMutex']) ? $coupon['isMutex'] : StatusCode::$standard, ]; $couponIds[] = $coupon['id']; } if (empty($insert)) return ResultWrapper::fail('已经领取过了', ErrorCode::$dberror); $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId); $this->objDCoupon->beginTransaction(); //写记录 $dbResult = $objMUserCoupon->add($insert, true); if (!$dbResult->isSuccess()) { $this->objDCoupon->rollBack(); return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } unset($dbResult); $dbResult = $this->objDCoupon->set_inc('receiveNum', ['id' => $couponIds]); if ($dbResult === false) { $this->objDCoupon->rollBack(); return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } $this->objDCoupon->commit(); return ResultWrapper::success('领取成功'); } /** * 优惠券盒子 * @param $selectParams * @return ResultWrapper * @throws \Exception */ public function selectAll($selectParams) { $limit = $selectParams['limit']; unset($selectParams['limit']); $offset = $selectParams['offset']; unset($selectParams['offset']); $nowTime = time(); $sql = 'SELECT * FROM qianniao_user_coupon_' . $this->onlineEnterpriseId . ' WHERE userId=' . $this->onlineUserId . ' AND'; $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId); switch ($selectParams['type']) { case self::$useStatus['waitUsed']://等待使用 $sql .= ' isUse=' . self::$useStatus['waitUsed'] . ' AND endTime>' . $nowTime; break; case self::$useStatus['alreadyUsed']://已使用 $sql .= ' isUse=' . self::$useStatus['alreadyUsed']; break; case self::$useStatus['expire']://已过期 $sql .= ' isUse=' . self::$useStatus['waitUsed'] . ' AND endTime<' . $nowTime; break; } $countQuery = $sql; $sql .= ' ORDER BY createTime DESC LIMIT ' . $offset . ',' . $limit; $dbResult = $objMUserCoupon->getUserCoupon($sql, true, '*', $countQuery); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode()); } $couponData = $dbResult->getData(); $return = [ 'data' => $objMUserCoupon->formatAll($couponData['data']), 'total' => $couponData['total'] ]; return ResultWrapper::success($return); } /** * 支付成功会员卡发放优惠券 * * @param $couponIds * @return ResultWrapper * @throws \Exception */ public function giveCoupon($couponIds, $vipCardId = '') { $coupons = $this->objDCoupon->select(['id' => $couponIds]); if ($coupons == false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId); if (!empty($coupons)) { //查询当前客户类型 $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId); $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId); if (!$dbResult->isSuccess()) { return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } $customer = $dbResult->getData(); $insert = []; foreach ($coupons as $key => $coupon) { /**if ($coupon['receiveNum'] >= $coupon['totalNum']) { * //数量不够发放 * unset($coupons[$key]); * continue; * } * $userCoupon = $objMUserCoupon->getUserCoupon(['couponId' => $coupon['id'], 'userId' => $this->onlineUserId]); * if (!$userCoupon->isSuccess()) { * unset($coupons[$key]); * continue; * } * $haveNum = count($userCoupon->getData()); * if ($haveNum >= $coupon['allowNum']) { * unset($coupons[$key]); * continue; * }**/ //优惠券记录信息 $insert [] = [ 'couponId' => $coupon['id'], 'name' => $coupon['name'], 'remark' => $coupon['remark'], 'couponType' => $coupon['couponType'], 'reducePrice' => $coupon['reducePrice'], 'minPrice' => $coupon['minPrice'], 'startTime' => time(), 'endTime' => time() + 30 * 24 * 3600, 'applyRange' => $coupon['applyRange'], 'categoryCollect' => $coupon['categoryCollect'], 'brandCollect' => $coupon['brandCollect'], 'goodsCollect' => $coupon['goodsCollect'], 'isExpire' => StatusCode::$standard, 'isUse' => StatusCode::$standard, 'userId' => $this->onlineUserId, 'customerId' => $customer['id'], 'useShop' => $coupon['useShop'], 'source' => $coupon['grantType'], 'createTime' => time(), 'updateTime' => time(), 'vipCardId' => $vipCardId, 'isMutex' => isset($coupon['isMutex']) ? $coupon['isMutex'] : StatusCode::$standard, ]; } if (empty($insert)) { return ResultWrapper::success([]); } $this->objDCoupon->beginTransaction(); //写记录 $dbResult = $objMUserCoupon->add($insert, true); if (!$dbResult->isSuccess()) { $this->objDCoupon->rollBack(); ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror); } unset($dbResult); //增加领取数量 $dbResult = $this->objDCoupon->set_inc('receiveNum', ['id' => $couponIds], 1); if ($dbResult === false) { $this->objDCoupon->rollBack(); ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } $this->objDCoupon->commit(); return ResultWrapper::success($dbResult); } } /** * 启用/禁用 * @param $params * @return ResultWrapper */ public function updateEnableStatus($params) { $dbResult = $this->objDCoupon->update(['enableStatus' => $params['enableStatus']], $params['id']); if ($dbResult === false) { return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror); } /*$_id = self::createEsDocumentId($params['id']); $this->objDCoupon->esupdateTypeFieldVaule([ 'enableStatus' => $params['enableStatus'] ], $_id);*/ return ResultWrapper::success($dbResult); } /** * 处理定向发放优惠劵脚本 */ public function grantCoupon() { // 查询审核通过未被删除当前时间在发放时间内没有发完的定向发放的普通优惠劵 $fields = 'id,isMutex,customerIds,startTime,endTime,name,couponType,reducePrice,minPrice,remark,grantType,totalNum,allowNum,customerSourceId,useShop,mustCondition,grantStartTime,grantEndTime,applyRange,categoryCollect,brandCollect,receiveNum,goodsCollect'; $nowTime = time(); $sql = 'SELECT ' . $fields . ' FROM qianniao_coupon_' . $this->onlineEnterpriseId . ' WHERE deleteStatus=' . StatusCode::$standard . ' AND enableStatus='.StatusCode::$standard.' AND auditStatus=' . StatusCode::$auditStatus['auditPass'] . ' AND grantStartTime<' . $nowTime . ' AND grantEndTime> ' . $nowTime . ' AND totalNum>receiveNum AND grantType=' . StatusCode::$grantType['grant'] .' AND couponType='.StatusCode::$couponType['commonly']; $couponList = $this->objDCoupon->query($sql); if ($couponList === false){ return ResultWrapper::fail($this->objDCoupon->error(),ErrorCode::$dberror); } // 提取定向发放优惠券的客户ids $allCustomerIds = []; foreach ($couponList as $key => $value){ $customerIdsStr = $value['customerIds']; if (empty($customerIdsStr)){ continue; } $customerIds = explode(',',$customerIdsStr); $allCustomerIds = array_merge($allCustomerIds,$customerIds); $couponList[$key]['customerIdsArray'] = $customerIds; } $allCustomerIds = array_values(array_unique($allCustomerIds)); if (empty($allCustomerIds)){ return ResultWrapper::success(true); } // 查询这批客户的数据 $objCustomer = new DCustomer(); $objCustomer->setTable('qianniao_customer_'.$this->onlineEnterpriseId); $customerList = $objCustomer->select(['id'=>$allCustomerIds],'userCenterId,id'); if ($customerList === false){ return ResultWrapper::fail($objCustomer->error(),ErrorCode::$dberror); } // 映射客户id和userCenterId $customerMap = []; foreach ($customerList as $value){ $customerMap[$value['id']] = $value['userCenterId']; } // 处理优惠劵 foreach ($couponList as $key => $val){ // 判断优惠劵是否领完了 if ($val['receiveNum'] >= $val['totalNum']){ echo '优惠券'.$val['id'].'已经领取完了'.PHP_EOL; unset($couponList[$key]); continue; } foreach ($val['customerIdsArray'] as $customerId){ $dbResult = $this->objDUserCoupon->count(['couponId' => $val['id'], 'userId' => isset($customerMap[$customerId]) ? $customerMap[$customerId] : 0]); if ($dbResult === false) { echo '领取记录查询失败' . $this->objDUserCoupon->error() . PHP_EOL; return ResultWrapper::fail($this->objDUserCoupon->error(),ErrorCode::$dberror); } // 当前这个用户是否领取过当前这张优惠券 if ($dbResult >= $val['allowNum']){ echo '优惠券'.$val['id'].'已经领取了'.$dbResult.'张,每人限领取'.$val['allowNum'].'张'.PHP_EOL; unset($couponList[$key]); continue; } // 剩余数量不足每人领取数量 if ($val['receiveNum']+$val['allowNum'] > $val['totalNum']){ $rec = $val['totalNum'] - $val['receiveNum']; $couponList[$key]['allowNum'] = $rec; } if (empty($couponList)) { echo '优惠券都领取过了' . PHP_EOL; continue; } echo '定向发放优惠券'.date('Y-m-d H:i:s').PHP_EOL; parent::coupon([ 'userCenterId' => isset($customerMap[$customerId]) ? $customerMap[$customerId] : 0, 'customerId' => $customerId, 'enterpriseId' => $this->onlineEnterpriseId, ], 'MGrantCoupon'); sleep(1);//优惠券首次审核后都处于等待发放,会有很多请求 } } /**foreach ($allCustomerIds as $id){ //检测用户是否领取过 parent::coupon([ 'userCenterId' => isset($customerMap[$id]) ? $customerMap[$id] : 0, 'customerId' => $id, 'enterpriseId' => $this->onlineEnterpriseId, ], 'MGrantCoupon'); }*/ return ResultWrapper::success(true); } }