zck 1 tydzień temu
rodzic
commit
450c83bd14

+ 3 - 1
application/api/controller/Achievementatestatistics.php

@@ -19,7 +19,9 @@ class  Achievementatestatistics extends Api
         // 获取所有部门(排除特定)
         $departments = Db::name('设备_基本资料')
             ->field('使用部门')
-            ->whereNotIn('使用部门', ['打样室', '智能车间'])
+            ->whereNotIn('使用部门', ['打样室', '智能车间','印后糊盒车间','数字化车间','精品手工车间','精品自动化车间',])
+            ->where('使用部门', '<>', '')        // 过滤空字符串
+            ->whereNotNull('使用部门')
             ->group('使用部门')
             ->select();
         // 部门名数组

+ 415 - 0
application/api/controller/Agent.php

@@ -0,0 +1,415 @@
+<?php
+
+namespace app\api\controller;
+
+use think\Controller;
+use think\Db;
+
+/**
+ * AI 报工核查(胶印难度系数)
+ *
+ * 不继承 Api 基类,避免被 FastAdmin 登录鉴权拦截。
+ * 用 URL 参数 key 做简单校验。
+ *
+ * 用法(宝塔计划任务每 30 分钟访问一次):
+ *   GET /api/agent/workReportAudit?key=你的cron_key
+ *   GET /api/agent/workReportAudit?key=你的cron_key&date=2026-11-07
+ */
+class Agent extends Controller
+{
+    /**
+     * 测试入口:验证路由是否通
+     * GET /api/agent/index
+     */
+    public function index()
+    {
+        return json(['code' => 0, 'msg' => 'Agent 控制器已加载', 'time' => date('Y-m-d H:i:s')]);
+    }
+
+    /**
+     * 定时任务入口:AI 胶印报工核查 → 入库 agent_难度系数校验结果
+     */
+    public function workReportAudit()
+    {
+        $cfg = $this->agentConfig();
+
+        // 1. 校验 key
+        $key = (string)$this->request->param('key', '');
+        if (empty($cfg['cron_key']) || !hash_equals((string)$cfg['cron_key'], $key)) {
+            return json(['code' => 1, 'msg' => '无权限']);
+        }
+        if (empty($cfg['user_id']) || empty($cfg['password'])) {
+            return json(['code' => 1, 'msg' => '请先在 application/extra/agent.php 配置 user_id 和 password']);
+        }
+
+        $date = $this->request->param('date') ?: date('Y-m-d');
+        $base = rtrim($cfg['base_url'], '/');
+        $timeout = (int)$cfg['timeout'];
+
+        try {
+            // 2. 登录
+            $loginResp = $this->http('POST', $base . $cfg['login_path'], [
+                'user_id'  => $cfg['user_id'],
+                'password' => $cfg['password'],
+            ], null, $timeout);
+            $token = isset($loginResp['access_token']) ? $loginResp['access_token'] : '';
+            if (!$token) {
+                throw new \RuntimeException('登录失败:' . json_encode($loginResp, JSON_UNESCAPED_UNICODE));
+            }
+
+            // 3. 验证登录
+            $this->http('GET', $base . $cfg['me_path'], null, $token, $timeout);
+
+            // 4. 提问
+            $askResp = $this->http('POST', $base . $cfg['ask_path'], [
+                'skill_id'          => $cfg['skill_id'],
+                'question'          => $date . $cfg['question_suffix'],
+                'params'            => new \stdClass(),
+                'include_knowledge' => false,
+            ], $token, $timeout);
+
+            if (empty($askResp['ok']) || empty($askResp['rows']) || !is_array($askResp['rows'])) {
+                throw new \RuntimeException('ask 接口无数据:' . json_encode($askResp, JSON_UNESCAPED_UNICODE));
+            }
+
+            // 5. 入库
+            $saved = $this->saveRows($askResp['rows']);
+
+            return json([
+                'code' => 0,
+                'msg'  => '成功',
+                'data' => [
+                    'date'  => $date,
+                    'rows'  => count($askResp['rows']),
+                    'saved' => $saved,
+                ],
+            ]);
+        } catch (\Exception $e) {
+            return json(['code' => 1, 'msg' => $e->getMessage()]);
+        }
+    }
+
+    /**
+     * 批量入库 agent_难度系数校验结果
+     * 数据一致则跳过,不一致才更新,新增才插入
+     */
+    private function saveRows($rows)
+    {
+        $data = [];
+        $reportIds = [];
+        foreach ($rows as $row) {
+            if (empty($row['report_id'])) {
+                continue;
+            }
+            $reportIds[] = (int)$row['report_id'];
+            $data[] = [
+                'UniqId'              => (int)$row['report_id'],
+                '工单编号'             => $this->str($row, 'work_order_no', 64),
+                'sczl_yino'           => $this->str($row, 'yjno_no', 64),
+                'sczl_gxh'            => $this->str($row, 'gxh_no', 32),
+                'sczl_jtbh'           => $this->str($row, 'machine_no', 255),
+                'sczl_rq'             => $this->datetime($row, 'report_date'),
+                'product_code'        => $this->str($row, 'product_code', 255),
+                'product_name'        => $this->str($row, 'product_name', 255),
+                'inventory_spec'      => $this->str($row, 'inventory_spec', 255),
+                'machine_class'       => $this->str($row, 'machine_class', 255),
+                'color_count'         => $this->str($row, 'color_count', 255),
+                'market'              => $this->str($row, 'market', 255),
+                'box_type'            => $this->str($row, 'box_type', 255),
+                'base_wage_coef'      => $this->str($row, 'base_wage_coef', 255),
+                'suggested_wage_coef' => $this->str($row, 'suggested_wage_coef', 255),
+                'wage_coef'           => $this->str($row, 'wage_coef', 255),
+                'audit_result'        => $this->str($row, 'audit_result', 120),
+                'audit_note'          => $this->str($row, 'audit_note', 100),
+            ];
+        }
+        if (!$data) {
+            return 0;
+        }
+
+        // 查已有数据,按 UniqId 索引
+        $exist = Db::name('agent_难度系数校验结果')->where('UniqId', 'in', $reportIds)->column('*', 'UniqId');
+
+        $insertData = [];
+        $updateData = [];
+        foreach ($data as $item) {
+            $uid = $item['UniqId'];
+            if (!isset($exist[$uid])) {
+                // 不存在 → 插入
+                $insertData[] = $item;
+            } else {
+                // 存在 → 对比字段是否变化
+                $old = $exist[$uid];
+                $changed = false;
+                foreach ($item as $k => $v) {
+                    if ($k === 'UniqId') continue;
+                    // 数据库返回的可能是 null,新数据也可能是 null,统一转字符串比较
+                    $oldVal = isset($old[$k]) ? (string)$old[$k] : '';
+                    $newVal = $v !== null ? (string)$v : '';
+                    if ($oldVal !== $newVal) {
+                        $changed = true;
+                        break;
+                    }
+                }
+                if ($changed) {
+                    $updateData[] = $item;
+                }
+            }
+        }
+
+        $saved = 0;
+        // 批量插入
+        if ($insertData) {
+            $cols = array_keys($insertData[0]);
+            $colSql = '`' . implode('`,`', $cols) . '`';
+            $bind = [];
+            $values = [];
+            foreach ($insertData as $item) {
+                $ph = [];
+                foreach ($cols as $c) {
+                    $ph[] = '?';
+                    $bind[] = $item[$c];
+                }
+                $values[] = '(' . implode(',', $ph) . ')';
+            }
+            $sql = 'INSERT INTO `agent_难度系数校验结果` (' . $colSql . ') VALUES ' . implode(',', $values);
+            Db::execute($sql, $bind);
+            $saved += count($insertData);
+        }
+
+        // 逐条更新(有变化的才更新)
+        foreach ($updateData as $item) {
+            $uid = $item['UniqId'];
+            unset($item['UniqId']);
+            Db::name('agent_难度系数校验结果')->where('UniqId', $uid)->update($item);
+            $saved++;
+        }
+
+        return $saved;
+    }
+
+    private function str($row, $key, $length)
+    {
+        if (!isset($row[$key]) || $row[$key] === null) {
+            return null;
+        }
+        return mb_substr((string)$row[$key], 0, $length, 'UTF-8');
+    }
+
+    private function datetime($row, $key)
+    {
+        if (empty($row[$key])) {
+            return null;
+        }
+        $ts = strtotime($row[$key]);
+        return $ts ? date('Y-m-d H:i:s', $ts) : null;
+    }
+
+    private function http($method, $url, $body = null, $token = null, $timeout = 60)
+    {
+        $ch = curl_init();
+        $headers = ['Accept: application/json'];
+        if ($body !== null) {
+            $headers[] = 'Content-Type: application/json';
+        }
+        if ($token) {
+            $headers[] = 'Authorization: Bearer ' . $token;
+        }
+        $opts = [
+            CURLOPT_URL            => $url,
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_CONNECTTIMEOUT => 15,
+            CURLOPT_TIMEOUT        => $timeout,
+            CURLOPT_HTTPHEADER     => $headers,
+            CURLOPT_SSL_VERIFYPEER => false,
+            CURLOPT_SSL_VERIFYHOST => false,
+        ];
+        if ($method === 'POST') {
+            $opts[CURLOPT_POST] = true;
+            $opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE);
+        }
+        curl_setopt_array($ch, $opts);
+        $resp = curl_exec($ch);
+        $err  = curl_error($ch);
+        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+        curl_close($ch);
+        if ($resp === false) {
+            throw new \RuntimeException('请求失败:' . $err);
+        }
+        $json = json_decode($resp, true);
+        if (!is_array($json)) {
+            throw new \RuntimeException('返回非 JSON:' . mb_substr($resp, 0, 200));
+        }
+        if ($code >= 400) {
+            $msg = isset($json['detail']) ? json_encode($json['detail'], JSON_UNESCAPED_UNICODE) : $resp;
+            throw new \RuntimeException('HTTP ' . $code . ':' . mb_substr($msg, 0, 300));
+        }
+        return $json;
+    }
+
+    /**
+     * 前端调用:AI 制程检验报表查询
+     * POST /api/agent/inspectionAsk
+     *
+     * 请求体:
+     *   skill_id    string  技能 ID,默认 inspection_analysis
+     *   question    string  问题/工单号
+     *   mode        string  summary|detail,默认 summary
+     *
+     * 返回 AI 平台 ask 接口的完整 JSON(ok/columns/rows/request_id/...)
+     */
+    public function inspectionAsk()
+    {
+        $cfg = $this->agentConfig();
+        $base = rtrim($cfg['base_url'], '/');
+        $timeout = (int)$cfg['timeout'];
+
+        $skillId = (string)$this->request->param('skill_id', 'inspection_analysis');
+        $question = (string)$this->request->param('question', '');
+        $mode = (string)$this->request->param('mode', 'summary');
+
+        if ($question === '') {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['ok' => false, 'detail' => 'question 不能为空']]);
+        }
+
+        // 账号优先级:前端传 user_id > 配置默认 admin
+        $userId = (string)$this->request->param('user_id', $cfg['user_id']);
+        // admin 账号强制使用专用密码,其他账号取前端传值或默认 12345678
+        if ($userId === 'admin') {
+            $password = 'b4f3e215f25d4413ce';
+        } else {
+            $password = (string)$this->request->param('password', '12345678');
+        }
+
+        try {
+            // 1. 登录
+            $loginResp = $this->http('POST', $base . $cfg['login_path'], [
+                'user_id'  => $userId,
+                'password' => $password,
+            ], null, $timeout);
+            $token = isset($loginResp['access_token']) ? $loginResp['access_token'] : '';
+            if (!$token) {
+                return json(['code' => 0, 'msg' => '成功', 'data' => [
+                    'ok'     => false,
+                    'detail' => 'AI 平台登录失败:' . json_encode($loginResp, JSON_UNESCAPED_UNICODE),
+                ]]);
+            }
+
+            // 2. 提问
+            $askResp = $this->http('POST', $base . $cfg['ask_path'], [
+                'skill_id'          => $skillId,
+                'question'          => $question,
+                'params'            => new \stdClass(),
+                'include_knowledge' => false,
+                'mode'              => $mode,
+            ], $token, $timeout);
+
+            return json(['code' => 0, 'msg' => '成功', 'data' => $askResp]);
+        } catch (\Exception $e) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['ok' => false, 'detail' => $e->getMessage()]]);
+        }
+    }
+
+    /**
+     * 前端调用:按产品名称查找同类产品检验报告(宝塔 public/uploads/Inspection 下的 word 文档)
+     * GET /api/agent/getInspectionDoc?cpmc=产品名称
+     *
+     * 返回 data.found=true 时附带 base64 文件内容,前端直接渲染预览
+     */
+    public function getInspectionDoc()
+    {
+        $cpmc = trim((string)$this->request->param('cpmc', ''));
+        if ($cpmc === '') {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '产品名称为空']]);
+        }
+
+        $dir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Inspection' . DS;
+        if (!is_dir($dir)) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告目录不存在:uploads/Inspection']]);
+        }
+
+        // 收集可用文档(word / pdf)
+        $candidates = [];
+        foreach ((array)@scandir($dir) as $file) {
+            if ($file === '.' || $file === '..') {
+                continue;
+            }
+            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
+            if (!in_array($ext, ['docx', 'doc', 'pdf'], true)) {
+                continue;
+            }
+            $candidates[] = [
+                'file'  => $file,
+                'base'  => pathinfo($file, PATHINFO_FILENAME),
+                'ext'   => $ext,
+                'norm'  => $this->normalizeName(pathinfo($file, PATHINFO_FILENAME)),
+            ];
+        }
+        if (!$candidates) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告目录下暂无文档']]);
+        }
+
+        $target = $this->normalizeName($cpmc);
+        $match = null;
+        // 1. 完全匹配
+        foreach ($candidates as $item) {
+            if ($item['norm'] === $target) {
+                $match = $item;
+                break;
+            }
+        }
+        // 2. 包含匹配,取名称最长的(最贴近产品名称)
+        if (!$match) {
+            foreach ($candidates as $item) {
+                if ($item['norm'] !== '' && (strpos($item['norm'], $target) !== false || strpos($target, $item['norm']) !== false)) {
+                    if (!$match || mb_strlen($item['norm']) > mb_strlen($match['norm'])) {
+                        $match = $item;
+                    }
+                }
+            }
+        }
+        if (!$match) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '未找到产品「' . $cpmc . '」对应的报告文档']]);
+        }
+
+        $path = $dir . $match['file'];
+        $size = (int)@filesize($path);
+        if ($size <= 0) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档为空']]);
+        }
+        if ($size > 10 * 1024 * 1024) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档超过 10MB,建议转换为 PDF 后再预览']]);
+        }
+
+        $content = @file_get_contents($path);
+        if ($content === false) {
+            return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档读取失败']]);
+        }
+
+        return json(['code' => 0, 'msg' => '成功', 'data' => [
+            'found'   => true,
+            'name'    => $match['file'],
+            'ext'     => $match['ext'],
+            'size'    => $size,
+            'content' => base64_encode($content),
+        ]]);
+    }
+
+    /**
+     * 名称归一化:去掉空白字符并转小写,用于产品名称与文件名的模糊匹配
+     */
+    private function normalizeName($name)
+    {
+        $name = preg_replace('/\s+/u', '', (string)$name);
+        return mb_strtolower($name, 'UTF-8');
+    }
+
+    /**
+     * 读 application/extra/agent.php
+     */
+    private function agentConfig()
+    {
+        $cfgFile = APP_PATH . 'extra' . DS . 'agent' . EXT;
+        return is_file($cfgFile) ? include $cfgFile : [];
+    }
+}

