quanwei
2025-11-28 3ea53e61cc23fdb3ddf8b38a199ca60a6da8c407
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
 
namespace app\common\model\plus\coupon;
 
//use think\Hook;
use app\common\model\BaseModel;
use app\common\model\plus\coupon\Coupon as CouponModel;
use app\common\model\store\Coupon as StoreCouponModel;
use app\supplier\model\supplier\Supplier as SupplierModel;
use app\common\model\order\OrderSettled as OrderSettledModel;
use app\common\model\supplier\Capital as SupplierCapitalModel;
 
/**
 * 用户优惠券模型
 */
class UserCoupon extends BaseModel
{
    protected $name = 'user_coupon';
    protected $pk = 'user_coupon_id';
 
    /**
     * 追加字段
     * @var array
     */
    protected $append = ['state'];
 
    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo('app\common\model\user\User');
    }
 
    /**
     * 关联优惠券表
     */
    public function coupon()
    {
        return $this->belongsTo('app\common\model\plus\coupon\Coupon');
    }
    /**
     * 关联供应商表
     */
    public function supplier()
    {
        return $this->belongsTo('app\\common\\model\\supplier\\Supplier', 'shop_supplier_id', 'shop_supplier_id')
            ->field(['shop_supplier_id', 'name']);
    }
 
    /**
     * 优惠券状态
     */
    public function getStateAttr($value, $data)
    {
        if ($data['is_use']) {
            return ['text' => '已使用', 'value' => 0];
        }
        if ($data['is_expire']) {
            return ['text' => '已过期', 'value' => 0];
        }
        return ['text' => '', 'value' => 1];
    }
 
    /**
     * 优惠券颜色
     */
    public function getColorAttr($value)
    {
        $status = [10 => 'blue', 20 => 'red', 30 => 'violet', 40 => 'yellow'];
        return ['text' => $status[$value], 'value' => $value];
    }
 
    /**
     * 优惠券类型
     */
    public function getCouponTypeAttr($value)
    {
        $status = [10 => '满减券', 20 => '折扣券', 30 => '兑换券'];
        return ['text' => $status[$value], 'value' => $value];
    }
 
    /**
     * 有效期-开始时间
     */
    public function getStartTimeAttr($value)
    {
        return ['text' => date('Y/m/d', $value), 'value' => $value];
    }
 
    /**
     * 有效期-结束时间
     */
    public function getEndTimeAttr($value)
    {
        return ['text' => date('Y/m/d', $value), 'value' => $value];
    }
 
    /**
     * 折扣率
     * @param $value
     * @return float|int
     */
    public function getDiscountAttr($value)
    {
        return $value / 10;
    }
 
    /**
     * 兑换券优惠项目转json by lyzflash
     * @param $value
     * @return json
     */
    public function setCouponProjectAttr($value)
    {
        return json_encode($value);
    }
 
    /**
     * 兑换券优惠项目转数组 by lyzflash
     * @param $value
     * @return array
     */
    public function getCouponProjectAttr($value)
    {
        return json_decode($value, true);
    }
 
    /**
     * 兑换券使用规则转json by lyzflash
     * @param $value
     * @return json
     */
    public function setCouponRuleAttr($value)
    {
        return json_encode($value);
    }
 
    /**
     * 兑换券使用规则转数组 by lyzflash
     * @param $value
     * @return array
     */
    public function getCouponRuleAttr($value)
    {
        return json_decode($value, true);
    }
 
    /**
     * 优惠券详情
     */
    public static function detail($coupon_id)
    {
        return (new static())->find($coupon_id);
        return $detail;
    }
 
    /**
     * 设置优惠券使用状态
     */
    public static function setIsUse($couponId, $isUse = true)
    {
        $model = new static();
        return $model->where(['user_coupon_id' => $couponId])->update(['is_use' => (int)$isUse]);
    }
 
    /**
     * 发卡领取优惠券
     * @param $coupon_ids
     * @param $user_id
     */
    public function addUserCardCoupon($coupons, $user, $order_id)
    {
        $model = new CouponModel();
        foreach ($coupons as $item) {
            $coupon = $model->where('coupon_id', '=', $item['coupon_id'])->find();
            // 计算有效期
            if ($coupon['expire_type'] == 10) {
                $start_time = time();
                $end_time = $start_time + ($coupon['expire_day'] * 86400);
            } else {
                $start_time = $coupon['start_time']['value'];
                $end_time = $coupon['end_time']['value'];
            }
            for ($i = 0; $i < $item['number']; $i++) {
                // 整理领取记录
                $data[] = [
                    'coupon_id' => $coupon['coupon_id'],
                    'name' => $coupon['name'],
                    'color' => $coupon['color']['value'],
                    'coupon_type' => $coupon['coupon_type']['value'],
                    'reduce_price' => $coupon['reduce_price'],
                    'discount' => $coupon['discount'],
                    'min_price' => $coupon['min_price'],
                    'expire_type' => $coupon['expire_type'],
                    'expire_day' => $coupon['expire_day'],
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'apply_range' => $coupon['apply_range'],
                    'user_id' => $user['user_id'],
                    'order_id' => $order_id,
                    'shop_supplier_id' => $coupon['shop_supplier_id'],
                    'app_id' => $user['app_id'],
                    // 返还金额
                    'back_money' => $coupon['back_money'],
                    // 兑换券价值金额
                    'product_price' => $coupon['product_price'],
                    // 兑换券使用次数 by lyzflash
                    'total_use_num' => $coupon['coupon_type']['value'] == 30 ? $coupon['total_use_num'] : 0,
                    'limit_use_num' => $coupon['coupon_type']['value'] == 30 ? $coupon['total_use_num'] : 0,
                    // 兑换券优惠项目
                    'coupon_project' => $coupon['coupon_project'],
                    // 使用规则
                    'coupon_rule' => $coupon['coupon_rule'],
                    // 每天核销上限
                    'verify_num' => $coupon['verify_num'],
                    // 优惠项目可用数量
                    'project_limit_num' => $coupon['project_limit_num'],
                    // 适用范围
                    'use_scope' => $coupon['use_scope'],
                ];
            }
        }
        $this->saveAll($data);
        return true;
    }
 
    /**
     * 撤销卡作废优惠券
     * @param $coupon_ids
     * @param $user_id
     */
    public function cancelUserCardCoupon($coupons, $user, $order_id)
    {
        foreach ($coupons as $item) {
            $data[] = [
                'data' => ['is_use' => 1],
                'where' => [
                    'coupon_id' => $item['coupon_id'],
                    'user_id' => $user['user_id'],
                    'order_id' => $order_id,
                ],
            ];
        }
        return $this->updateAll($data);
    }
 
    /**
     * 扣除兑换券使用次数
     * @param $user_coupon_id
     * @param $user_id
     */
    public static function setUseNum($user_coupon_id, $user_id, $num = 1)
    {
        // return (new self)->where('user_coupon_id', '=', $user_coupon_id)->where('user_id', '=', $user_id)->dec('limit_use_num', $num)->update();
        $model = static::detail($user_coupon_id);
        $data['limit_use_num'] = $model['limit_use_num'] - $num;
        if ($data['limit_use_num'] <= 0) {
            $data['limit_use_num'] = 0;
            $data['is_use'] = 1;
        }
        return $model->save($data);
    }
 
    /**
     * 返还兑换券使用次数
     * @param $user_coupon_id
     * @param $user_id
     */
    public static function backUseNum($user_coupon_id, $user_id, $num = 1)
    {
        // return (new self)->where('user_coupon_id', '=', $user_coupon_id)->where('user_id', '=', $user_id)->inc('limit_use_num', $num)->update();
        $model = static::detail($user_coupon_id);
        $data['limit_use_num'] = $model['limit_use_num'] + $num;
        if ($data['limit_use_num'] >= $model['total_use_num']) {
            $data['limit_use_num'] = $model['total_use_num'];
            $data['is_use'] = 0;
        }
        return $model->save($data);
    }
 
    /**
     * 确认核销(兑换券)
     */
    public function verificationOrder($extractClerkId, $project_id,$shop_supplier_id=0)
    {
        if ($this['is_use']) {
            $this->error = '该优惠券已使用';
            return false;
        }
        if ($this['coupon_type']["value"] == 30 && $this['limit_use_num'] <= 0) {
            $this->error = '该优惠券已使用';
            return false;
        }
        $time = time();
        if ($this['is_expire'] || $time > ($this['end_time']['value'] + 86400)) {
            $this->error = '该优惠券已过期';
            return false;
        }
        if ($time < $this['start_time']['value']) {
            $this->error = '该优惠券当前时间不可用';
            return false;
        }
        if (empty($extractClerkId)){
            $this->error = '核销人员不能为空';
            return false;
        }
        // 检查当天核销次数是否用完
        if($this['coupon_type']["value"] == 30){
            $verify_num = intval($this['coupon_project'][$project_id]['verify_num']);
            if ($verify_num && StoreCouponModel::getVerifyNum($this['user_coupon_id'], $project_id) >= $verify_num) {
                $this->error = '很抱歉,该券已达到当天核销上限';
                return false;
            }
        }
 
        return $this->transaction(function () use ($extractClerkId, $project_id,$shop_supplier_id) {
            // 更新优惠券可用次数
            static::setUseNum($this['user_coupon_id'], $this['user_id']);
 
            if($this['coupon_type']["value"] == 30){
                // 新增兑换券核销记录
                StoreCouponModel::add(
                    $this['user_coupon_id'],
                    $project_id,
                    $this['coupon_project'][$project_id]['cost_price'],
                    $this['extract_store_id'],
                    $extractClerkId,
                    $this['shop_supplier_id']
                );
            }else if($this['coupon_type']["value"] == 10){
                // 新增满减券核销记录
                StoreCouponModel::add(
                    $this['user_coupon_id'],
                    0,
                    $this['reduce_price'],
                    $this['extract_store_id'],
                    $extractClerkId,
                    $this['shop_supplier_id']
                );
                $this->addSupplierMoney($this,$this['reduce_price'],$shop_supplier_id);
            }
            return true;
        });
    }
 
    /**
     * 供应商金额=优惠券的抵扣金额 by yj 2024.1.16
     */
    private function addSupplierMoney($order,$add_supplier_money,$shop_supplier_id=0)
    {
        // 商家结算记录
        $supplierCapitalData = [
            'shop_supplier_id' => $shop_supplier_id,
            'money' => $add_supplier_money,
            'describe' => '优惠券核销结算,用户优惠券:' . $order['user_coupon_id'],
            'app_id' => $order['app_id']
        ];
        (new supplierModel())->where(['shop_supplier_id' => $shop_supplier_id])
            ->inc('total_money', $add_supplier_money)
            ->inc('money', $add_supplier_money)
            ->update();
        // 供应商结算明细金额
        (new SupplierCapitalModel())->save($supplierCapitalData);
        return true;
    }
 
}