liuhairui 4 сар өмнө
parent
commit
615525b922

+ 73 - 19
application/api/controller/Facility.php

@@ -33,7 +33,7 @@ class Facility extends Api
             foreach ($dirList as &$dir) {
                 $dir['new_image_count'] = Db::name('text_to_image')
                     ->where('status', 1)
-                    ->where('custom_image_url', '<>', '')
+                    ->where('new_image_url', '<>', '')
                     ->where('img_name', '<>', '')
                     ->whereLike('old_image_url', $dir['old_image_url'] . '/%')
                     ->count();
@@ -85,7 +85,7 @@ class Facility extends Api
 
         $img_count = Db::name('text_to_image')
             ->where('status', 1)
-            ->where('custom_image_url', '<>', '')
+            ->where('new_image_url', '<>', '')
             ->where('img_name', '<>', '')
             ->whereLike('old_image_url', $baseRelativePath . '/' . $relativeDir . '/%')
             ->count();
@@ -412,11 +412,24 @@ class Facility extends Api
         return json(['code' => 1, 'msg' => '没有文件上传', 'data' => null]);
     }
 
+    // 获取所有模版列表,并返回当前使用模版 ID
+    public function TemplateList()
+    {
+        $list = Db::name("template")->order('ids desc')->select();
+        return json([
+            'code' => 0,
+            'msg' => '模版列表',
+            'data' => [
+                'list' => $list,
+                'usedId' => Db::name("template")->where('ids', 1)->value('id')
+            ]
+        ]);
+    }
 
     /**
-     * 查询模版
+     * 查询使用模版
      */
