Litestoregoods.php
21.5 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
<?php
namespace app\admin\controller\litestore;
use app\admin\model\litestore\Litestoregoodsspec;
use app\common\controller\Backend;
use app\admin\model\litestore\Litestorespec as SpecModel;
use app\admin\model\litestore\Litestorespecvalue as SpecValueModel;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
/**
*
*
* @icon fa fa-circle-o
*/
class Litestoregoods extends Backend
{
private $SpecModel;
private $SpecValueModel;
/**
* Litestoregoods模型对象
* @var \app\admin\model\litestore\Litestoregoods
*/
protected $model = null;
protected $spec_model = null;
public function _initialize()
{
parent::_initialize();
$this->SpecModel = new SpecModel;
$this->SpecValueModel = new SpecValueModel;
$this->model = new \app\admin\model\litestore\Litestoregoods;
$this->spec_model = new \app\admin\model\litestore\Litestoregoodsspec();
$this->view->assign("specTypeList", $this->model->getSpecTypeList());
$this->view->assign("deductStockTypeList", $this->model->getDeductStockTypeList());
$this->view->assign("goodsStatusList", $this->model->getGoodsStatusList());
$this->view->assign("isDeleteList", $this->model->getIsDeleteList());
$this->view->assign("makeforList", $this->model->getMakeforList());
$this->view->assign("isIndexList", $this->model->getIsIndexList());
$this->view->assign("spec_attr", '');
$this->view->assign("spec_list", '');
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$total = $this->model
->with(['category', 'activity'])
->where($where)
->order($sort, $order)
->count();
$list = $this->model
->with(['category', 'activity'])
->where($where)
->order($sort, $order)
->limit($offset, $limit)
->select();
foreach ($list as $row) {
$row->getRelation('category')->visible(['name']);
$row->getRelation('activity')->visible(['name']);
// $row->getRelation('freight')->visible(['name']);
$row->stock_num = Litestoregoodsspec::where('goods_id', $row['goods_id'])->sum('stock_num');
}
$list = collection($list)->toArray();
$result = array("total" => $total, "rows" => $list);
return json($result);
}
$this->assign('template', $this->request->domain() . '/static/template/商品导入模板.xlsx');
return $this->view->fetch();
}
public function addSpec($spec_name, $spec_value)
{
// 判断规格组是否存在
if (!$specId = $this->SpecModel->getSpecIdByName($spec_name)) {
// 新增规格组and规则值
if ($this->SpecModel->add($spec_name)
&& $this->SpecValueModel->add($this->SpecModel['id'], $spec_value))
return $this->success('', '', [
'spec_id' => (int)$this->SpecModel['id'],
'spec_value_id' => (int)$this->SpecValueModel['id'],
]);
return $this->error();
}
//return ;
// 判断规格值是否存在
if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value)) {
return $this->success('', '', [
'spec_id' => (int)$specId,
'spec_value_id' => (int)$specValueId,
]);
}
// 添加规则值
if ($this->SpecValueModel->add($specId, $spec_value))
return $this->success('', '', [
'spec_id' => (int)$specId,
'spec_value_id' => (int)$this->SpecValueModel['id'],
]);
return $this->error();
}
/**
* 添加规格值
*/
public function addSpecValue($spec_id, $spec_value)
{
// 判断规格值是否存在
if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value)) {
return $this->success('', '', [
'spec_value_id' => (int)$specValueId,
]);
}
// 添加规则值
if ($this->SpecValueModel->add($spec_id, $spec_value))
return $this->success('', '', [
'spec_value_id' => (int)$this->SpecValueModel['id'],
]);
return $this->error();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
if ($params['spec_type'] == '20' && !$this->request->post("spec_many/a")) {
$this->error('请添加规格');
}
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
$this->model->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
if ($result !== false) {
//成功之后 存储商品规格
$spec_many_params = $this->request->post("spec_many/a");
$this->model->addGoodsSpec($params, $spec_many_params, $this->request->post("spec/a"));
$this->success();
} else {
$this->error($this->model->getError());
}
} catch (\think\exception\PDOException $e) {
$this->error($e->getMessage());
} catch (\think\Exception $e) {
$this->error($e->getMessage());
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 删除
*/
public function del($ids = "")
{
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$count = $this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
foreach ($list as $k => $v) {
// 删除商品sku
$v->removesku();
$count += $v->delete();
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
/**
* 编辑
*/
public function edit($ids = NULL)
{
$row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
if (!$row)
$this->error(__('No Results were found'));
$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");
if ($params) {
if ($params['spec_type'] == '20' && !$this->request->post("spec_many/a")) {
$this->error('请添加规格');
}
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = basename(str_replace('\\', '/', get_class($this->model)));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
$row->validate($validate);
}
$result = $row->allowField(true)->save($params);
if ($result !== false) {
//成功之后 存储商品规格
$spec_many_params = $this->request->post("spec_many/a");
$row->addGoodsSpec($params, $spec_many_params, $this->request->post("spec/a"), true);
// 删除购物车
Db::name('cart')->where('goods_id', $row->goods_id)->delete();
//删除我常买
Db::name('user_buylist')->where('goods_id', $row->goods_id)->delete();
$this->success();
} else {
$this->error($row->getError());
}
} catch (\think\exception\PDOException $e) {
$this->error($e->getMessage());
} catch (\think\Exception $e) {
$this->error($e->getMessage());
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
// 多规格信息
$specData = 'null';
if ($row['spec_type'] === '20') {
$specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
}
$row['specData'] = $specData;
$this->view->assign("row", $row);
return $this->view->fetch();
}
/**
* 导出
*/
public function export()
{
//1.从数据库中导出需要进行要导出的数据
$list = Db::name('litestore_goods_spec')->alias('c')
->join('fa_litestore_goods g', 'g.goods_id = c.goods_id', 'LEFT')
->select();
$list = collection($list)->toArray();
foreach ($list as &$item) {
$item['category_name'] = Db::name('litestore_category')->where('id', $item['category_id'])->value('name');
if (!empty($item['spec_sku_id'])) {
$sku_value = explode('_', $item['spec_sku_id']);
if (count($sku_value) > 1) {
$key = Db::name('litestore_spec_value')->where('id', $sku_value[0])->value('spec_value');
$value = Db::name('litestore_spec_value')->where('id', $sku_value[1])->value('spec_value');
$item['sku_value'] = $key . '_' . $value;
} else {
$key = Db::name('litestore_spec_value')->where('id', $sku_value[0])->value('spec_value');
$item['sku_value'] = $key;
}
} else {
$item['sku_value'] = '';
}
}
if (empty($list)) {
$this->error('没有可导出的数据');
}
//重要补助
//2.加载PHPExcle类库
vendor('PHPExcel.PHPExcel');
//3.实例化PHPExcel类
$objPHPExcel = new \PHPExcel();
//4.激活当前的sheet表
$objPHPExcel->setActiveSheetIndex(0);
//5.设置表格头(即excel表格的第一行)
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', '商品ID')
->setCellValue('B1', '商品名称')
->setCellValue('C1', '搜索关键词')
->setCellValue('D1', '分类名称')
->setCellValue('E1', '活动名称(新人用户=1,限时秒杀=2,进口商品=4)')
->setCellValue('F1', '商品规格(10=单规格,20=多规格)')
->setCellValue('G1', '库存')
->setCellValue('H1', '商品规格')
->setCellValue('I1', '商品原价')
->setCellValue('J1', '折扣')
->setCellValue('K1', '商品现价')
->setCellValue('L1', '已销数量')
->setCellValue('M1', '商品状态(10=上架,20=下架)')
->setCellValue('N1', '首页展示(0=未展示,1=已展示)')
->setCellValue('O1', '导出时间');
//设置A列水平居中
$objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//设置单元格宽度
//6.循环刚取出来的数组,将数据逐一添加到excel表格。
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('L')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('M')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('N')->setWidth(20);
$objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('O')->setWidth(20);
for ($i = 0; $i < count($list); $i++) {
$objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['goods_id']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['goods_name']);//商品名称
$objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['keywords']);//商品规格
$objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['category_name']);//原价
$objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['activity_id']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['spec_type']);//标签码
$objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['stock_num']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $list[$i]['sku_value']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $list[$i]['line_price']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), $list[$i]['discount']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('K' . ($i + 2), $list[$i]['goods_price']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('L' . ($i + 2), $list[$i]['goods_sales']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('M' . ($i + 2), $list[$i]['goods_status']);//ID
$objPHPExcel->getActiveSheet()->setCellValue('N' . ($i + 2), $list[$i]['is_index']);//标签码
$objPHPExcel->getActiveSheet()->setCellValue('O' . ($i + 2), datetime(time()));//标签码
}
ob_end_clean();
ob_start();
$title = '商品列表';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition:attachment;filename="' . $title . '.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output'); //文件通过浏览器下载
exit();
}
/**
*导入
*
* */
public function import()
{
$file = $this->request->request('file');
if (!$file) {
$this->error(__('Parameter %s can not be empty', 'file'));
}
$filePath = ROOT_PATH . DS . 'public' . DS . $file;
if (!is_file($filePath)) {
$this->error(__('No results were found'));
}
//实例化reader
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
$this->error(__('Unknown data format'));
}
if ($ext === 'csv') {
$file = fopen($filePath, 'r');
$filePath = tempnam(sys_get_temp_dir(), 'import_csv');
$fp = fopen($filePath, "w");
$n = 0;
while ($line = fgets($file)) {
$line = rtrim($line, "\n\r\0");
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
if ($encoding != 'utf-8') {
$line = mb_convert_encoding($line, 'utf-8', $encoding);
}
if ($n == 0 || preg_match('/^".*"$/', $line)) {
fwrite($fp, $line . "\n");
} else {
fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
}
$n++;
}
fclose($file) || fclose($fp);
$reader = new Csv();
} elseif ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
}
set_time_limit(0);
//加载文件
$insert = [];
try {
if (!$PHPExcel = $reader->load($filePath)) {
$this->error(__('Unknown data format'));
}
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
$maxColumnNumber = Coordinate::columnIndexFromString($allColumn); // 一共多少列
for ($i = 2; $i <= $allRow; $i++) {
if (!empty($PHPExcel->getActiveSheet()->getCell("A" . $i)->getValue())) {
$insert[$i]['goods_name'] = $PHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();//商品名称
$insert[$i]['keywords'] = $PHPExcel->getActiveSheet()->getCell("B" . $i)->getValue();//关键词
$category = $PHPExcel->getActiveSheet()->getCell("C" . $i)->getValue() ?? '';//类别
$insert[$i]['category_id'] = Db::name('litestore_category')->where('name', $category)->value('id') ?? '';
$insert[$i]['activity_id'] = $PHPExcel->getActiveSheet()->getCell("D" . $i)->getValue() ?? '';//活动类型
$insert[$i]['is_index'] = $PHPExcel->getActiveSheet()->getCell("I" . $i)->getValue() ?? '';//是否首页
$insert[$i]['goods_status'] = $PHPExcel->getActiveSheet()->getCell("H" . $i)->getValue() ?? '';//商品状态
$spec_insert[$i]['stock_num'] = $PHPExcel->getActiveSheet()->getCell("E" . $i)->getValue() ?? '';//库存
$spec_insert[$i]['goods_price'] = $PHPExcel->getActiveSheet()->getCell("G" . $i)->getValue() ?? '';//现价
$spec_insert[$i]['line_price'] = $PHPExcel->getActiveSheet()->getCell("F" . $i)->getValue() ?? '';//原价
}
}
} catch (\Exception $exception) {
$this->error($exception->getMessage());
}
if (!$insert) {
$this->error(__('No rows were updated'));
}
try {
$res_goods = $this->model->saveAll($insert);
foreach ($spec_insert as $key => &$v) {
$v['goods_id'] = $res_goods[$key]['goods_id'];
}
unset($v);
$this->spec_model->saveAll($spec_insert);
} catch (PDOException $exception) {
$msg = $exception->getMessage();
if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
$msg = "导入失败,包含【{$matches[1]}】的记录已存在";
};
$this->error($msg);
} catch (\Exception $e) {
$this->error($e->getMessage());
}
$this->success();
}
}