Goods.php
24.6 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
<?php
namespace addons\shopro\model;
use think\Model;
use addons\shopro\exception\Exception;
use addons\shopro\library\traits\ActivityCache;
use addons\shopro\model\GoodsSku;
use addons\shopro\model\GoodsSkuPrice;
use think\Db;
use traits\model\SoftDelete;
/**
* 商品模型
*/
class Goods extends Model
{
use SoftDelete, ActivityCache;
// 表名,不含前缀
protected $name = 'shopro_goods';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = 'deletetime';
protected $hidden = ['createtime', 'updatetime', 'status'];
//列表动态隐藏字段
protected static $list_hidden = ['content', 'params', 'images', 'service_ids'];
// 追加属性
protected $append = [
'dispatch_type_arr'
];
/**
* params 请求参数
* is_page 是否分页
*/
public static function getGoodsList($params, $is_page = true)
{
extract($params);
$where = [
'status' => 'up',
// 'id' => ['>',1], //现把ID为1的商品固定作为海报商品
];
//排序字段
if (isset($order) && $order !== '') {
$order = self::getGoodsListOrder($order);
}else{
$order = 'weigh desc';
}
if (isset($keywords) && $keywords !== '') {
$where['title|subtitle'] = ['like', "%$keywords%"];
// 记录搜索关键词
$user = User::info();
if($user->id){
$has = GoodsKeywords::where('user_id',$user->id)
->where('keywords',$keywords)
->find();
if(!$has){
$keywords_list = GoodsKeywords::order('createtime asc')->select();
// 超过10条的删除
if(count($keywords_list) > 10){
GoodsKeywords::where('id',$keywords_list[0]['id'])->delete();
}
GoodsKeywords::create([
'user_id' => $user->id,
'keywords' => $keywords
]);
}else{
$has->updatetime = time();
$has->save();
}
}
}
if (isset($goods_ids) && $goods_ids !== '') {
$goodsIdsArray = explode(',', $goods_ids);
$where['id'] = ['in', $goodsIdsArray];
}
$category_ids = [];
if (isset($category_id) && $category_id != 0) {
// 查询分类所有子分类,包括自己
$category_ids = Category::getCategoryIds($category_id);
}
$goods = self::where($where)->where(function ($query) use ($category_ids) {
// 所有子分类使用 find_in_set or 匹配,亲测速度并不慢
foreach($category_ids as $key => $category_id) {
$query->whereOrRaw("find_in_set($category_id, category_ids)");
}
});
// 过滤有活动的商品
if (isset($no_activity) && $no_activity) {
$goods = $goods->whereNotExists(function ($query) use ($where) {
$activityTableName = (new Activity())->getQuery()->getTable();
$goodsTableName = (new self())->getQuery()->getTable();
$query->table($activityTableName)->where("find_in_set(" . $goodsTableName . ".id, goods_ids)")->where('deletetime', 'null'); // 必须手动加上 deletetime = null
});
}
$goods = $goods->orderRaw($order);
$cacheKey = 'goodslist-' . ($is_page ? 'page' : 'all') . '-' . md5(json_encode($params));
// 判断缓存
$goodsCache = cache($cacheKey);
if ($goodsCache) {
// 存在缓存直接 返回
$goodsCache = json_decode($goodsCache, true);
return $goodsCache ? : [];
}
if ($is_page) {
$goods = $goods->paginate($per_page ?? 10);
$goodsData = $goods->items();
} else {
$goods = $goodsData = $goods->select();
}
$data = [];
if ($goodsData) {
$collection = collection($goodsData);
$data = $collection->hidden(self::$list_hidden);
// 处理活动
// load_relation($data, 'skuPrice'); // 只针对数组
$data->load('skuPrice'); // 延迟预加载
// if (!isset($no_activity) || !$no_activity) { // 没有 传入 no_activity 或者 no_activity = false
// 默认查询活动, no_activity 的时候这里也要执行一下,这里计算了销量规格等信息
foreach ($data as $key => $g) {
$data[$key] = self::operActivitySkuPrice($g, $g['sku_price']);
}
// }
}
if ($is_page) {
$goods->data = $data;
} else {
$goods = $data;
// 目前只缓存不分页的请求
cache($cacheKey, json_encode($goods), (600 + mt_rand(0, 300)));
}
return $goods;
}
public static function getGoodsListByIds($goodsIds)
{
$goodsIdsArray = explode(',', $goodsIds);
$where = [
'status' => 'up',
'deletetime' => null,
'id' => ['in', $goodsIdsArray]
];
$goods = self::where($where)->paginate(10);
if ($goods->items()) {
$collection = collection($goods->items());
$data = $collection->hidden(self::$list_hidden);
// 处理活动
// load_relation($data, 'skuPrice'); // 只针对数组
$data->load('skuPrice'); // 延迟预加载
foreach ($data as $key => $g) {
$data[$key] = self::operActivitySkuPrice($g, $g['sku_price']);
}
$goods->data = $data;
}
return $goods;
}
public static function getFavoriteGoodsList($type = 'normal', $status = 'up')
{
$where = [
'type' => $type,
'status' => $status,
'deletetime' => null,
];
$goods = self::where($where)->paginate(10);
if ($goods->items()) {
$collection = collection($goods->items());
$data = $collection->hidden(self::$list_hidden);
$goods->data = $data;
}
return $goods;
}
// 首页秒杀或拼团列表
public static function indexActivityGoodsList($where_type = 'seckill') {
$current_endtime = [
'hour' => 0,
'minute' => 0,
'second' => 0,
]; // 距本场结束时间
$soon_starttime = [
'hour' => 0,
'minute' => 0,
]; // 即将开抢时间
$tomorrow_start = strtotime(date('Y-m-d',strtotime('+1 day'))); //明日开始时间
$tomorrow_end = strtotime(date('Y-m-d',strtotime('+1 day'))) + 86400; //明日结束时间
$where['type'] = $where_type;
$activityList = Activity::where(array_merge([
'starttime' => ['<', time()],
'endtime' => ['>', time()]
],$where))->order('starttime')->select();
if(count($activityList) > 0){ //本场
$type = 'ing';
// 本场倒计时
$endtime_arr = array_column($activityList,'endtime');
$lefttime = min($endtime_arr) - time();
$lefttime = $lefttime > 0 ? $lefttime : 0;
$current_endtime = [
'hour' => $lefttime / (60*60) % 24,// 倒计时剩余的小时数
'minute' => $lefttime / 60 % 60,// 倒计时剩余的分钟数
'second' => $lefttime % 60,// 倒计时剩余的秒数
];
}else{ //下一场
$where['starttime'] = ['BETWEEN', [time(),$tomorrow_start]];
$activityList = Activity::where($where)->order('starttime')->select();
if(count($activityList) > 0){
$type = 'nostart';
$soon_starttime = [
'hour' => date('H', $activityList[0]['starttime']),
'minute' => date('i', $activityList[0]['starttime']),
];
}else{ //明日预告
$where['starttime'] = ['BETWEEN', [$tomorrow_start,$tomorrow_end]];
$activityList = Activity::where($where)->order('starttime')->select();
$type = 'tomorrow';
}
}
// 获取所有商品 id
$goodsIds = '';
foreach ($activityList as $key => $activity) {
$goodsIds .= ',' . $activity['goods_ids'];
}
if ($goodsIds) {
$goodsIds = trim($goodsIds, ',');
}
$goodsList = self::getGoodsListByIds($goodsIds);
$goodsList = $goodsList->toArray();
if($goodsList['total'] <= 0){
return [];
}
$goodsList = array_slice($goodsList['data'],0,4);
return compact('type','current_endtime','soon_starttime','goodsList');
}
// 获取秒杀商品列表
public static function getSeckillGoodsList($params) {
extract($params);
$type = $type ?? 'all';
if ((new self)->hasRedis()) {
// 如果有redis,读取 redis
$activityList = (new self)->getActivityList('seckill', $type);
} else {
$where = [
'type' => 'seckill'
];
$tomorrow_start = strtotime(date('Y-m-d',strtotime('+1 day'))); //明日开始时间
$tomorrow_end = strtotime(date('Y-m-d',strtotime('+1 day'))) + 86400; //明日结束时间
if ($type == 'ing') {
$where['starttime'] = ['<', time()];
$where['endtime'] = ['>', time()];
} else if ($type == 'nostart') {
$where['starttime'] = ['BETWEEN', [time(),$tomorrow_start]];
} else if ($type == 'ended') {
$where['endtime'] = ['<', time()];
} else if ($type == 'tomorrow') {
$where['starttime'] = ['BETWEEN', [$tomorrow_start,$tomorrow_end]];
}
$activityList = Activity::where($where)->select();
}
// 获取所有商品 id
$goodsIds = '';
foreach ($activityList as $key => $activity) {
$goodsIds .= ',' . $activity['goods_ids'];
}
if ($goodsIds) {
$goodsIds = trim($goodsIds, ',');
}
$goodsList = self::getGoodsListByIds($goodsIds);
return $goodsList;
}
// 获取拼团商品列表
public static function getGrouponGoodsList($params) {
extract($params);
$type = $type ?? 'all';
if ((new self)->hasRedis()) {
// 如果有redis,读取 redis
$activityList = (new self)->getActivityList('groupon', $type);
} else {
$where = [
'type' => 'groupon'
];
$tomorrow_start = strtotime(date('Y-m-d',strtotime('+1 day'))); //明日开始时间
$tomorrow_end = strtotime(date('Y-m-d',strtotime('+1 day'))) + 86400; //明日结束时间
if ($type == 'ing') {
$where['starttime'] = ['<', time()];
$where['endtime'] = ['>', time()];
} else if ($type == 'nostart') {
$where['starttime'] = ['BETWEEN', [time(),$tomorrow_start]];
} else if ($type == 'ended') {
$where['endtime'] = ['<', time()];
} else if ($type == 'tomorrow') {
$where['starttime'] = ['BETWEEN', [$tomorrow_start,$tomorrow_end]];
}
$activityList = Activity::where($where)->select();
}
// 获取所有商品 id
$goodsIds = '';
foreach ($activityList as $key => $activity) {
$goodsIds .= ',' . $activity['goods_ids'];
}
if ($goodsIds) {
$goodsIds = trim($goodsIds, ',');
}
$goodsList = self::getGoodsListByIds($goodsIds);
return $goodsList;
}
public static function getGoodsDetail($id)
{
$user = User::info();
$detail = (new self)->where('id', $id)->with(['favorite' => function ($query) use ($user) {
$user_id = empty($user) ? 0 : $user->id;
return $query->where(['user_id' => $user_id]);
}])->find();
if (!$detail || $detail->status === 'down') {
throw new Exception('商品不存在或已下架');
}
$detail = $detail->append(['service', 'sku', 'coupons']);
// 处理活动规格
$detail = self::operActivitySkuPrice($detail, $detail->sku_price);
return $detail;
}
/**
* 获取自提点
*/
public static function getGoodsStore($params) {
$user = User::info();
$id = $params['id'] ?? 0;
$latitude = $params['latitude'] ?? 0;
$longitude = $params['longitude'] ?? 0;
$detail = (new self)->where('id', $id)->find();
$selfetch = [];
if ($detail && strpos($detail['dispatch_type'], 'selfetch') !== false) {
// 商品支持自提,查询自提模板
$dispatch = Dispatch::where('type', 'selfetch')->where('id', 'in', $detail['dispatch_ids'])->find();
if ($dispatch) {
// 查询自提点模板
$dispatchSelfetch = DispatchSelfetch::where('id', 'in', $dispatch['type_ids'])
->order('id', 'asc')->find();
if ($dispatchSelfetch) {
// 查询自提点
$selfetch = Store::where('selfetch', 1)->where('id', 'in', $dispatchSelfetch['store_ids']);
if ($latitude && $longitude) {
$selfetch = $selfetch->field('*, ' . getDistanceBuilder($latitude, $longitude))->order('distance', 'asc');
}
$selfetch = $selfetch->select();
}
}
}
return $selfetch;
}
// 处理活动规格
public static function operActivitySkuPrice($detail, $sku_price) {
$activity = (new self)->getActivity($detail['id']);
// 原价
$prices = array_column($sku_price, 'price');
$detail['original_price'] = $prices ? min($prices) : 0;
// 会员价
$basicConfig = json_decode(\addons\shopro\model\Config::get(['name' => 'user'])->value, true);
$new_sku_price = [];
foreach ($sku_price as $s => $k) {
$new_sku_price[$s] = $k;
$new_sku_price[$s]['member_price'] = round($k['price'] * $basicConfig['discount'] / 10,2);
}
$sku_price = $new_sku_price;
$member_price = array_column($sku_price, 'member_price');
$detail['member_price'] = $member_price ? min($member_price) : 0;
if (!empty($activity)) {
switch ($activity['type']) {
case 'seckill':
$activity_goods_sku_price = $activity['activity_goods_sku_price'];
$new_sku_price = [];
foreach ($sku_price as $s => $k) {
$new_sku_price[$s] = $k;
$new_sku_price[$s]['stock'] = 0;
$new_sku_price[$s]['sales'] = 0;
foreach ($activity_goods_sku_price as $c) {
if ($k['id'] == $c['sku_price_id']) {
// 采用活动的 规格内容
$new_sku_price[$s]['stock'] = $c['stock'];
$new_sku_price[$s]['sales'] = $c['sales'];
$new_sku_price[$s]['price'] = $c['price'];
$new_sku_price[$s]['status'] = $c['status']; // 采用活动的上下架
// 记录相关活动类型
$new_sku_price[$s]['activity_type'] = $activity['type'];
$new_sku_price[$s]['activity_id'] = $activity['id'];
// 记录对应活动的规格的记录
$new_sku_price[$s]['item_goods_sku_price'] = $c;
break;
}
}
}
$sku_price = $new_sku_price;
break;
case 'groupon':
$activity_goods_sku_price = $activity['activity_goods_sku_price'];
$new_sku_price = [];
foreach ($sku_price as $s => $k) {
$new_sku_price[$s] = $k;
$new_sku_price[$s]['stock'] = 0;
$new_sku_price[$s]['sales'] = 0;
$new_sku_price[$s]['groupon_price'] = $k['price'];
foreach ($activity_goods_sku_price as $c) {
if ($k['id'] == $c['sku_price_id']) {
// 采用活动的 规格内容
$new_sku_price[$s]['stock'] = $c['stock'];
$new_sku_price[$s]['sales'] = $c['sales'];
$new_sku_price[$s]['groupon_price'] = $c['price']; // 不覆盖原来规格价格,用作单独购买,讲活动的价格设置为新的拼团价格
$new_sku_price[$s]['status'] = $c['status']; // 采用活动的上下架
// 记录相关活动类型
$new_sku_price[$s]['activity_type'] = $activity['type'];
$new_sku_price[$s]['activity_id'] = $activity['id'];
// 记录对应活动的规格的记录(不要了,减小响应包体积, 还得要,下单的时候需要存活动 的 sku_id)
$new_sku_price[$s]['item_goods_sku_price'] = $c;
break;
}
}
}
$sku_price = $new_sku_price;
break;
}
// 减小响应包体积
unset($activity['activity_goods_sku_price']);
}else{
// 会员价
$user = User::info();
if($user && $user->vip_end_time > time()){
$basicConfig = json_decode(\addons\shopro\model\Config::get(['name' => 'user'])->value, true);
$new_sku_price = [];
foreach ($sku_price as $s => $k) {
$new_sku_price[$s] = $k;
$new_sku_price[$s]['price'] = round($k['price'] * $basicConfig['discount'] / 10,2);
}
}
}
// 商品参与的活动
// 所有的都需要设置一下, 要不然找不到类的属性,如果不存在活动,则都是 null
$detail->activity = $activity ? : null;
$detail->activity_type = $activity['type'] ?? null;
// 移除下架的规格
foreach ($sku_price as $key => $sku) {
if ($sku['status'] != 'up') {
unset($sku_price[$key]);
}
}
// 展示金额用规格最小值
$prices = array_column($sku_price, 'price');
$detail['price'] = $prices ? min($prices) : 0; // min 里面不能是空数组
if ($activity) {
if ($activity['type'] == 'groupon') {
$grouponPrices = array_column($sku_price, 'groupon_price');
$detail['groupon_price'] = $grouponPrices ? min($grouponPrices) : 0;
}
$detail['sales'] = array_sum(array_column($sku_price, 'sales'));
} else {
// 正常商品加上显示销量
$detail['sales'] += $detail['show_sales'];
}
$detail['sku_price'] = array_values($sku_price);
$detail['stock'] = array_sum(array_column($sku_price, 'stock'));
return $detail;
}
public function getActivity($goods_id) {
if ($this->hasRedis()) {
// 如果有活动,读取 redis
$activity = $this->getGoodsActivity($goods_id);
return $activity;
}
// 没有配置 redis
$activity = Activity::where('find_in_set(:id,goods_ids)', ['id' => $goods_id])
->with(['activityGoodsSkuPrice' => function ($query) use ($goods_id) {
$query->where('goods_id', $goods_id)
->where('status', 'up');
}])
->where([
'deletetime' => null,
])->find();
return $activity;
}
public function getCouponsAttr($value, $data)
{
$goods_id = $data['id'];
$coupons = Coupons::where(function ($query) use ($goods_id) {
$query->where('find_in_set('. $goods_id .',goods_ids)')
->whereOr('goods_ids', 0);
})->select();
return $coupons;
}
protected function getSkuAttr($value, $data)
{
$sku = GoodsSku::all([
'goods_id'=>$data['id'],
'pid' => 0,
]);
foreach ($sku as $s => &$k) {
$sku[$s]['content'] = GoodsSku::all([
'goods_id' => $data['id'],
'pid' => $k['id']
]);
}
return $sku;
}
private static function getSkuPrice($value, $data)
{
return GoodsSkuPrice::all([
'goods_id' => $data['id'],
'status' => 'up',
'deletetime' => null
]);
}
public function getParamsAttr($value, $data)
{
return $value ? json_decode($value, true) : [];
}
public function getServiceAttr($value, $data)
{
$value = $data['service_ids'];
$serviceData = [];
if (!empty($value)) {
$serviceArray = explode(',', $value);
$serviceData = [];
foreach ($serviceArray as $v) {
$serviceData[] = \addons\shopro\model\GoodsService::get($v);
}
}
return $serviceData;
}
public function getImageAttr($value, $data)
{
if (!empty($value)) return cdnurl($value, true);
}
public function getImagesAttr($value, $data)
{
$imagesArray = [];
if (!empty($value)) {
$imagesArray = explode(',', $value);
$newImagesArray = [];
foreach ($imagesArray as $k => $v) {
$newImagesArray[$k]['url'] = cdnurl($v, true);
$info = pathinfo($v);
if(in_array($info['extension'],['jpg','png','bmp','jpeg','gif'])){
$newImagesArray[$k]['type'] = 'image';
}else{
$newImagesArray[$k]['type'] = 'video';
}
}
return $newImagesArray;
}
return $imagesArray;
}
public function getContentAttr($value, $data)
{
$content = $data['content'];
$content = str_replace("<img src=\"/uploads", "<img style=\"width: 100%;!important\" src=\"" . request()->domain() . "/uploads", $content);
$content = str_replace("<video src=\"/uploads", "<video style=\"width: 100%;!important\" src=\"" . request()->domain() . "/uploads", $content);
return $content;
}
public function getDispatchTypeArrAttr($value, $data)
{
return array_filter(explode(',', $data['dispatch_type']));
}
public function favorite()
{
return $this->hasOne(\addons\shopro\model\UserFavorite::class, 'goods_id', 'id');
}
public function scoreGoodsSkuPrice()
{
return $this->hasMany(\addons\shopro\model\scoreGoodsSkuPrice::class, 'goods_id', 'id')
->where('status', 'up')->order('id', 'asc');
}
public function skuPrice()
{
return $this->hasMany(\addons\shopro\model\GoodsSkuPrice::class, 'goods_id', 'id')
->order('id', 'asc');
}
//商品列表排序
private static function getGoodsListOrder($orderStr)
{
$order = 'weigh desc';
$orderList = json_decode(htmlspecialchars_decode($orderStr), true);
extract($orderList);
if (isset($defaultOrder) && $defaultOrder === 1) {
$order = 'weigh desc';
}
if (isset($priceOrder) && $priceOrder === 1) {
$order = "convert(`price`, DECIMAL(10, 2)) asc";
}elseif (isset($priceOrder) && $priceOrder === 2) {
$order = "convert(`price`, DECIMAL(10, 2)) desc";
}
if (isset($salesOrder) && $salesOrder === 1) {
$order = 'sales asc';
}elseif (isset($salesOrder) && $salesOrder === 2) {
$order = 'sales desc';
}
if (isset($newProdcutOrder) && $newProdcutOrder === 1){
$order = 'id desc';
}
return $order;
}
}