Redpack.php 13 KB

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