Redpack.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. 'userMap' => $ret['userMap'],
  85. // 'content' => Utils::encodeRC4($title),
  86. // 'ext' => compact('trxId'),
  87. ];
  88. ThirdApi::pushGroupEvent($groupId, $eventData);
  89. }
  90. }
  91. private static function _makeRandomArr($money, $num, $min = 1) {
  92. $list = [];
  93. while ($num > 0) {
  94. if ($num == 1) {
  95. $list[] = $money;
  96. break;
  97. } else {
  98. $max = ($money / $num) * 2;
  99. $_tmp = rand($min, $max);
  100. $_tmp <= $min && $_tmp = $min;
  101. $list[] = $_tmp;
  102. $money -= $_tmp;
  103. }
  104. $num--;
  105. }
  106. return $list;
  107. }
  108. /**
  109. * 抢红包
  110. * @author solu
  111. * @param $trxId
  112. * @param $userId
  113. * @return array
  114. * @throws Exception
  115. */
  116. public function grab($trxId, $userId) {
  117. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  118. if (!$row) {
  119. throw new Exception('miss redpack', CODE_NORMAL_ERROR);
  120. }
  121. if (self::STATUS_PLAYING != $row['status']) {
  122. throw new Exception('Too Late', -1001);
  123. }
  124. $objUserBindInfo = new UserBindInfo();
  125. $account = $objUserBindInfo->getAccountByUserId($userId);
  126. if (!$account) {
  127. throw new Exception('not bind EOS account', CODE_NORMAL_ERROR);
  128. }
  129. $objLog = new TableHelper('redpack_log', 'dw_chat');
  130. if ($objLog->getCount(['redpack_trx_id' => $trxId, 'user_id' => $userId])) {
  131. throw new Exception('repeat grab', CODE_NORMAL_ERROR);
  132. }
  133. $key = self::getRewardListKey($trxId);
  134. $objRedis = dwRedis::init(Eos::REDIS_SERV);
  135. $quantity = $objRedis->rPop($key);
  136. if (false === $quantity) {
  137. throw new Exception('Too Late', CODE_NORMAL_ERROR);
  138. }
  139. $strQuantity = Eos::toDisplayFormat($quantity);
  140. $redpackId = $row['id'];
  141. $data = [
  142. 'redpack_id' => $redpackId,
  143. 'redpack_trx_id' => $trxId,
  144. 'player' => $account,
  145. 'quantity' => $strQuantity,
  146. 'quantity_int' => $quantity,
  147. 'create_time' => NOW,
  148. 'user_id' => $userId,
  149. ];
  150. $objLog->addObject($data);
  151. $logId = $objLog->getInsertId();
  152. if (!$logId) {
  153. throw new Exception('log error', CODE_NORMAL_ERROR);
  154. }
  155. $parts = explode('-', $row['session_id']);
  156. $from = $objUserBindInfo->getUserIdBy($row['sender'], 'eos');
  157. $eventData = [
  158. 'type' => 'grab_redpack',
  159. 'from' => $from,
  160. 'to' => $userId,
  161. 'content' => [
  162. 'title' => $row['memo'],
  163. 'redpack_id' => $redpackId,
  164. 'redpack_trx_id' => $trxId,
  165. 'quantity' => $strQuantity,
  166. ],
  167. ];
  168. if (count($parts) == 1) {
  169. // 抢红包的信息,要发给发红包的人
  170. $groupId = current($parts);
  171. $eventData['group_id'] = $groupId;
  172. ThirdApi::pushGroupEvent($groupId, $eventData);
  173. } else {
  174. ThirdApi::pushPersonEvent($userId, $eventData);
  175. }
  176. Eos::grabRedpack($redpackId, $trxId, $logId, $account, $strQuantity);
  177. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  178. $ret = [
  179. 'from' => $from,
  180. 'quantity' => $quantity,
  181. 'type' => 'eos',
  182. 'num_total' => $row['num_total'],
  183. 'num_left' => $row['num_left'] - 1,
  184. 'quantity_total' => $row['quantity_total_int'] - $team,
  185. 'quantity_left' => $row['quantity_left_int'] - $quantity,
  186. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  187. ];
  188. return $ret;
  189. }
  190. /**
  191. * 红包详情
  192. * @author solu
  193. * @param $trxId
  194. * @return array
  195. */
  196. public function detail($trxId) {
  197. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  198. if (!$row) {
  199. return [];
  200. }
  201. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  202. $ret = [
  203. 'from' => $row['sender_id'],
  204. 'title' => $row['memo'],
  205. 'type' => 'eos',
  206. 'redpack_status' => $row['status'],
  207. 'num_total' => $row['num_total'],
  208. 'num_left' => $row['num_left'],
  209. 'quantity_total' => $row['quantity_total_int'] - $team,
  210. 'quantity_left' => $row['quantity_left_int'],
  211. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  212. ];
  213. return $ret;
  214. }
  215. /**
  216. * 发出的红包
  217. * @author solu
  218. * @param $userId
  219. * @param int $offset
  220. * @param int $size
  221. * @return array
  222. */
  223. public function sendList($userId, $offset = 0, $size = 20) {
  224. if (!$userId) {
  225. return [];
  226. }
  227. $list = $this->objTable->getAll(['sender_id' => $userId], [
  228. '_field' => 'id, session_id, num_total, num_left, quantity_total_int, quantity_left_int, memo as title, status, transfer_trx_id, create_time',
  229. '_sortKey' => 'id DESC',
  230. '_limit' => "{$offset}, {$size}",
  231. ]);
  232. $total_count = 0;
  233. $total_quantity = 0;
  234. if (0 == $offset) {
  235. $row = $this->objTable->getRow(['sender_id' => $userId], [
  236. '_field' => 'sum(quantity_total_int) as total_quantity, count(1) as c',
  237. ]);
  238. $total_count = (int)$row['c'];
  239. $total_quantity = (int)$row['total_quantity'];
  240. }
  241. return [$list, $total_count, $total_quantity];
  242. }
  243. /**
  244. * 收到的红包
  245. * @author solu
  246. * @param $userId
  247. * @param int $offset
  248. * @param int $size
  249. * @return array
  250. */
  251. public function receiveList($userId, $offset = 0, $size = 20) {
  252. if (!$userId) {
  253. return [];
  254. }
  255. $objRedpackLog = new RedpackLog();
  256. $list = $objRedpackLog->objTable->getAll(['user_id' => $userId], [
  257. '_field' => 'id, redpack_trx_id, quantity_int, create_time, status, best',
  258. '_sortKey' => 'id DEsc',
  259. '_limit' => "{$offset}, {$size}",
  260. ]);
  261. $trxIds = array_column($list, 'redpack_trx_id');
  262. $redpacks = $this->objTable->getAll(['transfer_trx_id' => $trxIds], [
  263. '_field' => 'id, transfer_trx_id, sender_id, memo, status',
  264. ]);
  265. $redpacks = arrayFormatKey($redpacks, 'transfer_trx_id');
  266. $senderIds = array_column($redpacks, 'sender_id');
  267. $objUser = new TableHelper('user_info', 'dw_chat');
  268. $users = $objUser->getAll(['user_id' => $senderIds], ['_field' => 'user_id, nick_name, cover_photo']);
  269. $users = arrayFormatKey($users, 'user_id', 'nick_name');
  270. foreach ($list as $k => $v) {
  271. $redpack = $redpacks[$v['redpack_trx_id']];
  272. $senderNick = $users[$redpack['sender_id']];
  273. $v['sender'] = $senderNick;
  274. $v['title'] = $redpack['memo'];
  275. $list[$k] = $v;
  276. }
  277. $total_count = 0;
  278. $best_count = 0;
  279. $total_quantity = 0;
  280. if (0 == $offset) {
  281. $row = $this->objTable->getRow(['sender_id' => $userId], [
  282. '_field' => 'sum(quantity_int) as total_quantity, count(1) as c, sum(best) best_count',
  283. ]);
  284. $total_count = (int)$row['c'];
  285. $total_quantity = (int)$row['total_quantity'];
  286. $best_count = (int)$row['best_count'];
  287. }
  288. return [$list, $total_count, $total_quantity, $best_count];
  289. }
  290. }