MVipCard.Class.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. <?php
  2. /**
  3. * 会员卡管理模块
  4. * Created by PhpStorm.
  5. * User: wxj
  6. * Date: 2019/10/30
  7. * Time: 14:02
  8. */
  9. namespace JinDouYun\Model\Market;
  10. use JinDouYun\Controller\Common\Logger;
  11. use Mall\Framework\Core\ErrorCode;
  12. use Mall\Framework\Core\StatusCode;
  13. use Mall\Framework\Core\ResultWrapper;
  14. use JinDouYun\Model\MBaseModel;
  15. use JinDouYun\Dao\Market\DVipCard;
  16. use JinDouYun\Dao\Market\DVipCardOrder;
  17. use JinDouYun\Model\Customer\MCustomer;
  18. use JinDouYun\Model\System\MPaymentSetting;
  19. use JinDouYun\Cache\SystemCache;
  20. use JinDouYun\Dao\Goods\DGoods;
  21. use JinDouYun\Dao\Market\DUserCoupon;
  22. use Mall\Framework\Factory;
  23. use Util\ByteDance\Pay as bytePay;
  24. use Util\WeiXin\Pay;
  25. use Util\AliPay\Pay as aliPay;
  26. class MVipCard extends MBaseModel {
  27. private $objDVipCard;
  28. private $objDVipCardOrder;
  29. private $objMCustomer;
  30. private $enterpriseId;
  31. private $userCenterId;
  32. private $isFront;
  33. private $objMPaymentSetting;
  34. private $objMCoupon;
  35. private $objDUserCoupon;
  36. private $objDGoods;
  37. public function __construct($enterpriseId, $userCenterId, $isFront = false)
  38. {
  39. $this->userCenterId = $userCenterId;
  40. $this->enterpriseId = $enterpriseId;
  41. $this->isFront = $isFront;
  42. parent::__construct($enterpriseId, $userCenterId);
  43. $this->objDVipCard = new DVipCard('default');
  44. $this->objDVipCardOrder = new DVipCardOrder('default');
  45. $this->objMCustomer = new MCustomer($enterpriseId, $userCenterId);
  46. $this->objMPaymentSetting = new MPaymentSetting($userCenterId, $enterpriseId);
  47. $this->objMCoupon = new MCoupon($userCenterId, $enterpriseId);
  48. $this->objDUserCoupon = new DUserCoupon('default');
  49. $this->objDGoods = new DGoods('default');
  50. $tableName = $this->objDGoods->getTableName('qianniao_goods_', $this->enterpriseId, 1);
  51. $this->objDGoods->setTable($tableName);
  52. $this->objDVipCard->setTable($this->objDVipCard->get_Table().'_'.$enterpriseId);
  53. $this->objDVipCardOrder->setTable($this->objDVipCardOrder->get_Table().'_'.$enterpriseId);
  54. $this->objDUserCoupon->setTable($this->objDUserCoupon->get_Table() . '_' . $enterpriseId);
  55. }
  56. /**
  57. * 添加会员卡
  58. *
  59. * @param array $params 会员卡数据
  60. *
  61. * @return ResultWrapper
  62. */
  63. public function addVipCard($params)
  64. {
  65. $VipCardId = $this->objDVipCard->insert($params);
  66. if($VipCardId === false){
  67. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  68. }else{
  69. return ResultWrapper::success($VipCardId);
  70. }
  71. }
  72. /**
  73. * 获取指定会员卡信息
  74. * @param $vipCardId
  75. * @return ResultWrapper
  76. */
  77. public function getVipCardInfo($vipCardId)
  78. {
  79. $dbResult = $this->objDVipCard->get($vipCardId);
  80. if($dbResult === false){
  81. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  82. }else{
  83. $dbResult = self::format([$dbResult], true);
  84. $dbResult = array_shift($dbResult);
  85. return ResultWrapper::success($dbResult);
  86. }
  87. }
  88. //前后端会员卡详情和会员卡列表使用此格式化方法
  89. public function format($params = [], $getDetail = false) {
  90. $vipCardIds = [];
  91. foreach ($params as &$data) {
  92. $data['effectiveMonth'] = $data['effectiveDate'] == -1 ? 0 : $data['effectiveDate'];
  93. $data['effectiveDate'] = $data['effectiveDate'] == -1 ? StatusCode::$standard : StatusCode::$delete;
  94. if ($this->isFront) {
  95. //前端会员卡列表
  96. $data['renew'] = StatusCode::$delete;
  97. }
  98. $vipCardIds[] = $data['id'];
  99. }
  100. unset($data);
  101. //详情页组装数据 商品名称 优惠券名称等
  102. if ($getDetail) {
  103. $couponIds = [];
  104. $goodsIds = [];
  105. foreach ($params as $value) {
  106. if (!empty($value['newCardCouponIds'])) {
  107. $couponIds = array_merge($couponIds, explode(',',$value['newCardCouponIds']));
  108. }
  109. if (!empty($value['monthCouponIds'])) {
  110. $couponIds = array_merge($couponIds, explode(',',$value['monthCouponIds']));
  111. }
  112. if (!empty($value['goodsIds'])) {
  113. $goodsIds = array_merge($goodsIds, explode(',',$value['goodsIds']));
  114. }
  115. }
  116. unset($value);
  117. //详情页面获取选中的优惠券和商品名称
  118. $couponData = [];
  119. if(!empty($couponIds)) {
  120. $couponResult = $this->objMCoupon->getAll(['limit'=>null,'offset'=>null,'id'=>array_values(array_unique(array_filter($couponIds)))],'id,name,reducePrice,endTime,totalNum,receiveNum,useShop');
  121. if($couponResult->isSuccess()) {
  122. $couponResultData = $couponResult->getData();
  123. foreach ($couponResultData['data'] as $coupon) {
  124. $couponData[$coupon['id']] = $coupon;
  125. }
  126. }
  127. }
  128. $goodsData = [];
  129. if(!empty($goodsIds)) {
  130. $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) .')';
  131. $goodsResult = $this->objDGoods->query($sql);
  132. if ($goodsResult != false) {
  133. foreach ($goodsResult as $goods) {
  134. $goodsData[$goods['id']] = $goods['title'];
  135. }
  136. }
  137. }
  138. foreach ($params as &$value) {
  139. $value['newCardCouponNames'] = [];
  140. $value['monthCouponNames'] = [];
  141. $value['monthCoupon'] = [];
  142. $value['goodsName'] = [];
  143. if (!empty($value['newCardCouponIds'])) {
  144. foreach (explode(',',$value['newCardCouponIds']) as $newCardCoupon) {
  145. $value['newCardCouponNames'][] = isset($couponData[$newCardCoupon]) ? $couponData[$newCardCoupon]['name'] : '';
  146. }
  147. }
  148. if (!empty($value['monthCouponIds'])) {
  149. foreach (explode(',',$value['monthCouponIds']) as $monthCoupon) {
  150. if (isset($couponData[$monthCoupon])) {
  151. $value['monthCouponNames'][] = $couponData[$monthCoupon]['name'];
  152. $value['monthCoupon'][] = $couponData[$monthCoupon];//每月领取优惠券数组
  153. }
  154. }
  155. }
  156. if (!empty($value['goodsIds'])) {
  157. foreach (explode(',',$value['goodsIds']) as $goodsId) {
  158. $value['goodsName'][] = isset($goodsData[$goodsId]) ? $goodsData[$goodsId] : '';
  159. }
  160. }
  161. //前端详情页面,判断会员是否领取过该会员卡下的优惠券
  162. if ($this->isFront) {
  163. $value['received'] = StatusCode::$delete;
  164. $value['hasBuy'] = StatusCode::$delete;//是否已购买此卡
  165. $value['renew'] = StatusCode::$delete;//立即开通
  166. $value['hasReceived'] = StatusCode::$delete;//是否已领取优惠券
  167. //当前会员是否拥有会员卡
  168. $myVipCardResult = self::getMyVipCards(['limit'=>null,'offset'=>null]);
  169. if ($myVipCardResult->isSuccess()) {
  170. $myVipCards = $myVipCardResult->getData();
  171. $myVipCardsList = $myVipCards['data'];
  172. if (!empty($myVipCardsList)) {
  173. $value['received'] = StatusCode::$standard;//已有会员卡
  174. }
  175. }
  176. $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;
  177. $userVipCard = $this->objDVipCardOrder->get($where);
  178. if ($userVipCard !== false && !empty($userVipCard)) {
  179. $value['hasBuy'] = StatusCode::$standard;//已购买
  180. $value['renew'] = StatusCode::$standard;//续费
  181. if (!empty($value['monthCouponIds'])) {
  182. //本月领取的该会员卡的优惠券id
  183. $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;
  184. $userCouponIds = $this->objDUserCoupon->query($sql);
  185. //如果本月已领取的和会员卡赠送的优惠券一致,则已领取过,不显示一键领取按钮
  186. if ($userCouponIds) {
  187. $noReceivedCouponId = array_diff(explode(',',$value['monthCouponIds']),array_column($userCouponIds,'couponId'));
  188. $value['hasReceived'] = empty($noReceivedCouponId) ? StatusCode::$standard : StatusCode::$delete;
  189. }
  190. }
  191. }
  192. }
  193. }
  194. }
  195. return $params;
  196. }
  197. /**
  198. * 编辑会员卡
  199. *
  200. * @param int|array $params 修改会员卡的数据
  201. *
  202. * @return ResultWrapper
  203. */
  204. public function editVipCard($params)
  205. {
  206. if( empty($params['id']) ){
  207. return ResultWrapper::fail('没有指定要修改的VipCardid', ErrorCode::$paramError);
  208. }
  209. $updateVipCardId = $params['id'];
  210. unset($params['id']);
  211. $dbResult = $this->objDVipCard->update($params, $updateVipCardId);
  212. if($dbResult === false){
  213. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  214. }else{
  215. return ResultWrapper::success($dbResult);
  216. }
  217. }
  218. /**
  219. * 删除会员卡
  220. *
  221. * @param array $delMarketIds 要删除的会员卡id
  222. *
  223. * @return ResultWrapper
  224. */
  225. public function delVipCard($delVipCardIds)
  226. {
  227. if (empty($delVipCardIds)) {
  228. return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
  229. }
  230. $dbResult = $this->objDVipCard->update( ['deleteStatus'=>StatusCode::$delete], $delVipCardIds );
  231. if($dbResult === false){
  232. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  233. }else{
  234. return ResultWrapper::success($dbResult);
  235. }
  236. }
  237. /**
  238. * 会员卡启用和禁用
  239. * @param array $params
  240. * @return ResultWrapper
  241. */
  242. public function updateVipCardStatus($params)
  243. {
  244. $dbResult = $this->objDVipCard->update( ['enableStatus'=>$params['enableStatus']], $params['id'] );
  245. if($dbResult === false){
  246. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  247. }else{
  248. return ResultWrapper::success($dbResult);
  249. }
  250. }
  251. /**
  252. * 获取所有会员卡数据
  253. *
  254. * @param array $selectParams 过滤条件
  255. *
  256. * @return ResultWrapper
  257. */
  258. public function getAllVipCard($selectParams)
  259. {
  260. $limit = $selectParams['limit'];
  261. unset($selectParams['limit']);
  262. $offset = $selectParams['offset'];
  263. unset($selectParams['offset']);
  264. $where ='deleteStatus='.StatusCode::$standard;
  265. if (isset($selectParams['enableStatus'])) {
  266. $where .= ' AND enableStatus='.$selectParams['enableStatus'];
  267. }
  268. if (isset($selectParams['name'])) {
  269. $where .= ' AND name like "%'.$selectParams['name'].'%"';
  270. }
  271. $dbResult = $this->objDVipCard->select($where, '*', 'sort desc,createTime desc', $limit, $offset);
  272. if($dbResult === false){
  273. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  274. }
  275. $total = $this->objDVipCard->count($where);
  276. $return = [
  277. 'data' => self::format($dbResult),
  278. 'total' => ($total)?intval($total):0,
  279. ];
  280. return ResultWrapper::success($return);
  281. }
  282. /**
  283. * 前台获取所有会员卡数据
  284. *
  285. * @param array $selectParams 过滤条件
  286. *
  287. * @return ResultWrapper
  288. */
  289. public function getAllFrontVipCard($selectParams)
  290. {
  291. $limit = $selectParams['limit'];
  292. unset($selectParams['limit']);
  293. $offset = $selectParams['offset'];
  294. unset($selectParams['offset']);
  295. $where ='deleteStatus='.StatusCode::$standard.' AND enableStatus='.StatusCode::$standard;
  296. $myVipCardResult = self::getMyVipCards(['limit'=>1000,'offset'=>0]);
  297. if ($myVipCardResult->isSuccess() == false) {
  298. return ResultWrapper::fail($myVipCardResult->getData(), $myVipCardResult->getErrorCode());
  299. }
  300. $myVipCards = $myVipCardResult->getData();
  301. $myVipCardsList = $myVipCards['data'];
  302. $myVipCardIds = [];
  303. if (!empty($myVipCardsList)) {
  304. $received = StatusCode::$standard;
  305. foreach ($myVipCardsList as $vipCard) {
  306. $myVipCardIds[] = $vipCard['id'];
  307. }
  308. }
  309. if (!empty($myVipCardIds)) {
  310. $where .= ' AND id NOT IN ('. implode(',',$myVipCardIds) .')';
  311. }
  312. $dbResult = $this->objDVipCard->select($where, '*', 'sort desc,createTime desc', $limit, $offset);
  313. if($dbResult === false){
  314. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  315. }
  316. $total = $this->objDVipCard->count($where);
  317. $return = [
  318. 'data' => self::format($dbResult),
  319. 'total' => ($total)?intval($total):0,
  320. 'received' => isset($received) ? $received : StatusCode::$delete
  321. ];
  322. return ResultWrapper::success($return);
  323. }
  324. /**
  325. * 获取所有领取记录
  326. *
  327. * @param array $selectParams 过滤条件
  328. *
  329. * @return ResultWrapper
  330. */
  331. public function getAllReceiveRecord($selectParams)
  332. {
  333. $limit = $selectParams['limit'];
  334. unset($selectParams['limit']);
  335. $offset = $selectParams['offset'];
  336. unset($selectParams['offset']);
  337. $where = '';
  338. if (isset($selectParams['outDate']) && !empty($selectParams['outDate'])) {
  339. $condition = empty($where) ? '' : ' AND ';
  340. $date = $selectParams['outDate'] == StatusCode::$standard ? '<=' : '>';
  341. $where .= $condition.'expireTime '. $date . ' unix_timestamp(now())';
  342. }
  343. // 筛选客户
  344. if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
  345. $condition = empty($where) ? '' : ' AND ';
  346. $where .= $condition.' customerId ='.$selectParams['customerId'];
  347. }
  348. // 筛选领取时间
  349. if (!empty($selectParams['createTime'])) {
  350. $condition = empty($where) ? '' : ' AND ';
  351. $where .= $condition. ' createTime >=' . $selectParams['createTime'];
  352. }
  353. if (!empty($selectParams['entTime'])) {
  354. $condition = empty($where) ? '' : ' AND ';
  355. $where .= $condition. ' createTime <=' . $selectParams['entTime'];
  356. }
  357. // 根据会员卡id进行筛选
  358. if (!empty($selectParams['vipCardId'])) {
  359. $condition = empty($where) ? '' : ' AND ';
  360. $where .= $condition. ' vipCardId =' . $selectParams['vipCardId'];
  361. }
  362. if (isset($selectParams['name']) && !empty($selectParams['name'])) {
  363. $vipCardIds = $this->objDVipCard->gets_field('id','name like "%'.$selectParams['name'].'%"');
  364. if (empty($vipCardIds)) {
  365. return ResultWrapper::success([
  366. 'data' => [],
  367. 'total' => 0,
  368. ]);
  369. }
  370. $condition = empty($where) ? '' : ' AND ';
  371. $where .= $condition.'vipCardId IN ('. implode(',', $vipCardIds) .')';
  372. }
  373. $condition = empty($where) ? '' : ' AND ';
  374. $where .= $condition.'payStatus='.StatusCode::$standard;
  375. $dbResult = $this->objDVipCardOrder->select($where, '*', 'createTime desc', $limit, $offset);
  376. if($dbResult === false){
  377. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  378. }
  379. $total = $this->objDVipCardOrder->count($where);
  380. $return = [
  381. 'data' => self::formatVipCardData($dbResult),
  382. 'total' => ($total)?intval($total):0,
  383. ];
  384. return ResultWrapper::success($return);
  385. }
  386. /**
  387. * 前台获取我的会员卡订单
  388. *
  389. * @param array $selectParams 过滤条件
  390. *
  391. * @return ResultWrapper
  392. */
  393. public function getMyVipCards($selectParams)
  394. {
  395. $limit = $selectParams['limit'];
  396. unset($selectParams['limit']);
  397. $offset = $selectParams['offset'];
  398. unset($selectParams['offset']);
  399. $fields = 'SELECT count(o.id) as total ';
  400. $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;
  401. $sql = $fields.$base;
  402. $dbResult = $this->objDVipCardOrder->query($sql);
  403. if($dbResult === false){
  404. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  405. }
  406. if( $dbResult[0]['total'] == 0 ){
  407. $return = [
  408. 'data' => [],
  409. 'total' => 0,
  410. 'received' => StatusCode::$standard
  411. ];
  412. return ResultWrapper::success($return);
  413. }
  414. $total = $dbResult[0]['total'];
  415. $fields = 'select o.expireTime,o.vipCardId,o.enableStatus ';
  416. $orderBy = ' ORDER BY o.createTime desc ';
  417. $limit = ($offset && $limit) ? ' limit '.$offset.','.$limit : '';
  418. $sql = $fields.$base.$orderBy.$limit;
  419. $dbResult = $this->objDVipCardOrder->query($sql);
  420. if($dbResult === false){
  421. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  422. }
  423. $return = [
  424. 'data' => self::formatVipCardData($dbResult),
  425. 'total' => $total,
  426. 'received' => StatusCode::$standard
  427. ];
  428. return ResultWrapper::success($return);
  429. }
  430. /**
  431. * Doc: (des="")
  432. * User: XMing
  433. * Date: 2021/3/17
  434. * Time: 6:06 下午
  435. * @param int $userCenterId
  436. * @return ResultWrapper
  437. */
  438. public function getVipCardNum(int $userCenterId): ResultWrapper
  439. {
  440. //userCenterId = $this->userCenterId AND payStatus = ".StatusCode::$standard." AND deleteStatus=".StatusCode::$standard.' AND expireTime >= unix_timestamp(now()) AND enableStatus ='.StatusCode::$standard
  441. $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;
  442. $count = $this->objDVipCardOrder->query($sql);
  443. if ($count === false){
  444. return ResultWrapper::fail($this->objDVipCardOrder->error(),ErrorCode::$dberror);
  445. }
  446. $total = isset($count[0]['total']) ? $count[0]['total'] : 0;
  447. return ResultWrapper::success($total);
  448. }
  449. //客户购买的会员卡每月赠送的优惠券列表
  450. public function myVipCardMonthCoupon() {
  451. $myVipCardResult = self::getMyVipCards(['limit'=>null,'offset'=>null]);
  452. if ($myVipCardResult->isSuccess() == false) {
  453. return ResultWrapper::fail($myVipCardResult->getData(), $myVipCardResult->getErrorCode());
  454. }
  455. $myVipCards = $myVipCardResult->getData();
  456. $myVipCardsList = $myVipCards['data'];
  457. $allCouponId = [];
  458. $vipCardIds = [];
  459. foreach ($myVipCardsList as $myVipCards) {
  460. $vipCardIds[] = $myVipCards['id'];
  461. if ($myVipCards['hasMonthCoupon'] == StatusCode::$standard && !empty($myVipCards['monthCouponIds'])) {
  462. foreach (explode(',',$myVipCards['monthCouponIds']) as $couponId) {
  463. $allCouponId[]=[
  464. 'vipCardId'=>$myVipCards['id'],
  465. 'couponId'=>$couponId
  466. ];
  467. }
  468. }
  469. }
  470. if (empty($allCouponId)) {
  471. return ResultWrapper::success($allCouponId);
  472. }
  473. //本月已领取的会员卡优惠券
  474. $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;
  475. $hasReceivedCouponThisMonth = $this->objDVipCard->query($sql);
  476. if ($hasReceivedCouponThisMonth === false) {
  477. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  478. }
  479. //过滤掉已经领取过的优惠券
  480. foreach ($allCouponId as $key => &$couponData) {
  481. foreach ($hasReceivedCouponThisMonth as $hasReceivedCoupon) {
  482. if ($hasReceivedCoupon['vipCardId'] == $couponData['vipCardId'] && $hasReceivedCoupon['couponId'] == $couponData['couponId']) {
  483. unset($allCouponId[$key]);
  484. }
  485. }
  486. }
  487. //剩余可领取的优惠券
  488. $couponIds = array_column($allCouponId, 'couponId');
  489. if (empty($couponIds)) {
  490. return ResultWrapper::success($allCouponId);
  491. }
  492. //查出优惠券详情,过滤掉已经过期的优惠券
  493. $couponListResult = $this->objMCoupon->getVipCardCouponInfo($couponIds);
  494. if ($couponListResult->isSuccess() === false) {
  495. return ResultWrapper::fail($couponListResult->getData(), $couponListResult->getErrorCode());
  496. }
  497. $couponList = $couponListResult->getData();
  498. if (empty($couponList)) {
  499. return ResultWrapper::success($couponList);
  500. }
  501. $couponList = array_column($couponList, null, 'id');
  502. $return = [];
  503. foreach ($allCouponId as $couponId) {
  504. if (isset($couponList[$couponId['couponId']])) {
  505. $couponList[$couponId['couponId']]['vipCardId'] = $couponId['vipCardId'];
  506. $return[] = $couponList[$couponId['couponId']];
  507. }
  508. }
  509. return ResultWrapper::success($return);
  510. }
  511. //格式化会员卡订单中的会员卡数据
  512. public function formatVipCardData($data) {
  513. $vipCardIds = [];
  514. foreach ($data as $order) {
  515. $vipCardIds[] = $order['vipCardId'];
  516. }
  517. $vipCardData = [];
  518. $vipCardResult = $this->objDVipCard->select(array_values(array_unique(array_filter($vipCardIds))));
  519. foreach ($vipCardResult as &$vipCard) {
  520. $vipCard['effectiveMonth'] = $vipCard['effectiveDate'] == -1 ? 0 : $vipCard['effectiveDate'];
  521. $vipCard['effectiveDate'] = $vipCard['effectiveDate'] == -1 ? StatusCode::$standard : StatusCode::$delete;
  522. $vipCardData[$vipCard['id']] = $vipCard;
  523. }
  524. unset($vipCard);
  525. foreach ($data as &$order) {
  526. if ($this->isFront) {
  527. $order['renew'] = StatusCode::$standard;//前端:续费
  528. }else {
  529. //针对后台领取记录列表,显示是否失效
  530. unset($vipCardData[$order['vipCardId']]['enableStatus']);
  531. if($order['enableStatus'] == StatusCode::$standard && $order['expireTime'] < time()) {
  532. $order['enableStatus'] = StatusCode::$delete;
  533. }
  534. }
  535. $order = array_merge($order, $vipCardData[$order['vipCardId']]);
  536. }
  537. return $data;
  538. }
  539. public function createVipCardOrder($params, $ip) {
  540. //查出会员卡信息,是否有库存,是否禁止出售
  541. $vipCardInfo = self::getVipCardInfo($params['vipCardId']);
  542. if($vipCardInfo->isSuccess() == false) {
  543. return ResultWrapper::fail($vipCardInfo->getData(), $vipCardInfo->getErrorCode());
  544. }
  545. $vipCard = $vipCardInfo->getData();
  546. if(empty($vipCard)) {
  547. return ResultWrapper::fail("会员卡不存在", ErrorCode::$userNotFount);
  548. }
  549. if ($vipCard['enableStatus'] == StatusCode::$delete || $vipCard['deleteStatus'] == StatusCode::$delete) {
  550. return ResultWrapper::fail("会员卡已禁售", ErrorCode::$userNotFount);
  551. }
  552. if (($vipCard['totalNum'] - $vipCard['num']) <= 0){
  553. return ResultWrapper::fail("会员卡库存不足", ErrorCode::$userNotFount);
  554. }
  555. //查出当前客户信息
  556. $customerData = $this->objMCustomer->getCustomerInfoByUserCenterId($this->userCenterId);
  557. if (!$customerData->isSuccess()) {
  558. return ResultWrapper::fail($customerData->getData(), $customerData->getErrorCode());
  559. }
  560. $customerData = $customerData->getData();
  561. if (empty($customerData)) {
  562. return ResultWrapper::fail("客户不存在", ErrorCode::$userNotFount);
  563. }
  564. //免费的会员卡,一个人只能领取一次
  565. /*$freeCard = $this->objDVipCardOrder->select(['customerId'=>$customerData['id'],'vipCardId'=>$vipCard['id'],'payAmount'=>0]);
  566. if ($freeCard === false) {
  567. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  568. }
  569. if (!empty($freeCard)) {
  570. return ResultWrapper::fail('每人限领一次', ErrorCode::$dberror);
  571. }*/
  572. $no = createOrderSn($params['source'], StatusCode::$orderType['vipCard'], $this->userCenterId);
  573. // 生成一个临时三方流水号,用来支持多个子订单作为一个订单支付,支付成功之后更新为对应的实际外部支付流水号
  574. $tmpOuterTradeNo = 'vip_tmp' . createOrderSn($params['source'], StatusCode::$orderType['vipCard'], $this->userCenterId);
  575. //新增的时候计算过期时间expireDate,当前时间加上
  576. $month = $vipCard['effectiveDate'] == StatusCode::$standard ? 1200 : $vipCard['effectiveMonth'];//永久有效则默认100年,1200个月
  577. $orderData = [
  578. 'no'=>$no,
  579. 'shopId'=> empty($customerData['shopId']) ? 0 : $customerData['shopId'],
  580. 'outerTradeNo'=>$tmpOuterTradeNo,
  581. 'totalMoney'=>$vipCard['price'],
  582. 'payAmount'=>$vipCard['price'],
  583. 'vipCardId'=>$vipCard['id'],
  584. 'customerName'=>$customerData['name'],
  585. 'customerId'=>$customerData['id'],
  586. 'payStatus'=> $vipCard['price'] == 0 ? StatusCode::$standard : StatusCode::$delete,//价格为0则免费
  587. 'payTime'=> $vipCard['price'] == 0 ? time() : '',//价格为0则免费
  588. 'successFullyTime'=> $vipCard['price'] == 0 ? time() : '',//价格为0则免费
  589. 'payType'=> $params['payType'],//支付方式
  590. 'source'=> $params['source'],//来源
  591. 'remark'=> $params['remark'],//来源
  592. 'expireTime'=>time() + $month * 30 * 24 * 60 * 60,
  593. 'deleteStatus'=>StatusCode::$standard,
  594. 'createTime'=>time(),
  595. 'updateTime'=>time(),
  596. 'salesManId'=>$customerData['salesManId'],
  597. 'salesManName'=>$customerData['salesManName'],
  598. 'customerType'=>$customerData['type'],
  599. 'userCenterId'=>$this->userCenterId
  600. ];
  601. $this->objDVipCardOrder->beginTransaction();
  602. $orderId = $this->objDVipCardOrder->insert($orderData);
  603. if ($orderId === false) {
  604. $this->objDVipCardOrder->rollBack();
  605. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  606. }
  607. //增加一个销量
  608. $result = $this->objDVipCard->set_inc('num',$orderData['vipCardId']);
  609. if ($result === false) {
  610. $this->objDVipCardOrder->rollBack();
  611. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  612. }
  613. if($vipCard['price'] == 0) {
  614. //领取免费的,旧的会员卡失效
  615. $sql = 'UPDATE '. $this->objDVipCardOrder->get_Table() .' SET enableStatus='.StatusCode::$delete.' WHERE id !='.$orderId.' AND customerId='.$orderData['customerId'].' AND enableStatus='.StatusCode::$standard;
  616. $result = $this->objDVipCardOrder->query($sql);
  617. if ($result === false) {
  618. $this->objDVipCardOrder->rollBack();
  619. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  620. }
  621. //免费的已支付,则发放优惠券
  622. if ($vipCard['hasNewCardCoupon'] == StatusCode::$standard) {
  623. if (!empty($vipCard['newCardCouponIds'])) {
  624. $dbResult = $this->objMCoupon->giveCoupon(explode(',', $vipCard['newCardCouponIds']), $vipCard['id']);
  625. if (!$dbResult->isSuccess()){
  626. $this->objDVipCardOrder->rollBack();
  627. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  628. }
  629. }
  630. }
  631. }
  632. $this->objDVipCardOrder->commit();
  633. if ($vipCard['price'] ==0 || $params['source'] == StatusCode::$source['manage'] || $params['payType'] == StatusCode::$payType['cashPay']) {
  634. return ResultWrapper::success(['orderId'=>$orderId]);
  635. }
  636. //获取支付配置
  637. $result = $this->objMPaymentSetting->getPayData($params['payType']);
  638. if (!$result->isSuccess() || empty($result->getData())) {
  639. return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
  640. }
  641. $payment = $result->getData();
  642. $payParams = '';
  643. if ($params['payType'] == StatusCode::$payType['aliPay']) {
  644. /*********读取支付宝支付参数(原配置)*********/
  645. /**$aliPayConfigData = Factory::config()->get('alipay');
  646. * if (empty($aliPayConfigData)) {
  647. * return ResultWrapper::fail('支付宝配置错误', ErrorCode::$configEroor);
  648. * }*/
  649. $payOrderData = [
  650. 'subject' => '千鸟云商',
  651. 'out_trade_no' => $tmpOuterTradeNo,
  652. 'total_amount' => $vipCard['price'],
  653. 'passback_params' => $this->enterpriseId . '|' . $this->userCenterId . '|' . $orderId
  654. ];
  655. $aliPayConfigData = [
  656. 'appid' => $payment['appid'],
  657. 'rsaPrivateKey' => $payment['rsaPrivateKey'],
  658. 'alipayrsaPublicKey' => $payment['alipayrsaPublicKey'],
  659. ];
  660. $objAliPay = new aliPay($aliPayConfigData['appid'], $aliPayConfigData['rsaPrivateKey'], $aliPayConfigData['alipayrsaPublicKey']);
  661. $payParams = $objAliPay->appPay($payOrderData);
  662. } else if ($params['payType'] == StatusCode::$payType['wxPay']) {
  663. /********************生成小程序唤起支付用到的参数(原配置)*****/
  664. /**$weixinConfigData = Factory::config()->get('weixin');
  665. * if (empty($weixinConfigData)) {
  666. * return ResultWrapper::fail('微信配置错误', ErrorCode::$configEroor);
  667. * }*/
  668. // 获取当前登录企业的小程序配置
  669. $objSystemCache = new SystemCache();
  670. $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->enterpriseId);
  671. if (empty($miniprogramSetting)) {
  672. return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
  673. }
  674. $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
  675. switch ($params['source']) {
  676. case StatusCode::$source['ByteProgram'];
  677. //$appid = $weixinConfigData['offiaccount']['appid'];
  678. $appid = $miniprogramSetting['appid'];
  679. $paySource = 'byteDanceH5';
  680. break;
  681. case StatusCode::$source['miniProgram'];
  682. $appid = $miniprogramSetting['appid'];
  683. $paySource = 'miniProgram';
  684. break;
  685. default :
  686. $appid = $payment['mobileAppid'];
  687. $paySource = 'APP';
  688. break;
  689. }
  690. $weixinConfigData = [
  691. 'mch_id' => $payment['mchId'],
  692. 'apiPartnerKey' => $payment['apiPartnerKey'],
  693. 'appid' => $appid
  694. ];
  695. Logger::logs(E_USER_ERROR,'weixinConfigData',__CLASS__,__LINE__,$weixinConfigData);
  696. $attach = $this->enterpriseId . '|' . $this->userCenterId . '|' . $orderId;
  697. //$objPay = new Pay($appid, $weixinConfigData['pay']['mch_id'], $weixinConfigData['pay']['apiPartnerKey']);//old
  698. $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
  699. $payParams = $objPay->unifiedorder($tmpOuterTradeNo, $vipCard['price'], $ip, $paySource, '千鸟云商', $customerData['openId'], $attach);
  700. }
  701. if (!$payParams->isSuccess()) {
  702. return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
  703. }
  704. if($params['source'] == StatusCode::$source['ByteProgram']){
  705. $mweb_url = $payParams->getData();
  706. // 获取配置文件字节小程序
  707. $byteDanceConfigData = Factory::config()->getAppoint('byteDance', 'pay');
  708. if (empty($byteDanceConfigData)) {
  709. return ResultWrapper::fail('字节跳动配置错误', ErrorCode::$configEroor);
  710. }
  711. $objbytePay = new bytePay($byteDanceConfigData['appid'], $byteDanceConfigData['merchant_id'], $byteDanceConfigData['app_secret']);
  712. unset($payParams);
  713. $payParams = $objbytePay->pay($tmpOuterTradeNo, $vipCard['price'], '千鸟云商', $ip, $mweb_url);
  714. if (!$payParams->isSuccess()) {
  715. return ResultWrapper::fail($payParams->getData(), $payParams->getErrorCode());
  716. }
  717. }
  718. Logger::logs(E_USER_ERROR,'ret params',__CLASS__,__LINE__,$payParams->getData());
  719. return ResultWrapper::success($payParams->getData());
  720. }
  721. /**
  722. * 修改订单支付状态,支付成功后赠送对应优惠券
  723. * @param $vipOrderData
  724. * @param $condition
  725. * @param bool $isNotify
  726. * @return ResultWrapper
  727. * @throws \Exception
  728. */
  729. public function updateVipOrderPayData($vipOrderData, $condition, $isNotify = false) {
  730. $orderData = $this->objDVipCardOrder->get($condition);
  731. if ($orderData === false) {
  732. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  733. }
  734. if (empty($orderData)) {
  735. return ResultWrapper::fail('不存在此会员卡购买订单', ErrorCode::$contentNotExists);
  736. }
  737. $vipCardInfo = $this->objDVipCard->get($orderData['vipCardId']);
  738. if ($vipCardInfo === false) {
  739. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  740. }
  741. $this->objDVipCardOrder->beginTransaction();
  742. //把会员原先会员片禁用掉
  743. $sql = 'UPDATE '. $this->objDVipCardOrder->get_Table() .' SET enableStatus='.StatusCode::$delete.' WHERE id !='.$orderData['id'].' AND customerId='.$orderData['customerId'].' AND enableStatus='.StatusCode::$standard;
  744. $result = $this->objDVipCardOrder->query($sql);
  745. if ($result === false) {
  746. $this->objDVipCardOrder->rollBack();
  747. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  748. }
  749. $vipOrderData['successFullyTime'] = time();
  750. $dbResult = $this->objDVipCardOrder->update($vipOrderData,$condition);
  751. if ($dbResult === false) {
  752. $this->objDVipCardOrder->rollBack();
  753. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  754. }
  755. if ($vipCardInfo['hasNewCardCoupon'] == StatusCode::$standard) {
  756. if (!empty($vipCardInfo['newCardCouponIds'])) {
  757. $dbResult = $this->objMCoupon->giveCoupon(explode(',', $vipCardInfo['newCardCouponIds']), $vipCardInfo['id']);
  758. if (!$dbResult->isSuccess()){
  759. $this->objDVipCardOrder->rollBack();
  760. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  761. }
  762. }
  763. }
  764. $this->objDVipCardOrder->commit();
  765. return ResultWrapper::success($dbResult);
  766. }
  767. /**
  768. * 指定客户会员卡一键失效
  769. * @param array $params
  770. * @return ResultWrapper
  771. */
  772. public function invalidVipCard($params)
  773. {
  774. $orderData = $this->objDVipCardOrder->get($params);
  775. if ($orderData === false) {
  776. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  777. }
  778. if (empty($orderData)) {
  779. return ResultWrapper::fail('没有找到该客户的vip卡', ErrorCode::$contentNotExists);
  780. }
  781. $dbResult = $this->objDVipCardOrder->update( ['enableStatus'=> StatusCode::$delete],$orderData['id']);
  782. if($dbResult === false){
  783. return ResultWrapper::fail($this->objDVipCard->error(), ErrorCode::$dberror);
  784. }
  785. return ResultWrapper::success($dbResult);
  786. }
  787. /**
  788. * 获取指定用户的所有会员卡数据
  789. */
  790. public function getAllVipCardByCustomerId($customerId)
  791. {
  792. if(empty($customerId)){
  793. return ResultWrapper::fail('请指定要查询得用户id', ErrorCode::$paramError);
  794. }
  795. $fields = 'SELECT c.* ';
  796. $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;
  797. $sql = $fields.$base;
  798. $dbResult = $this->objDVipCardOrder->query($sql);
  799. if($dbResult === false){
  800. return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  801. }
  802. return ResultWrapper::success($dbResult);
  803. }
  804. }