123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919 |
- <?php
- /**
- * 会员卡管理模块
- * Created by PhpStorm.
- * User: wxj
- * Date: 2019/10/30
- * Time: 14:02
- */
- namespace JinDouYun\Model\Market;
- use JinDouYun\Controller\Common\Logger;
- use Mall\Framework\Core\ErrorCode;
- use Mall\Framework\Core\StatusCode;
- use Mall\Framework\Core\ResultWrapper;
- use JinDouYun\Model\MBaseModel;
- use JinDouYun\Dao\Market\DVipCard;
- use JinDouYun\Dao\Market\DVipCardOrder;
- use JinDouYun\Model\Customer\MCustomer;
- use JinDouYun\Model\System\MPaymentSetting;
- use JinDouYun\Cache\SystemCache;
- use JinDouYun\Dao\Goods\DGoods;
- use JinDouYun\Dao\Market\DUserCoupon;
- use Mall\Framework\Factory;
- use Util\ByteDance\Pay as bytePay;
- use Util\WeiXin\Pay;
- use Util\AliPay\Pay as aliPay;
- class MVipCard extends MBaseModel {
- private $objDVipCard;
- private $objDVipCardOrder;
- private $objMCustomer;
- private $enterpriseId;
- private $userCenterId;
- private $isFront;
- private $objMPaymentSetting;
- private $objMCoupon;
- private $objDUserCoupon;
- private $objDGoods;
- public function __construct($enterpriseId, $userCenterId, $isFront = false)
- {
- $this->userCenterId = $userCenterId;
- $this->enterpriseId = $enterpriseId;
- $this->isFront = $isFront;
- parent::__construct($enterpriseId, $userCenterId);
- $this->objDVipCard = new DVipCard('default');
- $this->objDVipCardOrder = new DVipCardOrder('default');
- $this->objMCustomer = new MCustomer($enterpriseId, $userCenterId);
- $this->objMPaymentSetting = new MPaymentSetting($userCenterId, $enterpriseId);
- $this->objMCoupon = new MCoupon($userCenterId, $enterpriseId);
- $this->objDUserCoupon = new DUserCoupon('default');
- $this->objDGoods = new DGoods('default');
- $tableName = $this->objDGoods->getTableName('qianniao_goods_', $this->enterpriseId, 1);
- $this->objDGoods->setTable($tableName);
- $this->objDVipCard->setTable($this->objDVipCard->get_Table().'_'.$enterpriseId);
- $this->objDVipCardOrder->setTable($this->objDVipCardOrder->get_Table().'_'.$enterpriseId);
- $this->objDUserCoupon->setTable($this->objDUserCoupon->get_Table() . '_' . $enterpriseId);
- }
- /**
- * 添加会员卡
- *
- * @param array $params 会员卡数据
- *
- * @return ResultWrapper
- */
- public function addVipCard($params)
- {
- $VipCardId = $this->objDVipCard->insert($params);
- if($VipCardId === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }else{
- return ResultWrapper::success($VipCardId);
- }
- }
- /**
- * 获取指定会员卡信息
- * @param $vipCardId
- * @return ResultWrapper
- */
- public function getVipCardInfo($vipCardId)
- {
- $dbResult = $this->objDVipCard->get($vipCardId);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }else{
- $dbResult = self::format([$dbResult], true);
- $dbResult = array_shift($dbResult);
- return ResultWrapper::success($dbResult);
- }
- }
- //前后端会员卡详情和会员卡列表使用此格式化方法
- public function format($params = [], $getDetail = false) {
- $vipCardIds = [];
- foreach ($params as &$data) {
- $data['effectiveMonth'] = $data['effectiveDate'] == -1 ? 0 : $data['effectiveDate'];
- $data['effectiveDate'] = $data['effectiveDate'] == -1 ? StatusCode::$standard : StatusCode::$delete;
- if ($this->isFront) {
- //前端会员卡列表
- $data['renew'] = StatusCode::$delete;
- }
- $vipCardIds[] = $data['id'];
- }
- unset($data);
- //详情页组装数据 商品名称 优惠券名称等
- if ($getDetail) {
- $couponIds = [];
- $goodsIds = [];
- foreach ($params as $value) {
- if (!empty($value['newCardCouponIds'])) {
- $couponIds = array_merge($couponIds, explode(',',$value['newCardCouponIds']));
- }
- if (!empty($value['monthCouponIds'])) {
- $couponIds = array_merge($couponIds, explode(',',$value['monthCouponIds']));
- }
- if (!empty($value['goodsIds'])) {
- $goodsIds = array_merge($goodsIds, explode(',',$value['goodsIds']));
- }
- }
- unset($value);
- //详情页面获取选中的优惠券和商品名称
- $couponData = [];
- if(!empty($couponIds)) {
- $couponResult = $this->objMCoupon->getAll(['limit'=>null,'offset'=>null,'id'=>array_values(array_unique(array_filter($couponIds)))],'id,name,reducePrice,endTime,totalNum,receiveNum,useShop');
- if($couponResult->isSuccess()) {
- $couponResultData = $couponResult->getData();
- foreach ($couponResultData['data'] as $coupon) {
- $couponData[$coupon['id']] = $coupon;
- }
- }
- }
- $goodsData = [];
- if(!empty($goodsIds)) {
- $sql = 'select b.id,a.title from qianniao_goods_basic_'.$this->enterpriseId.' as a,qianniao_goods_'.$this->enterpriseId.' as b where a.id = b.basicGoodsId and b.id in ('. implode(',',$goodsIds) .')';
- $goodsResult = $this->objDGoods->query($sql);
- if ($goodsResult != false) {
- foreach ($goodsResult as $goods) {
- $goodsData[$goods['id']] = $goods['title'];
- }
- }
- }
- foreach ($params as &$value) {
- $value['newCardCouponNames'] = [];
- $value['monthCouponNames'] = [];
- $value['monthCoupon'] = [];
- $value['goodsName'] = [];
- if (!empty($value['newCardCouponIds'])) {
- foreach (explode(',',$value['newCardCouponIds']) as $newCardCoupon) {
- $value['newCardCouponNames'][] = isset($couponData[$newCardCoupon]) ? $couponData[$newCardCoupon]['name'] : '';
- }
- }
- if (!empty($value['monthCouponIds'])) {
- foreach (explode(',',$value['monthCouponIds']) as $monthCoupon) {
- if (isset($couponData[$monthCoupon])) {
- $value['monthCouponNames'][] = $couponData[$monthCoupon]['name'];
- $value['monthCoupon'][] = $couponData[$monthCoupon];//每月领取优惠券数组
- }
- }
- }
- if (!empty($value['goodsIds'])) {
- foreach (explode(',',$value['goodsIds']) as $goodsId) {
- $value['goodsName'][] = isset($goodsData[$goodsId]) ? $goodsData[$goodsId] : '';
- }
- }
- //前端详情页面,判断会员是否领取过该会员卡下的优惠券
- if ($this->isFront) {
- $value['received'] = StatusCode::$delete;
- $value['hasBuy'] = StatusCode::$delete;//是否已购买此卡
- $value['renew'] = StatusCode::$delete;//立即开通
- $value['hasReceived'] = StatusCode::$delete;//是否已领取优惠券
- //当前会员是否拥有会员卡
- $myVipCardResult = self::getMyVipCards(['limit'=>null,'offset'=>null]);
- if ($myVipCardResult->isSuccess()) {
- $myVipCards = $myVipCardResult->getData();
- $myVipCardsList = $myVipCards['data'];
- if (!empty($myVipCardsList)) {
- $value['received'] = StatusCode::$standard;//已有会员卡
- }
- }
- $where = "vipCardId = ". $value['id'] ." AND userCenterId = $this->userCenterId 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 && !empty($userVipCard)) {
- $value['hasBuy'] = StatusCode::$standard;//已购买
- $value['renew'] = StatusCode::$standard;//续费
- if (!empty($value['monthCouponIds'])) {
- //本月领取的该会员卡的优惠券id
- $sql = "select couponId from qianniao_user_coupon_".$this->enterpriseId." where vipCardId =". $value['id'] ." AND FROM_UNIXTIME(createTime,'%Y-%m')='".date('Y-m')."' AND userId=".$this->userCenterId;
- $userCouponIds = $this->objDUserCoupon->query($sql);
- //如果本月已领取的和会员卡赠送的优惠券一致,则已领取过,不显示一键领取按钮
- if ($userCouponIds) {
- $noReceivedCouponId = array_diff(explode(',',$value['monthCouponIds']),array_column($userCouponIds,'couponId'));
- $value['hasReceived'] = empty($noReceivedCouponId) ? StatusCode::$standard : StatusCode::$delete;
- }
- }
- }
- }
- }
- }
- return $params;
- }
- /**
- * 编辑会员卡
- *
- * @param int|array $params 修改会员卡的数据
- *
- * @return ResultWrapper
- */
- public function editVipCard($params)
- {
- if( empty($params['id']) ){
- return ResultWrapper::fail('没有指定要修改的VipCardid', ErrorCode::$paramError);
- }
- $updateVipCardId = $params['id'];
- unset($params['id']);
- $dbResult = $this->objDVipCard->update($params, $updateVipCardId);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }else{
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 删除会员卡
- *
- * @param array $delMarketIds 要删除的会员卡id
- *
- * @return ResultWrapper
- */
- public function delVipCard($delVipCardIds)
- {
- if (empty($delVipCardIds)) {
- return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
- }
- $dbResult = $this->objDVipCard->update( ['deleteStatus'=>StatusCode::$delete], $delVipCardIds );
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }else{
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 会员卡启用和禁用
- * @param array $params
- * @return ResultWrapper
- */
- public function updateVipCardStatus($params)
- {
- $dbResult = $this->objDVipCard->update( ['enableStatus'=>$params['enableStatus']], $params['id'] );
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }else{
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 获取所有会员卡数据
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- */
- public function getAllVipCard($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $where ='deleteStatus='.StatusCode::$standard;
- if (isset($selectParams['enableStatus'])) {
- $where .= ' AND enableStatus='.$selectParams['enableStatus'];
- }
- if (isset($selectParams['name'])) {
- $where .= ' AND name like "%'.$selectParams['name'].'%"';
- }
- $dbResult = $this->objDVipCard->select($where, '*', 'sort desc,createTime desc', $limit, $offset);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
- $total = $this->objDVipCard->count($where);
- $return = [
- 'data' => self::format($dbResult),
- 'total' => ($total)?intval($total):0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 前台获取所有会员卡数据
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- */
- public function getAllFrontVipCard($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $where ='deleteStatus='.StatusCode::$standard.' AND enableStatus='.StatusCode::$standard;
- $myVipCardResult = self::getMyVipCards(['limit'=>1000,'offset'=>0]);
- if ($myVipCardResult->isSuccess() == false) {
- return ResultWrapper::fail($myVipCardResult->getData(), $myVipCardResult->getErrorCode());
- }
- $myVipCards = $myVipCardResult->getData();
- $myVipCardsList = $myVipCards['data'];
- $myVipCardIds = [];
- if (!empty($myVipCardsList)) {
- $received = StatusCode::$standard;
- foreach ($myVipCardsList as $vipCard) {
- $myVipCardIds[] = $vipCard['id'];
- }
- }
- if (!empty($myVipCardIds)) {
- $where .= ' AND id NOT IN ('. implode(',',$myVipCardIds) .')';
- }
- $dbResult = $this->objDVipCard->select($where, '*', 'sort desc,createTime desc', $limit, $offset);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
- $total = $this->objDVipCard->count($where);
- $return = [
- 'data' => self::format($dbResult),
- 'total' => ($total)?intval($total):0,
- 'received' => isset($received) ? $received : StatusCode::$delete
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 获取所有领取记录
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- */
- public function getAllReceiveRecord($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $where = '';
- if (isset($selectParams['outDate']) && !empty($selectParams['outDate'])) {
- $condition = empty($where) ? '' : ' AND ';
- $date = $selectParams['outDate'] == StatusCode::$standard ? '<=' : '>';
- $where .= $condition.'expireTime '. $date . ' unix_timestamp(now())';
- }
- // 筛选客户
- if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
- $condition = empty($where) ? '' : ' AND ';
- $where .= $condition.' customerId ='.$selectParams['customerId'];
- }
- // 筛选领取时间
- if (!empty($selectParams['createTime'])) {
- $condition = empty($where) ? '' : ' AND ';
- $where .= $condition. ' createTime >=' . $selectParams['createTime'];
- }
- if (!empty($selectParams['entTime'])) {
- $condition = empty($where) ? '' : ' AND ';
- $where .= $condition. ' createTime <=' . $selectParams['entTime'];
- }
- // 根据会员卡id进行筛选
- if (!empty($selectParams['vipCardId'])) {
- $condition = empty($where) ? '' : ' AND ';
- $where .= $condition. ' vipCardId =' . $selectParams['vipCardId'];
- }
- if (isset($selectParams['name']) && !empty($selectParams['name'])) {
- $vipCardIds = $this->objDVipCard->gets_field('id','name like "%'.$selectParams['name'].'%"');
- if (empty($vipCardIds)) {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0,
- ]);
- }
- $condition = empty($where) ? '' : ' AND ';
- $where .= $condition.'vipCardId IN ('. implode(',', $vipCardIds) .')';
- }
- $condition = empty($where) ? '' : ' AND ';
- $where .= $condition.'payStatus='.StatusCode::$standard;
-
- $dbResult = $this->objDVipCardOrder->select($where, '*', 'createTime desc', $limit, $offset);
-
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
- $total = $this->objDVipCardOrder->count($where);
- $return = [
- 'data' => self::formatVipCardData($dbResult),
- 'total' => ($total)?intval($total):0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 前台获取我的会员卡订单
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- */
- public function getMyVipCards($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $fields = 'SELECT count(o.id) as total ';
- $base = ' FROM qianniao_vip_card_order_'.$this->enterpriseId.' o left join qianniao_vip_card_'.$this->enterpriseId.' c on c.id = o.vipCardId WHERE o.userCenterId = '.$this->userCenterId.' and c.enableStatus = '.StatusCode::$standard.' and c.deleteStatus = '.StatusCode::$standard.' AND o.payStatus = '.StatusCode::$standard.' AND o.deleteStatus = '.StatusCode::$standard.' AND o.expireTime >= unix_timestamp(now()) AND o.enableStatus = '.StatusCode::$standard;
- $sql = $fields.$base;
- $dbResult = $this->objDVipCardOrder->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- if( $dbResult[0]['total'] == 0 ){
- $return = [
- 'data' => [],
- 'total' => 0,
- 'received' => StatusCode::$standard
- ];
- return ResultWrapper::success($return);
- }
- $total = $dbResult[0]['total'];
- $fields = 'select o.expireTime,o.vipCardId,o.enableStatus ';
- $orderBy = ' ORDER BY o.createTime desc ';
- $limit = ($offset && $limit) ? ' limit '.$offset.','.$limit : '';
- $sql = $fields.$base.$orderBy.$limit;
- $dbResult = $this->objDVipCardOrder->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- $return = [
- 'data' => self::formatVipCardData($dbResult),
- 'total' => $total,
- 'received' => StatusCode::$standard
- ];
- return ResultWrapper::success($return);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/3/17
- * Time: 6:06 下午
- * @param int $userCenterId
- * @return ResultWrapper
- */
- public function getVipCardNum(int $userCenterId): ResultWrapper
- {
- //userCenterId = $this->userCenterId AND payStatus = ".StatusCode::$standard." AND deleteStatus=".StatusCode::$standard.' AND expireTime >= unix_timestamp(now()) AND enableStatus ='.StatusCode::$standard
- $sql = 'SELECT COUNT(id) as total FROM qianniao_vip_card_order_'.$this->enterpriseId.' WHERE userCenterId = '.$this->userCenterId .' AND payStatus = '.StatusCode::$standard.' AND deleteStatus='.StatusCode::$standard.' AND expireTime >= unix_timestamp(now()) AND enableStatus ='.StatusCode::$standard;
- $count = $this->objDVipCardOrder->query($sql);
- if ($count === false){
- return ResultWrapper::fail($this->objDVipCardOrder->error(),ErrorCode::$dberror);
- }
- $total = isset($count[0]['total']) ? $count[0]['total'] : 0;
- return ResultWrapper::success($total);
- }
- //客户购买的会员卡每月赠送的优惠券列表
- public function myVipCardMonthCoupon() {
- $myVipCardResult = self::getMyVipCards(['limit'=>null,'offset'=>null]);
- if ($myVipCardResult->isSuccess() == false) {
- return ResultWrapper::fail($myVipCardResult->getData(), $myVipCardResult->getErrorCode());
- }
- $myVipCards = $myVipCardResult->getData();
- $myVipCardsList = $myVipCards['data'];
- $allCouponId = [];
- $vipCardIds = [];
- foreach ($myVipCardsList as $myVipCards) {
- $vipCardIds[] = $myVipCards['id'];
- if ($myVipCards['hasMonthCoupon'] == StatusCode::$standard && !empty($myVipCards['monthCouponIds'])) {
- foreach (explode(',',$myVipCards['monthCouponIds']) as $couponId) {
- $allCouponId[]=[
- 'vipCardId'=>$myVipCards['id'],
- 'couponId'=>$couponId
- ];
- }
- }
- }
- if (empty($allCouponId)) {
- return ResultWrapper::success($allCouponId);
- }
- //本月已领取的会员卡优惠券
- $sql = "select couponId,vipCardId,createTime,userId from qianniao_user_coupon_".$this->enterpriseId." where vipCardId IN (". implode(',', $vipCardIds) .") AND FROM_UNIXTIME(createTime,'%Y-%m')='".date('Y-m')."' AND userId=".$this->userCenterId;
- $hasReceivedCouponThisMonth = $this->objDVipCard->query($sql);
- if ($hasReceivedCouponThisMonth === false) {
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
- //过滤掉已经领取过的优惠券
- foreach ($allCouponId as $key => &$couponData) {
- foreach ($hasReceivedCouponThisMonth as $hasReceivedCoupon) {
- if ($hasReceivedCoupon['vipCardId'] == $couponData['vipCardId'] && $hasReceivedCoupon['couponId'] == $couponData['couponId']) {
- unset($allCouponId[$key]);
- }
- }
- }
- //剩余可领取的优惠券
- $couponIds = array_column($allCouponId, 'couponId');
- if (empty($couponIds)) {
- return ResultWrapper::success($allCouponId);
- }
- //查出优惠券详情,过滤掉已经过期的优惠券
- $couponListResult = $this->objMCoupon->getVipCardCouponInfo($couponIds);
- if ($couponListResult->isSuccess() === false) {
- return ResultWrapper::fail($couponListResult->getData(), $couponListResult->getErrorCode());
- }
- $couponList = $couponListResult->getData();
- if (empty($couponList)) {
- return ResultWrapper::success($couponList);
- }
- $couponList = array_column($couponList, null, 'id');
- $return = [];
- foreach ($allCouponId as $couponId) {
- if (isset($couponList[$couponId['couponId']])) {
- $couponList[$couponId['couponId']]['vipCardId'] = $couponId['vipCardId'];
- $return[] = $couponList[$couponId['couponId']];
- }
- }
- return ResultWrapper::success($return);
- }
- //格式化会员卡订单中的会员卡数据
- public function formatVipCardData($data) {
- $vipCardIds = [];
- foreach ($data as $order) {
- $vipCardIds[] = $order['vipCardId'];
- }
- $vipCardData = [];
- $vipCardResult = $this->objDVipCard->select(array_values(array_unique(array_filter($vipCardIds))));
- foreach ($vipCardResult as &$vipCard) {
- $vipCard['effectiveMonth'] = $vipCard['effectiveDate'] == -1 ? 0 : $vipCard['effectiveDate'];
- $vipCard['effectiveDate'] = $vipCard['effectiveDate'] == -1 ? StatusCode::$standard : StatusCode::$delete;
- $vipCardData[$vipCard['id']] = $vipCard;
- }
- unset($vipCard);
- foreach ($data as &$order) {
- if ($this->isFront) {
- $order['renew'] = StatusCode::$standard;//前端:续费
- }else {
- //针对后台领取记录列表,显示是否失效
- unset($vipCardData[$order['vipCardId']]['enableStatus']);
- if($order['enableStatus'] == StatusCode::$standard && $order['expireTime'] < time()) {
- $order['enableStatus'] = StatusCode::$delete;
- }
- }
- $order = array_merge($order, $vipCardData[$order['vipCardId']]);
- }
- return $data;
- }
- public function createVipCardOrder($params, $ip) {
- //查出会员卡信息,是否有库存,是否禁止出售
- $vipCardInfo = self::getVipCardInfo($params['vipCardId']);
- if($vipCardInfo->isSuccess() == false) {
- return ResultWrapper::fail($vipCardInfo->getData(), $vipCardInfo->getErrorCode());
- }
- $vipCard = $vipCardInfo->getData();
- if(empty($vipCard)) {
- return ResultWrapper::fail("会员卡不存在", ErrorCode::$userNotFount);
- }
- if ($vipCard['enableStatus'] == StatusCode::$delete || $vipCard['deleteStatus'] == StatusCode::$delete) {
- return ResultWrapper::fail("会员卡已禁售", ErrorCode::$userNotFount);
- }
- if (($vipCard['totalNum'] - $vipCard['num']) <= 0){
- return ResultWrapper::fail("会员卡库存不足", ErrorCode::$userNotFount);
- }
- //查出当前客户信息
- $customerData = $this->objMCustomer->getCustomerInfoByUserCenterId($this->userCenterId);
- if (!$customerData->isSuccess()) {
- return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
- }
- $customerData = $customerData->getData();
- if (empty($customerData)) {
- return ResultWrapper::fail("客户不存在", ErrorCode::$userNotFount);
- }
- //免费的会员卡,一个人只能领取一次
- /*$freeCard = $this->objDVipCardOrder->select(['customerId'=>$customerData['id'],'vipCardId'=>$vipCard['id'],'payAmount'=>0]);
- if ($freeCard === false) {
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- if (!empty($freeCard)) {
- return ResultWrapper::fail('每人限领一次', ErrorCode::$dberror);
- }*/
- $no = createOrderSn($params['source'], StatusCode::$orderType['vipCard'], $this->userCenterId);
- // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号
- $tmpOuterTradeNo = 'vip_tmp' . createOrderSn($params['source'], StatusCode::$orderType['vipCard'], $this->userCenterId);
- //新增的时候计算过期时间expireDate,当前时间加上
- $month = $vipCard['effectiveDate'] == StatusCode::$standard ? 1200 : $vipCard['effectiveMonth'];//永久有效则默认100年,1200个月
- $orderData = [
- 'no'=>$no,
- 'shopId'=> empty($customerData['shopId']) ? 0 : $customerData['shopId'],
- 'outerTradeNo'=>$tmpOuterTradeNo,
- 'totalMoney'=>$vipCard['price'],
- 'payAmount'=>$vipCard['price'],
- 'vipCardId'=>$vipCard['id'],
- 'customerName'=>$customerData['name'],
- 'customerId'=>$customerData['id'],
- 'payStatus'=> $vipCard['price'] == 0 ? StatusCode::$standard : StatusCode::$delete,//价格为0则免费
- 'payTime'=> $vipCard['price'] == 0 ? time() : '',//价格为0则免费
- 'successFullyTime'=> $vipCard['price'] == 0 ? time() : '',//价格为0则免费
- 'payType'=> $params['payType'],//支付方式
- 'source'=> $params['source'],//来源
- 'remark'=> $params['remark'],//来源
- 'expireTime'=>time() + $month * 30 * 24 * 60 * 60,
- 'deleteStatus'=>StatusCode::$standard,
- 'createTime'=>time(),
- 'updateTime'=>time(),
- 'salesManId'=>$customerData['salesManId'],
- 'salesManName'=>$customerData['salesManName'],
- 'customerType'=>$customerData['type'],
- 'userCenterId'=>$this->userCenterId
- ];
- $this->objDVipCardOrder->beginTransaction();
- $orderId = $this->objDVipCardOrder->insert($orderData);
- if ($orderId === false) {
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- //增加一个销量
- $result = $this->objDVipCard->set_inc('num',$orderData['vipCardId']);
- if ($result === false) {
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
- if($vipCard['price'] == 0) {
- //领取免费的,旧的会员卡失效
- $sql = 'UPDATE '. $this->objDVipCardOrder->get_Table() .' SET enableStatus='.StatusCode::$delete.' WHERE id !='.$orderId.' AND customerId='.$orderData['customerId'].' AND enableStatus='.StatusCode::$standard;
- $result = $this->objDVipCardOrder->query($sql);
- if ($result === false) {
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- //免费的已支付,则发放优惠券
- if ($vipCard['hasNewCardCoupon'] == StatusCode::$standard) {
- if (!empty($vipCard['newCardCouponIds'])) {
- $dbResult = $this->objMCoupon->giveCoupon(explode(',', $vipCard['newCardCouponIds']), $vipCard['id']);
- if (!$dbResult->isSuccess()){
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- }
- }
- }
- $this->objDVipCardOrder->commit();
- if ($vipCard['price'] ==0 || $params['source'] == StatusCode::$source['manage'] || $params['payType'] == StatusCode::$payType['cashPay']) {
- return ResultWrapper::success(['orderId'=>$orderId]);
- }
- //获取支付配置
- $result = $this->objMPaymentSetting->getPayData($params['payType']);
- if (!$result->isSuccess() || empty($result->getData())) {
- return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
- }
- $payment = $result->getData();
- $payParams = '';
- if ($params['payType'] == StatusCode::$payType['aliPay']) {
- /*********读取支付宝支付参数(原配置)*********/
- /**$aliPayConfigData = Factory::config()->get('alipay');
- * if (empty($aliPayConfigData)) {
- * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor);
- * }*/
- $payOrderData = [
- 'subject' => '千鸟云商',
- 'out_trade_no' => $tmpOuterTradeNo,
- 'total_amount' => $vipCard['price'],
- 'passback_params' => $this->enterpriseId . '|' . $this->userCenterId . '|' . $orderId
- ];
- $aliPayConfigData = [
- 'appid' => $payment['appid'],
- 'rsaPrivateKey' => $payment['rsaPrivateKey'],
- 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'],
- ];
- $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']);
- $payParams = $objAliPay->appPay($payOrderData);
- } else if ($params['payType'] == StatusCode::$payType['wxPay']) {
- /********************生成小程序唤起支付用到的参数(原配置)*****/
- /**$weixinConfigData = Factory::config()->get('weixin');
- * if (empty($weixinConfigData)) {
- * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
- * }*/
- // 获取当前登录企业的小程序配置
- $objSystemCache = new SystemCache();
- $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->enterpriseId);
- if (empty($miniprogramSetting)) {
- return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
- }
- $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
- switch ($params['source']) {
- case StatusCode::$source['ByteProgram'];
- //$appid = $weixinConfigData['offiaccount']['appid'];
- $appid = $miniprogramSetting['appid'];
- $paySource = 'byteDanceH5';
- break;
- case StatusCode::$source['miniProgram'];
- $appid = $miniprogramSetting['appid'];
- $paySource = 'miniProgram';
- break;
- default :
- $appid = $payment['mobileAppid'];
- $paySource = 'APP';
- break;
- }
- $weixinConfigData = [
- 'mch_id' => $payment['mchId'],
- 'apiPartnerKey' => $payment['apiPartnerKey'],
- 'appid' => $appid
- ];
- Logger::logs(E_USER_ERROR,'weixinConfigData',__CLASS__,__LINE__,$weixinConfigData);
- $attach = $this->enterpriseId . '|' . $this->userCenterId . '|' . $orderId;
- //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
- $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
- $payParams = $objPay->unifiedorder($tmpOuterTradeNo, $vipCard['price'], $ip, $paySource, '千鸟云商', $customerData['openId'], $attach);
- }
- if (!$payParams->isSuccess()) {
- return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
- }
- if($params['source'] == StatusCode::$source['ByteProgram']){
- $mweb_url = $payParams->getData();
- // 获取配置文件字节小程序
- $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay');
- if (empty($byteDanceConfigData)) {
- return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor);
- }
- $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']);
- unset($payParams);
- $payParams = $objbytePay->pay($tmpOuterTradeNo, $vipCard['price'], '千鸟云商', $ip, $mweb_url);
- if (!$payParams->isSuccess()) {
- return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
- }
- }
- Logger::logs(E_USER_ERROR,'ret params',__CLASS__,__LINE__,$payParams->getData());
- return ResultWrapper::success($payParams->getData());
- }
- /**
- * 修改订单支付状态,支付成功后赠送对应优惠券
- * @param $vipOrderData
- * @param $condition
- * @param bool $isNotify
- * @return ResultWrapper
- * @throws \Exception
- */
- public function updateVipOrderPayData($vipOrderData, $condition, $isNotify = false) {
- $orderData = $this->objDVipCardOrder->get($condition);
- if ($orderData === false) {
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- if (empty($orderData)) {
- return ResultWrapper::fail('不存在此会员卡购买订单', ErrorCode::$contentNotExists);
- }
- $vipCardInfo = $this->objDVipCard->get($orderData['vipCardId']);
- if ($vipCardInfo === false) {
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
- $this->objDVipCardOrder->beginTransaction();
- //把会员原先会员片禁用掉
- $sql = 'UPDATE '. $this->objDVipCardOrder->get_Table() .' SET enableStatus='.StatusCode::$delete.' WHERE id !='.$orderData['id'].' AND customerId='.$orderData['customerId'].' AND enableStatus='.StatusCode::$standard;
- $result = $this->objDVipCardOrder->query($sql);
- if ($result === false) {
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- $vipOrderData['successFullyTime'] = time();
- $dbResult = $this->objDVipCardOrder->update($vipOrderData,$condition);
- if ($dbResult === false) {
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- if ($vipCardInfo['hasNewCardCoupon'] == StatusCode::$standard) {
- if (!empty($vipCardInfo['newCardCouponIds'])) {
- $dbResult = $this->objMCoupon->giveCoupon(explode(',', $vipCardInfo['newCardCouponIds']), $vipCardInfo['id']);
- if (!$dbResult->isSuccess()){
- $this->objDVipCardOrder->rollBack();
- return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
- }
- }
- }
- $this->objDVipCardOrder->commit();
- return ResultWrapper::success($dbResult);
- }
-
- /**
- * 指定客户会员卡一键失效
- * @param array $params
- * @return ResultWrapper
- */
- public function invalidVipCard($params)
- {
- $orderData = $this->objDVipCardOrder->get($params);
- if ($orderData === false) {
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- if (empty($orderData)) {
- return ResultWrapper::fail('没有找到该客户的vip卡', ErrorCode::$contentNotExists);
- }
- $dbResult = $this->objDVipCardOrder->update( ['enableStatus'=> StatusCode::$delete],$orderData['id']);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
- }
-
- return ResultWrapper::success($dbResult);
-
- }
- /**
- * 获取指定用户的所有会员卡数据
- */
- public function getAllVipCardByCustomerId($customerId)
- {
- if(empty($customerId)){
- return ResultWrapper::fail('请指定要查询得用户id', ErrorCode::$paramError);
- }
- $fields = 'SELECT c.* ';
- $base = ' FROM qianniao_vip_card_order_'.$this->enterpriseId.' o left join qianniao_vip_card_'.$this->enterpriseId.' c on c.id = o.vipCardId WHERE o.customerId = '.$customerId.' and c.enableStatus = '.StatusCode::$standard.' and c.deleteStatus = '.StatusCode::$standard.' AND o.payStatus = '.StatusCode::$standard.' AND o.deleteStatus = '.StatusCode::$standard.' AND o.expireTime >= unix_timestamp(now()) AND o.enableStatus = '.StatusCode::$standard;
- $sql = $fields.$base;
- $dbResult = $this->objDVipCardOrder->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- }
|