RechargeService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: king
  5. * Date: 2018/10/22
  6. * Time: 下午4:19
  7. */
  8. namespace app\common\services\point;
  9. use app\common\exceptions\ShopException;
  10. use app\common\models\point\RechargeModel;
  11. use app\common\services\finance\PointService;
  12. use Illuminate\Support\Facades\DB;
  13. class RechargeService
  14. {
  15. /**
  16. * @var RechargeModel
  17. */
  18. private $rechargeModel;
  19. public function __construct(RechargeModel $rechargeModel)
  20. {
  21. $this->rechargeModel = $rechargeModel;
  22. }
  23. public function tryRecharge()
  24. {
  25. DB::transaction(function () {
  26. $this->_tryRecharge();
  27. });
  28. return true;
  29. }
  30. /**
  31. * @throws ShopException
  32. */
  33. private function _tryRecharge()
  34. {
  35. $result = $this->updateMemberPoint();
  36. if (!$result) {
  37. throw new ShopException('充值失败:更新数据失败');
  38. }
  39. $result = $this->updateRechargeStatus();
  40. if (!$result) {
  41. throw new ShopException('充值失败:修改充值状态失败');
  42. }
  43. }
  44. /**
  45. * @return PointService|bool
  46. * @throws ShopException
  47. */
  48. private function updateMemberPoint()
  49. {
  50. return (new PointService($this->getChangeData()))->changePoint();
  51. }
  52. /**
  53. * @return bool
  54. */
  55. private function updateRechargeStatus()
  56. {
  57. $this->rechargeModel->status = RechargeModel::STATUS_SUCCESS;
  58. return $this->rechargeModel->save();
  59. }
  60. /**
  61. * @return array
  62. */
  63. private function getChangeData()
  64. {
  65. return [
  66. 'point_mode' => PointService::POINT_MODE_ADMIN,
  67. 'member_id' => $this->rechargeModel->member_id,
  68. 'point' => $this->rechargeModel->money,
  69. 'remark' => $this->rechargeRemark(),
  70. 'point_income_type' => $this->pointIncomeType()
  71. ];
  72. }
  73. /**
  74. * @return string
  75. */
  76. private function rechargeRemark()
  77. {
  78. return "充值变动['{$this->rechargeModel->money}']积分,充值记录ID【{$this->rechargeModel->id}】";
  79. }
  80. /**
  81. * @return int
  82. */
  83. private function pointIncomeType()
  84. {
  85. return $this->rechargeModel->money < 0 ? PointService::POINT_INCOME_LOSE : PointService::POINT_INCOME_GET;
  86. }
  87. }