Score.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\model\Exchange;
  4. use app\common\model\ExchangeOrder;
  5. use app\common\model\ScoreLog;
  6. use app\common\model\Address;
  7. use think\Db;
  8. /**
  9. * 积分兑换接口
  10. */
  11. class Score extends Base
  12. {
  13. protected $noNeedLogin = ['exchangeList'];
  14. /**
  15. * 积分日志
  16. */
  17. public function logs()
  18. {
  19. $list = ScoreLog::where(['user_id' => $this->auth->id])
  20. ->order('id desc')
  21. ->paginate(10);
  22. $this->success('', $list);
  23. }
  24. /**
  25. * 积分兑换列表
  26. */
  27. public function exchangeList()
  28. {
  29. $this->success('获取成功', Exchange::tableList($this->request->param()));
  30. }
  31. /**
  32. * 积分兑换
  33. */
  34. public function exchange()
  35. {
  36. $address_id = $this->request->post('address_id/d');
  37. $memo = $this->request->post('memo');
  38. $nums = (int)$this->request->post('nums/d', 1);
  39. $exchange_id = $this->request->post('exchange_id/d');
  40. $row = Exchange::get($exchange_id);
  41. if (empty($row)) {
  42. $this->error('兑换物品不存在');
  43. }
  44. $data = [];
  45. if ($row->type == 'reality') {
  46. $address = Address::where('status', 'normal')->where('id', $address_id)->find();
  47. if (empty($address)) {
  48. $this->error('未找到正确地址');
  49. }
  50. if ($address->user_id != $this->auth->id) {
  51. $this->error('不能越权操作');
  52. }
  53. $data = array_merge($data, [
  54. 'receiver' => $address->receiver,
  55. 'mobile' => $address->mobile,
  56. 'address' => $address->address
  57. ]);
  58. }
  59. if ($nums <= 0) {
  60. $nums = 1;
  61. }
  62. $score = bcmul($nums, $row['score']);
  63. if ($this->auth->score < $score) {
  64. $this->error('积分不足,无法兑换');
  65. }
  66. // 启动事务
  67. Db::startTrans();
  68. try {
  69. $data = array_merge($data, [
  70. 'type' => $row->type,
  71. 'memo' => $memo,
  72. 'score' => $score,
  73. 'nums' => $nums,
  74. 'user_id' => $this->auth->id,
  75. 'exchange_id' => $exchange_id
  76. ]);
  77. ExchangeOrder::createOrder($data);
  78. $row->setDec('stocks');
  79. $row->setInc('sales');
  80. \app\common\model\User::score(-$score, $this->auth->id, '积分兑换商品');
  81. // 提交事务
  82. Db::commit();
  83. } catch (\Exception $e) {
  84. // 回滚事务
  85. Db::rollback();
  86. $this->error('提交失败');
  87. }
  88. $this->success('提交成功,等待管理员处理!');
  89. }
  90. /**
  91. * 我的积分兑换
  92. */
  93. public function myExchange()
  94. {
  95. $param = $this->request->param();
  96. $param['user_id'] = $this->auth->id;
  97. $this->success('获取成功', ExchangeOrder::tableList($param));
  98. }
  99. }