Blame view

addons/exam/model/ScoreGoodOrderModel.php 2.34 KB
2db47680   hexiaodong   chore: 初始提交 php 遗...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  <?php

  

  namespace addons\exam\model;

  

  use addons\exam\enum\ScoreGoodOrderStatus;

  use addons\exam\enum\UserScoreType;

  use think\Db;

  

  class ScoreGoodOrderModel extends \app\admin\model\exam\ScoreGoodOrderModel

  {

      protected $type = [

          'status' => 'integer',

      ];

  

      public function user()

      {

          return $this->belongsTo(UserModel::class, 'user_id', 'id');

      }

  

      public function good()

      {

          return $this->belongsTo(ScoreGoodModel::class, 'good_id', 'id');

      }

  

      /**

       * 兑换积分商品

       * @param int            $user_id

       * @param ScoreGoodModel $good

       * @param int            $quantity

       * @param string         $user_name

       * @param string         $phone

       * @param string         $address

       * @return mixed|void

       */

      public static function exchange($user_id, ScoreGoodModel $good, int $quantity, string $user_name, string $phone, string $address)

      {

          try {

              return Db::transaction(function () use ($user_id, $good, $quantity, $user_name, $phone, $address) {

                  // 兑换记录

                  $exchange = self::create([

                      'order_no'    => generate_no('SG'),

                      'user_id'     => $user_id,

                      'user_name'   => $user_name,

                      'phone'       => $phone,

                      'address'     => $address,

                      'good_id'     => $good->id,

                      'quantity'    => $quantity,

                      'name'        => $good->getData('name'),

                      'first_image' => $good->first_image,

                      'price'       => $good->price,

                      'amount'      => $good->price * $quantity,

                      'status'      => ScoreGoodOrderStatus::PAID,

                      'pay_time'    => time(),

                  ]);

  

                  // 减积分

                  UserScoreLogModel::decrement($user_id, $exchange->amount, UserScoreType::EXCHANGE, $exchange, "兑换商品");

  

                  // 减库存

                  ScoreGoodModel::decrement($good, $quantity);

                  // $good->setDec('stocks', $quantity);

  

                  return $exchange;

              });

          } catch (\Exception $exception) {

              fail('兑换失败,系统异常:' . $exception->getMessage());

          }

      }

  }