| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use think\Db;
- class Product extends Api
- {
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- /**
- * 商户菜单
- * @return void
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function merchantGetab()
- {
- if (!$this->request->isGet()) {
- $this->error('请求错误');
- }
- $list = \db('product_merchant')
- ->where([
- 'status' => 1,
- 'deleteTime' => null,
- ])
- ->field('merchant_code,merchant_name')
- ->select();
- foreach ($list as $k => $v) {
- $list[$k]['tab'] = $v['merchant_name'].'('.$v['merchant_code'].')';
- }
- if (empty($list)) {
- $this->error('未找到商户数据');
- }else{
- $this->success('成功', $list);
- }
- }
- /**
- * 产品列表
- * @return void
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function productList()
- {
- // 1. 请求方法验证优化
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $param = $this->request->param();
- // 2. 参数验证优化
- if (empty($param['code']) || !is_string($param['code'])) {
- $this->error('商户编码参数错误');
- }
- // 3. 参数安全处理
- $merchantCode = trim($param['code']);
- $searchKeyword = isset($param['search']) ? trim($param['search']) : '';
- // 4. 分页参数处理
- $page = isset($param['page']) ? intval($param['page']) : 1;
- $pageSize = isset($param['pageSize']) ? intval($param['pageSize']) : 15;
- // 验证分页参数
- if ($page < 1) $page = 1;
- if ($pageSize < 1 || $pageSize > 100) $pageSize = 15; // 限制最大每页100条
- // 5. 构建查询条件
- $where = [
- 'b.merchant_code' => $merchantCode
- ];
- if (!empty($searchKeyword)) {
- // 使用更安全的查询方式
- $where['a.product_name|a.product_code'] = ['like', '%' . addslashes($searchKeyword) . '%'];
- }
- // 6. 查询数据(带分页)
- try {
- // 首先获取总记录数
- $total = \db('product')
- ->alias('a')
- ->join('product_merchant b', 'a.merchant_id = b.id')
- ->where('a.deleteTime', null)
- ->where($where)
- ->count();
- // 分页查询
- $list = \db('product')
- ->alias('a')
- ->join('product_merchant b', 'a.merchant_id = b.id')
- ->where($where)
- ->field([
- 'a.product_name as 产品名称',
- 'a.product_code as 产品编码',
- 'a.product_img',
- 'a.deleteTime',
- 'a.product_new_img',
- 'a.createTime as 创建时间',
- 'a.create_name as 创建人',
- 'b.merchant_code as 商户编码',
- 'a.id'
- ])
- ->where('a.deleteTime', null)
- ->order('a.createTime', 'desc')
- ->page($page, $pageSize)
- ->select();
- } catch (\Exception $e) {
- $this->error('查询数据失败:' . $e->getMessage());
- }
- // 7. 优化数据处理逻辑
- if (!empty($list)) {
- foreach ($list as &$item) {
- // 产品图片
- if (!empty($item['product_img'])) {
- $item['产品图片'] = ltrim($item['product_img'], '/');
- unset($item['product_img']); // 移除原始字段
- } else {
- $item['产品图片'] = ''; // 设置默认值
- }
- // 产品效果图
- if (!empty($item['product_new_img'])) {
- $item['产品效果图'] = ltrim($item['product_new_img'], '/');
- unset($item['product_new_img']); // 移除原始字段
- } else {
- $item['产品效果图'] = ''; // 设置默认值
- }
- }
- unset($item); // 解除引用
- }
- $result = [
- 'list' => $list,
- 'total' => $total,
- ];
- // 10. 统一返回格式
- $this->success('查询成功', $result);
- }
- /**
- * 产品原图图片上传
- * @return \think\response\Json|void
- */
- public function ImgUpload()
- {
- // 处理 CORS OPTIONS 预检请求
- if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Methods: POST, OPTIONS');
- header('Access-Control-Allow-Headers: Content-Type, Authorization');
- header('Access-Control-Max-Age: 86400');
- exit(204);
- }
- // 实际请求必须返回 CORS 头
- header('Access-Control-Allow-Origin: *');
- // 获取上传的文件
- $file = request()->file('image');
- $param = $this->request->param();
- if ($file) {
- // 生成日期格式的文件夹名 image_YYYYMMDD
- $dateFolder = 'image_' . date('Ymd');
- // 指定目标目录(包含日期文件夹)
- $targetPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'merchant' . DS . $param['merchant_code'] . DS . $param['product_code'] . DS . 'oldimg' . DS . $dateFolder;
- // 若目录不存在则创建
- if (!is_dir($targetPath)) {
- mkdir($targetPath, 0755, true);
- }
- // 获取原始文件名(或自定义新文件名)
- $originalName = $file->getInfo('name'); // 原始文件名
- $extension = pathinfo($originalName, PATHINFO_EXTENSION); // 文件扩展名
- $newFileName = uniqid() . '.' . $extension; // 生成唯一文件名(避免冲突)
- // 移动文件到指定目录,并验证大小/格式,同时指定自定义文件名
- $info = $file->validate([
- 'size' => 10485760, // 最大10MB
- 'ext' => 'jpg,png'
- ])->move($targetPath, $newFileName); // 关键:手动指定文件名,避免自动生成日期目录
- if ($info) {
- // 直接拼接路径,不依赖 getSaveName() 的返回值
- $imageUrl = '/uploads/merchant/'.$param['merchant_code'].'/'.$param['product_code'].'/oldimg/' . $dateFolder . '/' . $newFileName;
- return json(['code' => 0, 'msg' => '成功', 'data' => ['url' => $imageUrl]]);
- } else {
- $res = $file->getError();
- return json(['code' => 1, 'msg' => '失败', 'data' => $res]);
- }
- }
- return json(['code' => 1, 'msg' => '没有文件上传', 'data' => null]);
- }
- /**
- * 产品详情
- * @return void
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function productDetail()
- {
- // 1. 请求方法验证
- if (!$this->request->isGet()) {
- $this->error('只支持GET请求');
- }
- // 2. 参数获取与验证
- $param = $this->request->param();
- if (empty($param['id']) || !is_numeric($param['id'])) {
- $this->error('产品ID参数错误');
- }
- // 3. 参数安全处理
- $productId = intval($param['id']);
- if ($productId <= 0) {
- $this->error('产品ID必须为正整数');
- }
- // 4. 查询数据
- try {
- $product = \db('product')
- ->field([
- 'id',
- 'product_name as 产品名称',
- 'product_code as 产品编码',
- 'product_img',
- 'product_new_img',
- 'createTime as 创建时间',
- 'create_name as 创建人',
- ])
- ->where('id', $productId)
- ->whereNull('deleteTime')
- ->find();
- } catch (\Exception $e) {
- $this->error('查询产品详情失败:' . $e->getMessage());
- }
- // 5. 检查查询结果
- if (empty($product)) {
- $this->error('产品不存在或已被删除');
- }
- // 6. 优化图片路径处理
- // 产品图片
- if (!empty($product['product_img'])) {
- $product['产品图片'] = ltrim($product['product_img'], '/');
- } else {
- $product['产品图片'] = ''; // 设置默认空值
- }
- // 产品效果图 - 修复变量名错误(原代码中使用了$v)
- if (!empty($product['product_new_img'])) {
- $product['产品效果图'] = ltrim($product['product_new_img'], '/');
- } else {
- $product['产品效果图'] = ''; // 设置默认空值
- }
- $newImg = \db('product_new_img')
- ->where('product_id', $productId)
- ->whereNull('deleteTime')
- ->column('img_address');
- $product['newImg'] = $newImg;
- // 7. 移除原始图片字段,保持返回数据整洁
- unset($product['product_img'], $product['product_new_img']);
- $product_image = \db('product_image')
- ->where('product_id', $productId)
- ->order('id desc')
- ->select();
- return json([
- 'code' => 0,
- 'msg' => '获取产品详情成功',
- 'image' => $product_image,//历史图片
- 'data' => $product
- ]);
- }
- /**
- * 获取单条产品数据信息
- */
- public function GetProductFind(){
- if (!$this->request->isGet()) {
- $this->error('只支持GET请求');
- }
- $param = $this->request->param();
- if (empty($param['id']) || !is_numeric($param['id'])) {
- $this->error('产品ID参数错误');
- }
- $product = Db::name('product')->where('id', $param['id'])->find();
- if (empty($product)) {
- return json([
- 'code' => 1,
- 'msg' => '产品不存在',
- 'data' => null
- ]);
- }
- $this->success('获取成功', $product);
- }
- /**
- * 新增产品
- * @return void
- */
- public function productAdd()
- {
- // 1. 请求方法验证(可提取为公共方法)
- if (!$this->request->isPost()) {
- throw new \Exception('非法请求');
- }
- // 2. 获取并验证参数
- $param = $this->request->post();
- $this->validateProductParams($param, ['product_name', 'product_code']);
- // 3. 准备数据(使用助手函数处理时间)
- $data = [
- 'product_name' => $param['product_name'],
- 'product_code' => $param['product_code'],
- 'createTime' => date('Y-m-d H:i:s', time()),
- 'create_name' => isset($param['create_name']) ? $param['create_name'] : '',
- 'merchant_id' => isset($param['merchant_id']) ? intval($param['merchant_id']) : 0,
- 'product_img' => isset($param['product_img']) ? $param['product_img'] : '',
- ];
- // 4. 验证产品编码唯一性
- if (Db::name('product')->where('product_code', $data['product_code'])->count() > 0) {
- $this->error('产品编码已存在');
- }
- // 5. 使用事务确保数据一致性
- $result = Db::name('product')->insert($data);
- if ($result) {
- $this->success('新增成功');
- } else {
- $this->error('新增失败');
- }
- }
- /**
- * 修改产品数据
- * @return void
- */
- public function productEdit()
- {
- // 1. 请求方法验证
- if (!$this->request->isPost()) {
- throw new \Exception('非法请求');
- }
- // 2. 获取并验证参数
- $param = $this->request->post();
- $this->validateProductParams($param, ['id', 'product_name', 'product_code']);
- // 3. 检查产品是否存在
- $product = Db::name('product')->where('id', intval($param['id']))->find();
- if (!$product) {
- $this->error('产品不存在');
- }
- // 4. 准备更新数据
- $updateData = [
- 'product_name' => $param['product_name'],
- 'product_code' => $param['product_code'],
- ];
- // 5. 可选字段更新
- $optionalFields = ['create_name', 'merchant_id', 'product_img', 'product_new_img'];
- foreach ($optionalFields as $field) {
- if (isset($param[$field])) {
- $updateData[$field] = $param[$field];
- }
- }
- // 6. 验证产品编码唯一性(排除自身)
- $codeExists = Db::name('product')
- ->where('product_code', $updateData['product_code'])
- ->where('id', '<>', intval($param['id']))
- ->count();
- if ($codeExists > 0) {
- $this->error('产品编码已被其他产品使用');
- }
- // 7. 使用事务更新
- $result = Db::name('product')
- ->where('id', intval($param['id']))
- ->update($updateData);
- if ($result !== false) {
- $this->success('更新成功');
- } else {
- $this->error('更新失败');
- }
- }
- /**
- * 验证产品参数(私有方法,供内部使用)
- * @param array $param 参数数组
- * @param array $requiredFields 必要字段
- * @throws \Exception
- */
- private function validateProductParams($param, $requiredFields)
- {
- foreach ($requiredFields as $field) {
- if (!isset($param[$field]) || trim($param[$field]) === '') {
- throw new \Exception("缺少必要参数:{$field}");
- }
- }
- }
- /**
- * 获取商户ID
- * @return void
- */
- public function getMerchantId()
- {
- if (!$this->request->isGet()) {
- $this->error('请求错误');
- }
- $param = $this->request->param();
- if (empty($param['merchant_code'])) {
- $this->error('参数错误');
- }
- $id = \db('product_merchant')
- ->where('merchant_code', $param['merchant_code'])
- ->value('id');
- if (!empty($id)) {
- $this->success('成功', $id);
- }else{
- $this->error('失败');
- }
- }
- }
|