Redpack.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. /**
  3. * 红包
  4. * @author solu
  5. */
  6. class Redpack extends Model {
  7. protected $tableName = 'redpack';
  8. protected $dbKey = 'dw_chat';
  9. const REDIS_PRE_REDPACK_REWARD_LIST = 'mee:redpack_reward_list:';
  10. const REWARD_LIST_TTL = 86400 - 120; // 提前两分钟结束
  11. const MONEY_MIN_AVG = 1;
  12. const TEAM_DEDUCT = 0.02; // 团队提成
  13. const STATUS_PLAYING = 0; // 进行中
  14. const STATUS_FINISH = 1; // 已抢完
  15. const STATUS_TIMEOUT = 2; // 超时关闭
  16. private static function getRewardListKey($trxId) {
  17. return self::REDIS_PRE_REDPACK_REWARD_LIST . $trxId;
  18. }
  19. /**
  20. * 初始化红包
  21. * @author solu
  22. * @param $redpack Redpack
  23. * @param null $objRedis
  24. * @return bool
  25. */
  26. public function initReward($redpack, $objRedis = null) {
  27. $trxId = $redpack['transfer_trx_id'];
  28. $total = $redpack['quantity_total_int'];
  29. $num = $redpack['num_total'];
  30. !$objRedis && $objRedis = dwRedis::init(Eos::REDIS_SERV);
  31. $key = self::getRewardListKey($trxId);
  32. if (($total/$num) < self::MONEY_MIN_AVG) {
  33. alermErrorMsg("trxId:{$trxId}, total:{$total}, num:{$num} 平均红包金额太小");
  34. return false;
  35. }
  36. $objRedis->del($key);
  37. $total -= $total * self::TEAM_DEDUCT;
  38. $list = self::_makeRandomArr($total, $num);
  39. array_unshift($list, $key);
  40. call_user_func_array([$objRedis, 'lPush'], $list);
  41. $objRedis->expire($key, self::REWARD_LIST_TTL);
  42. self::redpackEvent($redpack['session_id'], $redpack['sender'], $trxId, $redpack['memo']);
  43. return true;
  44. }
  45. private static function redpackEvent($sessionId, $sender, $trxId, $title) {
  46. $objUserBindInfo = new UserBindInfo();
  47. $userId = $objUserBindInfo->getUserIdBy($sender, 'eos');
  48. $objSession = new Session();
  49. $se = explode('-', $sessionId);
  50. $data = json_encode(compact('title', 'trxId'));
  51. $data = Utils::encodeRC4($data);
  52. if (count($se) > 1) {
  53. // 发给个人
  54. $to = 0;
  55. foreach ($se as $_u) {
  56. if ($_u != $userId) {
  57. $to = $_u;
  58. break;
  59. }
  60. }
  61. // 插入一条聊天消息
  62. $ret = $objSession->sendPersonMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, $data, true);
  63. $eventData = [
  64. 'type' => 'new_redpack',
  65. 'from' => $userId,
  66. 'to' => $to,
  67. 'hash' => $ret['hash'],
  68. 'content' => $data
  69. // 'content' => Utils::encodeRC4($title),
  70. // 'ext' => compact('trxId'),
  71. ];
  72. ThirdApi::pushPersonEvent($to, $eventData);
  73. } else {
  74. // 插入一条聊天消息
  75. $ret = $objSession->sendGroupMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, $data, true);
  76. // 发给群组
  77. $groupId = current($se);
  78. $eventData = [
  79. 'type' => 'new_redpack',
  80. 'group_id' => $groupId,
  81. 'from' => $userId,
  82. 'hash' => $ret['hash'],
  83. 'content' => $data,
  84. // 'content' => Utils::encodeRC4($title),
  85. // 'ext' => compact('trxId'),
  86. ];
  87. ThirdApi::pushGroupEvent($groupId, $eventData);
  88. }
  89. }
  90. private static function _makeRandomArr($money, $num, $min = 1) {
  91. $list = [];
  92. while ($num > 0) {
  93. if ($num == 1) {
  94. $list[] = $money;
  95. break;
  96. } else {
  97. $max = ($money / $num) * 2;
  98. $_tmp = rand($min, $max);
  99. $_tmp <= $min && $_tmp = $min;
  100. $list[] = $_tmp;
  101. $money -= $_tmp;
  102. }
  103. $num--;
  104. }
  105. return $list;
  106. }
  107. /**
  108. * 抢红包
  109. * @author solu
  110. * @param $trxId
  111. * @param $userId
  112. * @return array
  113. * @throws Exception
  114. */
  115. public function grab($trxId, $userId) {
  116. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  117. if (!$row) {
  118. throw new Exception('miss redpack', CODE_NORMAL_ERROR);
  119. }
  120. if (self::STATUS_PLAYING != $row['status']) {
  121. throw new Exception('Too Late', -1001);
  122. }
  123. $objUserBindInfo = new UserBindInfo();
  124. $account = $objUserBindInfo->getAccountByUserId($userId);
  125. if (!$account) {
  126. throw new Exception('not bind EOS account', CODE_NORMAL_ERROR);
  127. }
  128. $objLog = new TableHelper('redpack_log', 'dw_chat');
  129. if ($objLog->getCount(['redpack_trx_id' => $trxId, 'user_id' => $userId])) {
  130. throw new Exception('repeat grab', CODE_NORMAL_ERROR);
  131. }
  132. $key = self::getRewardListKey($trxId);
  133. $objRedis = dwRedis::init(Eos::REDIS_SERV);
  134. $quantity = $objRedis->rPop($key);
  135. if (false === $quantity) {
  136. throw new Exception('Too Late', CODE_NORMAL_ERROR);
  137. }
  138. $strQuantity = Eos::toDisplayFormat($quantity);
  139. $redpackId = $row['id'];
  140. $data = [
  141. 'redpack_id' => $redpackId,
  142. 'redpack_trx_id' => $trxId,
  143. 'player' => $account,
  144. 'quantity' => $strQuantity,
  145. 'quantity_int' => $quantity,
  146. 'create_time' => NOW,
  147. 'user_id' => $userId,
  148. ];
  149. $objLog->addObject($data);
  150. $logId = $objLog->getInsertId();
  151. if (!$logId) {
  152. throw new Exception('log error', CODE_NORMAL_ERROR);
  153. }
  154. $parts = explode('-', $row['session_id']);
  155. $from = $objUserBindInfo->getUserIdBy($row['sender'], 'eos');
  156. $eventData = [
  157. 'type' => 'grab_redpack',
  158. 'from' => $from,
  159. 'to' => $userId,
  160. 'content' => [
  161. 'title' => $row['memo'],
  162. 'redpack_id' => $redpackId,
  163. 'redpack_trx_id' => $trxId,
  164. 'quantity' => $strQuantity,
  165. ],
  166. ];
  167. if (count($parts) == 1) {
  168. // 抢红包的信息,要发给发红包的人
  169. $groupId = current($parts);
  170. $eventData['group_id'] = $groupId;
  171. ThirdApi::pushGroupEvent($groupId, $eventData);
  172. } else {
  173. ThirdApi::pushPersonEvent($userId, $eventData);
  174. }
  175. Eos::grabRedpack($redpackId, $trxId, $logId, $account, $strQuantity);
  176. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  177. $ret = [
  178. 'from' => $from,
  179. 'quantity' => $quantity,
  180. 'type' => 'eos',
  181. 'num_total' => $row['num_total'],
  182. 'num_left' => $row['num_left'] - 1,
  183. 'quantity_total' => $row['quantity_total_int'] - $team,
  184. 'quantity_left' => $row['quantity_left_int'] - $quantity,
  185. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  186. ];
  187. return $ret;
  188. }
  189. /**
  190. * 红包详情
  191. * @author solu
  192. * @param $trxId
  193. * @return array
  194. */
  195. public function detail($trxId) {
  196. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  197. if (!$row) {
  198. return [];
  199. }
  200. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  201. $ret = [
  202. 'from' => $row['sender_id'],
  203. 'title' => $row['memo'],
  204. 'type' => 'eos',
  205. 'redpack_status' => $row['status'],
  206. 'num_total' => $row['num_total'],
  207. 'num_left' => $row['num_left'],
  208. 'quantity_total' => $row['quantity_total_int'] - $team,
  209. 'quantity_left' => $row['quantity_left_int'],
  210. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  211. ];
  212. return $ret;
  213. }
  214. /**
  215. * 发出的红包
  216. * @author solu
  217. * @param $userId
  218. * @param int $offset
  219. * @param int $size
  220. * @return array
  221. */
  222. public function sendList($userId, $offset = 0, $size = 20) {
  223. if (!$userId) {
  224. return [];
  225. }
  226. $list = $this->objTable->getAll(['sender_id' => $userId], [
  227. '_field' => 'id, session_id, num_total, num_left, quantity_total_int, quantity_left_int, memo as title, status, transfer_trx_id, create_time',
  228. '_sortKey' => 'id DESC',
  229. '_limit' => "{$offset}, {$size}",
  230. ]);
  231. $total_count = 0;
  232. $total_quantity = 0;
  233. if (0 == $offset) {
  234. $row = $this->objTable->getRow(['sender_id' => $userId], [
  235. '_field' => 'sum(quantity_total_int) as total_quantity, count(1) as c',
  236. ]);
  237. $total_count = (int)$row['c'];
  238. $total_quantity = (int)$row['total_quantity'];
  239. }
  240. return [$list, $total_count, $total_quantity];
  241. }
  242. /**
  243. * 收到的红包
  244. * @author solu
  245. * @param $userId
  246. * @param int $offset
  247. * @param int $size
  248. * @return array
  249. */
  250. public function receiveList($userId, $offset = 0, $size = 20) {
  251. if (!$userId) {
  252. return [];
  253. }
  254. $objRedpackLog = new RedpackLog();
  255. $list = $objRedpackLog->objTable->getAll(['user_id' => $userId], [
  256. '_field' => 'id, redpack_trx_id, quantity_int, create_time, status, best',
  257. '_sortKey' => 'id DEsc',
  258. '_limit' => "{$offset}, {$size}",
  259. ]);
  260. $trxIds = array_column($list, 'redpack_trx_id');
  261. $redpacks = $this->objTable->getAll(['transfer_trx_id' => $trxIds], [
  262. '_field' => 'id, transfer_trx_id, sender_id, memo, status',
  263. ]);
  264. $redpacks = arrayFormatKey($redpacks, 'transfer_trx_id');
  265. $senderIds = array_column($redpacks, 'sender_id');
  266. $objUser = new TableHelper('user_info', 'dw_chat');
  267. $users = $objUser->getAll(['user_id' => $senderIds], ['_field' => 'user_id, nick_name, cover_photo']);
  268. $users = arrayFormatKey($users, 'user_id', 'nick_name');
  269. foreach ($list as $k => $v) {
  270. $redpack = $redpacks[$v['redpack_trx_id']];
  271. $senderNick = $users[$redpack['sender_id']];
  272. $v['sender'] = $senderNick;
  273. $v['title'] = $redpack['memo'];
  274. $list[$k] = $v;
  275. }
  276. $total_count = 0;
  277. $best_count = 0;
  278. $total_quantity = 0;
  279. if (0 == $offset) {
  280. $row = $this->objTable->getRow(['sender_id' => $userId], [
  281. '_field' => 'sum(quantity_int) as total_quantity, count(1) as c, sum(best) best_count',
  282. ]);
  283. $total_count = (int)$row['c'];
  284. $total_quantity = (int)$row['total_quantity'];
  285. $best_count = (int)$row['best_count'];
  286. }
  287. return [$list, $total_count, $total_quantity, $best_count];
  288. }
  289. }