WalletLogic.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. namespace addons\Happiness\common\logic\voucher;
  3. use addons\Happiness\common\enums\HappinessEnum;
  4. use addons\Happiness\common\enums\HappinessVoucherEnum;
  5. use addons\Happiness\common\models\HappinessVoucherWallet;
  6. use addons\Happiness\common\models\HappinessVoucherLog;
  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. * @Author: zfh
  20. * @DateTime: 2024/05/06 20:39
  21. * @Copyright: copyright (c) 2023 广东七件事集团
  22. */
  23. class WalletLogic
  24. {
  25. use ErrorTrait;
  26. /**
  27. * 获取资金类型
  28. * @return array
  29. */
  30. public static function getWalletType()
  31. {
  32. return [
  33. 'balance'
  34. ];
  35. }
  36. public static function handle($data, $task_id = 0)
  37. {
  38. if (!empty($data['message_id'])) {
  39. $task_id = $data['message_id'];
  40. unset($data['message_id']);
  41. }
  42. $store_id = $data['store_id'];
  43. $wallet_type = $data['wallet_type'];
  44. $mall_id = $data['mall_id'];
  45. $level=$data['level'];
  46. $unfreeze = $data['unfreeze'] ?? false; //是否操作解冻资金
  47. $freeze_log_id = $data['freeze_log_id'] ?? 0; //操作解冻资金的记录ID
  48. $capital_types = self::getWalletType();
  49. if (!in_array($wallet_type, $capital_types)) {
  50. self::$static_error = '操作类型有误';
  51. Yii::error(__CLASS__ . ' handle error :' . self::$static_error);
  52. return false;
  53. }
  54. if(bccomp($data['change_num'],0,10) == 0){
  55. self::$static_error = '操作金额为0';
  56. Yii::error(__CLASS__ . ' handle error :' . self::$static_error);
  57. return false;
  58. }
  59. if ($unfreeze){
  60. if($freeze_log_id <= 0){
  61. self::$static_error = '解冻资金记录ID不存在';
  62. Yii::error(__CLASS__ . ' handle error :' . self::$static_error);
  63. return false;
  64. }
  65. $unfreeze_log = HappinessVoucherWallet::findOne(['id' => $freeze_log_id,'store_id' => $store_id,'status' =>
  66. CapitalLog::STATUS_WAIT_SEND]);
  67. if(!$unfreeze_log){
  68. self::$static_error = '解冻资金记录不存在';
  69. Yii::error(__CLASS__ . ' handle error :' . self::$static_error);
  70. return false;
  71. }
  72. }
  73. //lock
  74. $lock_key = RedisKeyEnum::suffix(HappinessVoucherEnum::LOCK_HAPPINESS_USER_WALLET, $store_id);
  75. $identification = uniqid();
  76. if (1==1) {
  77. $t = \Yii::$app->db->beginTransaction();
  78. try {
  79. $edit_field = $wallet_type;
  80. //修改用户钱包表
  81. $user_wallet_model = HappinessVoucherWallet::findOne(['mall_id' => $mall_id, 'store_id' => $store_id, 'status' =>
  82. StatusEnum::ENABLED,'level'=>$level]);
  83. if (empty($user_wallet_model)) {
  84. $user_wallet_model = HappinessVoucherWallet::setData([
  85. 'store_id' => $store_id,
  86. 'mall_id' => $mall_id,
  87. 'level'=>$level,
  88. 'balance'=>0,
  89. 'freeze_balance'=>0,
  90. 'status' => StatusEnum::ENABLED
  91. ]);
  92. if($user_wallet_model===false)
  93. {
  94. throw new Exception(HappinessVoucherWallet::getStaticError()());
  95. }
  96. }
  97. $current_num = $user_wallet_model->$edit_field;
  98. $after_num = bcadd($current_num, $data['change_num'], 10);
  99. if (bccomp($after_num, 0, 10) < 0) {
  100. throw new Exception('用户权重值不足');
  101. }
  102. $user_wallet_model->$edit_field = $after_num;
  103. if (!$user_wallet_model->save()) throw new Exception($user_wallet_model->getErrorMessage());
  104. //操作解冻:添加余额,修改记录状态
  105. if ($unfreeze){
  106. //查询记录
  107. $log_res = HappinessVoucherLog::updateAll(['status' => CapitalLog::STATUS_SEND,'after_num' => $after_num],['id' =>
  108. $freeze_log_id]);
  109. if (!$log_res) throw new Exception(HappinessVoucherLog::getStaticError());
  110. $log_res_id = $freeze_log_id;
  111. }else{
  112. $setData = [
  113. 'mall_id' => $mall_id,
  114. 'store_id' => $store_id,
  115. 'level'=>$level,
  116. 'change_type' => $data['change_num'] > 0 ? CapitalLog::CHANGE_TYPE_ADD : CapitalLog::CHANGE_TYPE_SUB,
  117. 'change_num' => abs($data['change_num']),
  118. 'after_num' => $after_num,
  119. 'desc' => $data['desc'] ?? '',
  120. 'source_table' => $data['source_table'] ?? '',
  121. 'source_table_id' => $data['source_table_id'] ?? 0,
  122. 'from_type' => $data['from_type'] ?? '',
  123. 'wallet_type' => $data['wallet_type'],
  124. 'addon_name' => $data['addon_name'] ?? HappinessVoucherEnum::ADDONS_NAME,
  125. 'status' => 1,
  126. 'order_no' => $data['order_no'] ?? ''
  127. ];
  128. $log_res = HappinessVoucherLog::setData($setData);
  129. if (!$log_res) throw new Exception(HappinessVoucherLog::getStaticError());
  130. $log_res_id = $log_res->id;
  131. }
  132. $t->commit();
  133. //unlock
  134. //LockHelper::uLock($lock_key, $identification);
  135. $task_id && self::setHandleResult($task_id, $log_res_id);
  136. return true;
  137. } catch (Exception $e) {
  138. Yii::error(__CLASS__ . ' handle exception : ' . $e->getMessage() . ',task_id:' . $task_id.',data:'.json_encode($data));
  139. $t->rollBack();
  140. //LockHelper::uLock($lock_key, $identification);
  141. self::$static_error = $e->getMessage();
  142. return false;
  143. }
  144. } else {
  145. //抢不到锁
  146. Yii::error(__CLASS__ . ' handle error : 抢不到锁,task_id:' . $task_id);
  147. self::$static_error = '操作太频繁';
  148. return false;
  149. }
  150. }
  151. /**
  152. * 获取处理结果
  153. * @param $task_id
  154. * @return array|bool|null|string
  155. * @throws \yii\db\Exception
  156. */
  157. public static function getHandleResult($task_id)
  158. {
  159. $result_key = HappinessVoucherEnum::USER_WALLET_RESULT_KEY_PREFIX . $task_id;
  160. $redis = \Yii::$app->redis;
  161. return $redis->executeCommand('GET', [$result_key]);
  162. }
  163. /**
  164. * 获取处理结果
  165. * @param $task_id
  166. * @param $result
  167. * @return array|bool|null|string
  168. * @throws \yii\db\Exception
  169. */
  170. public static function setHandleResult($task_id, $result)
  171. {
  172. $result_key = HappinessVoucherEnum::USER_WALLET_RESULT_KEY_PREFIX . $task_id;
  173. $redis = \Yii::$app->redis;
  174. return $redis->executeCommand('SET', [$result_key, $result, 'EX', 86400]);
  175. }
  176. /**
  177. * 异步队列操作用户钱包
  178. * @param array $data
  179. * @param bool $wait_result 是否阻塞,等待结果
  180. * @throws
  181. * @return bool
  182. */
  183. public static function handleInQueue($data, $wait_result = true)
  184. {
  185. if (!in_array($data['wallet_type'], self::getWalletType())) {
  186. throw new Exception('操作类型不合法');
  187. }
  188. $task_id = TaskHelper::pushTaskQueue(
  189. RabbitMqEnum::EXCHANGE_TASK_USER_WALLET,
  190. RabbitMqEnum::USER_WALLET_QUEUE,
  191. $data,
  192. __CLASS__,
  193. 'handle'
  194. );
  195. if (!$task_id) {
  196. throw new Exception('操作失败');
  197. }
  198. $result = true;
  199. //block for result
  200. if ($wait_result) {
  201. $hasWait = 0; //已经等待的时间:毫秒
  202. $max_wait_time = 3 * 1000; //最长等待 3s
  203. while (true) {
  204. $result = self::getHandleResult($task_id);
  205. if ($result) {
  206. break;
  207. }
  208. usleep(30 * 1000); //等待30ms
  209. $hasWait += 30;
  210. if ($hasWait > $max_wait_time) {
  211. //等待超时
  212. $result = false;
  213. break;
  214. }
  215. }
  216. }
  217. //注意:返回false 表示正在等待处理
  218. return $result;
  219. }
  220. /**
  221. * 处理 未处理记录
  222. * @return void
  223. * @throws
  224. */
  225. public static function unfrozen($frozen_log)
  226. {
  227. if($frozen_log['status'] != CapitalLog::STATUS_WAIT_SEND) return ;
  228. $res = self::handleInQueue($frozen_log);
  229. if($res){
  230. HappinessVoucherLog::updateAll(['status' => CapitalLog::STATUS_SEND],['id' => $frozen_log['id']]);
  231. }
  232. return true;
  233. }
  234. /**
  235. * 删除未处理记录
  236. * @param $frozen_log
  237. * @return void
  238. */
  239. public static function delfrozen($frozen_log)
  240. {
  241. if($frozen_log['status'] != CapitalLog::STATUS_WAIT_SEND) return ;
  242. HappinessVoucherLog::updateAll(['status' => CapitalLog::STATUS_FAIL],['id' => $frozen_log['id']]);
  243. return true;
  244. }
  245. }