+ 62 - 3
application/api/controller/CustomerFeedback.php

@@ -56,10 +56,57 @@ class CustomerFeedback extends Api
             'type'     => 'group',
         ];
 
+        // 年度客诉统计 —— 二级:年度,三级:年月(按客诉日期统计次数)
+        // 客诉日期存在 "2024.06.05"、"2024-06-05"、"2024/06/05" 等多种写法,统一替换后再截取
+        $dateExpr = "LEFT(REPLACE(REPLACE(REPLACE(rtrim(`客诉日期`),'.','-'),'/','-'),'年','-'), 7)";
+        $statRows = \db('db_客诉记录')
+            ->field($dateExpr . ' as ym,COUNT(*) as cnt')
+            ->whereRaw("rtrim(`客诉日期`) <> ''")
+            ->group('ym')
+            ->order('ym desc')
+            ->select();
+
+        $yearMap = [];
+        foreach ($statRows as $row) {
+            $ym = trim($row['ym']);
+            if (strlen($ym) < 7 || strpos($ym, '-') === false) continue;
+            $y = substr($ym, 0, 4);
+            $m = substr($ym, 5, 2);
+            $cnt = (int)$row['cnt'];
+            if (!ctype_digit($y) || !ctype_digit($m)) continue;
+            if (!isset($yearMap[$y])) {
+                $yearMap[$y] = ['cnt' => 0, 'months' => []];
+            }
+            $yearMap[$y]['cnt'] += $cnt;
+            $yearMap[$y]['months'][$m] = $cnt;
+        }
+        krsort($yearMap);
+
+        $yearChildren = [];
+        foreach ($yearMap as $y => $info) {
+            krsort($info['months']);
+            $monthChildren = [];
+            foreach ($info['months'] as $m => $cnt) {
+                $monthChildren[] = [
+                    'label'  => $y . $m . ' 【客诉 ' . $cnt . ' 次】',
+                    'type'   => 'month_stat',
+                    'year'   => (string)$y,
+                    'month'  => (string)$m,
+                ];
+            }
+            $yearChildren[] = [
+                'label'    => $y . ' 【客诉 ' . $info['cnt'] . ' 次】',
+                'type'     => 'year_stat',
+                'year'     => (string)$y,
+                'children' => $monthChildren,
+            ];
+        }
+
         // 年度客诉统计
         $treeData[] = [
-            'label' => '年度客诉统计',
-            'type'  => 'year_stat',
+            'label'    => '年度客诉统计',
+            'type'     => 'year_stat',
+            'children' => $yearChildren,
         ];
 
         $this->success('请求成功', $treeData);
@@ -97,7 +144,19 @@ class CustomerFeedback extends Api
                 $query->whereLike('Sys_id', '%' . $name . '%');
             }
         } elseif ($nodeType === 'year_stat') {
-            // 年度客诉统计 —— 查全部
+            // 年度客诉统计 —— 全部客诉;传 year 时按年度过滤
+            $year = isset($params['year']) ? trim($params['year']) : '';
+            if (!empty($year)) {
+                $query->whereRaw("LEFT(REPLACE(REPLACE(REPLACE(rtrim(`客诉日期`),'.','-'),'/','-'),'年','-'), 4) = '" . addslashes($year) . "'");
+            }
+        } elseif ($nodeType === 'month_stat') {
+            // 年度客诉统计 —— 年月节点
+            $year  = isset($params['year']) ? trim($params['year']) : '';
+            $month = isset($params['month']) ? trim($params['month']) : '';
+            if (!empty($year) && !empty($month)) {
+                $ym = $year . '-' . $month;
+                $query->whereRaw("LEFT(REPLACE(REPLACE(REPLACE(rtrim(`客诉日期`),'.','-'),'/','-'),'年','-'), 7) = '" . addslashes($ym) . "'");
+            }
         } else {
             // 默认:全部处理中(无处理完毕环节)
             $query->whereRaw($notDoneSql);

+ 400 - 106
application/api/controller/Decision.php

@@ -584,18 +584,126 @@ class Decision extends Api
         $this->success('成功', $formattedData);
     }
     /**
-     * 获取年分数据
-     * @return void
+     * 生产中心统计左侧菜单:年份 → 报表类型 → 下一级节点(全部从数据库动态取)
+     * 10 个报表类型固定返回,下一级节点按报表类型从对应数据源取实际值:
+     *   - month_* 月度类 (7个)       → 工单_质量考核汇总.sys_ny / 设备_产量计酬.sczl_rq 的 YYYYMM
+     *   - year_equipment_waste/box  → 设备_基本资料.设备编组(有实际产量数据的)
+     *   - day_output 产量日报        → 设备_产量计酬.sczl_rq 日期列表
      */
     public function GetYear()
     {
-        if ($this->request->isGet() === false){
+        if ($this->request->isGet() === false) {
             $this->error('请求错误');
         }
-        $data = \db('工单_质量考核汇总')
-                ->group('year')
-                ->column('YEAR(STR_TO_DATE(sys_ny, "%Y%m")) as year');
-        $this->success('成功',$data);
+
+        // 10 个报表类型(固定顺序)
+        $reportTypes = [
+            'month_output'           => '产量月统计报表',
+            'month_schedule'         => '排产达成率月统计',
+            'month_workhour'         => '工时达成率月统计报表',
+            'month_oee'              => 'OEE月统计报表',
+            'month_changeover'       => '换型效率月统计报表',
+            'month_ioi'              => '投入产出率月统计报表',
+            'month_processrate'      => '工序产出率月统计报表',
+            'year_equipment_waste'   => '年度设备编组废品统计',
+            'year_equipment_box'     => '年度设备大箱数统计',
+            'day_output'             => '产量日报表统计',
+        ];
+
+        // 1. 工单_质量考核汇总 有数据的年份+月份(sys_ny = YYYYMM)
+        $khMonths = Db::query("SELECT DISTINCT sys_ny AS ym FROM `工单_质量考核汇总` WHERE sys_ny REGEXP '^[0-9]{6}$' ORDER BY ym DESC");
+        $khYears = [];
+        foreach ($khMonths as $r) {
+            $y = substr($r['ym'], 0, 4);
+            $khYears[$y][] = $r['ym'];
+        }
+
+        // 2. 设备_产量计酬 有数据的年份+月份(过滤脏数据 0001xx)
+        $scMonths = Db::query("SELECT DISTINCT DATE_FORMAT(sczl_rq, '%Y%m') AS ym FROM `设备_产量计酬` WHERE sczl_rq >= '2000-01-01' AND sczl_rq IS NOT NULL ORDER BY ym DESC");
+        $scYears = [];
+        foreach ($scMonths as $r) {
+            $y = substr($r['ym'], 0, 4);
+            $scYears[$y][] = $r['ym'];
+        }
+
+        // 3. 设备_产量计酬 有数据的日期列表(近 90 天,避免太长)
+        $days = Db::query("SELECT DISTINCT DATE_FORMAT(sczl_rq, '%Y-%m-%d') AS d FROM `设备_产量计酬` WHERE sczl_rq >= DATE_SUB(CURDATE(), INTERVAL 90 DAY) AND sczl_rq IS NOT NULL ORDER BY d DESC");
+
+        // 4. 设备_基本资料 有实际产量数据的设备编组
+        $groups = Db::query("SELECT DISTINCT RTRIM(b.设备编组) AS `group`
+            FROM `设备_产量计酬` s
+            INNER JOIN `设备_基本资料` b
+                ON RTRIM(b.设备编号) = RTRIM(s.sczl_jtbh)
+            WHERE b.设备编组 IS NOT NULL AND b.设备编组 <> '' AND s.sczl_rq >= '2000-01-01'
+            ORDER BY b.设备编组 ASC");
+
+        // 所有出现过的年份(取并集,倒序)
+        $allYears = array_unique(array_merge(array_keys($khYears), array_keys($scYears)));
+        rsort($allYears);
+
+        // 月份 label:从 YYYYMM 提取 MM
+        $monthLabel = function ($ym) {
+            return intval(substr($ym, 4, 2)) . '月';
+        };
+
+        $result = [];
+        foreach ($allYears as $year) {
+            $yearInt = intval($year);
+            $yearNode = [
+                'key'    => "year_{$yearInt}",
+                'label'  => "{$yearInt}年",
+                'year'   => $yearInt,
+                'children' => [],
+            ];
+
+            foreach ($reportTypes as $typeKey => $typeLabel) {
+                $children = [];
+
+                if (strpos($typeKey, 'month_') === 0) {
+                    // 月度类:优先用 质量考核汇总 的月份,没有则 fallback 到 产量计酬
+                    $months = isset($khYears[$year]) ? $khYears[$year] : (isset($scYears[$year]) ? $scYears[$year] : []);
+                    sort($months); // 升序
+                    foreach ($months as $ym) {
+                        $children[] = [
+                            'key' => "{$yearInt}_{$ym}",
+                            'label' => $monthLabel($ym),
+                            'ym' => $ym,
+                        ];
+                    }
+                } elseif (strpos($typeKey, 'year_') === 0) {
+                    // 年度类:设备编组列表(每年份显示全部编组,数据按年份过滤在后端处理)
+                    foreach ($groups as $g) {
+                        $gname = $g['group'];
+                        $children[] = [
+                            'key' => "{$yearInt}_" . md5($gname),
+                            'label' => $gname,
+                            'group' => $gname,
+                        ];
+                    }
+                } elseif ($typeKey === 'day_output') {
+                    // 日报表:近 90 天日期
+                    foreach ($days as $d) {
+                        $dateStr = $d['d'];
+                        $children[] = [
+                            'key' => "{$yearInt}_{$dateStr}",
+                            'label' => substr($dateStr, 5), // MM-DD
+                            'date' => $dateStr,
+                        ];
+                    }
+                }
+
+                $yearNode['children'][] = [
+                    'key'     => "year_{$yearInt}_{$typeKey}",
+                    'label'   => $typeLabel,
+                    'typeKey' => $typeKey,
+                    'children' => $children,
+                ];
+            }
+
+            $result[] = $yearNode;
+        }
+
+        $this->success('成功', $result);
     }
 
     /**
@@ -1429,7 +1537,7 @@ class Decision extends Api
 
     /**
      * 年度成品入仓统计右侧表格
-     * 产品取自成品入仓(成品编码/成品名称),大箱数取自 db_包装计件 的 sczl_cl1-6,按 sczl_rq 月份汇总
+     * 产品取自成品入仓(成品编码/成品名称),大箱数取自 db_包装产量预报 的 sczl_cl1-6,按 sczl_rq 月份汇总
      */
     public function YearcprctjList()
     {
@@ -1485,8 +1593,8 @@ class Decision extends Api
             $this->success('成功', []);
         }
 
-        // 2、包装计件:按 sczl_rq 的月份汇总对应工单的 sczl_cl1-6
-        $packRows = \db('db_包装计件')
+        // 2、包装产量预报:按 sczl_rq 的月份汇总对应工单的 sczl_cl1-6
+        $packRows = \db('db_包装产量预报')
             ->field('sczl_rq, sczl_gdbh1, sczl_gdbh2, sczl_gdbh3, sczl_gdbh4, sczl_gdbh5, sczl_gdbh6, sczl_cl1, sczl_cl2, sczl_cl3, sczl_cl4, sczl_cl5, sczl_cl6')
             ->where('sczl_rq', '>=', $start)
             ->where('sczl_rq', '<', $end)
@@ -1969,29 +2077,73 @@ class Decision extends Api
                 "RTRIM(Gy0_sbbh) AS 设备编号",
                 "Gy0_计划接货数 AS 计划接货数",
                 "Gy0_ks AS 开数",
-                "Gy0_ls AS 印数",
+                "Gy0_ls AS 联数",
                 "Gy0_小时产能 AS 小时产能",
             ])
             ->whereIn('Gy0_gdbh', $gdbhs)
             ->order('工单编号, 印件号, 工序号')
             ->select();
 
