forked from summerblue/laravel-shop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOrder.php
123 lines (106 loc) · 3.3 KB
/
Order.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
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
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
class Order extends Model
{
const REFUND_STATUS_PENDING = 'pending';
const REFUND_STATUS_APPLIED = 'applied';
const REFUND_STATUS_PROCESSING = 'processing';
const REFUND_STATUS_SUCCESS = 'success';
const REFUND_STATUS_FAILED = 'failed';
const SHIP_STATUS_PENDING = 'pending';
const SHIP_STATUS_DELIVERED = 'delivered';
const SHIP_STATUS_RECEIVED = 'received';
public static $refundStatusMap = [
self::REFUND_STATUS_PENDING => '未退款',
self::REFUND_STATUS_APPLIED => '已申请退款',
self::REFUND_STATUS_PROCESSING => '退款中',
self::REFUND_STATUS_SUCCESS => '退款成功',
self::REFUND_STATUS_FAILED => '退款失败',
];
public static $shipStatusMap = [
self::SHIP_STATUS_PENDING => '未发货',
self::SHIP_STATUS_DELIVERED => '已发货',
self::SHIP_STATUS_RECEIVED => '已收货',
];
protected $fillable = [
'no',
'address',
'total_amount',
'remark',
'paid_at',
'payment_method',
'payment_no',
'refund_status',
'refund_no',
'closed',
'reviewed',
'ship_status',
'ship_data',
'extra',
];
protected $casts = [
'closed' => 'boolean',
'reviewed' => 'boolean',
'address' => 'json',
'ship_data' => 'json',
'extra' => 'json',
];
protected $dates = [
'paid_at',
];
protected static function boot()
{
parent::boot();
// 监听模型创建事件,在写入数据库之前触发
static::creating(function ($model) {
// 如果模型的 no 字段为空
if (!$model->no) {
// 调用 findAvailableNo 生成订单流水号
$model->no = static::findAvailableNo();
// 如果生成失败,则终止创建订单
if (!$model->no) {
return false;
}
}
});
}
public function user()
{
return $this->belongsTo(User::class);
}
public function items()
{
return $this->hasMany(OrderItem::class);
}
public function couponCode()
{
return $this->belongsTo(CouponCode::class);
}
public static function findAvailableNo()
{
// 订单流水号前缀
$prefix = date('YmdHis');
for ($i = 0; $i < 10; $i++) {
// 随机生成 6 位的数字
$no = $prefix.str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
// 判断是否已经存在
if (!static::query()->where('no', $no)->exists()) {
return $no;
}
usleep(100);
}
Log::warning(sprintf('find order no failed'));
return false;
}
public static function getAvailableRefundNo()
{
do {
// Uuid类可以用来生成大概率不重复的字符串
$no = Uuid::uuid4()->getHex();
// 为了避免重复我们在生成之后在数据库中查询看看是否已经存在相同的退款订单号
} while (self::query()->where('refund_no', $no)->exists());
return $no;
}
}