MCoupon.Class.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. <?php
  2. /**
  3. * 优惠券
  4. * Created by PhpStorm.
  5. * User: XiaoMing
  6. * Date: 2019/12/13
  7. * Time: 16:12
  8. */
  9. namespace JinDouYun\Model\Market;
  10. use JinDouYun\Controller\Common\Logger;
  11. use JinDouYun\Dao\Customer\DCustomer;
  12. use JinDouYun\Dao\Market\DUserCoupon;
  13. use JinDouYun\Dao\Market\DVipCard;
  14. use JinDouYun\Dao\Market\DVipCardOrder;
  15. use JinDouYun\Model\Goods\MGoods;
  16. use JinDouYun\Model\GoodsManage\MGoodsBrand;
  17. use Mall\Framework\Core\ErrorCode;
  18. use Mall\Framework\Core\ResultWrapper;
  19. use JinDouYun\Model\Customer\MCustomer;
  20. use JinDouYun\Cache\GoodsBasicRelevant;
  21. use JinDouYun\Model\System\MCustomerSource;
  22. use JinDouYun\Dao\Market\DCoupon;
  23. use JinDouYun\Model\MBaseModel;
  24. use Mall\Framework\Core\StatusCode;
  25. class MCoupon extends MBaseModel
  26. {
  27. private $onlineUserId;
  28. private $onlineEnterpriseId;
  29. private $objDCoupon;
  30. private $objDUserCoupon;
  31. private $objDVipCardOrder;
  32. private static $useStatus = [
  33. 'waitUsed' => 5,//等待使用
  34. 'alreadyUsed' => 4,//已使用
  35. 'expire' => 3,//已过期
  36. ];
  37. private $isGrant = false;
  38. /**
  39. * MCoupon constructor.
  40. * @param $onlineUserId
  41. * @param $onlineEnterpriseId
  42. * @throws \Exception
  43. */
  44. public function __construct($onlineUserId, $onlineEnterpriseId)
  45. {
  46. $this->onlineUserId = $onlineUserId;
  47. $this->onlineEnterpriseId = $onlineEnterpriseId;
  48. parent::__construct($this->onlineEnterpriseId, $onlineUserId);
  49. $this->objDCoupon = new DCoupon('default');
  50. $this->objDCoupon->setTable($this->objDCoupon->get_Table() . '_' . $this->onlineEnterpriseId);
  51. $this->objDUserCoupon = new DUserCoupon();
  52. $this->objDUserCoupon->setTable($this->objDUserCoupon->get_Table() . '_' . $this->onlineEnterpriseId);
  53. $this->objDVipCardOrder = new DVipCardOrder();
  54. $this->objDVipCardOrder->setTable($this->objDVipCardOrder->get_Table() . '_' . $this->onlineEnterpriseId);
  55. //$this->objDCoupon->setSearchIndex('coupon_search')->setType('coupon');
  56. }
  57. /**
  58. * @param $params
  59. * @return ResultWrapper
  60. */
  61. public function add($params)
  62. {
  63. $dbResult = $this->objDCoupon->insert($params);
  64. if ($dbResult === false) {
  65. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  66. }
  67. //self::updateEsData($dbResult, $params);
  68. return ResultWrapper::success($dbResult);
  69. }
  70. /**
  71. * 更新ES
  72. * @param $id
  73. * @param $params
  74. */
  75. public function updateEsData($id, $params)
  76. {
  77. $esData = [
  78. 'enterpriseId' => $this->onlineEnterpriseId,//enterpriseId,
  79. 'id' => $id,//自增id,
  80. 'startTime' => $params['startTime'],//优惠券生效开始时间
  81. 'endTime' => $params['endTime'],//结束时间
  82. 'name' => $params['name'],//优惠券名称
  83. 'couponType' => $params['couponType'],//优惠券类型
  84. 'reducePrice' => $params['reducePrice'],//满减券-减免金额(面值)
  85. 'minPrice' => $params['minPrice'],//最低消费金额 0.00不限金额
  86. 'remark' => $params['remark'],//使用说明
  87. 'grantType' => $params['grantType'],//发放方式(10主动领取 20定向发放 30注册领取 40在线支付赠送)
  88. 'totalNum' => $params['totalNum'],//发放总数量(-1为不限制)
  89. 'allowNum' => $params['allowNum'],//每人限制领取数量(-1为不限制)
  90. 'customerSourceId' => isset($params['customerSourceId']) ? $params['customerSourceId'] : '',//领取范围
  91. 'mustCondition' => isset($params['mustCondition']) ? $params['mustCondition'] : '0.00',//(40在线支付赠送)-满X金额发放 0.00所有在线支付不限金额可领取这个优惠券
  92. 'grantStartTime' => $params['grantStartTime'],//发放开始时间
  93. 'grantEndTime' => $params['grantEndTime'],//发放结束时间
  94. 'useShop' => $params['useShop'],//使用范围
  95. 'applyRange' => $params['applyRange'],//商品适用范围
  96. 'categoryCollect' => isset($params['categoryCollect']) ? $params['categoryCollect'] : '',//分类集合
  97. 'brandCollect' => isset($params['brandCollect']) ? $params['brandCollect'] : '',//品牌集合
  98. 'goodsCollect' => isset($params['goodsCollect']) ? $params['goodsCollect'] : '',
  99. 'receiveNum' => isset($params['receiveNum']) ? $params['receiveNum'] : 0,//品牌集合
  100. 'deleteStatus' => StatusCode::$standard,//删除状态
  101. 'auditStatus' => StatusCode::$auditStatus['auditing'],
  102. 'createTime' => $params['createTime'],
  103. 'updateTime' => $params['updateTime'],
  104. ];
  105. $_id = self::createEsDocumentId($id);
  106. $result = $this->objDCoupon->addUpSearchIndexDocument($esData, $_id);
  107. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  108. //echo "es操作成功";
  109. //return;
  110. } else {
  111. //echo "es操作失败";
  112. }
  113. }
  114. private function createEsDocumentId($id)
  115. {
  116. return 'EnterpriseId_' . $this->onlineEnterpriseId . '_id_' . $id;
  117. }
  118. /**
  119. * 详情
  120. * @param $id
  121. * @return ResultWrapper
  122. * @throws \Exception
  123. */
  124. public function getInfo($id)
  125. {
  126. $dbResult = $this->objDCoupon->get_by('id', $id);
  127. if ($dbResult === false) {
  128. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  129. }
  130. $formatResult = self::format($dbResult);
  131. if (!$formatResult->isSuccess()){
  132. return ResultWrapper::fail($formatResult->getData(),$formatResult->getErrorCode());
  133. }
  134. $format = $formatResult->getData();
  135. return ResultWrapper::success($format);
  136. }
  137. /**
  138. * 列表
  139. * @param $selectParams
  140. * @param $field
  141. * @return ResultWrapper
  142. */
  143. public function getAll($selectParams, $field = '*')
  144. {
  145. $limit = $selectParams['limit'];
  146. unset($selectParams['limit']);
  147. $offset = $selectParams['offset'];
  148. unset($selectParams['offset']);
  149. $selectParams['deleteStatus'] = StatusCode::$standard;
  150. $dbResult = $this->objDCoupon->select($selectParams, $field, 'createTime DESC', $limit, $offset);
  151. if ($dbResult === false) {
  152. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  153. }
  154. $total = $this->objDCoupon->count($selectParams);
  155. $return = [
  156. 'data' => self::formatAll($dbResult),
  157. 'total' => ($total) ? intval($total) : 0,
  158. ];
  159. $this->isGrant = true;
  160. return ResultWrapper::success($return);
  161. }
  162. /**
  163. * 更新审核状态
  164. * @param $params
  165. * @return ResultWrapper
  166. */
  167. public function updateAuditStatus($params)
  168. {
  169. $dbResult = $this->objDCoupon->update(['auditStatus' => $params['auditStatus']], $params['id']);
  170. if ($dbResult === false) {
  171. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  172. }
  173. /*$_id = self::createEsDocumentId($params['id']);
  174. $this->objDCoupon->esupdateTypeFieldVaule([
  175. 'auditStatus' => $params['auditStatus']
  176. ], $_id);*/
  177. return ResultWrapper::success($dbResult);
  178. }
  179. /**
  180. * 删除
  181. * @param $id
  182. * @return ResultWrapper
  183. */
  184. public function del($id)
  185. {
  186. $dbResult = $this->objDCoupon->update(['deleteStatus' => StatusCode::$delete], $id);
  187. if ($dbResult === false) {
  188. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  189. }
  190. /*$_id = self::createEsDocumentId($id);
  191. $this->objDCoupon->esupdateTypeFieldVaule([
  192. 'deleteStatus' => StatusCode::$delete
  193. ], $_id);*/
  194. return ResultWrapper::success($dbResult);
  195. }
  196. /**
  197. * 编辑
  198. * @param $params
  199. * @param $id
  200. * @return ResultWrapper
  201. */
  202. public function edit($params, $id)
  203. {
  204. $dbResult = $this->objDCoupon->update($params, $id);
  205. if ($dbResult === false) {
  206. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  207. }
  208. /*$_id = self::createEsDocumentId($id);
  209. $this->objDCoupon->esupdateTypeFieldVaule($params, $_id);*/
  210. return ResultWrapper::success($dbResult);
  211. }
  212. /**
  213. * 格式化列表页数据
  214. */
  215. private function formatAll($data)
  216. {
  217. if (empty($data)) return $data;
  218. foreach ($data as &$val) {
  219. if ($val['totalNum'] < 0) {
  220. $val['totalNum'] = '不限量';
  221. $val['usableNum'] = '不限量';
  222. } else {
  223. $val['usableNum'] = bcsub($val['totalNum'], $val['receiveNum'], 0);
  224. }
  225. $val['useShopName'] = ($val['useShop'] == 0) ? ['全店铺'] : array_values(self::getNameByShopId(explode(',', $val['useShop'])));
  226. $val['vipCardId'] = 0;//非会员卡优惠券
  227. }
  228. return $data;
  229. }
  230. /**
  231. * @param $data
  232. * @return ResultWrapper
  233. * @throws \Exception
  234. */
  235. private function format($data)
  236. {
  237. if (empty($data)) return ResultWrapper::success([]);
  238. $data['useShopName'] = ($data['useShop'] == 0) ? ['全店铺'] : array_values(self::getNameByShopId(explode(',', $data['useShop'])));
  239. if ($data['grantType'] == StatusCode::$grantType['receive']) {
  240. $objMCustomerSource = new MCustomerSource($this->onlineEnterpriseId);
  241. $dbResult = $objMCustomerSource->getCustomer(explode(',', $data['customerSourceId']));
  242. $customer = $dbResult->getData();
  243. $data['customerTypeName'] = !empty($customer) ? array_column($customer, 'name') : (object)[];
  244. }
  245. if ($data['customerIds'] == 0){
  246. $data['customerNames'] = ['全部'];
  247. }else{
  248. $objDCustomer = new DCustomer();
  249. $objDCustomer->setTable('qianniao_customer_'.$this->onlineEnterpriseId);
  250. $fields = 'id,name';
  251. $sql = 'SELECT '.$fields.' FROM qianniao_customer_'.$this->onlineEnterpriseId.' WHERE id in('.$data['customerIds'].')';
  252. $result = $objDCustomer->query($sql);
  253. if ($result === false){
  254. $result = [];
  255. }
  256. $map = [];
  257. foreach ($result as $item){
  258. $map[] = $item['name'];
  259. }
  260. $data['customerNames'] = $map;
  261. }
  262. switch ($data['applyRange']) {
  263. case StatusCode::$applyRange['appointCategory']:
  264. $data['categoryCollectName'] = array_values(parent::getCategoryNameByIds($this->onlineEnterpriseId, explode(',', $data['categoryCollect'])));
  265. break;
  266. case StatusCode::$applyRange['appointBrand']:
  267. $objMGoodsBrand = new MGoodsBrand($this->onlineUserId,$this->onlineEnterpriseId);
  268. $brandResult = $objMGoodsBrand->getBrandNameByIds(explode(',', $data['brandCollect']));
  269. if (!$brandResult->isSuccess()){
  270. return ResultWrapper::fail($brandResult->getData(),$brandResult->getErrorCode());
  271. }
  272. $brandMap = $brandResult->getData();
  273. $data['brandCollectName'] = array_values($brandMap);
  274. break;
  275. case StatusCode::$applyRange['goodsCollect']:
  276. $goodsListFormatResult = self::getGoodsByIds(explode(',', $data['goodsCollect']));
  277. if (!$goodsListFormatResult->isSuccess()){
  278. return ResultWrapper::fail($goodsListFormatResult->getData(),$goodsListFormatResult->getErrorCode());
  279. }
  280. $data['goodsCollectList'] = $goodsListFormatResult->getData();
  281. break;
  282. }
  283. return ResultWrapper::success($data);
  284. }
  285. /**
  286. * Doc: (des="格式化优惠券指定商品")
  287. * User: XMing
  288. * Date: 2020/9/21
  289. * Time: 3:11 下午
  290. * @param array $ids
  291. * @throws \Exception
  292. * @return ResultWrapper
  293. */
  294. private function getGoodsByIds($ids)
  295. {
  296. $objMGoods = new MGoods($this->onlineEnterpriseId,true,$this->onlineUserId);
  297. $goodsListResult = $objMGoods->getAllGoods(['offset' => 0,'limit' => count($ids),'id' => $ids]);
  298. if (!$goodsListResult->isSuccess()){
  299. return ResultWrapper::fail($goodsListResult->getData(),$goodsListResult->getErrorCode());
  300. }
  301. $goodsList = $goodsListResult->getData()['data'];
  302. $map = [];
  303. foreach ($goodsList as $value){
  304. $map[] = [
  305. 'id' => $value['id'],
  306. 'basicGoodsId' => $value['basicGoodsId'],
  307. 'shopId' => $value['shopId'],
  308. 'shopName' => $value['shopName'],
  309. 'title' => $value['title'],
  310. 'images' => $value['images'],
  311. 'code' => $value['code'],
  312. 'inventorTotal' => $value['inventorTotal']
  313. ];
  314. }
  315. return ResultWrapper::success($map);
  316. }
  317. /**
  318. *
  319. * @param $shopIds
  320. * @return array
  321. */
  322. public function getNameByShopId($shopIds)
  323. {
  324. $objGoodsBasicRelevantCache = new GoodsBasicRelevant($this->onlineEnterpriseId);
  325. $result = [];
  326. foreach ($shopIds as $shopId) {
  327. if (!empty($shopId)) $result[] = $objGoodsBasicRelevantCache->getNameByShopId($shopId);
  328. }
  329. return $result;
  330. }
  331. /**
  332. * 搜索
  333. * @param $selectParams
  334. * @return ResultWrapper
  335. */
  336. public function search($selectParams)
  337. {
  338. /*$defaultDSL = [
  339. 'from' => $selectParams['offset'],
  340. 'size' => $selectParams['limit'],
  341. 'sort' => [
  342. 'createTime' => [
  343. 'order' => 'desc'
  344. ],
  345. ],
  346. ];
  347. $dsl = [];
  348. $dsl['query']['bool']['must'][] = [
  349. 'term' => ['enterpriseId' => $this->onlineEnterpriseId],
  350. ];
  351. //名称
  352. if (!empty($selectParams['name'])) {
  353. $dsl['query']['bool']['must'][] = [
  354. 'multi_match' => [
  355. 'fields' => ['name'],
  356. 'query' => $selectParams['name'],
  357. 'fuzziness' => 'AUTO',
  358. ],
  359. ];
  360. }
  361. //使用范围
  362. if (!empty($selectParams['useShop'])) {
  363. $dsl['query']['bool']['must'][] = [
  364. 'multi_match' => [
  365. 'fields' => ['useShop'],
  366. 'query' => $selectParams['useShop'],
  367. 'fuzziness' => 'AUTO',
  368. ],
  369. ];
  370. }
  371. //发放方式
  372. if (!empty($selectParams['grantType'])) {
  373. $dsl['query']['bool']['filter'][] =
  374. ['term' => ['grantType' => $selectParams['grantType']]];
  375. }
  376. //发放方式
  377. if (!empty($selectParams['auditStatus'])) {
  378. $dsl['query']['bool']['filter'][] =
  379. ['term' => ['auditStatus' => $selectParams['auditStatus']]];
  380. }
  381. //商品适用范围
  382. if (!empty($selectParams['applyRange'])) {
  383. $dsl['query']['bool']['filter'][] =
  384. ['term' => ['applyRange' => $selectParams['applyRange']]];
  385. }
  386. //时间
  387. if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
  388. $dsl['query']['bool']['must'][] = [
  389. 'range' => [
  390. 'createTime' => [
  391. 'gte' => $selectParams['start'],
  392. 'lte' => $selectParams['end'],
  393. ]
  394. ]
  395. ];
  396. } else {
  397. if (!empty($selectParams['start'])) {
  398. $dsl['query']['bool']['must'][] = [
  399. 'range' => [
  400. 'createTime' => [
  401. 'gte' => $selectParams['start'],
  402. ]
  403. ]
  404. ];
  405. }
  406. if (!empty($selectParams['end'])) {
  407. $dsl['query']['bool']['must'][] = [
  408. 'range' => [
  409. 'createTime' => [
  410. 'lte' => $selectParams['end'],
  411. ]
  412. ]
  413. ];
  414. }
  415. }
  416. $dsl = array_merge($defaultDSL, $dsl);
  417. $result = $this->objDCoupon->getSearchQueryDsl($dsl);
  418. if (isset($result['status']) && $result['status'] == 400) {
  419. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  420. }
  421. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  422. return ResultWrapper::success([
  423. 'data' => [],
  424. 'total' => 0
  425. ]);
  426. }
  427. $total = $result['hits']['total'];
  428. $dbResult = $result['hits']['hits'];
  429. $list = [];
  430. foreach ($dbResult as $key => &$value) {
  431. $data = [];
  432. $data = $value['_source'];
  433. $list[] = $data;
  434. }*/
  435. $fields = '*';
  436. $sql = 'SELECT '.$fields.' FROM qianniao_coupon_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard;
  437. if (isset($selectParams['grantType']) && !empty($selectParams['grantType'])){
  438. $sql .= ' AND grantType = '.$selectParams['grantType'];
  439. }
  440. if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])){
  441. $sql .= ' AND auditStatus = '.$selectParams['auditStatus'];
  442. }
  443. if (isset($selectParams['applyRange']) && !empty($selectParams['applyRange'])){
  444. $sql .= ' AND applyRange = '.$selectParams['applyRange'];
  445. }
  446. if (isset($selectParams['useShop']) && !empty($selectParams['useShop'])){
  447. $sql .= ' AND find_in_set('.$selectParams['useShop'].',useShop) ';
  448. }
  449. if (isset($selectParams['name']) && !empty($selectParams['name'])){
  450. $sql .= ' AND name like "%'.$selectParams['name'].'%"';
  451. }
  452. if (isset($selectParams['start']) && !empty($selectParams['start']) && isset($selectParams['end']) && !empty($selectParams['end'])){
  453. $sql .= ' AND createTime BETWEEN '.$selectParams['start'].' AND '.$selectParams['end'];
  454. }
  455. $sql .= ' ORDER BY createTime DESC ';
  456. $count = count((array) $this->objDCoupon->query($sql));
  457. //分页
  458. if (isset($selectParams['offset']) && isset($selectParams['limit']) && !empty($selectParams['limit'])){
  459. $sql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit'];
  460. }
  461. $dbResult = $this->objDCoupon->query($sql);
  462. if ($dbResult === false){
  463. return ResultWrapper::fail($this->objDCoupon->error(),ErrorCode::$dberror);
  464. }
  465. $return = [
  466. 'data' => self::formatAll($dbResult),
  467. 'total' => $count,
  468. ];
  469. return ResultWrapper::success($return);
  470. }
  471. /**
  472. * 优惠券列表
  473. * @param $params
  474. * @return ResultWrapper
  475. * @throws \Exception
  476. */
  477. public function couponList($params)
  478. {
  479. $fields = 'id,startTime,endTime,name,couponType,reducePrice,minPrice,remark,grantType,totalNum,allowNum,customerSourceId,useShop,mustCondition,grantStartTime,grantEndTime,applyRange,categoryCollect,brandCollect,receiveNum';
  480. $nowTime = time();
  481. $sql = 'SELECT ' . $fields . ' FROM qianniao_coupon_' . $this->onlineEnterpriseId . '
  482. WHERE deleteStatus=' . StatusCode::$standard . '
  483. AND enableStatus='.StatusCode::$standard.'
  484. AND auditStatus=' . StatusCode::$auditStatus['auditPass'] . '
  485. AND grantStartTime<' . $nowTime . ' AND grantEndTime> ' . $nowTime . ' AND totalNum>receiveNum';
  486. switch ($params['grantType']) {
  487. case StatusCode::$grantType['register']://注册领取
  488. $sql .= ' AND grantType=' . StatusCode::$grantType['register'];
  489. $dbResult = self::registerCoupon($sql);
  490. break;
  491. case StatusCode::$grantType['receive']://主动领取
  492. $sql .= ' AND grantType=' . StatusCode::$grantType['receive'];
  493. $dbResult = self::receiveCoupon($sql, $params);
  494. break;
  495. case StatusCode::$grantType['onlinePay']://在线支付领取
  496. $sql .= ' AND grantType=' . StatusCode::$grantType['onlinePay'];
  497. $dbResult = self::onlinePayCoupon($sql, $params);
  498. break;
  499. default:
  500. $dbResult = self::registerCoupon($sql);
  501. break;
  502. }
  503. if (!$dbResult->isSuccess()) {
  504. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  505. }
  506. //格式化数据
  507. $result = self::formatAll($dbResult->getData());
  508. return ResultWrapper::success($result);
  509. }
  510. /**
  511. * 获取会员卡发放的优惠券
  512. *
  513. * @return array|mixed
  514. */
  515. public function vipCoupon()
  516. {
  517. $objMVipCard = new MVipCard($this->onlineEnterpriseId, $this->onlineUserId, true);
  518. $dbResult = $objMVipCard->myVipCardMonthCoupon();
  519. if (!$dbResult->isSuccess()) {
  520. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  521. }
  522. $dbResult = $dbResult->getData();
  523. return ResultWrapper::success($dbResult);
  524. }
  525. //查询会员卡优惠券
  526. public function getVipCardCouponInfo($ids=[]) {
  527. $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'];
  528. $dbResult = $this->objDCoupon->query($sql);
  529. if ($dbResult === false) {
  530. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  531. }
  532. return ResultWrapper::success($dbResult);
  533. }
  534. /**
  535. * 注册领取
  536. * @param $sql
  537. * @return ResultWrapper
  538. */
  539. private function registerCoupon($sql)
  540. {
  541. $dbResult = $this->objDCoupon->query($sql);
  542. if ($dbResult === false) {
  543. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  544. }
  545. return ResultWrapper::success($dbResult);
  546. }
  547. /**
  548. * @param $sql
  549. * @param $params
  550. * @return ResultWrapper
  551. */
  552. private function onlinePayCoupon($sql, $params)
  553. {
  554. if (!isset($params['payAmount'])) {
  555. return ResultWrapper::fail('缺少payAmount参数', ErrorCode::$paramError);
  556. }
  557. $sql .= ' AND mustCondition<=' . $params['payAmount'];
  558. $dbResult = $this->objDCoupon->query($sql);
  559. if ($dbResult === false) {
  560. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  561. }
  562. return ResultWrapper::success($dbResult);
  563. }
  564. /**
  565. * 主动领取
  566. * @param $sql
  567. * @param $params
  568. * @return ResultWrapper
  569. * @throws \Exception
  570. */
  571. private function receiveCoupon($sql, $params)
  572. {
  573. //查询当前客户类型
  574. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  575. //首页未登录
  576. if (!empty($this->onlineUserId)) {
  577. $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  578. if (!$dbResult->isSuccess()) {
  579. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  580. }
  581. $customerType = $dbResult->getData()['type'];
  582. unset($dbResult);
  583. if (!empty($customerType)) {
  584. $sql .= ' AND (FIND_IN_SET(' . $customerType . ',customerSourceId) or customerSourceId = 0) ';
  585. }
  586. }
  587. $dbResult = $this->objDCoupon->query($sql);
  588. if ($dbResult === false) {
  589. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  590. }
  591. return ResultWrapper::success($dbResult);
  592. }
  593. /**
  594. * 领取优惠券
  595. * @param $params
  596. * @return ResultWrapper
  597. * @throws \Exception
  598. */
  599. public function receive($params)
  600. {
  601. $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
  602. $coupon = $this->objDCoupon->get(['id' => $params['couponId']]);
  603. if ($coupon === false) return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  604. if (empty($coupon)) return ResultWrapper::fail('未知的优惠券', ErrorCode::$dberror);
  605. //会员卡优惠券验证
  606. if ($params['vipCardId'] != 0) {
  607. $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;
  608. $userVipCard = $this->objDVipCardOrder->get($where);
  609. if ($userVipCard === false) return ResultWrapper::fail($this->objDVipCardOrder->error(), ErrorCode::$dberror);
  610. if (empty($userVipCard)) return ResultWrapper::fail('成为会员才能领取会员卡优惠券', ErrorCode::$paramError);
  611. $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;
  612. $dbResult = $this->objDUserCoupon->query($sql);
  613. if ($dbResult === false) return ResultWrapper::fail($this->objDUserCoupon->error(), ErrorCode::$dberror);
  614. if (!empty($dbResult)) return ResultWrapper::fail('本月已近领取了', ErrorCode::$paramError);
  615. }
  616. //不是会员卡优惠券需要限制
  617. if (empty($params['vipCardId'])) {
  618. if ($coupon['grantStartTime'] > time() || $coupon['grantEndTime'] < time()) {
  619. //不在优惠券发放时间范围
  620. return ResultWrapper::fail('优惠券不在发放时间', ErrorCode::$dberror);
  621. }
  622. if ($coupon['receiveNum'] >= $coupon['totalNum']) {
  623. return ResultWrapper::fail('优惠券抢光了', ErrorCode::$dberror);
  624. }
  625. $allowNum = $coupon['allowNum'];//每人限制领取
  626. //验证是否可以领取此优惠券
  627. $userCoupon = $objMUserCoupon->getUserCoupon(['couponId' => $coupon['id'], 'userId' => $this->onlineUserId]);
  628. if (!$userCoupon->isSuccess()) return ResultWrapper::fail($userCoupon->getData(), ErrorCode::$dberror);
  629. $haveNum = count($userCoupon->getData());
  630. if ($haveNum >= $allowNum) {
  631. return ResultWrapper::fail('领取达到了上限', ErrorCode::$dberror);
  632. }
  633. }
  634. //查询当前客户类型
  635. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  636. $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  637. if (!$dbResult->isSuccess()) {
  638. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  639. }
  640. $customer = $dbResult->getData();
  641. unset($dbResult);
  642. //优惠券记录信息
  643. $insert = [
  644. 'couponId' => $coupon['id'],
  645. 'name' => $coupon['name'],
  646. 'remark' => $coupon['remark'],
  647. 'couponType' => $coupon['couponType'],
  648. 'reducePrice' => $coupon['reducePrice'],
  649. 'minPrice' => $coupon['minPrice'],
  650. 'startTime' => $coupon['startTime'],
  651. 'endTime' => $coupon['endTime'],
  652. 'applyRange' => $coupon['applyRange'],
  653. 'categoryCollect' => $coupon['categoryCollect'],
  654. 'brandCollect' => $coupon['brandCollect'],
  655. 'goodsCollect' => $coupon['goodsCollect'],
  656. 'isExpire' => StatusCode::$standard,
  657. 'isUse' => StatusCode::$standard,
  658. 'userId' => $this->onlineUserId,
  659. 'customerId' => $customer['id'],
  660. 'useShop' => $coupon['useShop'],
  661. 'source' => $coupon['grantType'],
  662. 'createTime' => time(),
  663. 'updateTime' => time(),
  664. 'vipCardId' => $params['vipCardId'],
  665. 'isMutex' => isset($coupon['isMutex']) ? $coupon['isMutex'] : StatusCode::$standard,
  666. ];
  667. //当优惠券是会员卡优惠券时,过期时间=当前时间+30天
  668. if ($params['vipCardId'] != 0) {
  669. $insert['startTime'] = time();
  670. $insert['endTime'] = time() + 30 * 24 * 3600;//到期时间
  671. }
  672. $this->objDCoupon->beginTransaction();
  673. //写记录
  674. $dbResult = $objMUserCoupon->add($insert);
  675. if (!$dbResult->isSuccess()) {
  676. $this->objDCoupon->rollBack();
  677. ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  678. }
  679. unset($dbResult);
  680. //增加领取量
  681. $sql = 'UPDATE qianniao_coupon_' . $this->onlineEnterpriseId . ' SET receiveNum=receiveNum+1 WHERE id=' . $coupon['id'];
  682. $dbResult = $this->objDCoupon->query($sql);
  683. if ($dbResult === false) {
  684. $this->objDCoupon->rollBack();
  685. ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  686. }
  687. $this->objDCoupon->commit();
  688. return ResultWrapper::success($dbResult);
  689. }
  690. /**
  691. * 一键领取优惠券(会员卡)
  692. * @param $params
  693. * @return ResultWrapper
  694. * @throws \Exception
  695. */
  696. public function oneKeyReceive($params)
  697. {
  698. $params['couponId'] = rtrim($params['couponId'], ',');
  699. $coupons = $this->objDCoupon->select(['id' => explode(',', $params['couponId'])]);
  700. if ($coupons === false) return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  701. if (empty($coupons)) return ResultWrapper::fail('未知的优惠券', ErrorCode::$dberror);
  702. //查询用户对应优惠券的已领取张数
  703. /**$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';
  704. * $countCoupon = $this->objDUserCoupon->query($sql);
  705. * if ($countCoupon === false) return ResultWrapper::fail($this->objDUserCoupon->error(), ErrorCode::$dberror);
  706. * $groupNum = [];//优惠券对应领取数量
  707. * if (!empty($countCoupon)) {
  708. * foreach ($countCoupon as $count) {
  709. * $groupNum[$count['couponId']] = $count['num'];
  710. * }
  711. * }**/
  712. $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;
  713. $userCoupon = $this->objDUserCoupon->query($sql);
  714. if ($userCoupon === false) return ResultWrapper::fail($this->objDUserCoupon->error(), ErrorCode::$dberror);
  715. $allCoupon = array_values(array_column($userCoupon, 'couponId'));
  716. //查询当前客户类型
  717. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  718. $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  719. if (!$dbResult->isSuccess()) {
  720. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  721. }
  722. $customer = $dbResult->getData();
  723. unset($dbResult);
  724. $insert = [];
  725. $couponIds = [];
  726. foreach ($coupons as $key => $coupon) {
  727. /**if ($coupon['grantStartTime'] > time() || $coupon['grantEndTime'] < time()) {
  728. * //不在优惠券发放时间范围
  729. * unset($coupons[$key]);
  730. * continue;
  731. * }
  732. * if ($coupon['receiveNum'] >= $coupon['totalNum']) {
  733. * //发放完了
  734. * unset($coupons[$key]);
  735. * continue;
  736. * }
  737. * $haveNum = isset($groupNum[$coupon['id']]) ? $groupNum[$coupon['id']] : 0;
  738. * if ($haveNum >= $coupon['allowNum']) {
  739. * //领取达到了上限
  740. * unset($coupons[$key]);
  741. * continue;
  742. * }*/
  743. if (!empty($allCoupon)) {
  744. if (in_array($coupon['id'], $allCoupon)) {
  745. unset($coupons[$key]);
  746. continue;
  747. }
  748. }
  749. $insert[] = [
  750. 'couponId' => $coupon['id'],
  751. 'name' => $coupon['name'],
  752. 'remark' => $coupon['remark'],
  753. 'couponType' => $coupon['couponType'],
  754. 'reducePrice' => $coupon['reducePrice'],
  755. 'minPrice' => $coupon['minPrice'],
  756. 'startTime' => empty($params['vipCardId']) ? $coupon['startTime'] : time(),
  757. 'endTime' => empty($params['vipCardId']) ? $coupon['endTime'] : time() + 30 * 24 * 3600,//到期时间
  758. 'applyRange' => $coupon['applyRange'],
  759. 'categoryCollect' => $coupon['categoryCollect'],
  760. 'brandCollect' => $coupon['brandCollect'],
  761. 'goodsCollect' => $coupon['goodsCollect'],
  762. 'isExpire' => StatusCode::$standard,
  763. 'isUse' => StatusCode::$standard,
  764. 'userId' => $this->onlineUserId,
  765. 'customerId' => $customer['id'],
  766. 'useShop' => $coupon['useShop'],
  767. 'source' => $coupon['grantType'],
  768. 'createTime' => time(),
  769. 'updateTime' => time(),
  770. 'vipCardId' => $params['vipCardId'],
  771. 'isMutex' => isset($coupon['isMutex']) ? $coupon['isMutex'] : StatusCode::$standard,
  772. ];
  773. $couponIds[] = $coupon['id'];
  774. }
  775. if (empty($insert)) return ResultWrapper::fail('已经领取过了', ErrorCode::$dberror);
  776. $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
  777. $this->objDCoupon->beginTransaction();
  778. //写记录
  779. $dbResult = $objMUserCoupon->add($insert, true);
  780. if (!$dbResult->isSuccess()) {
  781. $this->objDCoupon->rollBack();
  782. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  783. }
  784. unset($dbResult);
  785. $dbResult = $this->objDCoupon->set_inc('receiveNum', ['id' => $couponIds]);
  786. if ($dbResult === false) {
  787. $this->objDCoupon->rollBack();
  788. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  789. }
  790. $this->objDCoupon->commit();
  791. return ResultWrapper::success('领取成功');
  792. }
  793. /**
  794. * 优惠券盒子
  795. * @param $selectParams
  796. * @return ResultWrapper
  797. * @throws \Exception
  798. */
  799. public function selectAll($selectParams)
  800. {
  801. $limit = $selectParams['limit'];
  802. unset($selectParams['limit']);
  803. $offset = $selectParams['offset'];
  804. unset($selectParams['offset']);
  805. $nowTime = time();
  806. $sql = 'SELECT * FROM qianniao_user_coupon_' . $this->onlineEnterpriseId . ' WHERE userId=' . $this->onlineUserId . ' AND';
  807. $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
  808. switch ($selectParams['type']) {
  809. case self::$useStatus['waitUsed']://等待使用
  810. $sql .= ' isUse=' . self::$useStatus['waitUsed'] . ' AND endTime>' . $nowTime;
  811. break;
  812. case self::$useStatus['alreadyUsed']://已使用
  813. $sql .= ' isUse=' . self::$useStatus['alreadyUsed'];
  814. break;
  815. case self::$useStatus['expire']://已过期
  816. $sql .= ' isUse=' . self::$useStatus['waitUsed'] . ' AND endTime<' . $nowTime;
  817. break;
  818. }
  819. $countQuery = $sql;
  820. $sql .= ' ORDER BY createTime DESC LIMIT ' . $offset . ',' . $limit;
  821. $dbResult = $objMUserCoupon->getUserCoupon($sql, true, '*', $countQuery);
  822. if (!$dbResult->isSuccess()) {
  823. return ResultWrapper::fail($dbResult->getData(), $dbResult->getErrorCode());
  824. }
  825. $couponData = $dbResult->getData();
  826. $return = [
  827. 'data' => $objMUserCoupon->formatAll($couponData['data']),
  828. 'total' => $couponData['total']
  829. ];
  830. return ResultWrapper::success($return);
  831. }
  832. /**
  833. * 支付成功会员卡发放优惠券
  834. *
  835. * @param $couponIds
  836. * @return ResultWrapper
  837. * @throws \Exception
  838. */
  839. public function giveCoupon($couponIds, $vipCardId = '')
  840. {
  841. $coupons = $this->objDCoupon->select(['id' => $couponIds]);
  842. if ($coupons == false) {
  843. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  844. }
  845. $objMUserCoupon = new MUserCoupon($this->onlineUserId, $this->onlineEnterpriseId);
  846. if (!empty($coupons)) {
  847. //查询当前客户类型
  848. $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
  849. $dbResult = $objMCustomer->getCustomerInfoByUserCenterId($this->onlineUserId);
  850. if (!$dbResult->isSuccess()) {
  851. return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  852. }
  853. $customer = $dbResult->getData();
  854. $insert = [];
  855. foreach ($coupons as $key => $coupon) {
  856. /**if ($coupon['receiveNum'] >= $coupon['totalNum']) {
  857. * //数量不够发放
  858. * unset($coupons[$key]);
  859. * continue;
  860. * }
  861. * $userCoupon = $objMUserCoupon->getUserCoupon(['couponId' => $coupon['id'], 'userId' => $this->onlineUserId]);
  862. * if (!$userCoupon->isSuccess()) {
  863. * unset($coupons[$key]);
  864. * continue;
  865. * }
  866. * $haveNum = count($userCoupon->getData());
  867. * if ($haveNum >= $coupon['allowNum']) {
  868. * unset($coupons[$key]);
  869. * continue;
  870. * }**/
  871. //优惠券记录信息
  872. $insert [] = [
  873. 'couponId' => $coupon['id'],
  874. 'name' => $coupon['name'],
  875. 'remark' => $coupon['remark'],
  876. 'couponType' => $coupon['couponType'],
  877. 'reducePrice' => $coupon['reducePrice'],
  878. 'minPrice' => $coupon['minPrice'],
  879. 'startTime' => time(),
  880. 'endTime' => time() + 30 * 24 * 3600,
  881. 'applyRange' => $coupon['applyRange'],
  882. 'categoryCollect' => $coupon['categoryCollect'],
  883. 'brandCollect' => $coupon['brandCollect'],
  884. 'goodsCollect' => $coupon['goodsCollect'],
  885. 'isExpire' => StatusCode::$standard,
  886. 'isUse' => StatusCode::$standard,
  887. 'userId' => $this->onlineUserId,
  888. 'customerId' => $customer['id'],
  889. 'useShop' => $coupon['useShop'],
  890. 'source' => $coupon['grantType'],
  891. 'createTime' => time(),
  892. 'updateTime' => time(),
  893. 'vipCardId' => $vipCardId,
  894. 'isMutex' => isset($coupon['isMutex']) ? $coupon['isMutex'] : StatusCode::$standard,
  895. ];
  896. }
  897. if (empty($insert)) {
  898. return ResultWrapper::success([]);
  899. }
  900. $this->objDCoupon->beginTransaction();
  901. //写记录
  902. $dbResult = $objMUserCoupon->add($insert, true);
  903. if (!$dbResult->isSuccess()) {
  904. $this->objDCoupon->rollBack();
  905. ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
  906. }
  907. unset($dbResult);
  908. //增加领取数量
  909. $dbResult = $this->objDCoupon->set_inc('receiveNum', ['id' => $couponIds], 1);
  910. if ($dbResult === false) {
  911. $this->objDCoupon->rollBack();
  912. ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  913. }
  914. $this->objDCoupon->commit();
  915. return ResultWrapper::success($dbResult);
  916. }
  917. }
  918. /**
  919. * 启用/禁用
  920. * @param $params
  921. * @return ResultWrapper
  922. */
  923. public function updateEnableStatus($params)
  924. {
  925. $dbResult = $this->objDCoupon->update(['enableStatus' => $params['enableStatus']], $params['id']);
  926. if ($dbResult === false) {
  927. return ResultWrapper::fail($this->objDCoupon->error(), ErrorCode::$dberror);
  928. }
  929. /*$_id = self::createEsDocumentId($params['id']);
  930. $this->objDCoupon->esupdateTypeFieldVaule([
  931. 'enableStatus' => $params['enableStatus']
  932. ], $_id);*/
  933. return ResultWrapper::success($dbResult);
  934. }
  935. /**
  936. * 处理定向发放优惠劵脚本
  937. */
  938. public function grantCoupon()
  939. {
  940. // 查询审核通过未被删除当前时间在发放时间内没有发完的定向发放的普通优惠劵
  941. $fields = 'id,isMutex,customerIds,startTime,endTime,name,couponType,reducePrice,minPrice,remark,grantType,totalNum,allowNum,customerSourceId,useShop,mustCondition,grantStartTime,grantEndTime,applyRange,categoryCollect,brandCollect,receiveNum,goodsCollect';
  942. $nowTime = time();
  943. $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'];
  944. $couponList = $this->objDCoupon->query($sql);
  945. if ($couponList === false){
  946. return ResultWrapper::fail($this->objDCoupon->error(),ErrorCode::$dberror);
  947. }
  948. // 提取定向发放优惠券的客户ids
  949. $allCustomerIds = [];
  950. foreach ($couponList as $key => $value){
  951. $customerIdsStr = $value['customerIds'];
  952. if (empty($customerIdsStr)){
  953. continue;
  954. }
  955. $customerIds = explode(',',$customerIdsStr);
  956. $allCustomerIds = array_merge($allCustomerIds,$customerIds);
  957. $couponList[$key]['customerIdsArray'] = $customerIds;
  958. }
  959. $allCustomerIds = array_values(array_unique($allCustomerIds));
  960. if (empty($allCustomerIds)){
  961. return ResultWrapper::success(true);
  962. }
  963. // 查询这批客户的数据
  964. $objCustomer = new DCustomer();
  965. $objCustomer->setTable('qianniao_customer_'.$this->onlineEnterpriseId);
  966. $customerList = $objCustomer->select(['id'=>$allCustomerIds],'userCenterId,id');
  967. if ($customerList === false){
  968. return ResultWrapper::fail($objCustomer->error(),ErrorCode::$dberror);
  969. }
  970. // 映射客户id和userCenterId
  971. $customerMap = [];
  972. foreach ($customerList as $value){
  973. $customerMap[$value['id']] = $value['userCenterId'];
  974. }
  975. // 处理优惠劵
  976. foreach ($couponList as $key => $val){
  977. // 判断优惠劵是否领完了
  978. if ($val['receiveNum'] >= $val['totalNum']){
  979. echo '优惠券'.$val['id'].'已经领取完了'.PHP_EOL;
  980. unset($couponList[$key]);
  981. continue;
  982. }
  983. foreach ($val['customerIdsArray'] as $customerId){
  984. $dbResult = $this->objDUserCoupon->count(['couponId' => $val['id'], 'userId' => isset($customerMap[$customerId]) ? $customerMap[$customerId] : 0]);
  985. if ($dbResult === false) {
  986. echo '领取记录查询失败' . $this->objDUserCoupon->error() . PHP_EOL;
  987. return ResultWrapper::fail($this->objDUserCoupon->error(),ErrorCode::$dberror);
  988. }
  989. // 当前这个用户是否领取过当前这张优惠券
  990. if ($dbResult >= $val['allowNum']){
  991. echo '优惠券'.$val['id'].'已经领取了'.$dbResult.'张,每人限领取'.$val['allowNum'].'张'.PHP_EOL;
  992. unset($couponList[$key]);
  993. continue;
  994. }
  995. // 剩余数量不足每人领取数量
  996. if ($val['receiveNum']+$val['allowNum'] > $val['totalNum']){
  997. $rec = $val['totalNum'] - $val['receiveNum'];
  998. $couponList[$key]['allowNum'] = $rec;
  999. }
  1000. if (empty($couponList)) {
  1001. echo '优惠券都领取过了' . PHP_EOL;
  1002. continue;
  1003. }
  1004. echo '定向发放优惠券'.date('Y-m-d H:i:s').PHP_EOL;
  1005. parent::coupon([
  1006. 'userCenterId' => isset($customerMap[$customerId]) ? $customerMap[$customerId] : 0,
  1007. 'customerId' => $customerId,
  1008. 'enterpriseId' => $this->onlineEnterpriseId,
  1009. ], 'MGrantCoupon');
  1010. sleep(1);//优惠券首次审核后都处于等待发放,会有很多请求
  1011. }
  1012. }
  1013. /**foreach ($allCustomerIds as $id){
  1014. //检测用户是否领取过
  1015. parent::coupon([
  1016. 'userCenterId' => isset($customerMap[$id]) ? $customerMap[$id] : 0,
  1017. 'customerId' => $id,
  1018. 'enterpriseId' => $this->onlineEnterpriseId,
  1019. ], 'MGrantCoupon');
  1020. }*/
  1021. return ResultWrapper::success(true);
  1022. }
  1023. }