ScratchApiLogic.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. <?php
  2. namespace addons\Scratch\common\logic;
  3. use addons\Coupon\common\enums\AddonsCouponEnum;
  4. use addons\Coupon\common\models\AddonsCouponUserRelate;
  5. use addons\Scratch\common\enums\ScratchEnum;
  6. use addons\Scratch\common\models\CouponRelationModel;
  7. use addons\Scratch\common\models\ScratchCouponModel;
  8. use addons\Scratch\common\models\ScratchLogModel;
  9. use addons\Scratch\common\models\ScratchModel;
  10. use addons\Scratch\common\models\ScratchSettingModel;
  11. use common\enums\UserWalletEnum;
  12. use common\models\goods\GoodsAttr;
  13. use common\models\user\UserWallet;
  14. use services\common\UserWalletService;
  15. /**
  16. * Class ScratchApiLogic
  17. * @package addons\Scratch\common\logic
  18. */
  19. class ScratchApiLogic
  20. {
  21. public $id;
  22. public static $log;
  23. /**
  24. * @param $mallId
  25. * @param $userData
  26. * @param int $page
  27. * @return array|false|mixed|void
  28. * @throws \ErrorException
  29. */
  30. public static function getList($mallId, $userData, $page = 1)
  31. {
  32. try {
  33. $setting = CommonScratchLogic::getSetting($mallId);
  34. if (empty($setting)) {
  35. throw new \ErrorException('规则尚未配置');
  36. }
  37. //验证
  38. // self::validated($setting, $userData);
  39. //记录数
  40. self::$log = self::getLogCount($setting, $userData);
  41. //中奖记录
  42. $list = CommonScratchLogic::getLotteryRecord($mallId, ['page' => $page]);
  43. $backgroundImgs = isset($setting['background_imgs']) && $setting['background_imgs'] ? json_decode($setting['background_imgs'], true) : '';
  44. $list['background_imgs'] = $backgroundImgs;
  45. $list['oppty'] = $setting->oppty > self::$log ? $setting->oppty - self::$log : 0;
  46. $list['deplete_integral_num'] = $setting->deplete_integral_num;
  47. //积分检测
  48. $walletData = UserWallet::findOne(['user_id' => $userData->id]);
  49. $list['user_score'] = $walletData->score ?? 0;
  50. return $list;
  51. } catch (\ErrorException $errorException) {
  52. throw new \ErrorException($errorException->getMessage());
  53. } catch (\Exception $exception) {
  54. throw new \Exception($exception->getMessage());
  55. }
  56. }
  57. /**
  58. * @param $mallId
  59. * @param $userData
  60. * @return array
  61. * @throws \ErrorException
  62. */
  63. public static function getData($mallId, $userData)
  64. {
  65. try {
  66. $userId = $userData->id ?? 0;
  67. $setting = CommonScratchLogic::getSetting($mallId);
  68. if (empty($setting)) {
  69. throw new \ErrorException('规则尚未配置');
  70. }
  71. //记录数
  72. self::$log = self::getLogCount($setting, $userData);
  73. $list['background_imgs'] = isset($setting['background_imgs']) && $setting['background_imgs'] ? json_decode($setting['background_imgs'], true) : '';
  74. $list['oppty'] = $setting->oppty > self::$log ? $setting->oppty - self::$log : 0;
  75. $list['deplete_integral_num'] = $setting->deplete_integral_num;
  76. //积分检测
  77. $walletData = UserWallet::findOne(['user_id' => $userId]);
  78. $list['user_score'] = $walletData->score ?? 0;
  79. return $list;
  80. } catch (\ErrorException $errorException) {
  81. throw new \ErrorException($errorException->getMessage());
  82. } catch (\Exception $exception) {
  83. throw new \Exception($exception->getMessage());
  84. }
  85. }
  86. /**
  87. * @param $mallId
  88. * @param $userData
  89. * @param int $page
  90. * @return array|false|mixed|void
  91. * @throws \ErrorException
  92. */
  93. public static function getLogList($mallId, $userData, $page = 1)
  94. {
  95. try {
  96. $params = [
  97. 'with' => [
  98. 'user' => function ($q) {
  99. $q->select('id,nickname,avatar_url');
  100. },
  101. 'goods' => function ($q) {
  102. $q->select('id,goods_name,price');
  103. },
  104. 'coupon' => function ($q) {
  105. $q->select('id,name,sub_price');
  106. },
  107. ],
  108. 'where' => [
  109. ['=', 'mall_id', $mallId],
  110. ['=', 'user_id', $userData->id],
  111. ],
  112. 'page' => $postData['page'] ?? 1,
  113. 'limit' => $postData['limit'] ?? 10,
  114. 'order' => $postData['order'] ?? 'id desc',
  115. ];
  116. if (!empty($postData['type'])) {
  117. $params['where'][] = ['=', 'type', $postData['type']];
  118. } else {
  119. $params['where'][] = ['in', 'type', [1, 2, 3, 4, 5]];
  120. }
  121. $pageData = ScratchLogModel::listPage($params, false);
  122. if ($pageData === false) throw new \ErrorException(ScratchModel::getStaticError());
  123. $returnData = $data = [];
  124. foreach ($pageData['list'] as $val) {
  125. $data["goods"] = null;
  126. if ($val["type"] == ScratchModel::TYPE_GOODS) {
  127. $data['goods'] = $val['goods'];
  128. $data['goods']['attr_id'] = $val['attr_id'];
  129. $name = $val['goods']['goods_name'] ?? '';
  130. $title = "您已刮中商品" . $name . "奖励";
  131. } else if ($val["type"] == ScratchModel::TYPE_COUPON) {
  132. $name = $val['coupon']['name'] ?? '';
  133. $val['price'] = $val['coupon']['sub_price'] ?? 0;
  134. $title = "您已刮中优惠券 " . $name . " 奖励";
  135. } else {
  136. $name = CommonScratchLogic::getNewName($val);
  137. $title = "您已刮中" . $name . "奖励";
  138. }
  139. $goodsId = $val["goods_id"];
  140. $data['id'] = $val['id'];
  141. $data['status'] = $val['status'];
  142. $data["scratch_id"] = $val["scratch_id"];
  143. $data["goods_id"] = $goodsId;
  144. $data['name'] = $name;
  145. $data['title'] = $title;
  146. $data["type"] = intval($val["type"]);
  147. $data["price"] = floatval($val["price"]);
  148. $data["raffled_at"] = !empty($val["raffled_at"]) ? date("Y-m-d H:i:s", $val["raffled_at"]) : date("Y-m-d H:i:s", $val["created_at"]);
  149. $returnData["list"][] = $data;
  150. }
  151. $returnData["pagination"] = $pageData['pagination'];
  152. $returnData["page_count"] = $pageData['page_count'];
  153. return $returnData;
  154. } catch (\ErrorException $errorException) {
  155. throw new \ErrorException($errorException->getMessage());
  156. } catch (\Exception $exception) {
  157. throw new \Exception($exception->getMessage());
  158. }
  159. }
  160. /**
  161. * @param $id
  162. * @return array|false|mixed|void
  163. * @throws \ErrorException
  164. */
  165. public static function getEdit($id, $mallId)
  166. {
  167. try {
  168. } catch (\ErrorException $errorException) {
  169. throw new \ErrorException($errorException->getMessage());
  170. } catch (\Exception $exception) {
  171. throw new \Exception($exception->getMessage());
  172. }
  173. }
  174. /**
  175. * @param $setting
  176. * @param $userData
  177. * @throws \Exception
  178. */
  179. private static function validated($setting, $userData)
  180. {
  181. //记录数
  182. self::$log = self::getLogCount($setting, $userData);
  183. //时间检测 配置信息
  184. if ($setting->start_at > date('Y-m-d H:i:s') || $setting->end_at < date('Y-m-d H:i:s')) {
  185. throw new \Exception('活动未开始或已过期');
  186. }
  187. //积分检测
  188. if ($setting->deplete_integral_num > 0) {
  189. $walletData = UserWallet::findOne(['user_id' => $userData->id]);
  190. $integral = $walletData->score ?? 0;
  191. if ($integral < $setting->deplete_integral_num) {
  192. $score_name = \Yii::$app->services->setting->mall->get($setting->mall_id, 'score.score_name') ?? '积分';
  193. throw new \Exception($score_name.'不足');
  194. }
  195. }
  196. //机会检测
  197. if (self::$log >= $setting->oppty) {
  198. throw new \Exception("抽奖机会不足");
  199. }
  200. }
  201. /**
  202. * @param $setting
  203. * @param $userData
  204. * @throws \Exception
  205. */
  206. private static function getLogCount($setting, $userData)
  207. {
  208. $userId = $userData->id ?? 0;
  209. $query = ScratchLogModel::find()->where([
  210. 'AND',
  211. ['mall_id' => $setting->mall_id],
  212. ['user_id' => $userId],
  213. // ['<>', 'status', 0]
  214. ]);
  215. $todayStart = strtotime(date("Y-m-d 00:00:00"));
  216. $todayEnd = strtotime(date("Y-m-d 23:59:59"));
  217. if ($setting->type == ScratchSettingModel::TYPE_DAY) {
  218. $query->andWhere([
  219. 'AND',
  220. ['>=', 'created_at', $todayStart],
  221. ['<=', 'created_at', $todayEnd],
  222. ]);
  223. } elseif ($setting->type == ScratchSettingModel::TYPE_USER) {
  224. $query->andWhere([
  225. 'AND',
  226. ['>=', 'created_at', strtotime($setting->start_at)],
  227. ['<=', 'created_at', strtotime($setting->end_at)],
  228. ]);
  229. }
  230. //记录数
  231. $count = $query->count();
  232. return !empty($count) ? $count : 0;
  233. }
  234. /**
  235. * @param $item
  236. * @return bool
  237. */
  238. private static function verify($item)
  239. {
  240. if ($item->type == ScratchModel::TYPE_COUPON) {
  241. $coupon = ScratchCouponModel::find()
  242. ->where(['id' => $item->coupon_id, 'status' => ScratchEnum::ENABLED])
  243. ->select(['id', 'coupon_status', 'status'])
  244. ->one();
  245. if (empty($coupon)) {
  246. return false;
  247. }
  248. //优惠券状态,1:未开始,2:领取中,3:已过期,4:已失效(后台操作失效)
  249. if ($coupon->coupon_status > 2) {
  250. return false;
  251. }
  252. }
  253. if ($item->type == ScratchModel::TYPE_GOODS) {
  254. $goodsAttr = GoodsAttr::find()
  255. ->where(['id' => $item->attr_id, 'status' => 1])
  256. ->select(['id', 'goods_id', 'stock'])
  257. ->one();
  258. if (!$goodsAttr) {
  259. return false;
  260. }
  261. //库存不足
  262. if ($goodsAttr->stock <= 0) {
  263. return false;
  264. }
  265. }
  266. return true;
  267. }
  268. /**
  269. * 中奖
  270. * @param $setting
  271. * @param $userData
  272. * @return array|array[]|object|object[]|string[]
  273. * @throws \yii\db\Exception
  274. */
  275. private static function lottery($setting, $userData)
  276. {
  277. $scratch = ScratchModel::findAll([
  278. 'mall_id' => $setting['mall_id'],
  279. 'status' => ScratchEnum::ENABLED
  280. ]);
  281. $suc = [];
  282. foreach ($scratch as $v) {
  283. if ($v->stock > 0 && self::verify($v)) {
  284. $suc[$v->id] = $v->stock;
  285. }
  286. }
  287. $max = array_sum($suc);
  288. $rand = self::randomNum(1, 10000);
  289. if ($rand < $setting->probability && $max > 0) {
  290. $id = self::getRand($suc);
  291. /* @var Scratch $scratch */
  292. $scratch = ScratchModel::find()
  293. ->where([
  294. 'mall_id' => $userData->mall_id,
  295. 'id' => $id,
  296. 'status' => ScratchEnum::ENABLED,
  297. ])
  298. ->with("coupon")
  299. ->with("goods")
  300. ->one();
  301. $price = floatval($scratch->price);
  302. if ($scratch->type == ScratchModel::TYPE_BALANCE) {
  303. $price = floatval($scratch->balance);
  304. }
  305. $scratchLog = new ScratchLogModel();
  306. $scratchLog->mall_id = $userData->mall_id;
  307. $scratchLog->user_id = $userData->id;
  308. $scratchLog->scratch_id = $scratch->id;
  309. $scratchLog->status = ScratchLogModel::STATUS_PRE;
  310. $scratchLog->type = $scratch->type;
  311. $scratchLog->num = !empty($scratch->num) ? intval($scratch->num) : 1;
  312. $scratchLog->price = $price;
  313. $scratchLog->detail = '';
  314. if ($scratchLog->type == ScratchModel::TYPE_GOODS) {
  315. $scratchLog->goods_id = $scratch->goods->id;
  316. $scratchLog->attr_id = $scratch->attr_id;
  317. $scratchLog->price = $scratch->goods->price;
  318. } elseif ($scratchLog->type == ScratchModel::TYPE_COUPON) {
  319. $scratchLog->coupon_id = $scratch->coupon_id;
  320. }
  321. $t = \Yii::$app->db->beginTransaction();
  322. $sql = 'select * from ' . ScratchModel::tableName() . ' where mall_id = ' . $userData->mall_id . ' and id = ' . $id . ' and status = ' . ScratchModel::STATUS_ON . ' for update';
  323. $form = \Yii::$app->db->createCommand($sql)->queryOne();
  324. if ($form['stock'] > 0) {
  325. $scratch->stock = $form['stock'] - 1;
  326. if (!$scratch->save()) {
  327. $t->rollBack();
  328. throw new \Exception($scratch->getErrorMessage());
  329. }
  330. } else {
  331. $scratchLog->type = ScratchModel::TYPE_THANKS;
  332. $scratchLog->detail = '';
  333. $scratchLog->num = 0;
  334. $scratchLog->price = 0;
  335. }
  336. if ($scratchLog->save()) {
  337. $t->commit();
  338. $scratchLog = \yii\helpers\ArrayHelper::toArray($scratchLog);
  339. if ($scratchLog["type"] == ScratchModel::TYPE_GOODS) {
  340. $goodsData = CommonScratchLogic::getNewName($scratchLog, "end");
  341. $name = $goodsData["name"];
  342. $pic = $goodsData["pic"];
  343. } else {
  344. $name = CommonScratchLogic::getNewName1($scratch->mall_id, $scratch);
  345. $pic = $scratch->pic;
  346. }
  347. $scratchLog['name'] = $name;
  348. $scratchLog['pic'] = $pic;
  349. return $scratchLog;
  350. } else {
  351. $t->rollBack();
  352. throw new \Exception($scratchLog->getErrorMessage());
  353. }
  354. } else {
  355. $scratchLog = new ScratchLogModel();
  356. $scratchLog->mall_id = $userData->mall_id;
  357. $scratchLog->user_id = $userData->id;
  358. $scratchLog->scratch_id = 0;
  359. $scratchLog->detail = '';
  360. $scratchLog->status = 0;
  361. $scratchLog->price = 0;
  362. $scratchLog->type = ScratchModel::TYPE_THANKS;
  363. if ($scratchLog->save()) {
  364. $scratchLog = \yii\helpers\ArrayHelper::toArray($scratchLog);
  365. $scratchLog['name'] = CommonScratchLogic::getNewName($scratchLog);
  366. $scratchLog['pic'] = "";
  367. return $scratchLog;
  368. } else {
  369. throw new \Exception($scratchLog->getErrorMessage());
  370. }
  371. }
  372. }
  373. /**
  374. * @return array|bool
  375. * @throws \Exception
  376. */
  377. public static function toReceive($userData, $id)
  378. {
  379. $setting = CommonScratchLogic::getSetting($userData->mall_id);
  380. if (!$setting) {
  381. throw new \Exception('规则尚未配置');
  382. }
  383. self::validated($setting, $userData);
  384. $scratchLog = ScratchLogModel::findOne([
  385. 'mall_id' => $userData->mall_id,
  386. 'user_id' => $userData->id,
  387. 'status' => 1,
  388. 'id' => $id
  389. ]);
  390. return self::receive($setting, $scratchLog, $userData);
  391. }
  392. /**
  393. * 领取
  394. * @param $setting
  395. * @param $scratchLog
  396. * @param $userData
  397. * @return array|bool
  398. */
  399. public static function receive($setting, $scratchLog, $userData)
  400. {
  401. try {
  402. $scratchLog = ScratchLogModel::find()->where(['id' => $scratchLog['id'] ?? 0])->one();
  403. if (empty($scratchLog)) {
  404. throw new \Exception('数据异常');
  405. }
  406. //扣积分
  407. if ($setting->deplete_integral_num > 0) {
  408. $desc = '刮刮卡消耗' . (int)$setting->deplete_integral_num . '积分';
  409. $insert_wallet [] = [
  410. 'mall_id' => $userData->mall_id,
  411. 'user_id' => $userData->id,
  412. 'is_frozen' => false,
  413. 'wallet_type' => UserWalletService::WALLET_TYPE_SCORE,
  414. 'money' => -(int)$setting->deplete_integral_num,
  415. 'desc' => $desc,
  416. 'source_table' => 'addons_scratch_log',
  417. 'source_table_id' => $scratchLog->id,
  418. 'from_type' => UserWalletEnum::CONSUME,
  419. 'capital_type' => UserWalletEnum::DEDUCT,
  420. ];
  421. $res = UserWalletService::batchHandleByQueue($insert_wallet);
  422. if ($res === false) {
  423. throw new \Exception(UserWalletService::getStaticError());
  424. };
  425. }
  426. $scratchLog->status = ScratchLogModel::STATUS_NO_RECEIVED;
  427. if ($scratchLog->save()) {
  428. //兑奖
  429. return self::send($scratchLog);
  430. } else {
  431. throw new \Exception($scratchLog->getErrorMessage());
  432. }
  433. } catch (\Exception $e) {
  434. throw new \Exception($e->getMessage());
  435. }
  436. }
  437. /**
  438. * 领取
  439. * @param $scratchLog
  440. * @return array|bool
  441. * @throws \yii\db\Exception
  442. */
  443. public static function send($scratchLog)
  444. {
  445. $status = ScratchLogModel::STATUS_RECEIVED;
  446. $raffled_at = time();
  447. //红包
  448. if ($scratchLog->type == ScratchModel::TYPE_REDPACKET) {
  449. throw new \Exception('红包领取失败,该功能还未上线');
  450. $money = (float)$scratchLog->price;
  451. if ($money <= 0) {
  452. return true;
  453. }
  454. $t = \Yii::$app->db->beginTransaction();
  455. $desc = '刮刮卡获赠' . $money . '元';
  456. //状态
  457. $scratchLog->status = $status;
  458. $scratchLog->raffled_at = $raffled_at;
  459. if ($scratchLog->save()) {
  460. $currency = RedPacketUser::getCurrency();
  461. $res = CurrencyWallet::addLog($currency, \Yii::$app->user->id, \Yii::$app->mall->id, $money, $desc, 'scratch_give', 'scratch_log', $scratchLog->id, false);
  462. if ($res === false) {
  463. $t->rollBack();
  464. throw new \Exception($scratchLog->getErrorMessage());
  465. }
  466. $t->commit();
  467. return [
  468. 'code' => 0,
  469. 'msg' => '红包领取成功',
  470. 'data' => $scratchLog->id
  471. ];
  472. } else {
  473. $t->rollBack();
  474. throw new \Exception($scratchLog->getErrorMessage());
  475. }
  476. }
  477. //余额
  478. if ($scratchLog->type == ScratchModel::TYPE_BALANCE) {
  479. if (floatval($scratchLog->price) <= 0) {
  480. return true;
  481. }
  482. $t = \Yii::$app->db->beginTransaction();
  483. $desc = '刮刮卡获赠' . (float)$scratchLog->price . '元';
  484. $insert_wallet [] = [
  485. 'mall_id' => $scratchLog->mall_id,
  486. 'user_id' => $scratchLog->user_id,
  487. 'is_frozen' => false,
  488. 'wallet_type' => UserWalletService::WALLET_TYPE_BALANCE,
  489. 'money' => (float)$scratchLog->price,
  490. 'desc' => $desc,
  491. 'source_table' => 'addons_scratch_log',
  492. 'source_table_id' => $scratchLog->id,
  493. 'from_type' => UserWalletEnum::REWARD,
  494. 'capital_type' => UserWalletEnum::GIVE,
  495. ];
  496. $res = UserWalletService::batchHandleByQueue($insert_wallet);
  497. if ($res === false) {
  498. throw new \Exception(UserWalletService::getStaticError());
  499. };
  500. //状态
  501. $scratchLog->status = $status;
  502. $scratchLog->raffled_at = $raffled_at;
  503. if ($scratchLog->save()) {
  504. $t->commit();
  505. return [
  506. 'code' => 0,
  507. 'msg' => '余额领取成功',
  508. 'data' => $scratchLog->id
  509. ];
  510. } else {
  511. $t->rollBack();
  512. throw new \Exception($scratchLog->getErrorMessage());
  513. }
  514. }
  515. //优惠券
  516. if ($scratchLog->type == ScratchModel::TYPE_COUPON) {
  517. $t = \Yii::$app->db->beginTransaction();
  518. // 赠送优惠券
  519. $give_coupon_arr = AddonsCouponUserRelate::giveCoupon(
  520. $scratchLog->mall_id,
  521. $scratchLog->user_id,
  522. [$scratchLog->coupon_id => $scratchLog->num],
  523. AddonsCouponEnum::SEND_FROM10
  524. );
  525. $userRelate = AddonsCouponUserRelate::find()
  526. ->where([
  527. 'mall_id' => $scratchLog->mall_id,
  528. 'user_id' => $scratchLog->user_id,
  529. 'coupon_id' => $scratchLog->coupon_id,
  530. ])
  531. ->asArray()
  532. ->orderBy('id desc')
  533. ->select('id')
  534. ->one();
  535. //添加会员领取优惠券日志
  536. CouponRelationModel::setData([
  537. 'mall_id' => $scratchLog->mall_id,
  538. 'user_id' => $scratchLog->user_id,
  539. 'scratch_log_id' => $scratchLog->id,
  540. 'user_coupon_id' => $userRelate['id'] ?? 0
  541. ]);
  542. //状态
  543. $scratchLog->status = $status;
  544. $scratchLog->raffled_at = $raffled_at;
  545. if ($scratchLog->save()) {
  546. $t->commit();
  547. return [
  548. 'code' => 0,
  549. 'msg' => '优惠券领取成功',
  550. 'data' => $scratchLog->id
  551. ];
  552. } else {
  553. $t->rollBack();
  554. throw new \Exception($scratchLog->getErrorMessage());
  555. }
  556. }
  557. //积分
  558. if ($scratchLog->type == ScratchModel::TYPE_SCORE) {
  559. $t = \Yii::$app->db->beginTransaction();
  560. $desc = '刮刮卡获赠' . (int)$scratchLog->num . '积分';
  561. $insert_wallet [] = [
  562. 'mall_id' => $scratchLog->mall_id,
  563. 'user_id' => $scratchLog->user_id,
  564. 'is_frozen' => false,
  565. 'wallet_type' => UserWalletService::WALLET_TYPE_SCORE,
  566. 'money' => (int)$scratchLog->num,
  567. 'desc' => $desc,
  568. 'source_table' => 'addons_scratch_log',
  569. 'source_table_id' => $scratchLog->id,
  570. 'from_type' => UserWalletEnum::REWARD,
  571. 'capital_type' => UserWalletEnum::GIVE,
  572. ];
  573. $res = UserWalletService::batchHandleByQueue($insert_wallet);
  574. if ($res === false) {
  575. throw new \Exception(UserWalletService::getStaticError());
  576. };
  577. //状态
  578. $scratchLog->status = $status;
  579. $scratchLog->raffled_at = $raffled_at;
  580. if ($scratchLog->save()) {
  581. $t->commit();
  582. return [
  583. 'code' => 0,
  584. 'msg' => '积分领取成功',
  585. 'data' => $scratchLog->id
  586. ];
  587. } else {
  588. $t->rollBack();
  589. throw new \Exception($scratchLog->getErrorMessage());
  590. }
  591. }
  592. if ($scratchLog->type == ScratchModel::TYPE_GOODS) {
  593. return [
  594. 'code' => 0,
  595. 'msg' => '商品领取成功',
  596. 'data' => $scratchLog->id
  597. ];
  598. }
  599. if ($scratchLog->type == ScratchModel::TYPE_THANKS) {
  600. $scratchLog->status = $status;
  601. $scratchLog->raffled_at = $raffled_at;
  602. $scratchLog->save();
  603. return [
  604. 'code' => 0,
  605. 'msg' => '领取成功',
  606. 'data' => $scratchLog->id
  607. ];
  608. }
  609. }
  610. /**
  611. * @param $min
  612. * @param $max
  613. * @return int
  614. */
  615. private static function randomNum($min, $max)
  616. {
  617. return mt_rand() % ($max - $min + 1) - $min;
  618. }
  619. private static function getRand($probability)
  620. {
  621. $max = array_sum($probability);
  622. foreach ($probability as $key => $val) {
  623. $rand_number = self::randomNum(1, $max);
  624. if ($rand_number <= $val) {
  625. return $key;
  626. } else {
  627. $max -= $val;
  628. }
  629. }
  630. }
  631. /**
  632. * 刮卡
  633. * @param $mallId
  634. * @param $userData
  635. * @return mixed
  636. * @throws \ErrorException
  637. */
  638. public static function scratchCard($mallId, $userData)
  639. {
  640. try {
  641. $setting = CommonScratchLogic::getSetting($mallId);
  642. if (empty($setting)) {
  643. throw new \ErrorException('规则尚未配置');
  644. }
  645. /**
  646. * 验证数据
  647. */
  648. self::validated($setting, $userData);
  649. /**
  650. * 抽奖算法
  651. */
  652. $scratchLog = self::lottery($setting, $userData);
  653. /**
  654. * 领取
  655. */
  656. self::receive($setting, $scratchLog, $userData);
  657. $pic = "";
  658. $id = $scratchLog["scratch_id"];
  659. $scratch = ScratchModel::findOne($id);
  660. if (!empty($scratch)) {
  661. $pic = $scratch->pic;
  662. }
  663. $scratchLog["pic"] = $pic;
  664. $scratchLog["price"] = floatval($scratchLog["price"]);
  665. $scratchLog["created_at"] = date("Y-m-d H:i:s", $scratchLog["created_at"]);
  666. return [
  667. 'list' => $scratchLog,
  668. ];
  669. } catch (\Exception $ex) {
  670. \Yii::error("scratchForm errorMessage=" . $ex->getFile() . ";LINE:" . $ex->getLine() . ";message:" . $ex->getMessage());
  671. throw new \Exception($ex->getMessage());
  672. }
  673. }
  674. }