WalletLogic.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. namespace addons\Happiness\common\logic\pv;
  3. use addons\Happiness\common\enums\HappinessEnum;
  4. use addons\Happiness\common\enums\HappinessPvEnum;
  5. use addons\Happiness\common\models\HappinessPvWallet;
  6. use addons\Happiness\common\models\HappinessPvWalletLog;
  7. use common\enums\RabbitMqEnum;
  8. use common\enums\RedisKeyEnum;
  9. use common\enums\StatusEnum;
  10. use common\helpers\LockHelper;
  11. use common\helpers\TaskHelper;
  12. use common\models\common\CapitalLog;
  13. use common\traits\ErrorTrait;
  14. use Exception;
  15. use Yii;
  16. /**
  17. * Class WalletLogic
  18. * 新积分处理类
  19. */
  20. class WalletLogic
  21. {
  22. use ErrorTrait;
  23. /**
  24. * 获取资金类型
  25. * @return array
  26. */
  27. public static function getWalletType()
  28. {
  29. return [
  30. 'score_value',
  31. 'total_score_value',
  32. 'freeze_score_value',
  33. 'active_score_value'
  34. ];
  35. }
  36. public static function handle($data, $task_id = 0)
  37. {
  38. $user_id = $data['user_id'];
  39. $wallet_type = $data['wallet_type'];
  40. $mall_id = $data['mall_id'];
  41. $capital_types = self::getWalletType();
  42. if (!in_array($wallet_type, $capital_types)) {
  43. self::$static_error = '操作类型有误';
  44. Yii::error(__CLASS__ . ' handle error :' . self::$static_error);
  45. return false;
  46. }
  47. if(bccomp($data['change_num'],0,10) == 0){
  48. self::$static_error = '操作金额为0';
  49. Yii::error(__CLASS__ . ' handle error :' . self::$static_error);
  50. return false;
  51. }
  52. //lock
  53. $lock_key = RedisKeyEnum::suffix(HappinessPvEnum::HAPPINESS_PV_USER_WALLET, $user_id);
  54. $identification = uniqid();
  55. if (LockHelper::lock($lock_key, $identification, 100, 100)) {
  56. $t = \Yii::$app->db->beginTransaction();
  57. try {
  58. $edit_field = $wallet_type;
  59. //修改用户钱包表
  60. $user_wallet_model = HappinessPvWallet::findOne(['mall_id' => $mall_id, 'user_id' => $user_id]);
  61. if (empty($user_wallet_model)) {
  62. $user_wallet_model = HappinessPvWallet::setData([
  63. 'user_id' => $user_id,
  64. 'mall_id' => $mall_id,
  65. 'score_value' => 0,
  66. 'freeze_score_value' => 0,
  67. 'active_score_value' => 0,
  68. 'status' => StatusEnum::ENABLED,
  69. 'total_score_value' => 0,
  70. ]);
  71. if($user_wallet_model===false) throw new Exception(HappinessPvWallet::getStaticError());
  72. }
  73. $current_num = $user_wallet_model->$edit_field;
  74. $after_num = bcadd($current_num, $data['change_num'], 10);
  75. if (bccomp($after_num, 0, 10) < 0) {
  76. throw new Exception('用户新积分余额不足');
  77. }
  78. $user_wallet_model->$edit_field = $after_num;
  79. if (!$user_wallet_model->save()) throw new Exception($user_wallet_model->getErrorMessage());
  80. //操作解冻:添加余额,修改记录状态
  81. $setData = [
  82. 'mall_id' => $mall_id,
  83. 'user_id' => $user_id,
  84. 'change_type' => $data['change_num'] > 0 ? CapitalLog::CHANGE_TYPE_ADD : CapitalLog::CHANGE_TYPE_SUB,
  85. 'change_num' => abs($data['change_num']),
  86. 'before_num' => $current_num,
  87. 'after_num' => $after_num,
  88. 'desc' => $data['desc'] ?? '',
  89. 'source_table' => $data['source_table'] ?? '',
  90. 'source_table_id' => $data['source_table_id'] ?? 0,
  91. 'from_type' => $data['from_type'] ?? '',
  92. 'wallet_type' => $data['wallet_type'],
  93. 'addon_name' => $data['addon_name'] ?? HappinessEnum::ADDONS_NAME,
  94. 'status' => 1,
  95. 'order_no' => $data['order_no'] ?? ''
  96. ];
  97. $log_res = HappinessPvWalletLog::setData($setData);
  98. if (!$log_res) throw new Exception(HappinessPvWalletLog::getStaticError());
  99. $log_res_id = $log_res->id;
  100. $t->commit();
  101. //unlock
  102. LockHelper::uLock($lock_key, $identification);
  103. $task_id && self::setHandleResult($task_id, $log_res_id);
  104. return true;
  105. } catch (Exception $e) {
  106. Yii::error(__CLASS__ . ' handle exception : ' . $e->getMessage() . ',task_id:' . $task_id.',data:'.json_encode($data));
  107. $t->rollBack();
  108. LockHelper::uLock($lock_key, $identification);
  109. self::$static_error = $e->getMessage();
  110. return false;
  111. }
  112. } else {
  113. //抢不到锁
  114. Yii::error(__CLASS__ . ' handle error : 抢不到锁,task_id:' . $task_id);
  115. self::$static_error = '操作太频繁';
  116. return false;
  117. }
  118. }
  119. /**
  120. * 获取处理结果
  121. * @param $task_id
  122. * @return array|bool|null|string
  123. * @throws \yii\db\Exception
  124. */
  125. public static function getHandleResult($task_id)
  126. {
  127. $result_key = HappinessPvEnum::USER_WALLET_RESULT_KEY_PREFIX . $task_id;
  128. $redis = \Yii::$app->redis;
  129. return $redis->executeCommand('GET', [$result_key]);
  130. }
  131. /**
  132. * 获取处理结果
  133. * @param $task_id
  134. * @param $result
  135. * @return array|bool|null|string
  136. * @throws \yii\db\Exception
  137. */
  138. public static function setHandleResult($task_id, $result)
  139. {
  140. $result_key = HappinessPvEnum::USER_WALLET_RESULT_KEY_PREFIX . $task_id;
  141. $redis = \Yii::$app->redis;
  142. return $redis->executeCommand('SET', [$result_key, $result, 'EX', 86400]);
  143. }
  144. /**
  145. * 异步队列操作用户钱包
  146. * @param array $data
  147. * @param bool $wait_result 是否阻塞,等待结果
  148. * @throws
  149. * @return bool
  150. */
  151. public static function handleInQueue($data, $wait_result = true)
  152. {
  153. if (!in_array($data['wallet_type'], self::getWalletType())) {
  154. throw new Exception('操作类型不合法');
  155. }
  156. $task_id = TaskHelper::pushTaskQueue(
  157. RabbitMqEnum::EXCHANGE_TASK_USER_WALLET,
  158. RabbitMqEnum::USER_WALLET_QUEUE,
  159. $data,
  160. __CLASS__,
  161. 'handle'
  162. );
  163. if (!$task_id) {
  164. throw new Exception('操作失败');
  165. }
  166. $result = true;
  167. //block for result
  168. if ($wait_result) {
  169. $hasWait = 0; //已经等待的时间:毫秒
  170. $max_wait_time = 3 * 1000; //最长等待 3s
  171. while (true) {
  172. $result = self::getHandleResult($task_id);
  173. if ($result) {
  174. break;
  175. }
  176. usleep(30 * 1000); //等待30ms
  177. $hasWait += 30;
  178. if ($hasWait > $max_wait_time) {
  179. //等待超时
  180. $result = false;
  181. break;
  182. }
  183. }
  184. }
  185. //注意:返回false 表示正在等待处理
  186. return $result;
  187. }
  188. public static function batchHandle($data)
  189. {
  190. //外部加个事务
  191. try {
  192. unset($data['message_id']);
  193. foreach ($data as $log) {
  194. if(!isset($log['message_id'])) $log['message_id'] = '';
  195. $log['message_id'] = 0;
  196. $res=self::handle($log);
  197. if($res===false)
  198. {
  199. throw new Exception(self::getStaticError());
  200. }
  201. }
  202. return true;
  203. }catch (Exception $e)
  204. {
  205. Yii::error(__CLASS__ . ' batchHandle exception : ' . $e->getMessage() . ',data:'.json_encode($data));
  206. self::$static_error = $e->getMessage();
  207. return false;
  208. }
  209. }
  210. }