-        // 3、实际工时:设备_产量计酬 中同工单+印件+工序、设备运行工时不为0的记录
+        // 3、实际工时:设备_产量计酬 中同工单+印件+工序的记录,按 sczl_sj1~sczl_sj2 时间区间合并计算
+        // 同一工单记录基本连续,不连续时中间换成其他工单的时间自然被排除(只做区间并集,不跨区间累加)
         $actualRows = \db('设备_产量计酬')
             ->field([
                 "RTRIM(sczl_gdbh) AS 工单编号",
                 "FLOOR(sczl_yjno) AS 印件号",
                 "FLOOR(sczl_gxh) AS 工序号",
-                "MAX(sczl_设备运行工时) AS 实际工时",
+                "sczl_sj1",
+                "sczl_sj2",
             ])
             ->whereIn('sczl_gdbh', $gdbhs)
-            ->where('sczl_设备运行工时', '<>', 0)
-            ->group('RTRIM(sczl_gdbh), FLOOR(sczl_yjno), FLOOR(sczl_gxh)')
             ->select();
 
-        $actualMap = [];
+        // 按 工单+印件+工序 收集时间区间
+        $intervalMap = [];
         foreach ($actualRows as $row) {
-            $actualMap[$this->DyxlKey($row['工单编号'], $row['印件号'], $row['工序号'])] = (float)$row['实际工时'];
+            $t1 = strtotime(trim((string)$row['sczl_sj1']));
+            $t2 = strtotime(trim((string)$row['sczl_sj2']));
+            if ($t1 === false || $t2 === false || $t1 <= 0 || $t2 <= 0) {
+                continue;
+            }
+            if ($t2 < $t1) {
+                // 跨午夜:结束时间顺延一天
+                $t2 += 86400;
+            }
+            if ($t2 <= $t1) {
+                continue;
+            }
+            $key = $this->DyxlKey($row['工单编号'], $row['印件号'], $row['工序号']);
+            if (!isset($intervalMap[$key])) {
+                $intervalMap[$key] = [];
+            }
+            $intervalMap[$key][] = [$t1, $t2];
+        }
+
+        // 合并时间区间并计算总时长(小时)
+        $actualMap = [];
+        foreach ($intervalMap as $key => $intervals) {
+            usort($intervals, function ($a, $b) {
+                return $a[0] - $b[0];
+            });
+            $total = 0;
+            $curStart = $intervals[0][0];
+            $curEnd = $intervals[0][1];
+            $count = count($intervals);
+            for ($i = 1; $i < $count; $i++) {
+                if ($intervals[$i][0] <= $curEnd) {
+                    // 区间重叠或相连,合并
+                    if ($intervals[$i][1] > $curEnd) {
+                        $curEnd = $intervals[$i][1];
+                    }
+                } else {
+                    // 不连续:结算当前区间,中间其他工单时间不计入
+                    $total += $curEnd - $curStart;
+                    $curStart = $intervals[$i][0];
+                    $curEnd = $intervals[$i][1];
+                }
+            }
+            $total += $curEnd - $curStart;
+            $actualMap[$key] = $total / 3600;
         }
 
         $sumPlan = [];
