Balance.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace app\data\controller\api\auth;
  3. use app\data\controller\api\Auth;
  4. use app\data\controller\User;
  5. use app\data\service\UserService;
  6. use think\admin\extend\CodeExtend;
  7. /**
  8. * 用户余额转账
  9. * Class Balance
  10. * @package app\data\controller\api\auth
  11. */
  12. class Balance extends Auth
  13. {
  14. /**
  15. * 绑定数据表
  16. * @var string
  17. */
  18. private $table = 'DataUserBalanceTransfer';
  19. /**
  20. * 获取用户转账记录
  21. * @throws \think\db\exception\DataNotFoundException
  22. * @throws \think\db\exception\DbException
  23. * @throws \think\db\exception\ModelNotFoundException
  24. */
  25. public function get()
  26. {
  27. $query = $this->_query($this->table);
  28. $query->where(['uid|from' => $this->uuid, 'deleted' => 0]);
  29. $result = $query->order('id desc')->page(true, false, false, 15);
  30. if (count($result['list']) > 0) {
  31. UserService::instance()->buildByUid($result['list'], 'uid', 'selfer');
  32. UserService::instance()->buildByUid($result['list'], 'from', 'fromer');
  33. }
  34. $this->success('获取数据成功', $result);
  35. }
  36. /**
  37. * 创建余额转账申请
  38. * @throws \think\db\exception\DataNotFoundException
  39. * @throws \think\db\exception\DbException
  40. * @throws \think\db\exception\ModelNotFoundException
  41. */
  42. public function add()
  43. {
  44. $data = $this->_vali([
  45. 'from.value' => $this->uuid,
  46. 'code.value' => CodeExtend::uniqidDate(18, 'T'),
  47. 'uid.require' => '目标用户不能为空!',
  48. 'name.default' => '用户余额转账',
  49. 'amount.require' => '转账金额不能为空!',
  50. ]);
  51. if ($data['uid'] == $this->uuid) {
  52. $this->error('不能给自己转账!');
  53. }
  54. // 检测目标用户状态
  55. $map = ['id' => $data['uid'], 'deleted' => 0];
  56. $user = $this->app->db->name('DataUser')->where($map)->find();
  57. if (empty($user)) $this->error('目标用户不存在!');
  58. // 检测用户是否有足够的余额
  59. [$total, $used] = UserService::instance()->balance($this->uuid);
  60. if ($data['amount'] > $total - $used) $this->error('可转账余额不足!');
  61. // 写入余额转账记录
  62. if ($this->app->db->name($this->table)->insert($data) !== false) {
  63. UserService::instance()->balance($data['uid']);
  64. UserService::instance()->balance($data['from']);
  65. $this->success('余额转账成功!');
  66. } else {
  67. $this->error('余额转账失败!');
  68. }
  69. }
  70. }