-    public function Template(){
+    public function Template_ids(){
         $Template = Db::name("template")->where('ids',1)->find();
         return json([
             'code' => 0,
@@ -425,32 +438,73 @@ class Facility extends Api
         ]);
     }
 
+
+    /**
+     * 查询模版
+     */
+    public function Template()
+    {
+        $id = Request::instance()->param('id');
+        if (!$id) {
+            return json(['code' => 1, 'msg' => '参数错误']);
+        }
+
+        $template = Db::name("template")->where('id', $id)->find();
+        return json([
+            'code' => 0,
+            'msg' => '模版详情',
+            'data' => $template
+        ]);
+    }
+
     /**
      * 更新模版
      */
-    public function updatetemplate(){
-        if (Request::instance()->isPost() == false){
-            $this->error('非法请求');
+    public function updatetemplate()
+    {
+        if (!Request::instance()->isPost()) {
+            return json(['code' => 1, 'msg' => '非法请求']);
         }
+
         $params = Request::instance()->post();
+
         if (empty($params['textareaContent']) || empty($params['width']) || empty($params['height'])) {
             return json(['code' => 1, 'msg' => '参数缺失']);
         }
-        $Template = Db::name("template")
-            ->where('ids', 1)
-            ->update([
-                'english_content' => $params['english_content'],  // 更新文生文模版内容
-                'content' => $params['textareaContent'],  // 更新图生文模版内容
-                'width' => $params['width'],  // 更新宽度
-                'height' => $params['height'],  // 更新宽度
-            ]);
-        if ($Template){
-            return json(['code' => 0, 'msg' => '成功']);
-        }else{
-            return json(['code' => 1, 'msg' => '失败']);
+
+        $data = [
+            'english_content' => $params['english_content'],
+            'content' => $params['textareaContent'],
+            'width' => $params['width'],
+            'height' => $params['height'],
+        ];
+
+        if (!empty($params['id'])) {
+            // 更新已有模版
+            Db::name("template")->where('id', $params['id'])->update($data);
+        } else {
+            // 新增模版,默认设为备用
+            $data['ids'] = 0;
+            Db::name("template")->insert($data);
         }
+
+        return json(['code' => 0, 'msg' => '保存成功']);
+    }
+
+    public function setActiveTemplate()
+    {
+        $id = Request::instance()->param('id');
+        if (!$id) {
+            return json(['code' => 1, 'msg' => '参数错误']);
+        }
+
+        Db::name("template")->where('ids', 1)->update(['ids' => 0]); // 清除当前使用
+        Db::name("template")->where('id', $id)->update(['ids' => 1]); // 设置新的使用模版
+
+        return json(['code' => 0, 'msg' => '模版已设为当前使用']);
     }
 
+
     /**
      * 打包图片(支持对象结构中的 path 字段)
      */

+ 45 - 259
application/api/controller/OrderSuperLoss.php

@@ -21,292 +21,78 @@ class OrderSuperLoss extends Api
     }
 
     /**
-     * 获取左侧菜单栏
-     * @ApiMethod GET
+     * 修改
      */
     public function getTab()
     {
-        // 检查请求类型是否为 GET
-        if (!Request::instance()->isGet()) {
-            $this->error('非法请求');
+        if (!$this->request->isPost()) {
+            return json(['code' => 400, 'msg' => '请求方式错误'], 400);
         }
 
-        // SQL 查询,连接 db3 数据库
-        $sql = "SELECT   
-                DATE_FORMAT(a.jjcp_sj, '%Y-%m') AS date,  -- 格式化为年月  
-                RTRIM(b.`编号`) AS 编号,  
-                RTRIM(b.`名称`) AS 客户名称,  
-                COUNT(DISTINCT a.jjcp_gdbh) AS count   
-            FROM   
-                `成品入仓` a  
-            LEFT JOIN   
-                `物料_存货结构` b   
-                ON (CASE   
-                        WHEN LEFT(a.`jjcp_cpdh`, 1) REGEXP '^[A-Za-z]' THEN LEFT(a.`jjcp_cpdh`, 5)   
-                        ELSE LEFT(a.`jjcp_cpdh`, 4)   
-                    END) = RTRIM(b.`编号`)  -- 根据字母/数字判断连接方式  
-            WHERE   
-                a.jjcp_sj >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)  -- 最近12个月  
-                AND a.jjcp_sj >= '2025-01-01 00:00:00'               -- 限定从2025年开始  
-                AND a.`成品编码` != ''                                -- 编码不为空  
-                AND a.jjcp_smb IN ('末 板', '末板')                 -- 状态筛选  
-            GROUP BY   
-                DATE_FORMAT(a.jjcp_sj, '%Y-%m'),  
-                RTRIM(b.`编号`)   
-            ORDER BY   
-                date DESC,  
-                编号 ASC";
+        $param = $this->request->post([
+            'id',
+            'chinese_description',
+            'english_description',
+            'img_name'
+        ]);
 
-        // 执行查询,确保连接的是 db3 数据库
-        $db3 = \db()->connect(config('database.db3'));
-        $data = $db3->query($sql);
-        // 创建一个新数组存储整理后的数据
-        $organizedData = [];
-
-        // 遍历原始数据
-        foreach ($data as $entry) {
-            $date = date('Ym', strtotime($entry['date']));  // 格式化为年月,例如 202506
-
-            // 如果当前月份已经有数据,追加数据
-            if (isset($organizedData[$date])) {
-                $organizedData[$date][] = [
-                    '客户名称' => $entry['客户名称'],
-                    '客户编号' => $entry['编号'],
-                    'total' => $entry['count'],
-                ];
-                // 累加该月的总数
-                $organizedData[$date]['total_count'] += $entry['count'];
-            } else {
-                // 否则初始化该月数据
-                $organizedData[$date] = [
-                    [
-                        '客户名称' => $entry['客户名称'],
-                        '客户编号' => $entry['编号'],
-                        'total' => $entry['count'],
-                    ]
-                ];
-                // 初始化总数
-                $organizedData[$date]['total_count'] = $entry['count'];
-            }
+        if (empty($param['id'])) {
+            return json(['code' => 422, 'msg' => '缺少必要参数'], 422);
         }
 
-        // 整理成最终格式,以 "年月-总数" 为键
-        $finalData = [];
-        foreach ($organizedData as $date => $entries) {
-            $totalCount = $entries['total_count'];
-            $index = $date . '-' . $totalCount;
-            unset($entries['total_count']);  // 删除临时统计字段
-            $finalData[$index] = $entries;
-        }
+        $result = Db::name('text_to_image')
+            ->where('id', $param['id'])
+            ->update([
+                'chinese_description' => $param['chinese_description'] ?? '',
+                'english_description' => $param['english_description'] ?? '',
+                'img_name' => $param['img_name'] ?? ''
+            ]);
 
-        // 返回成功结果
-        $this->success('请求成功', $finalData);
+        if ($result !== false) {
+            $this->success('修改成功');
+        } else {
+            $this->success('修改失败');
+        }
     }
 
     /**
-     * 超节损列表
+     *
      */
     public function getList()
     {
-        if (!Request::instance()->isGet()) {
-            $this->error('非法请求');
-        }
-
         $params = Request::instance()->param();
-        $where = [];
 
-        // 设置默认分页和限制
-        $limit = empty($params['limit']) ? 15 : intval($params['limit']);
-        $pages = empty($params['page']) ? 1 : intval($params['page']);
+        // 分页参数(默认第1页,每页10条)
+        $page  = isset($params['page']) ? max((int)$params['page'], 1) : 1;
+        $limit = isset($params['limit']) ? max((int)$params['limit'], 10) : 10;
+        // 搜索关键词
+        $search = isset($params['search']) ? trim($params['search']) : '';
 
-        // 构建查询条件
-        if (!empty($params['code'])) {
-            $prefixLength = preg_match('/[A-Za-z]/', $params['code']) ? 5 : 4;
-            $where['a.jjcp_cpdh'] = ['LIKE', substr($params['code'], 0, $prefixLength) . '%'];
-        }
-
-        if (!empty($params['date'])) {
-            $year = substr($params['date'], 0, 4);
-            $month = substr($params['date'], 4, 2);
-            $formattedDate = $year . '-' . $month;
-            $where['a.jjcp_sj'] = ['like', $formattedDate . '%'];
-        }
-
-        if (!empty($params['search'])) {
-            if (!empty($params['date']) || !empty($params['code'])) {
-                $this->error('参数错误');
-            }
-            $where['a.jjcp_gdbh|a.jjcp_cpdh|a.jjcp_cpmc'] = ['like', '%' . $params['search'] . '%'];
+        $where = [];
+        if (isset($search)) {
+            $where['id|img_name|chinese_description|english_description'] = ['like', '%'. $search . '%'];
         }
 
-        // 数据库连接
-        $db3 = \db()->connect(config('database.db3'));
-
-        // 定义查询字段
-        $field = '
-        b.sys_ny,
-        a.jjcp_gdbh AS Gd_gdbh,
-        a.jjcp_yjno AS jjcp_yjno,
-        a.jjcp_yjno AS yj_Yjno,
-        c.yj_Yjdh as yjdh,
-        c.yj_ls AS yj_ls,
-        c.yj_cpdh AS 成品编码,
-        c.yj_yjmc AS 成品名称,
-        b.`实际投料`,
-        b.`计量单位`,
-        DATE(a.jjcp_sj) AS warehousing_date,
-        total_sl.warehousing_num,
-        SUM(DISTINCT b.`计划损耗`) AS `工单计划损耗`,
-        b.`废品合计`,
-        SUM(b.`CjsJe`) AS reward_money,
-        b.`印件无形损` AS 工单无形损,
-        b.`材料废`,
-        b.`零头处理`,
-        b.`外发废`,
-        SUM(b.`班组制程废品`) AS zcfp,
-        `工单质检废` AS 工单质检废,
-        c.质量考核
-    ';
-
-        // 子查询:计算入仓数量
-        $subQuery = $db3->name('成品入仓')
-            ->alias('a_sub')
-            ->field('
-            a_sub.jjcp_gdbh AS Gd_gdbh_sub,
-            a_sub.jjcp_yjno AS jjcp_yjno_sub,
-            SUM(a_sub.jjcp_sl) AS warehousing_num
-        ')
-            ->group('a_sub.jjcp_gdbh, a_sub.jjcp_yjno')
-            ->buildSql();
+        $count = Db::name('text_to_image')
+            ->where('new_image_url', '<>', '')
+            ->where('img_name', '<>', '')
+            ->select();
 
-        // 主查询
-        $list = $db3->name('成品入仓')
-            ->alias('a')
-            ->join('工单_质量考核汇总 b', 'a.jjcp_gdbh = b.Gy0_gdbh AND a.jjcp_yjno = b.印件及工序', 'left')
-            ->join('工单_印件资料 c', 'a.jjcp_gdbh = c.Yj_Gdbh AND a.jjcp_yjno = c.yj_Yjno', 'left')
-            ->join([$subQuery => 'total_sl'], 'a.jjcp_gdbh = total_sl.Gd_gdbh_sub AND a.jjcp_yjno = total_sl.jjcp_yjno_sub', 'left')
-            ->field($field)
+        $list = Db::name('text_to_image')
+            ->where('new_image_url', '<>', '')
+            ->where('img_name', '<>', '')
             ->where($where)
-            ->where('a.jjcp_smb', 'like', '末%')
-            ->group('Gd_gdbh, jjcp_yjno')
-            ->order('warehousing_date DESC')
-            ->page($pages, $limit)
+            ->order('update_time desc')
+            ->page($page, $limit)
             ->select();
 
-        // 后续处理结果
-        foreach ($list as $key => $value) {
-            $status = $db3->name('工单_印件资料')
-                ->where('Yj_Gdbh', $value['Gd_gdbh'])
-                ->where('yj_Yjno', $value['jjcp_yjno'])
-                ->value('质量考核');
-
-            $list[$key]['工单质检废'] = $value['废品合计'] - $value['zcfp'];
-            $list[$key]['质量考核'] = $status;
-            $list[$key]['考核'] = ($status == 1) ? '否' : '是';
-
-            if ($value['实际投料'] !== null) {
-                $actualMaterial = $value['实际投料'] * 10000;
-                $list[$key]['target_rate'] = $this->calculateRate($actualMaterial, $value['工单计划损耗']);
-                $realRate = $value['warehousing_num'] / $actualMaterial * 100;
-                $list[$key]['real_rate'] = number_format($realRate, 2) . '%';
-            } else {
-                $list[$key]['target_rate'] = null;
-                $list[$key]['real_rate'] = null;
-            }
-
-            $list[$key]['reward_rate'] = '1'; // 如有实际逻辑,可替换
-        }
-
-
-        //只保留考核为“是”的数据
-        $list = array_filter($list, function ($item) {
-            return $item['考核'] === '是';
-        });
-        // 重新整理数组索引(重0开始)
-        $list = array_values($list);
-
-        if (!empty($list)) {
-            $this->success('成功', $list);
-        } else {
-            $this->error('未找到数据');
-        }
+        $this->success('获取成功', [
+            'total' => count($count),
+            'list'  => $list
+        ]);
     }
 
-    // 计算合格率
-    private function calculateRate($actual, $loss)
-    {
-        if ($actual == 0) {
-            return '0.00%'; // 防止除以零
-        }
-        $rate = ($actual - $loss) / $actual * 100;
-        return number_format($rate, 2) . '%';
-    }
-
-
-    /**
-     * AI 超节损分析(月度)
-     */
-//    public function oversizedloss() {
-//        $params = $this->request->param();
-//        $service = new ImageService();
-//        $service->chaojiesun_handleImage($params);
-//        $this->success('任务成功提交至队列');
-//    }
-
 
-//    public function oversizedloss() {
-//        // 读取原始 POST JSON body
-//        $raw = $this->request->getInput();
-//        $params = json_decode($raw, true);
-//
-//        if (empty($params['content'])) {
-//            return json(['code' => 1, 'msg' => 'content 不能为空']);
-//        }
-//
-//        // 取出 content
-////        $promptData = $params['content']['content'];
-//        $promptData = $params['content'];
-//
-//        // 统一处理为字符串
-//        if (is_array($promptData)) {
-//            // 如果是二维数组(多个工单)
-//            if (isset($promptData[0]) && is_array($promptData[0])) {
-//                $lines = array_map(function($row) {
-//                    return implode(', ', array_map(
-//                        fn($k, $v) => "$k: $v",
-//                        array_keys($row),
-//                        array_values($row)
-//                    ));
-//                }, $promptData);
-//                $promptContent = implode("\n", $lines);
-//            }
-//            // 如果是一维数组(单个工单)
-//            else {
-//                $promptContent = implode(', ', array_map(
-//                    fn($k, $v) => "$k: $v",
-//                    array_keys($promptData),
-//                    array_values($promptData)
-//                ));
-//            }
-//        } else {
-//            // 已经是字符串,无需处理
-//            $promptContent = $promptData;
-//        }
-//
-//        // 查询模板内容
-//        $db3 = \db()->connect(config('database.db3'));
-//        $list = $db3->name('workorder_template')->where("id",1)->find();
-//
-//        $prompt = $list['content'] . "\n" . $promptContent;
-//
-//        // 调用 AI
-//        $ai = new AIGatewayService();
-//        $gptRes = $ai->chaojiesunGptApi($prompt);
-//
-//        $gptText = trim($gptRes['choices'][0]['message']['content'] ?? '');
-//
-//        return json(['code' => 0, 'data' => $gptText]);
-//    }
 }
 
 

+ 34 - 7
application/job/ImageJob.php

@@ -182,23 +182,50 @@ class ImageJob{
         //     FILE_APPEND
         // );
 
-        // 成功写入数据库
+        // // 成功写入数据库
+        // $record = [
+        //     'chinese_description' => $chineseDesc,
+        //     'english_description' => $englishDesc,
+        //     'old_image_url' => $relativePath,
+        //     'new_image_url' => '',
+        //     'custom_image_url' => '',
+        //     'img_name' => $img_name,
+        //     'status' => 0,
+        //     'status_name' => "图生文",
+        //     'model' => "",
+        //     'size' => "",
+        //     'error_msg' => '',
+        //     'created_time' => date('Y-m-d H:i:s'),
+        //     'update_time' => date('Y-m-d H:i:s')
+        // ];
+        // Db::name('text_to_image')->insert($record);
+        $now = date('Y-m-d H:i:s');
         $record = [
             'chinese_description' => $chineseDesc,
             'english_description' => $englishDesc,
-            'old_image_url' => $relativePath,
-            'new_image_url' => '',
-            'custom_image_url' => '',
             'img_name' => $img_name,
             'status' => 0,
             'status_name' => "图生文",
             'model' => "",
             'size' => "",
             'error_msg' => '',
-            'created_time' => date('Y-m-d H:i:s'),
-            'update_time' => date('Y-m-d H:i:s')
+            'update_time' => $now
         ];
-        Db::name('text_to_image')->insert($record);
+
+        // 查询是否存在相同的原图记录
+        $exists = Db::name('text_to_image')->where('old_image_url', $relativePath)->find();
+
+        if ($exists) {
+            // 如果已存在,执行更新
+            Db::name('text_to_image')->where('id', $exists['id'])->update($record);
+        } else {
+            // 不存在则添加必要字段并插入
+            $record['old_image_url'] = $relativePath;
+            $record['new_image_url'] = '';
+            $record['custom_image_url'] = '';
+            $record['created_time'] = $now;
+            Db::name('text_to_image')->insert($record);
+        }
         return ;
     }
 }

+ 2 - 2
application/job/ImageToImageJob.php

@@ -137,7 +137,7 @@ class ImageToImageJob{
             mkdir($fullBaseDir, 0755, true);
         }
 
-        $imgtoimgDir = $fullBaseDir . 'imgtoimg/';
+        $imgtoimgDir = $fullBaseDir . '1024x1303/';
         if (!is_dir($imgtoimgDir)) {
             mkdir($imgtoimgDir, 0755, true);
         }
@@ -171,7 +171,7 @@ class ImageToImageJob{
         }
 
         // 构造相对路径用于数据库
-        $relativeImgPath = rtrim($outputDirRaw, '/') . '/' . $dateDir . 'imgtoimg/' . $finalFileName;
+        $relativeImgPath = rtrim($outputDirRaw, '/') . '/' . $dateDir . '1024x1303/' . $finalFileName;
 
         // 更新数据库记录
         Db::name('text_to_image')->where('id', $record['id'])->update([

+ 36 - 32
application/job/TextToImageJob.php

@@ -46,7 +46,7 @@ class TextToImageJob
             $list = Db::name("text_to_image")
                 ->where('old_image_url', $old_image_url)
                 ->where('img_name', '<>', '')
-                ->where('status', 0)
+                // ->where('status', 0)
                 ->select();
 
             if (!empty($list)) {
@@ -163,6 +163,10 @@ class TextToImageJob
             ->order('id desc')
             ->find();
 
+        Db::name('text_to_image')->where('id', $record['id'])->update([
+            'new_image_url' => '',
+        ]);
+
         if (!$record) return '没有找到匹配的图像记录';
 
         // 过滤关键词
@@ -207,42 +211,42 @@ class TextToImageJob
         file_put_contents($path512, $imgData);
 
         // ➤ 是否执行裁剪(如不想裁剪,可注释以下 try-catch 整块)
-        try {
-            $im = imagecreatefromstring($imgData);
-            if (!$im) throw new \Exception("图像无法解析");
-
-            $srcW = imagesx($im);
-            $srcH = imagesy($im);
-            $srcRatio = $srcW / $srcH;
-            $dstRatio = $width / $height;
-
-            if ($srcRatio > $dstRatio) {
-                $cropW = intval($srcH * $dstRatio);
-                $cropH = $srcH;
-                $srcX = intval(($srcW - $cropW) / 2);
-                $srcY = 0;
-            } else {
-                $cropW = $srcW;
-                $cropH = intval($srcW / $dstRatio);
-                $srcX = 0;
-                $srcY = intval(($srcH - $cropH) / 2);
-            }
-
-            $dstImg = imagecreatetruecolor($width, $height);
-            imagecopyresampled($dstImg, $im, 0, 0, $srcX, $srcY, $width, $height, $cropW, $cropH);
-            imagepng($dstImg, $pathCustom);
-            imagedestroy($im);
-            imagedestroy($dstImg);
-        } catch (\Throwable $e) {
-            file_put_contents('/tmp/crop_error.png', $imgData);
-            throw new \Exception("图像裁剪失败:" . $e->getMessage());
-        }
+        // try {
+        //     $im = imagecreatefromstring($imgData);
+        //     if (!$im) throw new \Exception("图像无法解析");
+
+        //     $srcW = imagesx($im);
+        //     $srcH = imagesy($im);
+        //     $srcRatio = $srcW / $srcH;
+        //     $dstRatio = $width / $height;
+
+        //     if ($srcRatio > $dstRatio) {
+        //         $cropW = intval($srcH * $dstRatio);
+        //         $cropH = $srcH;
+        //         $srcX = intval(($srcW - $cropW) / 2);
+        //         $srcY = 0;
+        //     } else {
+        //         $cropW = $srcW;
+        //         $cropH = intval($srcW / $dstRatio);
+        //         $srcX = 0;
+        //         $srcY = intval(($srcH - $cropH) / 2);
+        //     }
+
+        //     $dstImg = imagecreatetruecolor($width, $height);
+        //     imagecopyresampled($dstImg, $im, 0, 0, $srcX, $srcY, $width, $height, $cropW, $cropH);
+        //     imagepng($dstImg, $pathCustom);
+        //     imagedestroy($im);
+        //     imagedestroy($dstImg);
+        // } catch (\Throwable $e) {
+        //     file_put_contents('/tmp/crop_error.png', $imgData);
+        //     throw new \Exception("图像裁剪失败:" . $e->getMessage());
+        // }
 
         // 数据库更新
         Db::name('text_to_image')->where('id', $record['id'])->update([
             'new_image_url' => str_replace($rootPath . 'public/', '', $path512),
             // 注释以下一行则不保存裁剪路径(适配你的配置)
-            'custom_image_url' => str_replace($rootPath . 'public/', '', $pathCustom),
+            // 'custom_image_url' => str_replace($rootPath . 'public/', '', $pathCustom),
             'img_name' => $img_name,
             'model' => $selectedOption,
             'status' => trim($img_name) === '' ? 0 : 1,