@@ -2110,13 +2262,13 @@ class Decision extends Api
     }
 
     /**
-     * 计划工时 = 计划接货数 * 开数 * 印数 / 小时产能
+     * 计划工时 = 计划接货数 * 开数 * 联数 / 小时产能
      */
     private function DyxlPlanHours($craft)
     {
         $qty = (float)$craft['计划接货数'];
         $ks = (float)$craft['开数'];
-        $ls = (float)$craft['印数'];
+        $ls = (float)$craft['联数'];
         $capacity = (float)$craft['小时产能'];
         if ($qty <= 0 || $ks <= 0 || $ls <= 0 || $capacity <= 0) {
             return null;
@@ -2510,9 +2662,10 @@ class Decision extends Api
         $machine = trim((string)(isset($param['machine']) ? $param['machine'] : ''));
 
         // 以数据库最新日期为基准,取最近 7 天
-        $maxDate = \db('设备_产量计酬')->max('sczl_rq'); 
+        // $maxDate = \db('设备_产量计酬')->max('sczl_rq'); 
+        $maxDate = "2026-10-11";
         if (!$maxDate) {
-            $this->success('成功', ['summary' => [], 'detail' => [], 'range' => ['start' => '', 'end' => '']]);
+            $this->success('成功', ['summary' => [], 'detail' => [], 'days' => [], 'range' => ['start' => '', 'end' => '']]);
         }
         $maxTs = strtotime($maxDate);
         $end = date('Y-m-d', $maxTs);
@@ -2520,41 +2673,90 @@ class Decision extends Api
         $startTime = $start . ' 00:00:00';
         $endTime = date('Y-m-d', $maxTs + 86400) . ' 00:00:00';
 
-        // 1、汇总:按机台编号聚合
-        $summaryQuery = \db('设备_产量计酬')
-            ->alias('s')
-            ->join('设备_基本资料 b', 'RTRIM(b.设备编号) = RTRIM(s.sczl_jtbh)', 'LEFT')
+        // 7 天日期列表(新 -> 旧)
+        $days = [];
+        for ($i = 0; $i < 7; $i++) {
+            $days[] = date('Y-m-d', $maxTs - $i * 86400);
+        }
+        $dayLabels = [];
+        foreach ($days as $d) {
+            $dayLabels[] = date('m.d', strtotime($d));
+        }
+
+        // 机台清单(与左侧树口径一致:排除研发中心、设备编组/机台编号为空)
+        $machineQuery = \db('设备_基本资料')
+            ->where('使用部门', '<>', '研发中心')
+            ->where('设备编组', '<>', '')
+            ->where('sys_sbID', '<>', '')
+            ->field('RTRIM(设备编号) AS 机台编号, RTRIM(设备名称) AS 设备名称')
+            ->order('设备编号');
+        if ($machine !== '') {
+            $machineQuery->where('设备编号', $machine);
+        }
+        $machineList = $machineQuery->select();
+
+        // 1、汇总:机台 x 日期 => 产量(当天汇总)+ 工时(sczl_sj2 - sczl_sj1 合计)
+        $recordQuery = \db('设备_产量计酬')
             ->field([
-                'RTRIM(s.sczl_jtbh) AS 机台编号',
-                'RTRIM(b.设备名称) AS 设备名称',
-                'RTRIM(b.使用部门) AS 使用部门',
-                'RTRIM(b.生产工序) AS 生产工序',
-                'RTRIM(b.设备编组) AS 设备编组',
-                'SUM(s.sczl_cl) AS 总产量',
-                'SUM(s.sczl_设备运行工时) AS 设备运行工时',
-                'SUM(s.sczl_装版工时) AS 装版工时',
-                'SUM(s.sczl_装版总工时) AS 装版总工时',
-                'SUM(s.sczl_保养工时) AS 保养工时',
-                'SUM(s.sczl_打样工时) AS 打样工时',
-                'SUM(s.sczl_打样总工时) AS 打样总工时',
-                'SUM(s.sczl_异常停机工时) AS 异常停机工时',
-                'SUM(s.sczl_zcfp) AS 制程废品',
-                'SUM(s.sczl_zccp) AS 制程次品',
-                'SUM(s.sczl_前工序废) AS 前工序废',
-                'SUM(s.sczl_来料少数) AS 来料少数',
-                'SUM(s.sczl_异常工时1) AS 异常补时',
+                'RTRIM(sczl_jtbh) AS 机台编号',
+                "DATE_FORMAT(sczl_rq, '%Y-%m-%d') AS 日期",
+                'sczl_cl',
+                'sczl_sj1',
+                'sczl_sj2',
             ])
-            ->where('s.sczl_rq', '>=', $startTime)
-            ->where('s.sczl_rq', '<', $endTime);
-
+            ->where('sczl_rq', '>=', $startTime)
+            ->where('sczl_rq', '<', $endTime);
         if ($machine !== '') {
-            $summaryQuery->where('s.sczl_jtbh', $machine);
+            $recordQuery->where('sczl_jtbh', $machine);
         }
+        $records = $recordQuery->select();
 
-        $summary = $summaryQuery
-            ->group('机台编号, 设备名称, 使用部门, 生产工序, 设备编组')
-            ->order('机台编号')
-            ->select();
+        $agg = [];
+        foreach ($records as $r) {
+            $code = trim((string)$r['机台编号']);
+            $day = trim((string)$r['日期']);
+            if ($code === '' || $day === '') {
+                continue;
+            }
+            if (!isset($agg[$code])) {
+                $agg[$code] = [];
+            }
+            if (!isset($agg[$code][$day])) {
+                $agg[$code][$day] = ['产量' => 0, '工时' => 0];
+            }
+            $agg[$code][$day]['产量'] += (float)$r['sczl_cl'];
+            $t1 = strtotime(trim((string)$r['sczl_sj1']));
+            $t2 = strtotime(trim((string)$r['sczl_sj2']));
+            if ($t1 !== false && $t2 !== false && $t1 > 0 && $t2 > 0) {
+                if ($t2 < $t1) {
+                    // 跨午夜:结束时间顺延一天
+                    $t2 += 86400;
+                }
+                if ($t2 > $t1) {
+                    $agg[$code][$day]['工时'] += ($t2 - $t1) / 3600;
+                }
+            }
+        }
+
+        $summary = [];
+        foreach ($machineList as $m) {
+            $code = trim((string)$m['机台编号']);
+            if ($code === '') {
+                continue;
+            }
+            $row = [
+                '机台编号' => $code,
+                '设备名称' => trim((string)$m['设备名称']),
+            ];
+            foreach ($days as $idx => $day) {
+                $label = $dayLabels[$idx];
+                $cl = isset($agg[$code][$day]) ? $agg[$code][$day]['产量'] : 0;
+                $gs = isset($agg[$code][$day]) ? $agg[$code][$day]['工时'] : 0;
+                $row['产量_' . $label] = $cl == 0 ? '' : round($cl, 2);
+                $row['工时_' . $label] = $gs == 0 ? '' : round($gs, 2);
+            }
+            $summary[] = $row;
+        }
 
         // 2、明细:工单级(按 机台编号 + 工单编号 + 日期 聚合)
         $detailQuery = \db('设备_产量计酬')
@@ -2592,14 +2794,6 @@ class Decision extends Api
             ->select();
 
         // 数值格式化(0 显示为空字符串)
-        foreach ($summary as &$row) {
-            foreach (['总产量', '设备运行工时', '装版工时', '装版总工时', '保养工时', '打样工时', '打样总工时', '异常停机工时', '制程废品', '制程次品', '前工序废', '来料少数', '异常补时'] as $k) {
-                $v = (float)$row[$k];
-                $row[$k] = $v === 0 ? '' : round($v, 2);
-            }
-        }
-        unset($row);
-
         foreach ($detail as &$row) {
             foreach (['产量', '设备运行工时', '装版工时', '保养工时', '打样工时', '异常停机工时', '制程废品', '制程次品'] as $k) {
                 $v = (float)$row[$k];
@@ -2611,6 +2805,7 @@ class Decision extends Api
         $this->success('成功', [
             'summary' => $summary,
             'detail' => $detail,
+            'days' => $dayLabels,
             'range' => ['start' => $start, 'end' => $end],
         ]);
     }
@@ -2625,15 +2820,26 @@ class Decision extends Api
             $this->error('请求错误');
         }
 
+        // 条件:近12个月内「末版入仓完工」的工单(末版入仓 jjcp_smb like 末% 即视为完工)
+        // 月份分组 = 末版入仓完工日期 MAX(jjcp_sj)
+        // 客户代号/客户名称:产品_基本资料(按成品编码 Gd_cpdh 关联),工单自身客户字段只做兜底
         $sql = "SELECT
-            DATE_FORMAT(a.接单日期, '%Y%m') AS date,
+            DATE_FORMAT(c.完工时间, '%Y%m') AS date,
             COUNT(DISTINCT a.Gd_gdbh) AS cnt,
-            RTRIM(a.Gd_客户代号) AS code,
-            RTRIM(a.Gd_客户名称) AS name
+            RTRIM(COALESCE(p.客户编号, a.Gd_客户代号)) AS code,
+            RTRIM(COALESCE(p.客户名称, a.Gd_客户名称)) AS name
         FROM `工单_基本资料` a
-        WHERE a.接单日期 >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
-          AND a.接单日期 IS NOT NULL
-          AND (a.工单完工日期 IS NOT NULL OR EXISTS (SELECT 1 FROM `成品入仓` c WHERE c.jjcp_gdbh = a.Gd_gdbh))
+        LEFT JOIN `产品_基本资料` p
+            ON RTRIM(a.Gd_cpdh) = RTRIM(p.产品编号)
+        INNER JOIN (
+            SELECT jjcp_gdbh, jjcp_yjno, MAX(jjcp_sj) AS 完工时间
+            FROM `成品入仓`
+            WHERE jjcp_smb LIKE '末%'
+            GROUP BY jjcp_gdbh, jjcp_yjno
+        ) c
+            ON a.Gd_gdbh = c.jjcp_gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(c.jjcp_yjno AS UNSIGNED)
+        WHERE c.完工时间 >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
+          AND c.完工时间 IS NOT NULL
         GROUP BY date, code, name
         ORDER BY date DESC, code ASC";
         $rows = Db::query($sql);
@@ -2691,16 +2897,15 @@ class Decision extends Api
         $offset = ($page - 1) * $limit;
 
         $where = [];
-        $where[] = "a.接单日期 >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)";
-        $where[] = "a.接单日期 IS NOT NULL";
-        $where[] = "(a.工单完工日期 IS NOT NULL AND a.工单完工日期 <> '1900-01-01 00:00:00') OR EXISTS (SELECT 1 FROM `成品入仓` c2 WHERE c2.jjcp_gdbh = a.Gd_gdbh)";
+        $where[] = "c.完工时间 >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)";
+        $where[] = "c.完工时间 IS NOT NULL";
 
         if ($date !== '') {
-            $where[] = "DATE_FORMAT(a.接单日期, '%Y%m') = " . intval($date);
+            $where[] = "DATE_FORMAT(c.完工时间, '%Y%m') = " . intval($date);
         }
         if ($code !== '') {
             $escaped = str_replace("'", "''", $code);
-            $where[] = "UPPER(RTRIM(a.Gd_客户代号)) = UPPER(RTRIM('{$escaped}'))";
+            $where[] = "UPPER(RTRIM(COALESCE(p.客户编号, a.Gd_客户代号))) = UPPER(RTRIM('{$escaped}'))";
         }
         if ($search !== '') {
             $escaped = str_replace("'", "''", $search);
@@ -2709,19 +2914,37 @@ class Decision extends Api
 
         $whereSql = implode(' AND ', $where);
 
-        // 公共 FROM 段(与 a 表 1:1 关联,可用于统计总数)
+        // 公共 FROM 段(成品入仓只取末版 jjcp_smb like 末%,无末版入仓的工单不参与统计)
         $fromSql = "FROM `工单_基本资料` a
+        LEFT JOIN `产品_基本资料` p
+            ON RTRIM(a.Gd_cpdh) = RTRIM(p.产品编号)
         LEFT JOIN `工单_印件资料` b
-            ON a.Gd_gdbh = b.Yj_Gdbh AND CAST(a.行号 AS UNSIGNED) = b.yj_Yjno
-        LEFT JOIN (
+            ON a.Gd_gdbh = b.Yj_Gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(b.yj_Yjno AS UNSIGNED)
+        INNER JOIN (
             SELECT jjcp_gdbh, jjcp_yjno,
                 SUM(jjcp_sl) AS 入仓数量,
-                MIN(jjcp_sj) AS 检验日期,
-                MAX(jjcp_sj) AS 入仓完工日期
+                MIN(jjcp_sj) AS 检验时间,
+                MAX(jjcp_sj) AS 完工时间
             FROM `成品入仓`
+            WHERE jjcp_smb LIKE '末%'
             GROUP BY jjcp_gdbh, jjcp_yjno
         ) c
-            ON a.Gd_gdbh = c.jjcp_gdbh AND CAST(a.行号 AS UNSIGNED) = c.jjcp_yjno
+            ON a.Gd_gdbh = c.jjcp_gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(c.jjcp_yjno AS UNSIGNED)
+        LEFT JOIN (
+            SELECT RTRIM(sczl_gdbh) AS gdbh, sczl_yjno,
+                MIN(sczl_rq) AS 生产开工时间,
+                MIN(CASE WHEN sczl_gxmc LIKE '%模切%' THEN sczl_rq END) AS 模切开工时间
+            FROM `设备_产量计酬`
+            WHERE sczl_rq >= DATE_SUB(CURDATE(), INTERVAL 13 MONTH)
+            GROUP BY RTRIM(sczl_gdbh), sczl_yjno
+        ) gy
+            ON a.Gd_gdbh = gy.gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(gy.sczl_yjno AS UNSIGNED)
+        LEFT JOIN (
+            SELECT Gy0_gdbh, 印件及工序 AS 印件号, SUM(DISTINCT 计划损耗) AS 计划损耗
+            FROM `工单_质量考核汇总`
+            GROUP BY Gy0_gdbh, 印件及工序
+        ) q
+            ON a.Gd_gdbh = q.Gy0_gdbh AND CAST(a.行号 AS UNSIGNED) = CAST(q.印件号 AS UNSIGNED)
         WHERE {$whereSql}";
 
         // 总数
@@ -2738,47 +2961,63 @@ class Decision extends Api
             a.实际投料,
             RTRIM(a.计量单位) AS 计量单位,
             IFNULL(c.入仓数量, 0) AS 入仓数量,
-            DATEDIFF(COALESCE(DATE(c.检验日期), DATE(a.工单完工日期)), DATE(a.接单日期)) AS 工单周期,
-            DATE(COALESCE(c.检验日期, a.工单完工日期)) AS 检验日期,
-            TIME(COALESCE(c.检验日期, a.工单完工日期)) AS 检验时间,
+            DATE(c.检验时间) AS 检验日期,
+            DATE(COALESCE(c.完工时间, NULLIF(a.入仓日期, '1900-01-01 00:00:00'), NULLIF(a.工单完工日期, '1900-01-01 00:00:00'))) AS 入仓完工日期,
             DATE(a.接单日期) AS 接单日期,
-            DATE(COALESCE(c.入仓完工日期, NULLIF(a.入仓日期, '1900-01-01 00:00:00'), a.工单完工日期)) AS 入仓完工日期,
-            RTRIM(a.Gd_客户代号) AS 客户代号,
-            RTRIM(a.Gd_客户名称) AS 客户名称,
+            DATE(gy.生产开工时间) AS 生产开工日期,
+            DATE(gy.模切开工时间) AS 模切开工日期,
+            IFNULL(q.计划损耗, 0) AS 计划损耗,
+            RTRIM(COALESCE(p.客户编号, a.Gd_客户代号)) AS 客户代号,
+            RTRIM(COALESCE(p.客户名称, a.Gd_客户名称)) AS 客户名称,
             RTRIM(a.销售订单号) AS 销售订单号
         {$fromSql}
-        ORDER BY COALESCE(c.检验日期, a.工单完工日期) DESC, a.Gd_gdbh DESC
+        ORDER BY COALESCE(c.完工时间, a.工单完工日期) DESC, a.Gd_gdbh DESC
         LIMIT {$offset}, {$limit}";
 
         $list = Db::query($sql);
 
-        foreach ($list as &$row) {
-            $row['生产公分'] = '';
-            $row['工单公休'] = '';
-            $row['计划开工日期'] = '';
-            $row['实际开工日期'] = '';
-            $row['目标合格率'] = '';
-
-            foreach (['订单数量', '实际投料'] as $k) {
-                $v = (float)$row[$k];
-                $row[$k] = $v === 0 ? '' : number_format($v, 2);
-            }
-            $row['入仓数量'] = (int)$row['入仓数量'] === 0 ? '' : (int)$row['入仓数量'];
-            $row['工单周期'] = $row['工单周期'] === null ? '' : (int)$row['工单周期'];
-
-            $sl = (int)$row['入仓数量'];
-            $tl = (float)$row['实际投料'];
-            if ($sl > 0 && $tl > 0) {
-                $row['实际合格率'] = number_format($sl / ($tl * 10000) * 100, 2) . '%';
-            } else {
-                $row['实际合格率'] = '';
-            }
+        // 月度公休记录(用于生产公休/检验公休/工单公休)
+        $holidayMap = $this->CopsHolidayMap();
 
-            foreach (['检验日期', '检验时间', '接单日期', '入仓完工日期'] as $k) {
-                if ($row[$k] === null || $row[$k] === '1900-01-01' || $row[$k] === '1900-01-01 00:00:00') {
+        foreach ($list as &$row) {
+            // 先取原始数值,避免格式化后再次转换出错
+            $rawOrder = (float)$row['订单数量'];
+            $rawActual = (float)$row['实际投料'];
+            $warehouseNum = (int)$row['入仓数量'];
+            $planLoss = (float)$row['计划损耗'];
+
+            $row['订单数量'] = $rawOrder == 0 ? '' : number_format($rawOrder, 2);
+            $row['实际投料'] = $rawActual == 0 ? '' : number_format($rawActual, 2);
+            $row['入仓数量'] = $warehouseNum === 0 ? '' : $warehouseNum;
+
+            // 目标合格率 = (实际投料*10000 - 计划损耗) / (实际投料*10000)
+            $row['目标合格率'] = $rawActual > 0
+                ? number_format(($rawActual * 10000 - $planLoss) / ($rawActual * 10000) * 100, 2) . '%'
+                : '';
+            // 实际合格率 = 入仓数量 / (实际投料*10000)
+            $row['实际合格率'] = ($warehouseNum > 0 && $rawActual > 0)
+                ? number_format($warehouseNum / ($rawActual * 10000) * 100, 2) . '%'
+                : '';
+
+            // 日期空值处理
+            foreach (['检验日期', '接单日期', '入仓完工日期', '生产开工日期', '模切开工日期'] as $k) {
+                $v = (string)$row[$k];
+                if ($v === '' || $v === '0000-00-00' || strpos($v, '1900-01-01') === 0) {
                     $row[$k] = '';
                 }
             }
+
+            // 周期(自然日)
+            // $row['生产周期'] = $this->CopsCycle($row['生产开工日期'], $row['检验日期']);
+            // $row['检验周期'] = $this->CopsCycle($row['检验日期'], $row['入仓完工日期']);
+            $row['工单周期'] = $this->CopsCycle($row['接单日期'], $row['入仓完工日期']);
+
+            // // 公休天数(区间内 人事_班组公休记录 之和)
+            // $row['生产公休'] = $this->CopsHolidaySum($holidayMap, $row['生产开工日期'], $row['检验日期']);
+            // $row['检验公休'] = $this->CopsHolidaySum($holidayMap, $row['检验日期'], $row['入仓完工日期']);
+            // $row['工单公休'] = $this->CopsHolidaySum($holidayMap, $row['接单日期'], $row['入仓完工日期']);
+
+            unset($row['计划损耗']);
         }
         unset($row);
 
@@ -2789,4 +3028,59 @@ class Decision extends Api
             'limit' => $limit,
         ]);
     }
+
+    /**
+     * 读取月度公休记录(人事_班组公休记录),返回 [Y-m-d => 公休天数]
+     */
+    private function CopsHolidayMap()
+    {
+        $map = [];
+        $rows = Db::query("SELECT DATE_FORMAT(公休_日期, '%Y-%m-%d') AS d, SUM(公休_天数) AS days
+            FROM `人事_班组公休记录`
+            WHERE 公休_日期 IS NOT NULL
+            GROUP BY d");
+        foreach ($rows as $r) {
+            $map[$r['d']] = (float)$r['days'];
+        }
+        return $map;
+    }
+
+    /**
+     * 统计区间 (start, end] 内的公休天数
+     */
+    private function CopsHolidaySum(array $map, $start, $end)
+    {
+        if (empty($start) || empty($end)) {
+            return '';
+        }
+        $s = strtotime($start);
+        $e = strtotime($end);
+        if ($s === false || $e === false || $e <= $s) {
+            return 0;
+        }
+        $sum = 0;
+        foreach ($map as $d => $days) {
+            $t = strtotime($d);
+            if ($t !== false && $t > $s && $t <= $e) {
+                $sum += $days;
+            }
+        }
+        return round($sum, 1);
+    }
+
+    /**
+     * 两个日期之间的自然日天数
+     */
+    private function CopsCycle($start, $end)
+    {
+        if (empty($start) || empty($end)) {
+            return '';
+        }
+        $s = strtotime($start);
+        $e = strtotime($end);
+        if ($s === false || $e === false) {
+            return '';
+        }
+        return (int)round(($e - $s) / 86400);
+    }
 }

+ 287 - 6
application/api/controller/Facility.php

@@ -86,7 +86,7 @@ class Facility extends Api
      * @throws \think\db\exception\ModelNotFoundException
      * @throws \think\exception\DbException
      */
-    public function chanLiang()
+      public function chanLiang()
     {
         if ($this->request->isGet() === false){
             $this->error('请求错误');
@@ -1265,6 +1265,50 @@ class Facility extends Api
         $this->success('成功',$list);
     }
 
+    /**
+     * 换型清场->根据机台获取设备_产量采集最新两个工单
+     * 返回工单编号、印件号、工序名称,以及关联工单_印件资料得到的印件名称(yj_yjmc)
+     * @ApiMethod (GET)
+     * @param string $machine 设备编号
+     * @return void
+     */
+    public function RemodelLastOrders()
+    {
+        if ($this->request->isGet() === false){
+            $this->error('请求错误');
+        }
+        $machine = rtrim(trim($this->request->param('machine')), '#');
+        if (empty($machine)){
+            $this->error('参数错误');
+        }
+        // 设备_产量采集中的设备编号有的带 # 后缀(如 JP01#),有的不带,统一兼容
+        $rows = \db('设备_产量采集')
+            ->where('设备编号', 'in', [$machine, $machine . '#'])
+            ->where('工单编号', '<>', '')
+            ->field('工单编号, 印件号, 工序名称, MAX(UniqId) AS latest')
+            ->group('工单编号, 印件号, 工序名称')
+            ->order('latest desc')
+            ->limit(2)
+            ->select();
+
+        $list = [];
+        foreach ($rows as $row) {
+            $gdbh = rtrim($row['工单编号']);
+            $yjno = rtrim($row['印件号']);
+            $printName = \db('工单_印件资料')
+                ->where('Yj_Gdbh', $gdbh)
+                ->where('yj_Yjno', $yjno)
+                ->value('yj_yjmc');
+            $list[] = [
+                '工单编号' => $gdbh,
+                '印件号'   => $yjno,
+                '工序名称' => rtrim($row['工序名称']),
+                '印件名称' => $printName ? rtrim($printName) : '',
+            ];
+        }
+        $this->success('成功', $list);
+    }
+
     /**
      * 换型清场->当前设备清场记录
      * @ApiMethod (GET)
@@ -2743,9 +2787,212 @@ class Facility extends Api
         }
         if ($i!==0){
             $this->error('修改失败');
-        }else{
-            $this->success('修改成功');
         }
+        // 同步标记 AI 校验结果:已按推荐系数修正,避免刷新后仍显示 ❌
+        // 下次定时校验会重新用最新工价系数比对并覆盖本状态
+        try {
+            \db('agent_难度系数校验结果')
+                ->where('UniqId','in',$idList)
+                ->update([
+                    'audit_result' => '✅已修正',
+                    'audit_note'   => '已按推荐系数修正为 '.$params['工价系数'],
+                ]);
+        } catch (\Exception $e) {
+            // 校验结果表异常不影响工价系数修改主流程
+        }
+        $this->success('修改成功');
+    }
+
+    /**
+     * 难度系数校验 - 左侧菜单(车间→日期两级,日期为最近30天)
+     * @ApiMethod (GET)
+     * @return void
+     */
+    public function getCoefTab()
+    {
+        if ($this->request->isGet() === false){
+            $this->error('请求错误');
+        }
+        // 近30天有校验结果的日期(从 agent 表取,只看有校验的)
+        $startDate = date('Y-m-d 00:00:00', strtotime('-30 days'));
+        // 先从 agent 表拿到 UniqId,再关联产量计酬表取机台和日期
+        $agentUids = \db('agent_难度系数校验结果')
+            ->where('难度系数校验','>=',$startDate)
+            ->column('UniqId');
+        if (empty($agentUids)){
+            $this->success('成功',[]);
+        }
+        $list = \db('设备_产量计酬')
+            ->where('UniqId','in',$agentUids)
+            ->where('sczl_rq','>=',$startDate)
+            ->distinct(true)
+            ->field('rtrim(sczl_jtbh) as 机台编号,DATE(sczl_rq) as sczl_date')
+            ->select();
+        if (empty($list)){
+            $this->success('成功',[]);
+        }
+        $machineCodes = array_values(array_unique(array_column($list,'机台编号')));
+        // 机台所属车间
+        $machines = \db('设备_基本资料')
+            ->whereIn('设备编号',$machineCodes)
+            ->where('使用部门','<>','研发中心')
+            ->where('sys_sbID','<>','')
+            ->column('rtrim(使用部门)','rtrim(设备编号)');
+        // 按 车间 → 日期 分组
+        $data = [];
+        foreach ($list as $row){
+            $workshop = isset($machines[$row['机台编号']]) ? $machines[$row['机台编号']] : '未知车间';
+            $date = $row['sczl_date'];
+            if (!isset($data[$workshop])){
+                $data[$workshop] = [];
+            }
+            $data[$workshop][$date] = true;
+        }
+        // 排序:日期倒序
+        foreach ($data as &$dates){
+            krsort($dates);
+            $dates = array_keys($dates);
+        }
+        $this->success('成功',$data);
+    }
+
+    /**
+     * 难度系数校验 - 按日期查询产量数据(带推荐系数和校验结果)
+     * @ApiMethod (GET)
+     * @param string $date 日期 YYYY-MM-DD
+     * @return void
+     */
+    public function getCoefList()
+    {
+        if ($this->request->isGet() === false){
+            $this->error('请求错误');
+        }
+        $date = input('date');
+        if (empty($date)){
+            $this->error('参数错误');
+        }
+        // 先拿 agent 表中该日期的 UniqId
+        $startDay = $date.' 00:00:00';
+        $endDay   = $date.' 23:59:59';
+        $agentList = \db('agent_难度系数校验结果')
+            ->where('sczc_rq','>=',$startDay)
+            ->where('sczc_rq','<=',$endDay)
+            ->field('UniqId,suggested_wage_coef,audit_result,audit_note')
+            ->select();
+        if (empty($agentList)){
+            $this->success('成功',[]);
+        }
+        $agentRows = [];
+        $uniqIds = [];
+        foreach ($agentList as $agent){
+            $uid = trim($agent['UniqId']);
+            $agentRows[$uid] = $agent;
+            $uniqIds[] = $uid;
+        }
+        $uniqIds = array_values(array_unique($uniqIds));
+        $field = 'rtrim(sczl_jtbh) as 机台编号,rtrim(sczl_gdbh) as 工单编号,rtrim(sczl_yjno) as yjno,
+        rtrim(sczl_gxh) as gxh,rtrim(sczl_gxmc) as gxmc,
+        rtrim(sczl_bzdh) as bzdh,rtrim(UniqId) as UniqId,
+        rtrim(sczl_工价系数) as 难度系数,
+        sczl_bh1,sczl_bh2,sczl_bh3,sczl_bh4,sczl_bh5,sczl_bh6,sczl_bh7,sczl_bh8,sczl_bh9,sczl_bh10';
+        $list = \db('设备_产量计酬')
+            ->where('UniqId','in',$uniqIds)
+            ->field($field)
+            ->select();
+        if (empty($list)){
+            $this->success('成功',[]);
+        }
+        // 过滤:只保留 agent 表有的 UniqId(产量表可能有多条同 UniqId,其实是 1:1)
+        $list = array_values(array_filter($list,function($row) use ($agentRows){
+            return isset($agentRows[trim($row['UniqId'])]);
+        }));
+        if (empty($list)){
+            $this->success('成功',[]);
+        }
+        // 批量取产品名称
+        $gdbhs = array_values(array_unique(array_column($list,'工单编号')));
+        $productMap = [];
+        $productList = \db('工单_基本资料')
+            ->whereIn('Gd_gdbh',$gdbhs)
+            ->field('rtrim(Gd_gdbh) as gdbh,rtrim(成品名称) as 成品名称')
+            ->select();
+        foreach ($productList as $product){
+            $productMap[trim($product['gdbh'])] = $product['成品名称'];
+        }
+        // 批量取工价系数
+        $processMap = [];
+        $processList = \db('工单_工艺资料')
+            ->whereIn('Gy0_gdbh',$gdbhs)
+            ->field('rtrim(Gy0_gdbh) as gdbh,rtrim(Gy0_yjno) as yjno,rtrim(Gy0_gxh) as gxh,rtrim(工价系数) as 工价系数')
+            ->select();
+        foreach ($processList as $process){
+            $processMap[trim($process['gdbh']).'|'.trim($process['yjno']).'|'.trim($process['gxh'])] = $process['工价系数'];
+        }
+        // 批量取组员姓名
+        $memberCodes = [];
+        foreach ($list as $row){
+            for ($i=1;$i<11;$i++){
+                if (!empty($row['sczl_bh'.$i])){
+                    $memberCodes[] = $row['sczl_bh'.$i];
+                }
+            }
+        }
+        $memberCodes = array_values(array_unique($memberCodes));
+        $memberMap = [];
+        if (!empty($memberCodes)){
+            $memberList = \db('人事_基本资料')
+                ->whereIn('员工编号',$memberCodes)
+                ->field('rtrim(员工编号) as 员工编号,rtrim(员工姓名) as 员工姓名')
+                ->select();
+            foreach ($memberList as $member){
+                $memberMap[trim($member['员工编号'])] = $member['员工姓名'];
+            }
+        }
+        foreach ($list as $key=>$value){
+            $gdbh = trim($value['工单编号']);
+            // 产品名称(带工单编号)
+            $productName = isset($productMap[$gdbh]) && $productMap[$gdbh] !== '' ? $productMap[$gdbh] : $gdbh;
+            $list[$key]['产品名称'] = $gdbh.' '.$productName;
+            // 难度系数 = 基础工价系数 x 计酬难度系数
+            $processKey = $gdbh.'|'.trim($value['yjno']).'|'.trim($value['gxh']);
+            if (isset($processMap[$processKey])){
+                if ($value['难度系数'] == 0){
+                    $list[$key]['难度系数'] = $processMap[$processKey];
+                }else{
+                    $list[$key]['难度系数'] = $processMap[$processKey].'x'.$value['难度系数'];
+                }
+            }else{
+                $list[$key]['难度系数'] = '';
+            }
+            // 工序展示
+            if ($value['yjno']<10){
+                $yjno = '0'.$value['yjno'];
+            }else{
+                $yjno = $value['yjno'];
+            }
+            $list[$key]['工序'] = $yjno.'-'.$value['gxmc'];
+            // 组员
+            $codes = [];
+            $names = [];
+            for ($i=1;$i<11;$i++){
+                $bh = 'sczl_bh'.$i;
+                if (!empty($value[$bh])){
+                    $codes[] = $value[$bh];
+                    $names[] = $value[$bh].(isset($memberMap[$value[$bh]]) ? $memberMap[$value[$bh]] : '');
+                }
+                unset($list[$key][$bh]);
+            }
+            $list[$key]['组员编码'] = $codes;
+            $list[$key]['组员姓名'] = $names;
+            $list[$key]['组员文本'] = implode(',',$names);
+            // AI 推荐系数 + 审核结果
+            $agent = $agentRows[trim($value['UniqId'])];
+            $list[$key]['推荐系数'] = $agent['suggested_wage_coef'];
+            $auditResult = trim((string)$agent['audit_result']);
+            $auditNote = trim((string)$agent['audit_note']);
+            $list[$key]['结果'] = $auditResult.($auditNote !== '' ? ':'.$auditNote : '');
+        }
+        $this->success('成功',$list);
     }
 
     /**
@@ -3207,8 +3454,42 @@ class Facility extends Api
             '设备编号' => $param['machine'],
             '提交时间' => ['like',$param['date'].'%'],
         ];
-        $field = '类别,工单编号,印件号,工序名称,流程单号,班组编号,检验项目,检验备注,提交时间';
-        $data = \db('制程检验_记录')->where($where)->field($field)->select();
-        $this->success('成功',$data);
+        $field = '类别,工单编号,印件号,工序名称,流程单号,班组编号,检验项目,检验备注,提交时间,检验结果,相关标准 as 修改标准';
+        $rows = \db('制程检验_记录')->where($where)->field($field)->order('提交时间')->select();
+
+        // 按 提交时间 分组合并(与 ProductionLot::ProcessInspection 口径保持一致)
+        $grouped = [];
+        $orderKey = [];
+        foreach ($rows as $row) {
+            $key = (string)$row['提交时间'];
+            if (!isset($grouped[$key])) {
+                $grouped[$key] = [
+                    '类别'     => $row['类别'],
+                    '工单编号' => $row['工单编号'],
+                    '印件号'   => $row['印件号'],
+                    '工序名称' => $row['工序名称'],
+                    '流程单号' => $row['流程单号'],
+                    '班组编号' => $row['班组编号'],
+                    '检验项目' => $row['检验项目'],
+                    '检验备注' => $row['检验备注'],
+                    '提交时间' => $row['提交时间'],
+                    'items'    => [],   // 这一次提交的所有项目
+                ];
+                $orderKey[] = $key;
+            }
+            $grouped[$key]['items'][] = $row;
+        }
+
+        // 检验项目:只放首个 + "共N项"
+        $result = [];
+        foreach ($orderKey as $key) {
+            $g = $grouped[$key];
+            $cnt = count($g['items']);
+            if ($cnt > 1) {
+                $g['检验项目'] = $g['items'][0]['检验项目'] . ' ... (共' . $cnt . '项)';
+            }
+            $result[] = $g;
+        }
+        $this->success('成功',$result);
     }
 }

+ 463 - 2
application/api/controller/OrderSuperLoss.php

@@ -1615,10 +1615,10 @@ class OrderSuperLoss extends Api
         b.`材料废`,  
         b.`零头处理`,  
         b.`外发废`,  
-        SUM(b.`班组制程废品`) AS zcfp,  
+        SUM(b.`班组制程废品`) AS zcfp,
         `工单质检废` AS 工单质检废,
         c.质量考核,
-        c.工单类型
+        IFNULL(cs.索赔合计, 0) AS 材料索赔
     ';
 
         // 子查询:计算所有记录的 jjcp_sl 总和(入仓数量)
@@ -1632,11 +1632,23 @@ class OrderSuperLoss extends Api
             ->group('a_sub.jjcp_gdbh, a_sub.jjcp_yjno')
             ->buildSql();
 
+        // 子查询:材料索赔合计(按 工单编号+印件号 汇总 工单_索赔记录.num)
+        $claimSub = \db('工单_索赔记录')
+            ->alias('cl')
+            ->field('
+        cl.gdbh AS claim_gdbh,
+        cl.yjno AS claim_yjno,
+        SUM(cl.num) AS 索赔合计
+        ')
+            ->group('cl.gdbh, cl.yjno')
+            ->buildSql();
+
         $list = \db('成品入仓')
             ->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')
             ->join([$subQuery => 'total_sl'], 'a.jjcp_gdbh = total_sl.Gd_gdbh_sub AND a.jjcp_yjno = total_sl.jjcp_yjno_sub', 'left')
+            ->join([$claimSub => 'cs'], 'a.jjcp_gdbh = cs.claim_gdbh AND a.jjcp_yjno = cs.claim_yjno', 'left')
             ->field($field)
             ->where($where)
             ->where('a.jjcp_smb','like','末%')
@@ -3077,5 +3089,454 @@ class OrderSuperLoss extends Api
         }
 
     }
+
+    // ============ 工单索赔记录(工单_索赔记录 表) ============
+
+    /**
+     * 获取索赔记录列表
+     * @ApiMethod GET
+     * @params string gdbh  工单编号
+     * @params int    yjno  印件号
+     */
+    public function getClaimList()
+    {
+        if (!$this->request->isGet()) {
+            $this->error('非法请求');
+        }
+        $params = $this->request->param();
+        if (empty($params['gdbh']) || empty($params['yjno'])) {
+            $this->error('参数错误');
+        }
+        $list = \db('工单_索赔记录')
+            ->where('gdbh', $params['gdbh'])
+            ->where('yjno', intval($params['yjno']))
+            ->order('sys_rq desc, Uniqid desc')
+            ->select();
+        $this->success('成功', $list);
+    }
+
+    /**
+     * 新增索赔记录
+     * @ApiMethod POST
+     */
+    public function addClaim()
+    {
+        if (!$this->request->isPost()) {
+            $this->error('请求错误');
+        }
+        $param = $this->request->post();
+        $required = ['gdbh', 'yjno', 'wlbh', 'wl_name', 'num', 'sys_id'];
+        foreach ($required as $f) {
+            if (!isset($param[$f]) || $param[$f] === '' || $param[$f] === null) {
+                $this->error("参数 {$f} 不能为空");
+            }
+        }
+        $data = [
+            'gdbh'       => $param['gdbh'],
+            'yjno'       => intval($param['yjno']),
+            'wlbh'       => $param['wlbh'],
+            '物料名称'    => $param['wl_name'],
+            'num'        => intval($param['num']),
+            'sys_id'     => $param['sys_id'],
+            'sys_rq'     => date('Y-m-d'),
+        ];
+        $sql = \db('工单_索赔记录')->fetchSql(true)->insert($data);
+        $res = Db::execute($sql);
+        if ($res) {
+            $this->success('新增成功');
+        } else {
+            $this->error('新增失败');
+        }
+    }
+
+    /**
+     * 修改索赔记录(只允许修改 num;wlbh/物料名称 如需改也允许)
+     * @ApiMethod POST
+     */
+    public function updateClaim()
+    {
+        if (!$this->request->isPost()) {
+            $this->error('请求错误');
+        }
+        $param = $this->request->post();
+        if (empty($param['Uniqid'])) {
+            $this->error('参数 Uniqid 不能为空');
+        }
+        $update = [];
+        if (isset($param['num'])) {
+            $update['num'] = intval($param['num']);
+        }
+        if (isset($param['sys_id']) && $param['sys_id'] !== '') {
+            $update['sys_id'] = $param['sys_id'];
+        }
+        if (empty($update)) {
+            $this->error('没有需要更新的字段');
+        }
+        $sql = \db('工单_索赔记录')
+            ->where('Uniqid', intval($param['Uniqid']))
+            ->fetchSql(true)
+            ->update($update);
+        $res = Db::execute($sql);
+        if ($res !== false) {
+            $this->success('修改成功');
+        } else {
+            $this->error('修改失败');
+        }
+    }
+
+    /**
+     * 删除索赔记录
+     * @ApiMethod POST
+     */
+    public function deleteClaim()
+    {
+        if (!$this->request->isPost()) {
+            $this->error('请求错误');
+        }
+        $param = $this->request->post();
+        if (empty($param['Uniqid'])) {
+            $this->error('参数 Uniqid 不能为空');
+        }
+        $sql = \db('工单_索赔记录')->where('Uniqid', intval($param['Uniqid']))->fetchSql(true)->delete();
+        $res = Db::execute($sql);
+        if ($res !== false) {
+            $this->success('删除成功');
+        } else {
+            $this->error('删除失败');
+        }
+    }
+
+    /**
+     * 产品质量改善措施管理 —— 工序质量缺陷明细
+     * 根据工单编号 + 印件号,从 db_qczl 汇总 fp_lb1-13 / fp_sl1-13,
+     * 相同类别的数量求和 → 每行一个"工序质量缺陷"类别。
+     * 占比 = 废品合计 / waste_ref(上方主表的"工单质检废"值)× 100,保留两位小数。
+     * @ApiMethod GET
+     * @Param string order    工单编号
+     * @Param string yjno     印件号
+     * @Param number waste_ref 可选,上方主表对应行的"工单质检废"值,用于计算占比
+     */
+    public function getOrderQuality()
+    {
+        if ($this->request->isGet() === false) {
+            $this->error('非法请求');
+        }
+        $params = $this->request->param();
+        if (empty($params['order']) || empty($params['yjno'])) {
+            $this->error('参数错误');
+        }
+        $order    = trim($params['order']);
+        $yjno     = trim($params['yjno']);
+        $wasteRef = isset($params['waste_ref']) ? floatval($params['waste_ref']) : 0;
+
+        // 从 db_qczl 取 fp_lb1-13 / fp_sl1-13 / sys_id(品质量员)
+        $sql = "SELECT
+                    fp_lb1,fp_lb2,fp_lb3,fp_lb4,fp_lb5,fp_lb6,fp_lb7,fp_lb8,fp_lb9,fp_lb10,fp_lb11,fp_lb12,fp_lb13,
+                    fp_sl1,fp_sl2,fp_sl3,fp_sl4,fp_sl5,fp_sl6,fp_sl7,fp_sl8,fp_sl9,fp_sl10,fp_sl11,fp_sl12,fp_sl13,
+                    rtrim(sys_id) as sys_id
+                FROM db_qczl
+                WHERE qczl_gdbh = '{$order}' AND qczl_yjno = '{$yjno}'";
+        $rows = Db::query($sql);
+
+        // 按类别汇总数量:key = 类别名,value = 累计数量
+        $aggMap = [];
+        foreach ($rows as $entry) {
+            for ($i = 1; $i <= 13; $i++) {
+                $label = trim($entry['fp_lb' . $i] ?? '');
+                if ($label === '' || $label === null) continue;
+                $sl = floatval($entry['fp_sl' . $i] ?? 0);
+                if (!isset($aggMap[$label])) {
+                    $aggMap[$label] = 0;
+                }
+                $aggMap[$label] += $sl;
+            }
+        }
+
+        // 品质量员(取非空的第一个 sys_id)
+        $sysIds = array_values(array_unique(array_filter(array_column($rows, 'sys_id'))));
+        $qualityStaff = !empty($sysIds) ? $sysIds[0] : '';
+
+        // 印件名称
+        $productName = db('工单_基本资料')
+            ->where('Gd_gdbh', $order)
+            ->where('行号', $yjno)
+            ->value('成品名称');
+        if (empty($productName)) {
+            $productName = db('工单_基本资料')
+                ->where('Gd_gdbh', $order)
+                ->value('成品名称');
+        }
+        $productName = rtrim($productName ?: '');
+
+        // 组装返回
+        $list = [];
+        foreach ($aggMap as $label => $total) {
+            $rate = '';
+            if ($wasteRef > 0) {
+                $rate = number_format(($total / $wasteRef) * 100, 2) . '%';
+            } else {
+                $rate = '0.00%';
+            }
+            $list[] = [
+                '工序质量缺陷' => $label,
+                '废品合计'    => $total,
+                '占比'        => $rate,
+                '品质量员'    => $qualityStaff,
+                '印件号'      => $yjno,
+                '印件名称'    => $productName,
+            ];
+        }
+        // 按废品合计倒序
+        usort($list, function ($a, $b) {
+            return $b['废品合计'] <=> $a['废品合计'];
+        });
+
+        $this->success('成功', $list);
+    }
+
+    /**
+     * 产品品质统计 —— 左侧树(年 → 月 → 厂商/客户)
+     * 数据源:成品入仓(末板完工工单)
+     * @ApiMethod GET
+     */
+    public function getProductQualityTab()
+    {
+        if (Request::instance()->isGet() == false) {
+            $this->error('非法请求');
+        }
+        $sql = "SELECT
+                    DATE_FORMAT(a.jjcp_sj, '%Y') AS y,
+                    DATE_FORMAT(a.jjcp_sj, '%m') AS m,
+                    RTRIM(b.`编号`) AS 客户编号,
+                    RTRIM(b.`名称`) AS 客户名称,
+                    COUNT(DISTINCT a.jjcp_gdbh) AS cnt
+                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_smb IN ('末 板', '末板')
+                    AND a.`成品编码` != ''
+                    AND a.jjcp_sj >= DATE_SUB(CURDATE(), INTERVAL 24 MONTH)
+                GROUP BY y, m, 客户编号
+                ORDER BY y DESC, m DESC, 客户编号 ASC";
+        $rows = Db::query($sql);
+
+        $years = [];
+        foreach ($rows as $r) {
+            $y = $r['y'];
+            $m = $r['m'];
+            $custCode = $r['客户编号'] ?: '';
+            $custName = $r['客户名称'] ?: '(未匹配客户)';
+            $cnt = intval($r['cnt']);
+
+            if (!isset($years[$y])) {
+                $years[$y] = ['year' => $y, 'total' => 0, 'months' => []];
+            }
+            if (!isset($years[$y]['months'][$m])) {
+                $years[$y]['months'][$m] = ['month' => $m, 'total' => 0, 'customers' => []];
+            }
+            $years[$y]['months'][$m]['customers'][] = [
+                '客户编号' => $custCode,
+                '客户名称' => $custName,
+                'total'    => $cnt,
+            ];
+            $years[$y]['months'][$m]['total'] += $cnt;
+            $years[$y]['total'] += $cnt;
+        }
+
+        $result = [];
+        foreach ($years as $year) {
+            krsort($year['months']);
+            $months = [];
+            foreach ($year['months'] as $month) {
+                $months[] = $month;
+            }
+            $year['months'] = $months;
+            $result[] = $year;
+        }
+        $this->success('请求成功', $result);
+    }
+
+    /**
+     * 产品品质统计 —— 按产品合计 / 单产品工单明细
+     * @ApiMethod GET
+     * @Param string year     年份,如 2026
+     * @Param string month    月份,如 11(可选,不传则为整年)
+     * @Param string customer 客户编号(可选)
+     * @Param string cpdh     产品代号(可选,传值时返回该产品的工单明细)
+     */
+    public function getProductQualityList()
+    {
+        if (Request::instance()->isGet() == false) {
+            $this->error('非法请求');
+        }
+        $params   = Request::instance()->param();
+        $year     = trim($params['year'] ?? '');
+        $month    = trim($params['month'] ?? '');
+        $customer = trim($params['customer'] ?? '');
+        $cpdh     = trim($params['cpdh'] ?? '');
+        if ($year === '') {
+            $this->error('参数错误');
+        }
+
+        $dateLike = $month !== ''
+            ? $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '%'
+            : $year . '-%';
+        $rows = $this->queryProductQualityRows($dateLike);
+
+        // 按客户编号过滤(客户编号由产品代号前缀推导,与左侧树口径一致)
+        $filtered = [];
+        foreach ($rows as $r) {
+            $custCode = $this->productCustomerCode($r['产品代号']);
+            if ($customer === '__NONE__') {
+                // 左侧树的"未匹配客户"节点
+                if ($custCode !== '') {
+                    continue;
+                }
+            } elseif ($customer !== '' && $custCode !== $customer) {
+                continue;
+            }
+            $r['客户编号'] = $custCode;
+            $filtered[] = $r;
+        }
+
+        // 工单明细
+        if ($cpdh !== '') {
+            $detail = [];
+            foreach ($filtered as $r) {
+                if (trim($r['产品代号']) !== $cpdh) {
+                    continue;
+                }
+                $feed = floatval($r['实际投料']) * 10000;
+                $in   = floatval($r['入仓数量']);
+                $loss = floatval($r['计划损耗']);
+                $fp   = floatval($r['废品合计']);
+                $zcfp = floatval($r['制程废']);
+                $detail[] = [
+                    '工单编号'   => $r['Gd_gdbh'],
+                    '印件号'     => $r['yjno'],
+                    '产品代号'   => $r['产品代号'],
+                    '产品名称'   => $r['产品名称'],
+                    '入仓日期'   => $r['入仓日期'],
+                    '入仓数量'   => $in,
+                    '实际投料'   => $feed / 10000,
+                    '废品合计'   => $fp,
+                    '工单制程废' => $zcfp,
+                    '工单检验废' => $fp - $zcfp,
+                    '目标合格率' => $feed > 0 ? number_format(($feed - $loss) / $feed * 100, 2) . '%' : '',
+                    '实际合格率' => $feed > 0 ? number_format($in / $feed * 100, 2) . '%' : '',
+                ];
+            }
+            $this->success('成功', ['summary' => [], 'detail' => $detail]);
+            return;
+        }
+
+        // 按产品代号合计
+        $agg = [];
+        foreach ($filtered as $r) {
+            $code = trim($r['产品代号']);
+            if (!isset($agg[$code])) {
+                $agg[$code] = [
+                    '产品代号'   => $code,
+                    '产品名称'   => $r['产品名称'],
+                    '工单数'     => 0,
+                    '入仓数量'   => 0,
+                    '实际投料'   => 0,
+                    '废品合计'   => 0,
+                    '工单制程废' => 0,
+                    '计划损耗'   => 0,
+                    '工单集合'   => [],
+                ];
+            }
+            $agg[$code]['工单集合'][$r['Gd_gdbh']] = true;
+            $agg[$code]['入仓数量']   += floatval($r['入仓数量']);
+            $agg[$code]['实际投料']   += floatval($r['实际投料']);
+            $agg[$code]['废品合计']   += floatval($r['废品合计']);
+            $agg[$code]['工单制程废'] += floatval($r['制程废']);
+            $agg[$code]['计划损耗']   += floatval($r['计划损耗']);
+        }
+
+        $summary = [];
+        foreach ($agg as $item) {
+            $feed = $item['实际投料'] * 10000;
+            $in   = $item['入仓数量'];
+            $loss = $item['计划损耗'];
+            $fp   = $item['废品合计'];
+            $zcfp = $item['工单制程废'];
+            $summary[] = [
+                '产品代号'   => $item['产品代号'],
+                '产品名称'   => $item['产品名称'],
+                '工单数'     => count($item['工单集合']),
+                '入仓数量'   => $in,
+                '实际投料'   => $item['实际投料'],
+                '废品合计'   => $fp,
+                '工单制程废' => $zcfp,
+                '工单检验废' => $fp - $zcfp,
+                '目标合格率' => $feed > 0 ? number_format(($feed - $loss) / $feed * 100, 2) . '%' : '',
+                '实际合格率' => $feed > 0 ? number_format($in / $feed * 100, 2) . '%' : '',
+            ];
+        }
+        // 按废品合计倒序
+        usort($summary, function ($a, $b) {
+            return $b['废品合计'] <=> $a['废品合计'];
+        });
+
+        $this->success('成功', ['summary' => $summary, 'detail' => []]);
+    }
+
+    /**
+     * 产品品质统计 —— 基础数据(按 工单编号+印件号 一行)
+     */
+    private function queryProductQualityRows($dateLike)
+    {
+        $subQuery = \db('成品入仓')
+            ->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();
+
+        $field = '
+            a.jjcp_gdbh AS Gd_gdbh,
+            a.jjcp_yjno AS yjno,
+            RTRIM(a.jjcp_cpdh) AS 产品代号,
+            RTRIM(c.yj_yjmc) AS 产品名称,
+            DATE(a.jjcp_sj) AS 入仓日期,
+            total_sl.warehousing_num AS 入仓数量,
+            b.`实际投料` AS 实际投料,
+            b.`废品合计` AS 废品合计,
+            SUM(b.`班组制程废品`) AS 制程废,
+            SUM(DISTINCT b.`计划损耗`) AS 计划损耗
+        ';
+
+        return \db('成品入仓')
+            ->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)
+            ->where('a.jjcp_smb', 'in', ['末 板', '末板'])
+            ->where('a.成品编码', '<>', '')
+            ->where('a.jjcp_sj', 'like', $dateLike)
+            ->group('a.jjcp_gdbh, a.jjcp_yjno')
+            ->order('a.jjcp_sj DESC')
+            ->select();
+    }
+
+    /**
+     * 产品代号 → 客户编号(与左侧树 SQL 的 CASE 口径保持一致)
+     */
+    private function productCustomerCode($cpdh)
+    {
+        $cpdh = trim((string)$cpdh);
+        if ($cpdh === '') {
+            return '';
+        }
+        return preg_match('/^[A-Za-z]/', $cpdh) ? substr($cpdh, 0, 5) : substr($cpdh, 0, 4);
+    }
+
+    
 }
 

+ 62 - 37
application/api/controller/PrintingPlate.php

@@ -566,50 +566,75 @@ class PrintingPlate extends Api
      * @throws \think\db\exception\ModelNotFoundException
      * @throws \think\exception\DbException
      */
-    public function getPrintDateList()
-    {
-        if (!$this->request->isGet()) {
-            $this->error('请求错误');
-        }
+   public function getPrintDateList()
+{
+    if (!$this->request->isGet()) {
+        $this->error('请求错误');
+    }
 
-        $result = db('产品_印版库')
-            ->field([
-                'YEAR(报废日期) as year',
-                'DATE_FORMAT(报废日期, "%Y-%m") as month',
-                'DATE_FORMAT(报废日期, "%Y-%m-%d") as day'
-            ])
-            ->where('报废日期', '<>', '1900-01-01 00:00:00')
-            ->group('day')
-            ->order('day desc')
-            ->select();
+    $result = db('产品_印版库')
+        ->field([
+            'YEAR(报废日期) as year',
+            'DATE_FORMAT(报废日期, "%Y-%m") as month',
+            'DATE_FORMAT(报废日期, "%Y-%m-%d") as day'
+        ])
+        ->where('报废日期', '<>', '1900-01-01 00:00:00')
+        ->group('day')
+        ->order('day desc')
+        ->select();
+
+    if (empty($result)) {
+        $this->success('成功', []);
+    }
 
-        if (empty($result)) {
-            $this->success('成功', []);
+    // 先按年、月分组,日保持在数组里
+    $grouped = [];   // $grouped[$year][$month][] = $day
+    foreach ($result as $item) {
+        if (empty($item['year']) || empty($item['month']) || empty($item['day'])) {
+            continue;
         }
+        $year  = (string)$item['year'];
+        $month = $item['month'];
+        $day   = $item['day'];
 
-        // 构建层次结构
-        $data = [];
-        foreach ($result as $item) {
-            if (empty($item['year']) || empty($item['month']) || empty($item['day'])) {
-                continue;
-            }
-
-            $year = (string)$item['year'];
-            $month = $item['month'];
-            $day = $item['day'];
-
-            if (!isset($data[$year])) {
-                $data[$year] = [];
-            }
-            if (!isset($data[$year][$month])) {
-                $data[$year][$month] = [];
-            }
-
-            $data[$year][$month][] = $day;
+        if (!isset($grouped[$year])) {
+            $grouped[$year] = [];
+        }
+        if (!isset($grouped[$year][$month])) {
+            $grouped[$year][$month] = [];
         }
+        $grouped[$year][$month][] = $day;
+    }
 
-        $this->success('成功', $data);
+    // 年份倒序、月份倒序、日期倒序
+    krsort($grouped);
+    foreach ($grouped as &$months) {
+        krsort($months);
+        foreach ($months as &$days) {
+            rsort($days);
+        }
+        unset($days);
     }
+    unset($months);
+
+    // 转成数组结构,避开 JS 对象整数 key 重排
+    $data = [];
+    foreach ($grouped as $year => $months) {
+        $monthList = [];
+        foreach ($months as $month => $days) {
+            $monthList[] = [
+                'month' => $month,
+                'days'  => $days,
+            ];
+        }
+        $data[] = [
+            'year'   => (string)$year,
+            'months' => $monthList,
+        ];
+    }
+
+    $this->success('成功', $data);
+}
 
 
     /**

+ 77 - 0
application/api/controller/Product.php

@@ -216,6 +216,56 @@ class Product extends Api
             ->where($option)->field($gy_field)->order('a.Gy0_yjno asc,a.Gy0_gxh asc')->select();
         $this->success('请求成功',$gyRes);
     }
+    /**
+     * 预览修改工艺参数(仅返回影响的工单列表,不执行修改)
+     *
+     * @ApiMethod POST
+     * @params array data
+     */
+    public function editGyPreview(){
+        if (Request::instance()->isPost() == false){
+            $this->error('非法请求');
+        }
+        $params = Request::instance()->post();
+        if (!isset($params) || !isset($params[0]['UniqID'])){
+            $this->error('参数不能为空');
+        }
+        $affected = [];
+        foreach ($params as $value) {
+            $newSbbh = isset($value['machine']) ? trim((string)$value['machine']) : '';
+            if ($newSbbh === '') continue;
+            $gyInfo = \db('产品_工艺资料')->where('UniqID', $value['UniqID'])->field('Gy0_cpdh, Gy0_yjno, Gy0_gxh, Gy0_sbbh')->find();
+            if (empty($gyInfo)) continue;
+            $oldSbbh = trim($gyInfo['Gy0_sbbh']);
+            if ($oldSbbh === $newSbbh) continue; // 没改机台跳过
+            $cpdh = trim($gyInfo['Gy0_cpdh']);
+            $yjno = trim($gyInfo['Gy0_yjno']);
+            $gxh  = trim($gyInfo['Gy0_gxh']);
+            if ($cpdh === '' || $yjno === '' || $gxh === '') continue;
+            $rows = \db('工单_工艺资料')
+                ->alias('w')
+                ->join('工单_基本资料 o', 'w.Gy0_gdbh = o.Gd_gdbh', 'left')
+                ->where('w.Gy0_sj1', '1900-01-01 00:00:00')
+                ->where('w.Gy0_yjno', $yjno)
+                ->where('w.Gy0_gxh', $gxh)
+                ->whereIn('w.Gy0_gdbh', function($query) use ($cpdh) {
+                    $query->table('工单_基本资料')->where('Gd_cpdh', $cpdh)->field('Gd_gdbh');
+                })
+                ->field('w.Gy0_gdbh as gdbh, w.Gy0_yjno as yjno, w.Gy0_gxh as gxh, rtrim(w.Gy0_sbbh) as old_sbbh, rtrim(o.Gd_cpdh) as cpdh')
+                ->select();
+            foreach ($rows as $r) {
+                $affected[] = [
+                    'gdbh'     => $r['gdbh'],
+                    'yjno'     => $r['yjno'],
+                    'gxh'      => $r['gxh'],
+                    'old_sbbh' => $r['old_sbbh'],
+                    'new_sbbh' => $newSbbh,
+                    'cpdh'     => $r['cpdh'],
+                ];
+            }
+        }
+        $this->success('预览成功', $affected);
+    }
     /**
      * 修改工艺参数
      *
@@ -257,11 +307,38 @@ class Product extends Api
             if (!empty($value['Gy0_site'])){
                 $data['Gy0_site'] = $value['Gy0_site'];
             }
+            // 如果修改了设备编号 → 同步未开工工单_工艺资料
+            $newSbbh = isset($value['machine']) ? trim((string)$value['machine']) : '';
+            $syncSql = '';
+            if ($newSbbh !== '') {
+                // 取产品_工艺资料的 Gy0_cpdh / Gy0_yjno / Gy0_gxh
+                $gyInfo = \db('产品_工艺资料')->where('UniqID', $value['UniqID'])->field('Gy0_cpdh, Gy0_yjno, Gy0_gxh')->find();
+                if (!empty($gyInfo)) {
+                    $cpdh = trim($gyInfo['Gy0_cpdh']);
+                    $yjno = trim($gyInfo['Gy0_yjno']);
+                    $gxh  = trim($gyInfo['Gy0_gxh']);
+                    if ($cpdh !== '' && $yjno !== '' && $gxh !== '') {
+                        $syncSql = \db('工单_工艺资料')
+                            ->where('Gy0_sj1', '1900-01-01 00:00:00')
+                            ->where('Gy0_yjno', $yjno)
+                            ->where('Gy0_gxh', $gxh)
+                            ->whereIn('Gy0_gdbh', function($query) use ($cpdh) {
+                                $query->table('工单_基本资料')->where('Gd_cpdh', $cpdh)->field('Gd_gdbh');
+                            })
+                            ->fetchSql(true)
+                            ->update(['Gy0_sbbh' => $newSbbh]);
+                    }
+                }
+            }
             $sql = db('产品_工艺资料')->where('UniqID',$value['UniqID'])->fetchSql(true)->update($data);
             $res = Db::query($sql);
             if ($res !== false){
                 $i++;
             }
+            // 执行级联同步(不影响主更新的成功判定)
+            if ($syncSql !== '') {
+                Db::execute($syncSql);
+            }
         }
         if ($i !== 0){
             $this->success('更新成功');

+ 74 - 15
application/api/controller/ProductionLot.php

@@ -91,8 +91,23 @@ class ProductionLot extends Api
         if (empty($list)){
             $this->success('未找到流程单信息');
         }
+
+        // 一次性批量查出该工单在 制程检验_记录 中按 (工单编号, 流程单号) 分组的提交次数(相同提交时间算一次)
+        $escGdbh = str_replace("'", "''", $param['gdbh']);
+        $yjno = intval($param['yjno']);
+        $checkSql = "SELECT `流程单号` AS num, COUNT(DISTINCT `提交时间`) AS cnt FROM `制程检验_记录`
+            WHERE `工单编号` = '{$escGdbh}' GROUP BY `流程单号`";
+        $checkRows = \think\Db::query($checkSql);
+        $checkMap = [];
+        foreach ($checkRows as $cr) {
+            $checkMap[(int)$cr['num']] = (int)$cr['cnt'];
+        }
+
         foreach ($list as $key => $value){
-            $list[$key]['流程单'] = '第'.$value['num'].'个流程单';
+            $num = (int)$value['num'];
+            $sum = isset($checkMap[$num]) ? $checkMap[$num] : 0;
+            $list[$key]['sum'] = $sum;
+            $list[$key]['流程单'] = '第'.$value['num'].'个流程单'.($sum > 0 ? ' ('.$sum.')' : '');
         }
         $this->success('成功',$list);
     }
@@ -189,26 +204,70 @@ class ProductionLot extends Api
         if (!isset($param['gdbh']) || !isset($param['yjno'])|| !isset($param['num'])){
             $this->success('参数错误');
         }
-        $page = $param['page'] ?? 1;
-        $pageSize = $param['pageSize'] ?? 50;
-        $list = db('制程检验_记录')
-            ->field('工单编号,流程单号,工序名称,班组编号,类别,检验项目,检验结果,检验备注 as 项目备注,相关标准 as 修改标准')
+        // 取出所有明细,PHP 端按 提交时间 分组合并
+        $rawList = db('制程检验_记录')
+            ->field('工单编号,流程单号,工序名称,班组编号,类别,检验项目,检验结果,检验备注 as 项目备注,相关标准 as 修改标准,提交时间 as 检验时间')
             ->where('工单编号',$param['gdbh'])
             ->where('印件号',$param['yjno'])
             ->where('流程单号',$param['num'])
-            ->where('类别', 'neq', '现场巡查记录')
-            ->order('流程单号')
-            ->page($page,$pageSize)
+            ->order('检验时间')
             ->select();
-        $total = count($list);
-        $data = [
-            'data' => $list,
-            'total' => $total
-        ];
-        if (empty($list)){
+
+        // 按 提交时间 分组合并
+        $grouped = [];
+        $orderKey = [];
+        foreach ($rawList as $row) {
+            $key = $row['检验时间'];
+            if (!isset($grouped[$key])) {
+                $grouped[$key] = [
+                    '工单编号'   => $row['工单编号'],
+                    '流程单号'   => $row['流程单号'],
+                    '工序名称'   => $row['工序名称'],
+                    '班组编号'   => $row['班组编号'],
+                    '类别'       => $row['类别'],
+                    '检验项目'   => $row['检验项目'],
+                    '检验结果'   => $row['检验结果'],
+                    '项目备注'   => $row['项目备注'],
+                    '修改标准'   => $row['修改标准'],
+                    '检验时间'   => $row['检验时间'],
+                    'items'      => [],   // 这一次提交的所有项目
+                ];
+                $orderKey[] = $key;
+            }
+            $grouped[$key]['items'][] = $row;
+        }
+        // 检验项目:只放首个 + "共N项"
+        $result = [];
+        foreach ($orderKey as $key) {
+            $g = $grouped[$key];
+            $cnt = count($g['items']);
+            if ($cnt > 1) {
+                $g['检验项目'] = $g['items'][0]['检验项目'] . ' ... (共' . $cnt . '项)';
+            }
+            $result[] = $g;
+        }
+        // 按 类别 统计提交次数(相同提交时间算一次;含现场巡查记录)
+        $escGdbh = str_replace("'", "''", $param['gdbh']);
+        $yjno = intval($param['yjno']);
+        $num = intval($param['num']);
+        $catSql = "SELECT `类别` AS category, COUNT(DISTINCT `提交时间`) AS cnt
+            FROM `制程检验_记录`
+            WHERE `工单编号` = '{$escGdbh}' AND `印件号` = {$yjno} AND `流程单号` = {$num}
+            GROUP BY `类别`";
+        $catRows = \think\Db::query($catSql);
+        $categories = [];
+        $catTotal = 0;
+        foreach ($catRows as $cr) {
+            $categories[] = [
+                'category' => $cr['category'],
+                'count'    => (int)$cr['cnt'],
+            ];
+            $catTotal += (int)$cr['cnt'];
+        }
+        if (empty($result)){
             $this->success('未找到制程检验记录');
         }
-        $this->success('成功',$data);
+        $this->success('成功', ['data' => $result, 'total' => count($result), 'categories' => $categories, 'catTotal' => $catTotal]);
 
     }
 

+ 32 - 12
application/api/controller/WorkOrder.php

@@ -2518,18 +2518,38 @@ class WorkOrder extends Api
                     $this->error('该产品印件号'.$value['Gy0_yjno'].'工序号为'.$value['gy0_gxmc'].'的损耗代号错误,请调整之后再引用');
                 }
             }
-            //设置默认机台
-            $machineList = \db('设备_基本资料')
-                ->where('生产工序','like','%'.$value['gy0_gxmc'].'%')
-                ->where('使用部门','<>','研发中心')
-                ->where('设备编组','<>','')
-                ->where('sys_sbID','<>','')
-                ->order('设备编号')
-                ->value('设备编号');
-            $ProcessList[$key]['Gy0_sbbh'] = '';
-            if (!empty($machineList)){
-                $ProcessList[$key]['Gy0_sbbh'] = $machineList;
-            }
+            //设置默认机台 + 对应排单小时定额
+            $productMachine = isset($value['Gy0_sbbh']) ? trim((string)$value['Gy0_sbbh']) : '';
+                $ProcessList[$key]['Gy0_sbbh'] = '';
+                $ProcessList[$key]['Gy0_小时产能'] = 0;
+                $sbbhForCapacity = '';
+                if ($productMachine !== '') {
+                    $ProcessList[$key]['Gy0_sbbh'] = $productMachine;
+                    $sbbhForCapacity = $productMachine;
+                } else {
+                    $machineRow = \db('设备_基本资料')
+                        ->where('生产工序', 'like', '%' . $value['gy0_gxmc'] . '%')
+                        ->where('使用部门', '<>', '研发中心')
+                        ->where('设备编组', '<>', '')
+                        ->where('sys_sbID', '<>', '')
+                        ->order('设备编号')
+                        ->field('设备编号, 排单小时定额')
+                        ->find();
+                    if (!empty($machineRow)) {
+                        $ProcessList[$key]['Gy0_sbbh'] = trim($machineRow['设备编号']);
+                        $sbbhForCapacity = trim($machineRow['设备编号']);
+                        if (!empty($machineRow['排单小时定额'])) {
+                            $ProcessList[$key]['Gy0_小时产能'] = intval($machineRow['排单小时定额']);
+                        }
+                    }
+                }
+                // 产品自带机台:也去设备_基本资料取排单小时定额
+                if ($sbbhForCapacity !== '' && $productMachine !== '') {
+                    $capacity = \db('设备_基本资料')->where('设备编号', $sbbhForCapacity)->value('排单小时定额');
+                    if (!empty($capacity)) {
+                        $ProcessList[$key]['Gy0_小时产能'] = intval($capacity);
+                    }
+                }
             $ProcessList[$key]['Gy0_yjno'] = $value['Gy0_yjno'];
             $ProcessList[$key]['Gy0_gdbh'] = $param['workorder'];
             $ProcessList[$key]['Gy0_gxmc'] = $value['gy0_gxmc'];