UserBalanceService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace app\data\service;
  3. use app\data\model\DataUser;
  4. use app\data\model\DataUserBalance;
  5. use app\data\model\ShopOrder;
  6. use think\admin\Exception;
  7. use think\admin\Service;
  8. /**
  9. * 用户余额数据服务
  10. * Class UserBalanceService
  11. * @package app\data\service
  12. */
  13. class UserBalanceService extends Service
  14. {
  15. /**
  16. * 验证订单发放余额
  17. * @param string $orderNo
  18. * @return array [total, count]
  19. * @throws \think\admin\Exception
  20. * @throws \think\db\exception\DataNotFoundException
  21. * @throws \think\db\exception\DbException
  22. * @throws \think\db\exception\ModelNotFoundException
  23. */
  24. public static function confirm(string $orderNo): array
  25. {
  26. $order = ShopOrder::mk()->where([['status', '>=', 4], ['order_no', '=', $orderNo]])->find();
  27. if (empty($order)) throw new Exception('需处理的订单状态异常');
  28. if ($order['reward_balance'] > 0) DataUserBalance::mUpdate([
  29. 'uuid' => $order['uuid'],
  30. 'code' => "CZ{$order['order_no']}",
  31. 'name' => "订单余额充值",
  32. 'remark' => "来自订单 {$order['order_no']} 的余额充值 {$order['reward_balance']} 元",
  33. 'amount' => $order['reward_balance'],
  34. ], 'code');
  35. return static::amount($order['uuid']);
  36. }
  37. /**
  38. * 同步刷新用户余额
  39. * @param int $uuid 用户UID
  40. * @param array $nots 排除的订单
  41. * @return array [total, count]
  42. */
  43. public static function amount(int $uuid, array $nots = []): array
  44. {
  45. if ($uuid > 0) {
  46. $total = abs(DataUserBalance::mk()->whereRaw("uuid='{$uuid}' and amount>0 and deleted=0")->sum('amount'));
  47. $count = abs(DataUserBalance::mk()->whereRaw("uuid='{$uuid}' and amount<0 and deleted=0")->sum('amount'));
  48. if (empty($nots)) {
  49. DataUser::mk()->where(['id' => $uuid])->update(['balance_total' => $total, 'balance_used' => $count]);
  50. } else {
  51. $count -= DataUserBalance::mk()->whereRaw("uuid={$uuid}")->whereIn('code', $nots)->sum('amount');
  52. }
  53. } else {
  54. $total = abs(DataUserBalance::mk()->whereRaw("amount>0 and deleted=0")->sum('amount'));
  55. $count = abs(DataUserBalance::mk()->whereRaw("amount<0 and deleted=0")->sum('amount'));
  56. }
  57. return [$total, $count];
  58. }
  59. }