Goods.php
24.2 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
<?php
namespace app\admin\controller\shopro\goods;
use app\admin\model\shopro\activity\Activity;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
/**
* 商品
*
* @icon fa fa-circle-o
*/
class Goods extends Backend
{
/**
* Goods模型对象
* @var \app\admin\model\shopro\Goods
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\shopro\goods\Goods;
$this->view->assign("typeList", $this->model->getTypeList());
$this->view->assign("statusList", $this->model->getStatusList());
$this->view->assign("dispatchTypeList", $this->model->getDispatchTypeList());
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = false;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
// list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
$sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
$sort = $sort == 'price' ? 'convert(`price`, DECIMAL(10, 2))' : $sort;
$order = $this->request->get("order", "DESC");
$offset = $this->request->get("offset", 0);
$limit = $this->request->get("limit", 0);
$activity_type = $this->request->get("activity_type", 'all'); // 活动类型
$total = $this->buildSearchOrder()->count();
// 构建查询数据条件
$list = $this->buildSearchOrder();
$subsql = \app\admin\model\shopro\goods\SkuPrice::where('status', 'up')->field('sum(stock) as stock, goods_id')->group('goods_id')->buildSql();
$goodsTableName = $this->model->getQuery()->getTable();
// 关联规格表,获取总库存
$list = $list->join([$subsql => 'w'], $goodsTableName . '.id = w.goods_id', 'left');
// 关联查询当前商品的活动,一个商品可能存在多条活动记录,关联条件 只有 find_in_set 会存在一个商品出现多次,所以使用 group
$actSubSql = \app\admin\model\shopro\activity\Activity::field('type as activity_type, id as activity_id, goods_ids')->buildSql();
$list = $list->join([$actSubSql => 'act'], "find_in_set(" . $goodsTableName . ".id, goods_ids)", 'left')->group('id');
// 关联查询当前商品是否设置有积分
$scoreSubSql = \app\admin\model\shopro\app\ScoreSkuPrice::field("'score' as app_type, goods_id as score_goods_id")->group('score_goods_id')->buildSql();
$list = $list->join([$scoreSubSql => 'score'], $goodsTableName . '.id = score.score_goods_id', 'left');
$list = $list->orderRaw($sort . ' ' . $order)
->limit($offset, $limit)
->select();
foreach ($list as $row) {
$row->visible(['id', 'type', 'activity_id', 'activity_type', 'app_type', 'title', 'status', 'weigh', 'category_ids', 'image', 'price', 'likes', 'views', 'sales', 'stock', 'show_sales', 'dispatch_type', 'updatetime']);
}
$list = collection($list)->toArray();
$result = array("total" => $total, "rows" => $list);
if ($this->request->get("page_type") == 'select') {
return json($result);
}
return $this->success('操作成功', null, $result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$sku = $this->request->post("sku/a");
if ($params) {
$params = $this->preExcludeFields($params);
if (!$params['is_sku']) {
// 单规格,price 必须是数字
if (!preg_match('/^[0-9]+(.[0-9]{1,8})?$/', $params['price'])) {
$this->error("请填写正确的价格");
}
}else{
$params['price'] = 0;
}
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
$result = $this->model->validate('\app\admin\validate\shopro\Goods.add')->allowField(true)->save($params);
if (!$result) {
$this->error($this->model->getError());
}
$this->editSku($this->model, $sku, 'add');
// 多规格-把规格最小值作为商品价格
if($params['is_sku']){
// 把规格最小值作为商品价格
$skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $this->model->id]);
$this->model->save(['price'=>min(array_column($skuPrice,'price'))]);
}
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success("添加成功");
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 查看详情
*/
public function detail($ids = null) {
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$row->append(['category_ids_arr', 'params_arr', 'dispatch_group_ids_arr']);
$result = [];
if ($row['is_sku']) {
$skuList = \app\admin\model\shopro\goods\Sku::all(['pid' => 0, 'goods_id' => $ids]);
if ($skuList) {
foreach ($skuList as &$s) {
$s->children = \app\admin\model\shopro\goods\Sku::all(['pid' => $s->id, 'goods_id' => $ids]);
}
}
$result['skuList'] = $skuList;
$skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $ids]);
$result['skuPrice'] = $skuPrice;
} else {
// 将单规格的部分数据直接放到 row 上
$goodsSkuPrice = \app\admin\model\shopro\goods\SkuPrice::where('goods_id', $ids)->order('id', 'asc')->find();
$row['stock'] = $goodsSkuPrice['stock'] ?? 0;
$row['sn'] = $goodsSkuPrice['sn'] ?? "";
$row['weight'] = $goodsSkuPrice['weight'] ?? 0;
$result['skuList'] = [];
$result['skuPrice'] = [];
}
$result['detail'] = $row;
return $this->success('获取成功', null, $result);
}
/**
* 编辑
*/
public function edit($ids = null)
{
if(!$ids) {
$ids = $this->request->get('id');
}
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$row->updatetime = time();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$sku = $this->request->post("sku/a");
if ($params) {
$this->excludeFields = ['is_sku', 'type'];
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
$result = $row->validate('\app\admin\validate\shopro\Goods.edit')->allowField(true)->save($params);
if (!$result) {
$this->error($row->getError());
} else {
$this->editSku($row, $sku, 'edit');
// 多规格-把规格最小值作为商品价格
if($row['is_sku']){
// 把规格最小值作为商品价格
$skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $row->id]);
$row->save(['price'=>min(array_column($skuPrice,'price'))]);
}
Db::commit();
}
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success("编辑成功");
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
$skuList = \app\admin\model\shopro\goods\Sku::all(['pid' => 0, 'goods_id' => $ids]);
if ($skuList) {
foreach ($skuList as &$s) {
$s->children = \app\admin\model\shopro\goods\Sku::all(['pid' => $s->id, 'goods_id' => $ids]);
}
}
$this->assignconfig('skuList', $skuList);
$skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $ids]);
$this->assignconfig('skuPrice', $skuPrice);
return $this->view->fetch();
}
/**
* 删除
*/
public function del($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$id_arr = explode(',',$ids);
if(in_array(1,$id_arr)){
$this->error('禁止删除海报商品');
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
Db::startTrans();
try {
foreach ($list as $k => $v) {
$count += $v->delete();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
public function select()
{
if ($this->request->isAjax()) {
return $this->index();
}
$categoryModel = new \app\admin\model\shopro\Category;
$category = $categoryModel->with('children.children.children')->where('pid', 0)->order('weigh desc, id asc')->select();
$this->assignconfig('category', $category);
return $this->view->fetch();
}
public function setStatus($ids, $status) {
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
Db::startTrans();
try {
foreach ($list as $k => $v) {
$v->status = $status;
$count += $v->save();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
protected function editSku($goods, $sku, $type = 'add')
{
if ($goods['is_sku']) {
// 多规格
$this->editMultSku($goods, $sku, $type);
} else {
$this->editSimSku($goods, $sku, $type);
}
}
/**
* 添加编辑单规格
*/
protected function editSimSku($goods, $sku, $type = 'add') {
$params = $this->request->post("row/a");
$data = [
"goods_id" => $goods['id'],
"stock" => $params['stock'] ?? 0,
"sn" => $params['sn'] ?? "",
"weight" => $params['weight'] ? intval($params['weight']) : 0,
"price" => $params['price'] ?? 0,
"status" => 'up'
];
if ($type == 'add') {
$goodsSkuPrice = new \app\admin\model\shopro\goods\SkuPrice();
} else {
// 查询
$goodsSkuPrice = \app\admin\model\shopro\goods\SkuPrice::where('goods_id', $goods['id'])->order('id', 'asc')->find();
if (!$goodsSkuPrice) {
$goodsSkuPrice = new \app\admin\model\shopro\goods\SkuPrice();
}
}
$goodsSkuPrice->save($data);
}
/**
* 添加编辑多规格
*/
protected function editMultSku($goods, $sku, $type = 'add') {
$skuList = json_decode($sku['listData'], true);
$skuPrice = json_decode($sku['priceData'], true);
if (count($skuList) < 1) {
throw Exception('请填写规格列表');
}
foreach ($skuList as $key => $sku) {
if (count($sku['children']) <= 0) {
throw Exception('主规格至少要有一个子规格');
}
}
if (count($skuPrice) < 1) {
throw Exception('请填写规格价格');
}
foreach ($skuPrice as &$price) {
if (empty($price['price']) || $price['price'] == 0) {
throw Exception('请填写规格价格');
}
if ($price['stock'] === '') {
throw Exception('请填写规格库存');
}
if (empty($price['weight'])) {
$price['weight'] = 0;
}
}
// 编辑保存规格项
$allChildrenSku = $this->saveSkuList($goods, $skuList, $type);
if ($type == 'add') {
// 创建新产品,添加规格列表和规格价格
foreach ($skuPrice as $s3 => &$k3) {
$k3['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_temp_ids'], $allChildrenSku);
$k3['goods_id'] = $goods->id;
$k3['goods_sku_text'] = implode(',', $k3['goods_sku_text']);
$k3['weight'] = intval($k3['weight']);
$k3['createtime'] = time();
$k3['updatetime'] = time();
unset($k3['id']);
unset($k3['temp_id']); // 前端临时 id
unset($k3['goods_sku_temp_ids']); // 前端临时规格 id,查找真实 id 用
}
$res = \app\admin\model\shopro\goods\SkuPrice::insertAll($skuPrice);
} else {
// 编辑旧商品,先删除老的不用的 skuPrice
$oldSkuPriceIds = array_column($skuPrice, 'id');
// 删除当前商品老的除了在基础上修改的skuPrice
\app\admin\model\shopro\goods\SkuPrice::where('goods_id', $goods->id)
->where('id', 'not in', $oldSkuPriceIds)->delete();
foreach ($skuPrice as $s3 => &$k3) {
$data['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_temp_ids'], $allChildrenSku);
$data['goods_id'] = $goods->id;
$data['goods_sku_text'] = implode(',', $k3['goods_sku_text']);
$data['weigh'] = $k3['weigh'];
$data['image'] = $k3['image'];
$data['stock'] = $k3['stock'];
$data['sn'] = $k3['sn'];
$data['weight'] = intval($k3['weight']);
$data['price'] = $k3['price'];
$data['status'] = $k3['status'];
$data['createtime'] = time();
$data['updatetime'] = time();
if ($k3['id']) {
// 编辑
\app\admin\model\shopro\goods\SkuPrice::where('id', $k3['id'])->update($data);
} else {
// 新增数据
\app\admin\model\shopro\goods\SkuPrice::insert($data);
}
}
}
}
// 根据前端临时 temp_id 获取真实的数据库 id
private function checkRealIds($newGoodsSkuIds, $allChildrenSku)
{
$newIdsArray = [];
foreach ($newGoodsSkuIds as $id) {
$newIdsArray[] = $allChildrenSku[$id];
}
return implode(',', $newIdsArray);
}
// 差异更新 规格规格项(多的删除,少的添加)
private function saveSkuList($goods, $skuList, $type = 'add') {
$allChildrenSku = [];
if ($type == 'edit') {
// 删除无用老规格
// 拿出需要更新的老规格
$oldSkuIds = [];
foreach ($skuList as $key => $sku) {
$oldSkuIds[] = $sku['id'];
$childSkuIds = [];
if ($sku['children']) {
// 子项 id
$childSkuIds = array_column($sku['children'], 'id');
}
$oldSkuIds = array_merge($oldSkuIds, $childSkuIds);
$oldSkuIds = array_unique($oldSkuIds);
}
// 删除老的除了在基础上修改的规格项
\app\admin\model\shopro\goods\Sku::where('goods_id', $goods->id)->where('id', 'not in', $oldSkuIds)->delete();
}
foreach ($skuList as $s1 => &$k1) {
//添加主规格
if ($k1['id']) {
// 编辑
\app\admin\model\shopro\goods\Sku::where('id', $k1['id'])->update([
'name' => $k1['name'],
]);
$skuId[$s1] = $k1['id'];
} else {
// 新增
$skuId[$s1] = \app\admin\model\shopro\goods\Sku::insertGetId([
'name' => $k1['name'],
'pid' => 0,
'goods_id' => $goods->id
]);
}
$k1['id'] = $skuId[$s1];
foreach ($k1['children'] as $s2 => &$k2) {
if ($k2['id']) {
// 编辑
\app\admin\model\shopro\goods\Sku::where('id', $k2['id'])->update([
'name' => $k2['name'],
]);
$skuChildrenId[$s1][$s2] = $k2['id'];
} else {
$skuChildrenId[$s1][$s2] = \app\admin\model\shopro\goods\Sku::insertGetId([
'name' => $k2['name'],
'pid' => $k1['id'],
'goods_id' => $goods->id
]);
}
$allChildrenSku[$k2['temp_id']] = $skuChildrenId[$s1][$s2];
$k2['id'] = $skuChildrenId[$s1][$s2];
$k2['pid'] = $k1['id'];
}
}
return $allChildrenSku;
}
// 构建查询条件
private function buildSearchOrder()
{
$search = $this->request->get("search", ''); // 关键字
$status = $this->request->get("status", 'all');
$activity_type = $this->request->get("activity_type", 'all');
$app_type = $this->request->get("app_type", 'all');
$min_price = $this->request->get("min_price", "");
$max_price = $this->request->get("max_price", "");
$category_id = $this->request->get('category_id', 0);
$dealer_id = $this->request->get('dealer_id', 0);
$name = $this->model->getQuery()->getTable();
$tableName = $name . '.';
$goods = $this->model;
if ($search) {
// 模糊搜索字段
$searcharr = ['title', 'id'];
foreach ($searcharr as $k => &$v) {
$v = stripos($v, ".") === false ? $tableName . $v : $v;
}
unset($v);
$goods = $goods->where(function ($query) use ($searcharr, $search, $tableName) {
$query->where(implode("|", $searcharr), "LIKE", "%{$search}%");
});
}
$goods_ids = [];
// 活动
if ($activity_type != 'all') {
// 同一请求,会组装两次请求条件,缓存 10 秒
$activities = Activity::cache(10)->where('type', $activity_type)->column('goods_ids');
foreach ($activities as $key => $goods_id) {
$ids = explode(',', $goods_id);
$goods_ids = array_merge($goods_ids, $ids);
}
}
// 积分
if ($app_type == 'score') {
$score_goods_ids = \app\admin\model\shopro\app\ScoreSkuPrice::cache(10)->group('goods_id')->column('goods_id');
$goods_ids = array_merge($goods_ids, $score_goods_ids);
}
// 经销商
if(isset($dealer_id) && $dealer_id != 0) {
$dealer_goods_ids = \app\admin\model\dealer\DealerStock::alias('a')
->join('shopro_goods_sku_price b','a.sku_price_id = b.id')
->where('dealer_id',$dealer_id)
->column('a.goods_id');
$goods_ids = array_merge($goods_ids, $dealer_goods_ids);
}
$goods_ids = array_filter(array_unique($goods_ids));
if ($goods_ids) {
$goods = $goods->where('id', 'in', $goods_ids);
}
// 价格
if ($min_price != '') {
$goods = $goods->where('convert(`price`, DECIMAL(10, 2)) >= ' . round($min_price, 2));
}
if ($max_price != '') {
$goods = $goods->where('convert(`price`, DECIMAL(10, 2)) <= ' . round($max_price, 2));
}
// 商品状态
if ($status != 'all') {
$goods = $goods->where('status', $status);
}
if(isset($category_id) && $category_id != 0) {
$category_ids = [];
// 查询分类所有子分类,包括自己
$category_ids = \addons\shopro\model\Category::getCategoryIds($category_id);
$goods = $goods->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)");
}
});
}
return $goods;
}
}