Redpack.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. private function getTokenType($redpack) {
  20. $parts = explode(' ', $redpack['quantity_total']);
  21. $tokenType = strtoupper($parts[1]);
  22. return $tokenType;
  23. }
  24. private function checkValidType($redpack) {
  25. $tokenType = $this->getTokenType($redpack);
  26. if ($redpack['code'] == 'eosio.token' && $tokenType == 'EOS') {
  27. return true;
  28. }
  29. // 检查是否乱发红包
  30. $parts = explode('-', $redpack['session_id']);
  31. if (count($parts) > 1) {
  32. // 个人转账只能转EOS
  33. return false;
  34. }
  35. $group_id = (int) $redpack['session_id'];
  36. $objGroupEos = new TableHelper('group_eos', 'dw_chat');
  37. $row = $objGroupEos->getRow(compact('group_id'));
  38. if ($row['token_code'] == $redpack['code'] && $row['token'] == $tokenType) {
  39. return true;
  40. } else {
  41. return false;
  42. }
  43. }
  44. /**
  45. * 初始化红包
  46. * @author solu
  47. * @param $redpack Redpack
  48. * @param null $objRedis
  49. * @return bool
  50. */
  51. public function initReward($redpack, $objRedis = null) {
  52. $trxId = $redpack['transfer_trx_id'];
  53. $total = $redpack['quantity_total_int'];
  54. $num = $redpack['num_total'];
  55. // 检查红包类型是否正确
  56. $flag = $this->checkValidType($redpack);
  57. if (!$flag) {
  58. alermErrorMsg("trxId:{$trxId}, quantity_total:{$redpack['quantity_total']}, num:{$num} 发送的红包类型错误");
  59. return false;
  60. }
  61. !$objRedis && $objRedis = dwRedis::init(Eos::REDIS_SERV);
  62. $key = self::getRewardListKey($trxId);
  63. if (($total/$num) < self::MONEY_MIN_AVG) {
  64. alermErrorMsg("trxId:{$trxId}, total:{$total}, num:{$num} 平均红包金额太小");
  65. return false;
  66. }
  67. $objRedis->del($key);
  68. $total -= $total * self::TEAM_DEDUCT;
  69. $list = self::_makeRandomArr($total, $num);
  70. array_unshift($list, $key);
  71. call_user_func_array([$objRedis, 'lPush'], $list);
  72. $objRedis->expire($key, self::REWARD_LIST_TTL);
  73. $tokenType = $this->getTokenType($redpack);
  74. self::redpackEvent($redpack['session_id'], $redpack['sender'], $trxId, $redpack['memo'], $tokenType);
  75. return true;
  76. }
  77. private static function redpackEvent($sessionId, $sender, $trxId, $title, $tokenType = 'EOS') {
  78. $objUserBindInfo = new UserBindInfo();
  79. $userId = $objUserBindInfo->getUserIdBy($sender, 'eos');
  80. $objSession = new Session();
  81. $se = explode('-', $sessionId);
  82. $data = json_encode(compact('title', 'trxId', 'tokenType'));
  83. $data = Utils::encodeRC4($data);
  84. if (count($se) > 1) {
  85. // 发给个人
  86. $to = 0;
  87. foreach ($se as $_u) {
  88. if ($_u != $userId) {
  89. $to = $_u;
  90. break;
  91. }
  92. }
  93. // 插入一条聊天消息
  94. $ret = $objSession->sendPersonMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, $data, true);
  95. $eventData = [
  96. 'type' => 'new_redpack',
  97. 'msg_type' => Session::MSG_TYPE_REDPACK,
  98. 'from' => $userId,
  99. 'to' => $to,
  100. 'name' => User::getUserNameById($userId),
  101. 'hash' => $ret['hash'],
  102. 'content' => $data
  103. // 'content' => Utils::encodeRC4($title),
  104. // 'ext' => compact('trxId'),
  105. ];
  106. ThirdApi::pushPersonEvent($userId, $eventData);
  107. ThirdApi::pushPersonEvent($to, $eventData);
  108. } else {
  109. // 插入一条聊天消息
  110. $ret = $objSession->sendGroupMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, $data, true);
  111. // 发给群组
  112. $groupId = current($se);
  113. $eventData = [
  114. 'type' => 'new_redpack',
  115. 'msg_type' => Session::MSG_TYPE_REDPACK,
  116. 'group_id' => $groupId,
  117. 'from' => $userId,
  118. 'name' => GroupInfo::getGroupNameById($groupId),
  119. 'hash' => $ret['hash'],
  120. 'content' => $data,
  121. 'userMap' => $ret['userMap'],
  122. // 'content' => Utils::encodeRC4($title),
  123. // 'ext' => compact('trxId'),
  124. ];
  125. ThirdApi::pushGroupEvent($groupId, $eventData);
  126. }
  127. }
  128. private static function _makeRandomArr($money, $num, $min = 1) {
  129. $list = [];
  130. while ($num > 0) {
  131. if ($num == 1) {
  132. $list[] = $money;
  133. break;
  134. } else {
  135. $max = ($money / $num) * 2;
  136. $_tmp = rand($min, $max);
  137. $_tmp <= $min && $_tmp = $min;
  138. $list[] = $_tmp;
  139. $money -= $_tmp;
  140. }
  141. $num--;
  142. }
  143. return $list;
  144. }
  145. /**
  146. * 抢红包
  147. * @author solu
  148. * @param $trxId
  149. * @param $userId
  150. * @return array
  151. * @throws Exception
  152. */
  153. public function grab($trxId, $userId) {
  154. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  155. if (!$row) {
  156. throw new Exception('miss redpack', CODE_NORMAL_ERROR);
  157. }
  158. if (self::STATUS_PLAYING != $row['status']) {
  159. throw new Exception('Too Late', -1001);
  160. }
  161. $objUserBindInfo = new UserBindInfo();
  162. $account = $objUserBindInfo->getAccountByUserId($userId);
  163. if (!$account) {
  164. throw new Exception('not bind EOS account', CODE_NORMAL_ERROR);
  165. }
  166. $objLog = new TableHelper('redpack_log', 'dw_chat');
  167. if ($objLog->getCount(['redpack_trx_id' => $trxId, 'user_id' => $userId])) {
  168. throw new Exception('repeat grab', CODE_NORMAL_ERROR);
  169. }
  170. $key = self::getRewardListKey($trxId);
  171. $objRedis = dwRedis::init(Eos::REDIS_SERV);
  172. $quantity = $objRedis->rPop($key);
  173. if (false === $quantity) {
  174. throw new Exception('Too Late', CODE_NORMAL_ERROR);
  175. }
  176. $tokenType = $this->getTokenType($row);
  177. $strQuantity = Eos::toDisplayFormat($quantity, $tokenType);
  178. $redpackId = $row['id'];
  179. $data = [
  180. 'redpack_id' => $redpackId,
  181. 'redpack_trx_id' => $trxId,
  182. 'player' => $account,
  183. 'quantity' => $strQuantity,
  184. 'quantity_int' => $quantity,
  185. 'create_time' => NOW,
  186. 'user_id' => $userId,
  187. ];
  188. $objLog->addObject($data);
  189. $logId = $objLog->getInsertId();
  190. if (!$logId) {
  191. throw new Exception('log error', CODE_NORMAL_ERROR);
  192. }
  193. $parts = explode('-', $row['session_id']);
  194. $from = $objUserBindInfo->getUserIdBy($row['sender'], 'eos');
  195. $eventData = [
  196. 'type' => 'grab_redpack',
  197. 'from' => $from,
  198. 'to' => $userId,
  199. 'content' => [
  200. 'title' => $row['memo'],
  201. 'redpack_id' => $redpackId,
  202. 'redpack_trx_id' => $trxId,
  203. 'quantity' => $strQuantity,
  204. ],
  205. ];
  206. if (count($parts) == 1) {
  207. // 抢红包的信息,要发给发红包的人
  208. $groupId = current($parts);
  209. $eventData['group_id'] = $groupId;
  210. ThirdApi::pushGroupEvent($groupId, $eventData);
  211. } else {
  212. if ($userId != $from) {
  213. ThirdApi::pushPersonEvent($userId, $eventData);
  214. }
  215. ThirdApi::pushPersonEvent($from, $eventData);
  216. }
  217. Eos::grabRedpack($redpackId, $trxId, $logId, $account, $strQuantity);
  218. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  219. $ret = [
  220. 'from' => $from,
  221. 'quantity' => $quantity,
  222. 'type' => 'eos',
  223. 'tokenType' => $this->getTokenType($row),
  224. 'num_total' => $row['num_total'],
  225. 'num_left' => $row['num_left'] - 1,
  226. 'quantity_total' => $row['quantity_total_int'] - $team,
  227. 'quantity_left' => $row['quantity_left_int'] - $quantity,
  228. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  229. ];
  230. return $ret;
  231. }
  232. /**
  233. * 红包详情
  234. * @author solu
  235. * @param $trxId
  236. * @return array
  237. */
  238. public function detail($trxId) {
  239. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  240. if (!$row) {
  241. return [];
  242. }
  243. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  244. $ret = [
  245. 'from' => $row['sender_id'],
  246. 'title' => $row['memo'],
  247. 'tokenType' => $this->getTokenType($row),
  248. 'type' => 'EOS',
  249. 'redpack_status' => $row['status'],
  250. 'num_total' => $row['num_total'],
  251. 'num_left' => $row['num_left'],
  252. 'quantity_total' => $row['quantity_total_int'] - $team,
  253. 'quantity_left' => $row['quantity_left_int'],
  254. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  255. ];
  256. return $ret;
  257. }
  258. /**
  259. * 发出的红包
  260. * @author solu
  261. * @param $userId
  262. * @param int $offset
  263. * @param int $size
  264. * @return array
  265. */
  266. public function sendList($userId, $offset = 0, $size = 20) {
  267. if (!$userId) {
  268. return [];
  269. }
  270. $list = $this->objTable->getAll(['sender_id' => $userId], [
  271. '_field' => 'id, session_id, num_total, num_left, quantity_total_int, quantity_left_int, memo as title, status, transfer_trx_id, create_time',
  272. '_sortKey' => 'id DESC',
  273. '_limit' => "{$offset}, {$size}",
  274. ]);
  275. $total_count = 0;
  276. $total_quantity = 0;
  277. if (0 == $offset) {
  278. $row = $this->objTable->getRow(['sender_id' => $userId], [
  279. '_field' => 'sum(quantity_total_int) as total_quantity, count(1) as c',
  280. ]);
  281. $total_count = (int)$row['c'];
  282. $total_quantity = (int)$row['total_quantity'];
  283. }
  284. return [$list, $total_count, $total_quantity];
  285. }
  286. /**
  287. * 收到的红包
  288. * @author solu
  289. * @param $userId
  290. * @param int $offset
  291. * @param int $size
  292. * @return array
  293. */
  294. public function receiveList($userId, $offset = 0, $size = 20) {
  295. if (!$userId) {
  296. return [];
  297. }
  298. $objRedpackLog = new RedpackLog();
  299. $list = $objRedpackLog->objTable->getAll(['user_id' => $userId], [
  300. '_field' => 'id, redpack_trx_id, quantity_int, create_time, status, best',
  301. '_sortKey' => 'id DEsc',
  302. '_limit' => "{$offset}, {$size}",
  303. ]);
  304. $trxIds = array_column($list, 'redpack_trx_id');
  305. $redpacks = $this->objTable->getAll(['transfer_trx_id' => $trxIds], [
  306. '_field' => 'id, transfer_trx_id, sender_id, memo, status',
  307. ]);
  308. $redpacks = arrayFormatKey($redpacks, 'transfer_trx_id');
  309. $senderIds = array_column($redpacks, 'sender_id');
  310. $objUser = new TableHelper('user_info', 'dw_chat');
  311. $users = $objUser->getAll(['user_id' => $senderIds], ['_field' => 'user_id, nick_name, cover_photo']);
  312. $users = arrayFormatKey($users, 'user_id', 'nick_name');
  313. foreach ($list as $k => $v) {
  314. $redpack = $redpacks[$v['redpack_trx_id']];
  315. $senderNick = $users[$redpack['sender_id']];
  316. $v['sender'] = $senderNick;
  317. $v['title'] = $redpack['memo'];
  318. $list[$k] = $v;
  319. }
  320. $total_count = 0;
  321. $best_count = 0;
  322. $total_quantity = 0;
  323. if (0 == $offset) {
  324. $row = $this->objTable->getRow(['sender_id' => $userId], [
  325. '_field' => 'sum(quantity_int) as total_quantity, count(1) as c, sum(best) best_count',
  326. ]);
  327. $total_count = (int)$row['c'];
  328. $total_quantity = (int)$row['total_quantity'];
  329. $best_count = (int)$row['best_count'];
  330. }
  331. return [$list, $total_count, $total_quantity, $best_count];
  332. }
  333. }