Files
bsh_sample/app/admin/controller/SkuController.php
T

346 lines
11 KiB
PHP
Raw Normal View History

2025-12-08 17:37:34 +08:00
<?php
namespace app\admin\controller;
use app\common\controller\BaseController;
2025-12-11 17:25:10 +08:00
use app\common\model\PostCategory;
2025-12-13 16:35:34 +08:00
use app\common\model\Sku;
2025-12-13 10:48:51 +08:00
use app\common\model\SkuAttribute;
2025-12-11 14:17:24 +08:00
use app\common\service\OssService;
2025-12-15 14:07:07 +08:00
use app\common\service\UploadService;
2025-12-08 17:37:34 +08:00
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\SkuService;
2025-12-13 16:35:34 +08:00
use PhpOffice\PhpSpreadsheet\IOFactory;
2025-12-16 10:16:25 +08:00
use PhpOffice\PhpWord\IOFactory as WordIOFactory;
2025-12-13 16:35:34 +08:00
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use support\Db;
2025-12-09 15:33:21 +08:00
use support\Request;
2025-12-13 16:35:34 +08:00
use support\Response;
2025-12-16 10:16:25 +08:00
use ZipArchive;
2025-12-08 17:37:34 +08:00
class SkuController extends BaseController
{
use CrudControllerTrait;
2025-12-13 16:35:34 +08:00
protected $noNeedLogin = ['template'];
protected $noNeedHeaderData = ['template'];
2025-12-08 17:37:34 +08:00
protected $service;
public function __construct()
{
$this->service = new SkuService();
}
2025-12-09 15:33:21 +08:00
/**
* 创建
*
* @param Request $request 请求对象
* @return mixed 返回创建成功的数据或信息
*/
public function store(Request $request)
{
try {
$data = $this->validate($this->service->getValidator(), $request->post(), 'store');
$res = $this->service->serviceStore($request, $data);
return $this->success($res, '创建成功');
} catch (\Throwable $e) {
2025-12-11 14:17:24 +08:00
return $this->error($e->getMessage());
2025-12-09 15:33:21 +08:00
}
}
2025-12-08 17:37:34 +08:00
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
2025-12-09 15:33:21 +08:00
protected function indexFormat($data)
{
if (isset($data['created_at']))
$data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
if (isset($data['updated_at']))
$data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
2025-12-13 10:48:51 +08:00
if (isset($data['spec_json'])){
2025-12-10 14:59:41 +08:00
$data['spec'] = json_decode($data['spec_json'], true);
2025-12-13 10:48:51 +08:00
foreach ($data['spec'] as $k=>$v){
$data['spec'][$k]['attr_type'] = SkuAttribute::where('id', $v['attr_id'])->value('attr_type');
}
}
2025-12-11 17:25:10 +08:00
if (isset($data['category_id']))
$data['category_name'] = PostCategory::where('id', $data['category_id'])->value('name');
2025-12-11 14:17:24 +08:00
$ossservice = new OssService();
2025-12-12 14:15:24 +08:00
if (!empty($data['image'])){
2025-12-11 14:17:24 +08:00
$data['image'] = explode(',',$data['image']);
foreach ($data['image'] as $key => $image){
$data['image_pull'][$key] = $ossservice->generatePrivateUrl($image);
}
2025-12-12 14:15:24 +08:00
}else{
$data['image'] = [];
$data['image_pull'] = [];
2025-12-11 14:17:24 +08:00
}
2025-12-12 14:15:24 +08:00
if (!empty($data['main_image'])){
2025-12-11 14:17:24 +08:00
$data['main_image_pull'] = $ossservice->generatePrivateUrl($data['main_image']);
2025-12-12 14:15:24 +08:00
} else {
$data['main_image_pull'] = [];
}
2025-12-09 15:33:21 +08:00
return $data;
}
2025-12-13 16:35:34 +08:00
public function import(Request $request)
{
2025-12-16 10:16:25 +08:00
2025-12-13 16:35:34 +08:00
$file = $request->file('file');
if (!$file) return json(['code'=>1,'msg'=>'未上传文件']);
2025-12-16 10:16:25 +08:00
$zipPath = runtime_path('upload/' . uniqid() . '.zip');
$file->move($zipPath);
$extractTo = runtime_path('upload/import/' . uniqid());
$this->unzipPackage($zipPath,$extractTo);
@unlink($zipPath);
2025-12-13 16:35:34 +08:00
2025-12-16 10:16:25 +08:00
$path = runtime_path('upload/import/product.xlsx');
2025-12-13 16:35:34 +08:00
$spreadsheet = IOFactory::load($path);
$sheet = $spreadsheet->getActiveSheet();
// 提取图片(按行号)
2025-12-16 10:16:25 +08:00
//$rowImages = $this->extractImages($sheet);
2025-12-13 16:35:34 +08:00
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$header = $sheet->rangeToArray("A1:{$highestCol}1")[0];
2025-12-13 17:31:15 +08:00
// $header = array_map('trim', $header);
2025-12-13 16:35:34 +08:00
$allowFields = [
'product_name' => '产品名称',
'model' => '产品型号',
'brand' => '品牌',
'category_id' => '分类',
'price' => '价格',
2025-12-16 10:16:25 +08:00
//'spec_json' => '商品属性'
2025-12-13 16:35:34 +08:00
];
$fieldsName = array_flip($allowFields);
$insertData = [];
$now = time();
Db::beginTransaction();
2025-12-16 10:16:25 +08:00
$uploadService = new UploadService();
2025-12-13 16:35:34 +08:00
try {
for ($row = 2; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray(
"A{$row}:{$highestCol}{$row}", null, true, false
)[0];
$data = [];
foreach ($header as $i => $field) {
if (in_array($field, $allowFields)) {
$data[$fieldsName[$field]] = trim((string)($rowData[$i] ?? ''));
}
}
if (empty($data['product_name'])) {
continue;
}
$data['category_id'] = PostCategory::where('name', $rowData[3])->value('id')??0;
2025-12-16 10:16:25 +08:00
//商品属性
2025-12-15 14:07:07 +08:00
if(!empty($rowData[5])){
2025-12-15 14:52:43 +08:00
$speci = explode(';', $rowData[5]);
2025-12-15 14:45:16 +08:00
$spec = [];
foreach ($speci as $k => $v){
2025-12-15 14:52:43 +08:00
$item = explode(':', $v);
2025-12-15 14:12:13 +08:00
if (count($item) != 2) {
continue;
}
2025-12-15 14:07:07 +08:00
$attr = ['attr_name'=>$item[0],'attr_value'=>$item[1]];
2025-12-16 10:16:25 +08:00
$skuAttribute = SkuAttribute::where('attr_name', $item[0])
->where('category_id', $data['category_id'])->first();
2025-12-15 14:07:07 +08:00
if (empty($skuAttribute)) {
continue;
}
$attr['attr_id'] = $skuAttribute->id;
2025-12-16 10:16:25 +08:00
$attr['category_id'] = $data['category_id'];
2025-12-15 14:45:16 +08:00
$spec[] = $attr;
$data['spec_json'] = json_encode($spec);
2025-12-15 14:07:07 +08:00
}
}
2025-12-13 16:35:34 +08:00
2025-12-16 10:16:25 +08:00
//主图
if(!empty($rowData[6])){
$tmpPath = runtime_path('upload/import/main_pic/'.$rowData[6]);
$res = $uploadService->uploadLocalFile(['path' => $tmpPath, 'scene' => 'sku']);
$data['main_image'] = $res['file_url'];
}
//详情
if(!empty($rowData[7])){
$docxFullPath = runtime_path('upload/import/docs/'.$rowData[7]);
$data['desc'] =$this->docxToHtmlWithImages($docxFullPath);
}
2025-12-13 16:35:34 +08:00
$data['code'] = $this->service->generateUniqueCode();
$data['brand'] = $data['brand'] ?: '西门子';
$data['price'] = $data['price'] ?: 0;
$data['status'] = $data['status'] ?? 2;
// 图片
2025-12-16 10:16:25 +08:00
//$data['main_image'] = $rowImages[$row] ?? null;
2025-12-13 16:35:34 +08:00
$data['created_at'] = $now;
$data['updated_at'] = $now;
$insertData[] = $data;
if (count($insertData) >= 200) {
Sku::insert($insertData);
// Db::table('sku')->insert($insertData);
$insertData = [];
}
}
if ($insertData) {
Sku::insert($insertData);
// Db::table('sku')->insert($insertData);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollBack();
return $this->error($e->getMessage());
} finally {
@unlink($path);
}
return $this->success([], '导入成功');
}
2025-12-16 10:16:25 +08:00
/**
* 解压 zip 文件
*
* @param string $zipPath zip 文件绝对路径
* @param string $extractTo 解压目录
* @return bool
*/
function unzipPackage(string $zipPath, string $extractTo): bool
{
if (!file_exists($zipPath)) {
throw new \Exception('ZIP 文件不存在');
}
if (!is_dir($extractTo)) {
mkdir($extractTo, 0755, true);
}
$zip = new ZipArchive();
if ($zip->open($zipPath) !== true) {
throw new \Exception('ZIP 文件打开失败');
}
$zip->extractTo($extractTo);
$zip->close();
return true;
}
/**
* docx 转 HTML(自动上传图片到 OSS)
*
* @param string $docxPath docx 文件绝对路径
* @return string HTML
*/
function docxToHtmlWithImages(string $docxPath): string
{
if (!is_file($docxPath)) {
return '';
}
// 1. 读取 docx
$phpWord = WordIOFactory::load($docxPath);
// 2. 输出 HTML 到临时文件
$tmpHtml = runtime_path('tmp/' . uniqid() . '.html');
if (!is_dir(dirname($tmpHtml))) {
mkdir(dirname($tmpHtml), 0755, true);
}
$writer = WordIOFactory::createWriter($phpWord, 'HTML');
$writer->save($tmpHtml);
$html = file_get_contents($tmpHtml);
$uploadService = new UploadService();
// 3. 处理 HTML 中的图片
$html = preg_replace_callback(
'/<img[^>]+src="([^"]+)"[^>]*>/i',
function ($matches) use ($tmpHtml,$uploadService) {
$src = $matches[1];
// docx 导出的图片一般是相对路径
if (!str_starts_with($src, 'http')) {
$localImg = dirname($tmpHtml) . '/' . $src;
if (is_file($localImg)) {
// 上传到 OSS
$ossUrl = $uploadService->uploadLocalFile(['path' => $localImg, 'scene' => 'desc']);
return str_replace($src, $ossUrl, $matches[0]);
}
}
return $matches[0];
},
$html
);
// 清理临时文件
@unlink($tmpHtml);
return $html;
}
2025-12-13 16:35:34 +08:00
private function extractImages($sheet): array
{
$images = [];
2025-12-15 14:07:07 +08:00
$uploadService = new UploadService();
2025-12-13 16:35:34 +08:00
foreach ($sheet->getDrawingCollection() as $drawing) {
if ($drawing instanceof Drawing) {
2025-12-15 14:07:07 +08:00
// 取行号
2025-12-13 16:35:34 +08:00
preg_match('/\d+/', $drawing->getCoordinates(), $m);
$row = (int)$m[0];
2025-12-15 14:07:07 +08:00
// Excel 临时图片路径
$tmpPath = $drawing->getPath();
if (!is_file($tmpPath)) {
continue;
}
2025-12-13 16:35:34 +08:00
2025-12-15 14:07:07 +08:00
// 上传到 OSS
$ossUrl = $uploadService->uploadLocalFile(['path' => $tmpPath, 'scene' => 'sku']);
2025-12-13 16:35:34 +08:00
2025-12-15 14:07:07 +08:00
// 一行只保留一张主图
$images[$row] = $ossUrl['file_url'];
2025-12-13 16:35:34 +08:00
}
}
2025-12-15 14:07:07 +08:00
2025-12-13 16:35:34 +08:00
return $images;
}
/**
* 下载 Excel 示例模板
*/
public function template(Request $request): Response
{
2025-12-13 17:26:43 +08:00
$filePath = runtime_path() . '/upload/import.xlsx';
2025-12-13 16:35:34 +08:00
if (!file_exists($filePath)) {
return response('文件不存在', 404);
}
return response()->download(
$filePath,
'导入示例.xlsx' // 下载时显示的文件名
);
}
2025-12-08 17:37:34 +08:00
}