ExtensionBalpayLogEntity.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\Balpay\Entity;
  4. use app\model\User;
  5. use SixShop\Core\Helper;
  6. use SixShop\Balpay\Enum\BalpayLogTypeEnum;
  7. use SixShop\Core\Entity\BaseEntity;
  8. use think\Paginator;
  9. /**
  10. * @mixin \SixShop\Balpay\Model\ExtensionBalpayLogModel
  11. */
  12. class ExtensionBalpayLogEntity extends BaseEntity
  13. {
  14. public function change(int $userID, float $amount, BalpayLogTypeEnum $type, string $description, int $orderID = 0): void
  15. {
  16. $user = User::withTrashed()->find($userID);
  17. if (!$user) {
  18. throw new \RuntimeException('用户不存在');
  19. }
  20. if ($type->negative()) {
  21. if ($user->balance < $amount) {
  22. Helper::throw_logic_exception('余额不足', status: 'not_enough_balance');
  23. }
  24. $user->dec('balance', $amount);
  25. $amount = -$amount;
  26. } else {
  27. $user->inc('balance', $amount);
  28. }
  29. $this->transaction(function () use ($user, $amount, $type, $description, $orderID) {
  30. $user->save();
  31. $this->create([
  32. 'user_id' => $user->id,
  33. 'order_id' => $orderID,
  34. 'amount' => $amount,
  35. 'type' => $type,
  36. 'description' => $description,
  37. 'balance' => $user->balance,
  38. ]);
  39. });
  40. }
  41. public function getList(int $user_id, ?BalpayLogTypeEnum $type, array $pageAndLimit): Paginator
  42. {
  43. return $this->where('user_id', $user_id)
  44. ->when($type, fn($query) => $query->where('type', $type))
  45. ->append(['type_text'])
  46. ->order('id', 'desc')
  47. ->paginate($pageAndLimit);
  48. }
  49. }