Redpack.php 12 KB

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