UserWalletModel.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Model\Arts;
  4. use App\Model\Model;
  5. use Hyperf\DbConnection\Db;
  6. use function Hyperf\Config\config;
  7. class UserWalletModel extends Model
  8. {
  9. /**
  10. * The table associated with the model.
  11. *
  12. * @var ?string
  13. */
  14. protected ?string $table = 'user_wallet';
  15. protected ?string $dateFormat = 'U';
  16. public bool $timestamps = false;
  17. /**
  18. * 默认查询字段
  19. *
  20. * @var array|string[]
  21. */
  22. public array $select = [
  23. '*'
  24. ];
  25. /**
  26. * 获取钱包信息
  27. * @param int $user_id
  28. * @param string $field
  29. * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|mixed|object|string|null
  30. */
  31. public static function getOne(int $user_id, string $field = '')
  32. {
  33. //所有钱包余额
  34. $wallet = self::query()->where(['user_id' => $user_id])->first();
  35. if (!empty($field)) {
  36. return $wallet[$field] ?? '';
  37. }
  38. return $wallet;
  39. }
  40. /**
  41. * 钱包操作
  42. * @param int $user_id
  43. * @param float $money
  44. * @param string $remark
  45. * @param int $type
  46. * @return bool
  47. */
  48. public function change(int $user_id, float $money, string $remark = '', int $type = 3)
  49. {
  50. if (!in_array($type, [3, 4])) {
  51. return $this->error('余额类型错误');
  52. }
  53. $wallet = (new static())->getOne($user_id);
  54. if ($type == 3) {
  55. // 消费
  56. $data = [
  57. 'money' => bcadd($wallet['money'], (string)(-$money), 2),
  58. 'disburse_money' => bcadd($wallet['disburse_money'], (string)$money, 2)
  59. ];
  60. if ($data['money'] < 0) {
  61. return $this->error('余额不足');
  62. }
  63. $log_money = -$money;
  64. } else {
  65. // 退还
  66. $data = [
  67. 'money' => bcadd($wallet['money'], (string)$money, 2),
  68. 'disburse_money' => bcadd($wallet['disburse_money'], (string)(-$money), 2)
  69. ];
  70. $log_money = $money;
  71. }
  72. if (!$this->query()->where(['user_id' => $user_id, 'money' => $wallet['money']])->update($data)) {
  73. $this->error('操作失败');
  74. }
  75. if (!UserMoneyLogModel::query()->insert(['user_id' => $user_id, 'type' => $type, 'money' => $log_money, 'before' => $wallet['money'], 'after' => $data['money'], 'remark' => $remark, 'create_time' => time()])) {
  76. $this->error('记录操作失败');
  77. }
  78. return $this->success('操作成功');
  79. }
  80. }